libds architecture#

How libds, the reference runtime, is built: its module decomposition, public surfaces, dependency discipline, compiler / runtime split, and build artefacts.

This doc is the "how" of libds. The "what" — what every conforming runtime must provide — lives at [RARC]. Treat the runtime-spec subsystem names (consumption loop, working memory, Rete, agenda, dispatcher, recorder) as fixed vocabulary; this doc picks where each one lives in libds code.

What this is not#

  • Not the abstract runtime spec. [RARC] is authoritative for that; this doc implements it.

  • Not an API reference. The public surface is runtime/include/libds.h.

  • Not a data-model spec. Struct layouts and ownership rules are [IDAT]; allocation routing is [IALC]; the error model is [IERR].

  • Not a threading design. libds spawns no threads and does not sleep or block ([IARC.1.10]); the runtime spec commits to single-writer consumption per tier, and the integrator owns whatever thread calls in.


Library and surface commitments [IARC.1]#

  • [IARC.1.2] One static library artefact. libds builds as a single libds.a — the native Rete engine included. Integrators link it against their chosen transport glue. No shared-object distribution in v1.

  • [IARC.1.3] C99 baseline. libds is implemented in C so that it links from the deployment contexts DS targets: Home Assistant custom components, Python via ctypes, Rust via FFI, and embedded. It uses no GNU extensions, no C11-only features and no compiler-specific pragmas, which keeps the library portable across the widest integrator set.

  • [IARC.1.4] One public header. runtime/include/libds.h carries the entire integrator surface — engine lifecycle, opaque handles, slot-value union, schema registry, fact assert / retract, pump, all typed callback signatures and event payloads, and every set_*_callback setter. Internal headers stay alongside their .c under runtime/src/libds/; four of them — sha256.h, rfcs/rfcs.h, the rfcs/atoms.h it includes, and ds_re2.h — additionally ship under include/internal/ for integrators reusing libds's hashing, fact-stream primitives or RE2 seam, and carry no API-stability guarantee.

  • [IARC.1.5] Source layout. libds's sources and their companion internal .h files live under runtime/src/libds/. The engine's own modules sit at its top, and a subsystem with files of its own takes a subdirectory: rete/ the matching network, dsc/ the artefact loader, rfcs/ the fact-stream codec, series/ the series backings, and the others beside them. Public headers are a separate tree (see [IARC.1.4]).

see also: IARC.1.4

  • [IARC.1.6] The compiler is separate from the engine ([RARC.9.1]). The reference compiler is written in Mercury and produces .dsc bundles at author or CLI time. It ships separately under compiler/; libds itself carries no compiler code.

see also: RARC.9.1

  • [IARC.1.7] Subsystem names match the runtime spec. Module names follow runtime-spec subsystem names one-for-one where possible. Reading the runtime spec and finding the corresponding libds code is a mechanical lookup, not an interpretive one.

  • [IARC.1.8] Opaque handles. The four handle types, ds_engine_t, ds_fact_t, ds_schema_t and ds_json_t, are opaque: libds.h forward-declares each, the integrator passes it as a pointer, and its layout is private to its owning module, so it can change without ABI churn ([IDAT.1.2], [IARC.6]). Every other type libds.h declares, the stream event ds_stream_ev_t among them, has its layout in libds.h.

see also: IARC.6, IDAT.1.2

  • [IARC.1.9] The Rete engine is a native module. libds implements its own C Rete matching network — the rete module ([IRET]) — not a vendored rule engine. The network is libds's own code, compiled and owned like every other module.

  • [IARC.1.10] Async-first, never depends on threads. Load-bearing design invariant across every libds module, not just the consumption loop. libds never depends on threads for anything: no pthread_* calls, no sleep / nanosleep, no internally-spawned threads, no background timers, no thread-local state as a semantic mechanism, no locks held across a callback. The consumption loop exposes a pump function (ds_engine_pump(engine)) that runs to agenda exhaustion and returns ([NLFC.2.2]). Every other module — dispatcher, recorder, wm — is equally thread-free: they produce callbacks, consume callbacks, mutate state on the pump's call stack, and that is all. The integrator may freely use threads in their own code — e.g. running pump on a dedicated thread, or calling pump from a thread pool — but libds does not require them to, does not assume them, and does not spawn them. The design assumption is that integrators are comfortable with async programming; we do not ship sync-mode conveniences or thread wrappers. Pure async-event deployment (no threads at all) is the primary target. Any module design that forces threading — "this callback must run on a different thread," "this lock must be held across an await," "this operation blocks pending I/O" — is a design regression to flag and redesign. All blocking I/O goes through callbacks the integrator's runtime drives; libds never waits, never spawns, never sleeps.

see also: NLFC.2.2

  • [IARC.1.11] One ds_engine_t = one independent engine. An integrator may instantiate multiple ds_engine_t instances in the same process; each is fully independent, with its own working memory, agenda, rule set, clock, recorder, and Rete network. libds holds no global state and no singletons; every public function that acts on an engine takes its handle (or a sub-handle the engine owns) as its first argument. Four kinds act on none: ds_engine_new, which makes one; the ds_json_* functions, whose trees belong to no engine; ds_free, which releases memory libds returned; and ds_build_capabilities, which reports what the build has code for. All engine state hangs off the handle — there is no ambient or process-global engine context. Important for real-world deployments — the integration in particular runs multiple DS contexts (per-tier, per-room, per-experiment) and depends on them being independent within one process. Combined with [IARC.1.10], it means an integrator can pump N engines from one async runtime without any threading or cross-engine interference.

    Test obligations: spec/test_arch_invariants_spec pins the per-engine isolation invariant black-box (facts, clock state, stream callbacks, typed callbacks, and rule sets are all per-engine; no cross-engine bleed). The schema-registry slice of the same invariant lives in spec/test_schema_registry_spec per IDAT.5.5.

ratified — see also: IARC.1.10, IDAT.5.5

  • [IARC.1.12] Consistent ds_result_t at every call site. Every libds function that can fail — public API, internal module-to-module, static helpers — returns ds_result_t. No status as an int, no thread-local errno, no "success-return / call-again-for-detail" two-step. A function that cannot fail returns its value or nothing: ds_free, ds_build_capabilities, and the visitor callbacks libds calls for each node, edge, trace step or refraction entry (libds.h declares each void), are such functions. One pattern to learn; one pattern to review; nothing to translate at the public / internal boundary.

    Its shape is a status and a detail and nothing else ([IERR.1.3]): 16 bytes, which fits in registers under SysV x86-64 (RAX:RDX) and AAPCS64. No status carries a source location: libds parses no DS source, and an author's source location comes from the artefact's LineSpan atoms ([NDBG.3.1]). The status enum is [IERR.2], detail-string stability [IERR.4]. Wire-error propagation is not part of it — libds defines no wire encoding for error codes ([IERR.6.1]).

    The corollary that the engine's pending-error slot preserves first-error-wins for sibling RHS actions (where the later sibling succeeds — the trampoline only overwrites pending on non-OK, and wm.c's save-and-restore around ds_engine_assert keeps the prior error intact across nested calls per IDSP.1.6) is pinned in spec/test_arch_invariants_spec.

    This decision fixes only the shape and the one-everywhere discipline: a failure is never reported any other way.

ratified — see also: IDSP.1.6, IERR.1.3, IERR.2, IERR.4, IERR.6.1, NDBG.3.1

  • [IARC.1.13] Per-object allocation; no arena. Every libds struct has ds_<type>_new(engine, ...) that allocates and ds_<type>_free(obj) that frees. No bulk arena allocation, no copy-on-write. Exactly one owner at any time; explicit ownership transfer where needed (documented per-function in headers, never implicit). Reference counting is used in two places and no others: the intern table's counted entries ([IDAT.4.7]), and the immutable structures a clone shares with its source ([IARC.11.1]).

    Rete-network memory — fact storage in working memory, alpha/beta-node state, tokens — is owned by the rete and wm modules and follows the same per-object discipline; it routes through the DS_* allocation macros ([IALC.1]) like all libds allocation.

    OOM surfaces via ds_result_t. Allocation failure returns a DS_ERR_OOM status through the standard result path ([IARC.1.12]); libds never aborts on OOM. Callers clean up anything partially constructed and propagate the failure. No try / rescue / longjmp.

    Rationale: simple to reason about, trivially profilable with standard heap tools (valgrind, Massif, tcmalloc hooks). At v1 fact / activation footprints (hundreds to low thousands active) allocation churn is a third-order concern. Arena-style escape hatches are reserved for specific hot paths if profiling warrants, not a global policy.

see also: IALC.1, IARC.1.12, IARC.11.1, IDAT.4.7

  • [IARC.1.14] Every external-service interaction is an integrator callback; libds never hard-codes a service shape. Load-bearing design invariant across every libds module. libds defines the shape of the data that crosses a boundary — metric name + value + labels, log event + level + message, cache key + value + TTL, call-target request / reply — and the integrator fills in a callback that routes that data to whatever infrastructure they run (Prometheus / StatsD / Loki / OpenTelemetry / Redis / Postgres / stderr / an in-process queue / anything else). libds never opens a socket, writes a file, or calls a specific remote API directly.

    Applies to (non-exhaustive):

    • Metrics — internal counters / gauges surface through a metrics-emit callback.

    • Operational logs — "cooldown kicked in," "rule set reloaded," anything an operator wants to see — surface through a log-emit callback. (Distinct from ds_result_t errors, which travel as return values.)

    • Call targets — call actions go to an integrator-provided dispatch callback (the integrator decides whether the call stays in-process or is bridged elsewhere).

    • Storage writes — cache_* land via typed integrator callbacks; the integrator hits whatever backend they like (in-process SQLite, remote Redis, anything).

    • Stream events — fact lifecycle, rule firing, action dispatch all surface to the integrator-registered stream callback. Debug tooling, replay stores, audit logs subscribe here.

    Shape rules:

    • Every callback takes the engine handle (per [IARC.1.11]) as first argument.

    • Every callback whose work can fail returns ds_result_t (per [IARC.1.12]); the visitors libds calls while walking its own structures return nothing.

    • Every callback is invoked synchronously, on the stack of the call that fires it (per [IARC.1.10], [NCBK.1.7]); callbacks must be non-blocking and thread-free from libds's perspective. What the integrator does with the data after is their concern.

    • An unregistered (NULL) callback is a silent drop for non-essential verbs (log / cache when not required) and an explicit error for essential ones (call when no target is registered, etc.).

    No wire, no protocol, no peer module. libds's surface is typed C callbacks plus structured event payloads. Bytes are an integrator concern: if two libds instances or processes need to communicate, the integrators define and implement that protocol themselves. libds emits typed events; integrators encode bytes if they want bytes. See [IARC.2.3].

    Rejection rule: a PR that hard-codes fprintf(stderr, ...), syslog(...), a TCP connect, a metrics-library emission, or any other concrete destination for telemetry / logs / storage lands in review as a redesign request. The right shape is always "define the data, expose the callback."

    Rationale: libds embeds in Home Assistant custom components, standalone daemons, research harnesses, CI test runs, and future embeddings we haven't imagined. The integrator knows their stack; we don't. Coupling to specific services or wire formats would make those embeddings impossible or require conditional-compilation mazes. Applying the callback-only discipline universally keeps every deployment context first-class.

see also: IARC.1.10, IARC.1.11, IARC.1.12, IARC.2.3, NCBK.1.7

  • [IARC.1.16] libds links no function of the C printf family. No object libds itself compiles may define or reference printf, fprintf, sprintf, snprintf, dprintf, asprintf, their v-prefixed and wide-character forms, or a fortified __*printf_chk variant. The libprotobuf-c archive shipped beside libds is held to the same rule. In a libds archive built without RE2 the rule binds every member, because every member is DS's. In one that carries RE2, the RE2 and Abseil objects folded into it are linked as upstream built them and are not bound: nothing libds renders is formatted by them.

    Every text libds produces is rendered by libds's own formatting operations: integers, the canonical Float form and its parse ([LDET.3.2.7], [LDET.3.2.8]), and interpolation ([LGRA.2.9.6.10]). No format string reaches the runtime: an interpolated string arrives as primitives, and the loader refuses one whose alignment, type or time field is not a member of its enumeration in proto/rete_expr.proto with DS_ERR_DSC_SEMANTIC ([NERR.8.1]). It does not check a spec part against the type it formats: the compiler refuses those ([LGRA.2.9.6.5]), and a value rendered under a spec it does not take raises as [IRET.9.6] states.

    A build whose archive violates this is invalid, whatever its tests report. The check is a symbol census over the members the rule binds, and it fails on the first printf-family symbol.

see also: IRET.9.6, LDET.3.2.7, LDET.3.2.8, LGRA.2.9.6.10, LGRA.2.9.6.5, NERR.8.1

  • [IARC.1.15] Compiled artefacts are bytes libds owns; cross-process surfaces are not. The "no wire, no protocol" stance ([IARC.1.14]) governs runtime interactions across libds's process boundary — telemetry, action dispatch, fact assertion from the outside, debug subscription, peer bridging. The DS compiler artefact (.dsc, specified at [RDSC]) is a different category: it is a one-way compiler-to-runtime artefact loaded once at engine setup, not a continuing communication channel. libds owns its decoder (protobuf-c per [IARC.7.4]) the same way it owns the Rete network — internal machinery, not a surface. This narrowly authorises libds to read structured bytes from disk while preserving the invariant that every runtime boundary remains a typed C callback. libds must not use the DSC dependency (protobuf-c) for any other purpose: wire encoding for cross-engine bridging, telemetry serialisation, debug protocol, peer transport. Schema-typed cross-boundary serialisation by the integrator (each schema has a generated .proto shipped inside the artefact per [LFAC.8] and [RDSC.5.8]) is enabled by the artefact, not performed by libds: the integrator who wants to encode a fact reads the schema's .proto from the loaded engine and runs their own protobuf encoder. libds supplies the shape; the integrator owns the bytes.


see also: IARC.1.14, IARC.7.4, LFAC.8, RDSC.5.8

Module graph [IARC.2]#

[IARC.2.1] libds modules and their dependency edges:

              ┌────────────────────────────────────────────┐
              │  Public headers  (runtime/include/libds)  │
              │  - typed callback signatures               │
              │  - structured event payloads               │
              │  - opaque handles                          │
              └──────────────────┬─────────────────────────┘
                                 │
                  ┌──────────────▼──────────────────┐
                  │   engine                        │
                  │   (pump-driven consumption;     │
                  │   one Rete network per instance)│
                  └─┬──────┬──────────┬──────┬──────┘
                    │      │          │      │
       ┌────────────┘      │          │      └────────────────┐
       ▼                   ▼          ▼                       ▼
┌──────────┐        ┌──────────┐ ┌──────────┐          ┌──────────┐
│ wm       │        │ schema   │ │dispatcher│          │ recorder │
│(working  │        │(registry)│ │(RHS      │          │(stream   │
│ memory)  │        │          │ │ actions) │          │ writer)  │
└────┬─────┘        └──────────┘ └────┬─────┘          └────▲─────┘
     │                                │                     │
     │          rete                  │                     │
     └────────────────────────────────┤                     │
                                      │                     │
                                      └─► integrator ───────┘
                                          callbacks
                                       (call / cache /
                                        stream / ...)

              ┌──────────────────────────────┐
              │  clock    (leaf; no deps)    │
              │  telemetry (callback dispatch)│
              └──────────────────────────────┘

[IARC.2.2] Edges are directed; a module may call only downward in this diagram. Horizontal calls (wm ↔ dispatcher) happen via the engine, not directly.

[IARC.2.3] No protocol, no peer, no wire. Every interaction that crosses libds's boundary — telemetry emission, action dispatch, fact assertion from outside, debug subscription — goes through a typed callback the integrator registers. libds defines the shape of the data that crosses (struct layouts, event payloads, opaque handles); it never defines bytes, framing, or transport. Cross-process or cross-machine concerns (e.g., bridging two libds instances, network-attached storage, remote debugging) are entirely the integrator's responsibility. See [IARC.1.14] for the load-bearing invariant; this module graph reflects it.

see also: IARC.1.14

[IARC.2.4] Dependency discipline (enforced by header hygiene, not a tool in v1):

  • [IARC.2.5] clock.h depends on nothing module-side; it is the leaf. Everyone else depends on clock.h for timestamps.

  • [IARC.2.6] wm.h, schema.h, dispatcher.h, recorder.h, telemetry.h depend on libds.h and clock.h. They do not depend on each other; the engine composes them.

  • [IARC.2.7] engine.h depends on every other module's internal header. It is the composition point.

  • [IARC.2.8] libds.h depends only on <stdint.h> and friends from the standard library. Public-API surface; no internal types ever leak through.


Per-module responsibilities [IARC.3]#

[IARC.3.1] Summary. Each module gets its own impl doc as implementation pulls on it.

engine [IARC.3.2]#

[IARC.3.2.1] Hosts the engine's Rete network and the consumption-loop state machine that drives it (per [IARC.1.11]). When pumped, drains what the integrator has asserted — directly through the assert API, or by event-trace replay; there is no engine-owned intake ([IARC.2.3]) — assigns seq, dispatches to recorder + wm + agenda in order, runs fired activations through the dispatcher, and returns. Breakpoint and step-state introspection is the integrator's, over the stream-event callback ([IARC.8.4]). Does not spawn threads, does not sleep, does not block (per [IARC.1.10]).

see also: IARC.1.10, IARC.1.11, IARC.2.3, IARC.8.4

[IARC.3.2.2] The runtime spec commitment to "single-writer" ([RARC.6]) is satisfied structurally: the pump function is the only writer, and the integrator runs it from one context at a time. The engine does not enforce this with locks; the integrator is responsible for not calling pump concurrently from multiple contexts on the same engine. Documented, not policed — keeps the library thread-free.

see also: RARC.6

[IARC.3.2.3] Multiple engines in one process are first-class: each engine is an independent Rete network, fully isolated from other engines. An async runtime can pump N engines from the same thread without interference.

[IARC.3.2.4] Public entry points (integrator-facing, exported in libds.h): engine create / destroy, load compiled rules, feed inbound messages, pump the loop, install adapter / storage / debug callbacks. No start / stop — the integrator drives pump from wherever they want.

[IARC.3.2.5] Subsystem init / teardown order invariant. Every subsystem init runs inside ds_engine_new, and every destroy inside ds_engine_free. A subsystem may borrow from another, so libds must init a subsystem after every subsystem it borrows from, and must destroy it before every one of them: teardown never invalidates a borrow a subsystem not yet destroyed still holds. That is the whole rule; teardown is not the reverse of init. The clock holds nothing to destroy.

ds_engine_new inits, in this order:

  1. the clock, ds_clock_init, which reads the CLOCK_MONOTONIC baseline;

  2. telemetry, ds_telemetry_init;

  3. the recorder, ds_recorder_init;

  4. the schema registry, ds_schema_registry_init;

  5. working memory, ds_wm_init, which borrows the engine; its facts borrow schemas;

  6. the dispatcher, ds_dispatcher_init;

  7. the rete engine, ds_rete_engine_create, which owns the matching network and the per-engine string-intern table;

  8. the cache, ds_cache_init;

  9. the series-state registry, ds_series_state_registry_init;

  10. the series-backend registry, ds_engine_series_registry_init, then filled with the built-in backends.

ds_engine_free destroys, in this order:

  1. the dispatcher;

  2. working memory, which frees its facts, before the schemas they borrow;

  3. the schema registry;

  4. the recorder;

  5. telemetry;

  6. the series-state registry, once each row's backend state is released through its backend's instance_free ([ISBK.1.2]), so before the series-backend registry that holds those backends;

  7. the cache;

  8. the series-backend registry;

  9. the rete engine, last, because every other subsystem may reference its intern table.

A subsystem added later is inited after, and destroyed before, every subsystem it borrows from. When an init fails, ds_engine_new destroys the subsystems already inited before it returns.

ratified — checks: alloy×8 — see also: ISBK.1.2

wm [IARC.3.3]#

[IARC.3.3.1] Working memory. Owns:

  • [IARC.3.3.2] Fact-identity hashing (for no-op-reassertion suppression, [LFAC.2]).

see also: LFAC.2

  • [IARC.3.3.3] TTL bookkeeping — every ttl fact carries a deadline; the TTL sweep ([IRET.19.3]) retracts expired facts and emits their stream events, once per pump, before the pump's firing loop ([IRET.19.4]).

see also: IRET.19.3, IRET.19.4

  • [IARC.3.3.4] Logical-fact truth maintenance and justifier coalescence per [LLOG].

  • [IARC.3.3.5] Translation between DS-typed values and the Rete network's internal slot-value encodings.

agenda [IARC.3.4]#

[IARC.3.4.1] The conflict-resolution strategy enforcing the total firing order committed to at [RARC.5.4]: the terminal ordinal (source order), then activation-creation order within one rule. Also exposes agenda introspection (unfired activation list) for the debugger.

see also: RARC.5.4

dispatcher [IARC.3.5]#

[IARC.3.5.1] Executes the RHS of a fired rule. Dispatches the action verbs (log, call, emit, publish, cache_*) to the correct downstream surface — a registered integrator callback, inline wm mutations, recorder entries. Dispatch is synchronous into integrator code; there is no outbound queue ([IARC.2.3]). Also handles the refraction bookkeeping the agenda needs to pick the next activation.

see also: IARC.2.3

[IARC.3.5.2] In addition to per-verb routing, the dispatcher owns the typed integrator-callback table for the action verbs that need one — call, cache / cache_delete. Each verb's handler decodes the rule's RHS args, invokes the matching typed callback if registered, surfaces errors via the engine pending slot. NULL callback is a silent drop for non-essential verbs (log) and an explicit error code for essential ones (storage when storage-required). See [IARC.1.14] for the discipline.

see also: IARC.1.14

[IARC.3.5.3] No "peer", "wire", "adapter", "storage", or "debug" modules. libds's surface is typed C callbacks plus structured event payloads, full stop. If two libds instances or processes need to talk to each other (cross-tier publish, remote storage, external debugger), the integrator on each side defines and implements that protocol. libds emits typed events; integrators encode bytes if they want bytes.

recorder [IARC.3.6]#

[IARC.3.6.1] The recorder (recorder.h) is libds's stream-event dispatch: one emit helper per event kind assigns the event its seq, stamps it with the engine clock and hands it to the integrator's stream callback, or drops it when none is registered. Every observable event passes through it before anything downstream sees it ([RARC.5.8.1]). It writes no trace and keeps no event after delivering it: a recording is the integrator's.

see also: RARC.5.8.1

clock [IARC.3.11]#

[IARC.3.11.1] Sole reader of wall time per RARC.5.5. Mockable interface — in live mode clock_gettime(CLOCK_MONOTONIC) and clock_gettime(CLOCK_REALTIME), read together; in replay / test mode, the harness or recording drives it. No other module reads time(NULL) or equivalent; this is an architectural invariant, and reviews enforce it. The one exception is the pump-WCET measurement of a real-time tier, which reads elapsed host time directly. No rule reads that value; it decides only the halt of [RTCT.7.3]. On a microcontroller build the clock source reads the board's shim ([IARC.3.11.2]).

see also: IARC.3.11.2, RARC.5.5, RTCT.7.3

[IARC.3.11.2] On a microcontroller build the board supplies the live clocks. ds_platform_now_ns is required and is the monotonic source. ds_platform_wall_ns is optional: a board may define it, and it reports whether the wall clock has a value and, when it does, UTC nanoseconds since the Unix epoch. The integrator implements it over whatever the board learns the time from — an RTC, a network time source, an upstream message — and has it report no value until then. A board that does not define it, or before it reports a value, has a live wall clock with no value ([LTIM.2.8.3]).

The shim is the only way to give a live wall clock its value. The mock setter is not ([NLFC.5.3]).

Deferred: not binding in this edition.

see also: LTIM.2.8.3, NLFC.5.3

telemetry [IARC.3.12]#

[IARC.3.12.1] Per-engine dispatch table for metric and operational- log integrator callbacks per [IARC.1.14]. Holds two {cb, user} pairs; emit helpers route to the registered callback or silently drop if NULL. No state owned beyond the function pointers; teardown is a zeroing.

see also: IARC.1.14

Public headers (runtime/include/) [IARC.3.13]#

[IARC.3.13.1] One header: libds.h. Everything an integrator sees lives in that one file — engine lifecycle, opaque handles, slot-value tagged union, schema- registry surface, fact assert / retract, pump, the typed event payloads (ds_log_event_t, ds_metric_t, etc.), the typed callback signatures, and the per-area set_*_callback setters. Internal module headers (engine.h, wm.h, etc.) are not reachable via the public -I path.

schema [IARC.3.14]#

[IARC.3.14.1] Owns ds_schema_t and the per-engine schema registry. Validates and registers fact-type declarations; resolves slot names, types, and unit dimensions; is the authority wm and dispatcher consult to type-check asserted facts and decoded RHS args. Engine-lifetime once registered; freed on registry destroy ([IARC.6.2]).

see also: IARC.6.2

json [IARC.3.15]#

[IARC.3.15.1] Owns ds_json_t and ds_json_free. Parses, builds, queries, and serialises the structured JSON payloads carried by emit / publish / cache_* and Json call arguments. Trees are caller-owned and released via ds_json_free ([IARC.6.2]).


see also: IARC.6.2

Subsystem → module mapping [IARC.4]#

[IARC.4.1] libds's runtime surface, mapped to its modules.

Runtime concern

libds module

Consumption loop

engine

Working memory

wm

Schema registry

schema

Rete network

rete

Agenda + conflict resolver

agenda

Clock source

clock

Recorder (stream events)

recorder

Dispatcher (action-verb routing)

dispatcher

Telemetry (metric + log callbacks)

telemetry

Cross-process / cross-machine I/O

integrator territory — not a libds module

[IARC.4.2] Additional modules libds introduces beyond the runtime-spec subsystem list — justified because the runtime spec is topology-agnostic and these are concrete integration surfaces:

libds module

Why it exists

dispatcher

Action-verb routing — registers each verb as a native Rete builtin ([IRET.13]), holds the integrator-callback table for verbs that need one. No spec correspondence; it's the glue between the Rete network and the runtime spec's "dispatcher" concept.

telemetry

Per-engine metric + log callback dispatch, a callback-based contract per [IARC.1.14].

schema

Per-engine schema registry. C-specific; not a separate runtime-spec subsystem.

libds.h

Public API surface; no spec correspondence.


see also: IARC.1.14, IRET.13

Compiler / runtime split [IARC.5]#

[IARC.5.1] libds (this tree) is engine-only C code. The DS compiler is a separate program, written in Mercury ([IARC.1.6]), under the top-level compiler/ tree (see [IARC.9.2]). It runs as its own process and produces the .dsc artefact the engine loads ([RARC.2.5.1]). Neither tree links the other.

see also: IARC.1.6, IARC.9.2, RARC.2.5.1

[IARC.5.2] Input: compiled .dsc bundles. libds loads the bundles the DS compiler produces ([RDSC.1]). Test fixtures and example programs are compiled to .dsc ahead of time and land under the author reference's example corpus as .ds source plus their compiled .dsc.

see also: RDSC.1

[IARC.5.3] The hand-off: the compiler, dsc, turns .ds source into a .dsc artefact, and libds loads the artefact at startup. libds contains no compiler.

[IARC.5.4] Artefacts the compiler produces, consumed by libds at load time:

  • [IARC.5.5] The .dsc bundle — compiled schema, rule, and the Rete network (AlphaNode / BetaNode / TerminalNode), which is the program ([RLOW]).

  • [IARC.5.6] Sidecar metadata file(s): DS-level rule / schema / binding names and source locations. Used by the debugger and the recorder to emit DS-level names rather than internal node labels.

  • [IARC.5.7] Conformance-suite inputs.

[IARC.5.8] libds never invokes the compiler at engine init. Precompilation is an author / CI step. The artefacts are the unit of deployment.


Data boundaries [IARC.6]#

[IARC.6.1] The public surface hands an integrator a fixed set of handles and never their layout. The handles are ds_engine_t, ds_fact_t, ds_schema_t and ds_json_t, and each is a pointer to a structure the holder cannot see inside ([IDAT.1.2]).

That is where the data boundary is drawn: at the type, not at the function. Because a caller can hold nothing but the pointer, the owning module stays free to change what the structure contains without breaking anyone who compiled against an earlier header, and every read has to route through that module's exported functions ([IARC.6.3]). The cost is an accessor for each readable field; the return is that layout is never part of the contract.

Every one of these belongs to exactly one module, which is also what fixes its lifetime ([IARC.6.2]).

The stream event is not a handle. ds_stream_ev_t is a callback payload whose layout the public header states, and the stream callback reads its members in place, for the length of the call ([NCBK.2.2], [IDAT.1.2]).

see also: IARC.6.2, IARC.6.3, IDAT.1.2, NCBK.2.2

[IARC.6.2] Each handle of [IARC.6.1], and the stream event, is owned by exactly one module:

Type

Owning module

Lifetime

ds_engine_t

engine

Integrator creates / destroys. One handle = one Rete network; multiple coexist independently.

ds_fact_t

wm

Lives in working memory; retracted on TTL / truth-maint.

ds_schema_t

schema

Engine-lifetime once registered; freed on registry destroy.

ds_stream_ev_t

recorder

Caller-stack value during the stream callback only.

ds_json_t

json

Caller-owned tree; released via ds_json_free.

see also: IARC.6.1

[IARC.6.3] Consumers receive opaque pointers; they do not peek through. Mutation is only through exported functions on the owning module. This keeps layout changes interior to the module.

[IARC.6.4] Concrete struct shapes, allocation discipline, and ownership transfer rules are [IDAT]'s.


Build artefacts [IARC.7]#

[IARC.7.1] libds builds produce:

Artefact

Path

Purpose

libds.a

runtime/src/libds/libds.a

Static library; the integrator links this.

[IARC.7.1.1] libds.a is built with -fPIC. Required so the archive can link into Python's pyds C extension (a shared object). Standalone test binaries link the same archive without trouble — PIC is a superset of non-PIC. libds.build ([IARC.10.1.7]) sets the flag unconditionally on every compile of the archive's objects; do not remove it without checking that the pyds extension still links.

see also: IARC.10.1.7

[IARC.7.2] libds links against:

  • [IARC.7.4] libprotobuf-c — the DSC artefact loader ([RDSC.12]) decodes protobuf atom bodies. Scope is artefact load only per [IARC.1.15]; no other libds module may use it. Atom bodies ([RDSC.4.5]) are stored uncompressed, so libds carries no decompressor and no -lz dependency — libprotobuf-c is the sole non-vendored load-path lib.

see also: IARC.1.15, RDSC.12, RDSC.4.5

  • [IARC.7.15] RE2 and Abseil, in a build that carries RE2. Their objects are folded into libds.a at pinned versions ([IARC.1.16]), so an integrator links nothing further for them and matches no versions. A build without RE2 ([LNRE.4.1]) carries neither.

see also: IARC.1.16, LNRE.4.1

  • [IARC.7.6] Standard C library and libm. The platform libraries a row links are that row's, and its tarball names them ([NGST.3.1]). A thread library among them, such as -lpthread, is a transitive libc/toolchain need, not a thread dependency: libds makes no pthread_* calls and starts no threads, consistent with [IARC.1.10] — link-time presence ≠ call-time use.

see also: IARC.1.10, NGST.3.1

[IARC.7.7] libds does not link against:

  • [IARC.7.8] cmocka — that is test-binary-only, not library.

  • [IARC.7.9] No wire / transport / RPC library. If an integrator wants to bridge libds across a process boundary, they pick and link their own encoder (msgpack, protobuf, JSON, anything) on their side per [IARC.1.14]; libds exposes typed C structs and lets the integrator decide. The protobuf-c dependency declared at [IARC.7.4] is artefact-load substrate ([IARC.1.15]) and does not reverse this.


see also: IARC.1.14, IARC.1.15, IARC.7.4

[IARC.7.10] CORE-MATH is vendored. libds compiles the correctly-rounded functions [LEXP.3.9.2] requires from CORE-MATH's binary64 sources at one pinned upstream commit, through the same pinned-fetch path as RE2, with the files unmodified. They are compiled with libds's flags (-O2 -ffp-contract=off, and -std=gnu11 for the 128-bit integer types) on a toolchain whose FLT_EVAL_METHOD is 0.

A release row whose compiler has no 128-bit integer type must compile the functions that compute in one from a portable layer instead: copies of those files at the same upstream commit, in which the 128-bit integer is a class of two 64-bit words, compiled as C++ with no C++ runtime. The layer is vendored at a pin of its own, and every change it makes to an upstream file is marked in that file. The layer must compute what the upstream file computes, bit for bit, on every input. A release row whose compiler has the type must not use the layer.

The pin, the layer's pin and the flags are recorded together: a change to any of them changes the functions, and a release row built with it is admitted again before it ships ([NDET.1.4], [NDET.1.4.1]).

see also: LEXP.3.9.2, NDET.1.4, NDET.1.4.1

[IARC.7.11] Where there is no double FPU, libds carries its own double arithmetic. On the RP2350, RP2040 and nRF52833 every double operation in libds and in CORE-MATH compiles to a helper call that a static archive would leave for the integrator's link to resolve. libds must instead link its own:

  • the double helpers LLVM compiler-rt's builtins select for that target, at one pinned release, compiled unmodified;

  • the libm functions CORE-MATH calls (fma, sqrt, roundeven, floor, ceil, round, trunc, fmin, fmax), from a pinned source admitted on that target ([NDET.1.4]).

The build renames these symbols, and the matching references in libds's and CORE-MATH's objects, to names private to libds; only link names change, never source. Neither the integrator's runtime nor an SDK that intercepts double helpers can then reach libds's arithmetic, and the integrator's own double code is untouched. Targets with a hardware double FPU need none of this.

Deferred: not binding in this edition.

see also: NDET.1.4

[IARC.7.14] libds carries its own fma on every row. The fused multiply-add [LEXP.3.2.2] requires must be one correctly rounded implementation compiled into libds: musl's fma, from one pinned release, compiled unmodified with the flags its pin records and renamed, with every reference to it in libds's and CORE-MATH's objects, to a name private to libds. A fused multiply-add CORE-MATH's functions compute ([IARC.7.10]) must be either that function or, on a row whose baseline ISA has one, the fused multiply-add instruction. libds's objects must not reference the C library's fma. This holds on every release row, with a hardware double FPU or without one.

The C library's fma is the integrator's, and not every one rounds once: on a row without a hardware fused multiply-add instruction in its baseline ISA, calling it would make a Float result depend on the libc the integrator links. The instruction and the private function compute the one value IEEE 754 defines for the operation, so which of them CORE-MATH executes moves no result. The Mercury runtime's math.fma must call the same compiled function, so both runtimes compute one value ([LDET.3.3a.8]). A change to the pin or the flags admits each release row again before it ships ([NDET.1.4]).

ratified — see also: IARC.7.10, LDET.3.3a.8, LEXP.3.2.2, NDET.1.4

[IARC.7.12] The undefined symbols of a shipped libds.a are a closed set. Each release row carries an allowlist of the symbols its libds.a may leave undefined, and the build must fail on any other. A denylist cannot stand in for it: a double helper missed by name (__adddf3, __floatundidf, __floatuntidf, __fixdfdi) would resolve from the integrator's runtime and put unadmitted arithmetic under [IARC.7.11]'s guarantee.

Deferred: not binding in this edition.

see also: IARC.7.11

[IARC.7.13] Float text is vendored, not written. libds converts between Float and decimal text ([LDET.3.2.8]) with published, proven code and none of its own: Dragonbox's to_chars with its compact cache renders the shortest text, and fast_float parses text. Both are vendored unmodified, at pinned releases, with every file's digest recorded beside them. A fixed precision ([LGRA.2.9.6.10]) is rounded from the binary value by exact integer arithmetic, with no table and no allocation. The compiler and the second runtime in this repository call the same vendored code, so a value computed at compile time and at run time has one definition ([LDET.3.3a.8]).

see also: LDET.3.2.8, LGRA.2.9.6.10, LDET.3.3a.8

Module-addition checklist [IARC.10]#

[IARC.10.1] What to do when adding a new module to libds (i.e. a new .c/.h pair under runtime/src/libds/). Captured so contributors don't have to reverse-engineer the pattern from four examples.

  1. [IARC.10.1.2] Create runtime/src/libds/<module>.h with the header guard LIBDS2_INTERNAL_<MODULE>_H. Internal headers include libds.h for ds_result_t / ds_status_t and whatever sibling module headers they borrow from.

  1. [IARC.10.1.3] Declare the module's state struct (ds_<module>_state_t) if it has per-engine state, plus init / destroy prototypes taking a struct ds_engine * parent pointer.

  1. [IARC.10.1.4] Every function in the new module returns ds_result_t per [IARC.1.12]. No int returns.

see also: IARC.1.12

  1. [IARC.10.1.5] Follow the single-ownership discipline per [IARC.1.13] — ds_<type>_new / _free pairs, OOM surfaces as DS_ERR_OOM.

see also: IARC.1.13

  1. [IARC.10.1.6] Create runtime/src/libds/<module>.c.

  1. [IARC.10.1.7] Declare the .c file in libds.build, the one source of libds's build. A file directly under runtime/src/libds/, or under its rete/ or series/, is compiled by that directory's glob; a file under dsc/ needs a row in the Obj table, and a top-level file whose include flags differ from the default a row in the IFlags table. runtime/src/libds/Makefile is generated from libds.build and is not edited.

  1. [IARC.10.1.8] If the module has per-engine state: add the struct member to struct ds_engine in engine.h at the correct position for init / teardown order ([IARC.3.2.5]); add init in ds_engine_new with correct error-path cleanup; add destroy in ds_engine_free before every subsystem the module borrows from.

see also: IARC.3.2.5

  1. [IARC.10.1.9] If the module exposes public surface: add prototypes to runtime/include/libds.h (or a new runtime/include/libds/<area>.h per [IARC.1.4] if the surface justifies its own header). Internal module headers stay private.

see also: IARC.1.4

  1. [IARC.10.1.10] Add a white-box test at runtime/tests/libds/impl/test_<module>_basic.c per [ITST.5], and register it per [ITST.6.2].

see also: ITST.5, ITST.6.2

  1. [IARC.10.1.11] Run the libds suites on a build host per [ITST.7.1].

see also: ITST.7.1

  1. [IARC.10.1.12] Commit the module + its test together with a message that cites any relevant IARC / IDAT / IERR / ITST IDs the implementation satisfies.

[IARC.10.2] Common gotchas:

  • [IARC.10.2.1] Forgetting to destroy the module in the engine error path of a later subsystem's init failure. Result: leak at ds_engine_new returns an error. Symptom: valgrind complains.

  • [IARC.10.2.2] Adding a forward-declaration in another module's header instead of including the new module's header. Both are valid C, but prefer the include unless a circular dependency forces the forward decl — consistency eases grep-ability.

  • [IARC.10.2.3] Using int return instead of ds_result_t for a "can't fail" accessor. Return the result anyway per [IARC.1.12]; future-proofs against later additions that might fail.


see also: IARC.1.12

Design commitments [IARC.8]#

[IARC.8.1] Error-propagation convention. Every libds function that can fail returns ds_result_t — public API, internal calls, static helpers, all of them ([IARC.1.12]). The status codes are [IERR.2], detail-string stability [IERR.4], and the result's shape [IERR.1.3].

see also: IARC.1.12, IERR.1.3, IERR.2, IERR.4

[IARC.8.2] Memory discipline. Per-object allocation with matching free; no arena, reference counting only where [IARC.1.13] names it, no longjmp-based error recovery. OOM surfaces through ds_result_t. See [IARC.1.13]. Specific struct layouts and ownership-transfer rules per API are [IDAT]'s.

see also: IARC.1.13

[IARC.8.3] Thread lifecycle ownership. libds is async-first and ships zero threading primitives; the integrator drives ds_engine_pump() from their own scheduler. See the load-bearing design invariant at [IARC.1.10].

see also: IARC.1.10

[IARC.8.4] Debug / introspection. Integrators subscribe to the existing stream-event callback for trace + breakpoint-style introspection, and any debug-protocol bridge (integrator's debugger talks to integrator's harness that talks to libds in-process) is the integrator's to build. See [IARC.2.3].

see also: IARC.2.3

[IARC.8.6] No wire / protocol surface. libds has no protobuf wire codec, no peer abstraction and no per-role peer specializations (adapter / storage / debug / sibling tier). Its interaction with anything outside its own process is entirely via typed C callbacks the integrator registers. If integrators want bytes, they do the encoding themselves on whatever wire fits their stack. See [IARC.1.14] and [IARC.2.3].


see also: IARC.1.14, IARC.2.3

Decisions and deferrals [IARC.9]#

[IARC.9.1] Module decomposition. The shipped layout is a nine-module shape: engine, wm, schema, agenda, dispatcher, recorder, telemetry, clock, json — plus the public libds.h header. Of these, engine / wm / schema / agenda / recorder / json each own a public opaque type ([IARC.6.2]); dispatcher / telemetry / clock own none.

see also: IARC.6.2

[IARC.9.2] Compiler tree location. The compiler lives under a top-level compiler/ tree, peer to runtime/, not under impl/src/: the compiler and runtime are independently shippable with different build stacks and release cadences. See [IARC.5].

see also: IARC.5

[IARC.9.3] Public header shape. One header runtime/include/libds.h carries the entire public surface ([IARC.3.13]). Internal headers stay alongside their .c files under runtime/src/libds/, except the two that ship under include/internal/ per [IARC.1.4].

see also: IARC.1.4, IARC.3.13

[IARC.9.4] Confirm the [IARC.8] picks individually before each downstream impl doc commits to them.

see also: IARC.8

Engine clone — implementation [IARC.11]#

Implements the ds_engine_clone contract ([NLFC.8]); the equivalence check is [LDET.2.2b].

see also: LDET.2.2b, NLFC.8

[IARC.11.1] Share-immutable / deep-copy-mutable. The immutable-per-session structures — the Rete network topology (AlphaNode/BetaNode/TerminalNode nodes, tests, salience), the schema registry, the loaded DSC — MAY be shared read-only behind a refcount (cheaper — they are the large parts) or copied (simplest ownership); either conforms, but a shared owner must refcount so the two engines free in any order. The mutable state must be deep-copied: the fact set; the Rete memories (alpha hash-sets, beta tokens); the TMS justifier table; series backings; the TTL FIFO/heap; the agenda + refraction sets; the clock value; the cache map ([LSTO.4.7], mutable engine state); the string intern table (deep-copied, not shared: it interns String-typed slot values and grows at runtime, so sharing it is shared-mutable state that races the parallel-clone use and, even serial, leaks a discarded clone's strings back into the source). The cache copies verbatim — its values are opaque (JSON-text keyed by string), so it needs no fact-pointer remap. The deep-copy is a graph clone with fact-pointer remap — build an old_fact* → new_fact* map while copying facts, then repoint every fact reference (beta tokens, alpha/beta memories, FACT_REF slots — the fact data model ([IDAT])). The intern table is re-created — content re-interned into the clone's own fresh table — and interned-string references remap via the resulting old→new string map.

see also: LSTO.4.7

[IARC.11.2] All monotonic counters and randomised state are preserved exactly. fact_id, seq, activation timetags, and every internal monotonic counter continue from the source's current values — required for both synthetic-id determinism and byte-identical divergence from the clone point ([IARC.11.3] / [LDET.2.2b]). Series backings are copied verbatim — Welford (n, mean, M2), ring/deque contents, and the reservoir xorshift64 PRNG state — so series are exact, not cold-started (the [LDET.2.2a] warm-up bias is avoided). The TMS keys on fact_id (a value), so it survives the copy directly.

see also: IARC.11.3, LDET.2.2a, LDET.2.2b

[IARC.11.3] Counters continue independently; byte-identical divergence. The clone copies all monotonic counter state — fact_id, seq, activation timetags, gensym, and cycle generation ([IARC.11.2]) — and from the clone point each engine continues its own copy. Two engines driven with identical input from that point produce byte-identical streams ([LDET.2.2b]), whether run in parallel or serial — the property the equivalence check pins and the warm-standby / SMR use case ([NLFC.8]) relies on. The primitive imposes no ordering, single-active, or frozen-source discipline: parallel clones on different cores (same or different inputs) are a first-class use. One integrator pattern — serial speculate/commit/discard, where the source is held unpumped so a committed clone's post-clone events splice onto the source's recorded prefix with gap-free seq and a discarded clone's events stay off-stream — is a non-normative integrator how-to ([NLFC.8.3]): a discipline the integrator chooses, not a property of ds_engine_clone.

see also: IARC.11.2, LDET.2.2b, NLFC.8, NLFC.8.3

Cache seed — implementation [IARC.12]#

[IARC.12.1] A direct cache-store upsert, not a dispatch verb. ds_engine_cache_seed(engine, key, value, ttl_ns) writes key → value straight into the engine-owned cache store ([LSTO.4.7.1]). Unlike a rule cache write it must not route through the dispatcher ([IDSP.7]): it emits no ACTION_CACHE_SET stream event and invokes no write-through set callback. It is arrange / restore — seeding from a durable snapshot or a test's initial: block, not a rule action — so there is no cache write to record and no persistence loop to close ([RARC.5.7.10]). A recording carries the seed itself, in its prelude ([RFCS.26.1]).

see also: IDSP.7, LSTO.4.7.1, RARC.5.7.10, RFCS.26.1

[IARC.12.2] Canonical serialisation for byte-identity. value is a parsed tree (const ds_json_t *); the engine must serialise it with the same canonical serialiser the rule cache-write path uses (ds_json_serialize) before storing. A seeded value and a rule-written value with the same logical JSON therefore store byte-identically, so a later cached(key) read and the recorded-write replay path ([RARC.5.7.10]) cannot tell the two apart. The caller retains ownership of the tree.

see also: RARC.5.7.10

[IARC.12.3] Setup-phase only. ds_engine_cache_seed accepts a seed in the window [NLFC.9.1] states, before the engine's first stream event, and refuses one after it with DS_ERR_STATE ([NLFC.9.2]). The window binds the host's seed only: the artefact's initial block places its cache items at the first step ([LGRA.24.3]), the step that emits that event, and the window does not refuse them. Seeding adds no new error codes.

see also: LGRA.24.3, NLFC.9.1, NLFC.9.2

[IARC.12.4] Upsert, cap-enforced. An existing key is overwritten; ttl_ns = 0 is no expiry; a non-zero one is a lifetime that counts from the engine's first sample ([NLFC.9.4]), after which the entry expires as a cache … ttl: entry does. The store must enforce the cache bounds ([LSTO.4.7.5], set by ds_engine_set_cache_cap, [NSTG.2.6.1]) before it mutates; a breach returns DS_ERR_CONTRACT_BREACH and leaves the cache unchanged.

see also: LSTO.4.7.5, NLFC.9.4, NSTG.2.6.1

[IARC.12.5] Two consumers. An integrator restoring the cache from write-through persistence on startup ([NSTG.9] / [LSTO.4.5.2]), and the .dstest interpreter applying an initial: cache "k": v arrange ([RTIM.14.4] / [LTSL.5.2] / [RLOW.17.1]). The interpreter parses the seed's JSON text to a tree once, at setup, then calls the primitive.

see also: LSTO.4.5.2, LTSL.5.2, NSTG.9, RLOW.17.1, RTIM.14.4