# libds data model

The data structures of libds: the struct layouts,
enums, ownership rules, and inter-module data-flow
shapes that [IARC] references abstractly.

It takes these decisions of [IARC] as fixed:

- `ds_result_t` at every call site ([IARC.1.12]).
- Per-object `malloc` with single ownership
  ([IARC.1.13]).
- One `ds_engine_t` = one independent engine
  ([IARC.1.11]).
- Thread-free / async-first ([IARC.1.10]) — no
  atomics, no locks, no thread-local state in
  struct layouts.
- Opaque handles ([IARC.1.8]).

## What this is not

- Not a wire-format spec. libds has no wire format —
  see [IARC.2.3].
  Integrators that bridge libds across processes pick
  their own encoding.
- Not the Rete-network internals reference. The native
  matching network (alpha / beta / terminal nodes,
  tokens) is specified in [IRET]; this
  doc covers the cross-module data structures, not the
  network internals.
- Not an action-dispatch spec. Dispatcher behaviour
  is its own doc, [IDSP].
- Not an error-code taxonomy. `ds_result_t`'s shape
  is here; the full enum of `ds_status_t` values
  and detail-string stability rules are in
  [IERR].

---

(IDAT-1)=
## Data-model commitments [IDAT.1]

(IDAT-1-1)=
[IDAT.1.1] Restated so this doc reads standalone.

(IDAT-1-2)=
- [IDAT.1.2] **Opaque public types.** `ds_engine_t`,
  `ds_fact_t` and `ds_schema_t`
  are forward-declared structs in public headers; their
  layouts are private to the owning module (an internal
  header, **never `libds.h`**). Integrators receive and pass
  pointers; never dereference. `ds_json_t` is likewise
  opaque (accessor-mediated): its layout (`struct ds_json` /
  `ds_json_kv`) lives in the private `internal/json.h`, never
  `libds.h`, which exposes only the forward typedef, the
  `ds_json_kind_t` enum, and the accessor/builder API.
  `ds_stream_ev_t` is **not**
  opaque: it is a transparent, library-owned callback payload
  (an inline tagged union, [IDAT.7.1]) the stream callback reads
  field-by-field — borrowed lifetime, public layout.

*see also:* [IDAT.7.1](#IDAT-7-1)

(IDAT-1-3)=
- [IDAT.1.3] **`ds_result_t` reports every failure.** Every
  libds function that can fail returns it ([IARC.1.12]).

*see also:* [IARC.1.12](#IARC-1-12)

(IDAT-1-4)=
- [IDAT.1.4] **Single ownership.** Every heap allocation has
  exactly one owner at any time. Ownership transfer
  happens only at explicitly-named APIs
  (e.g. `ds_engine_take_fact(engine, fact)`). Default
  is "caller keeps ownership of its arguments; callee
  keeps ownership of its returns." Borrows (non-owning
  pointers) are documented per-function.

*checks:* `alloy×2`

(IDAT-1-5)=
- [IDAT.1.5] **No thread-aware types.** No `_Atomic`, no
  `pthread_mutex_t`, no `stdatomic.h` uses in struct
  layouts. libds's thread-free discipline
  ([IARC.1.10]) means struct access is always serial
  on the pump's call stack.

*see also:* [IARC.1.10](#IARC-1-10)

(IDAT-1-6)=
- [IDAT.1.6] **Per-engine state, no globals.** Every struct
  instance an engine owns belongs to exactly one
  `ds_engine_t`; a `ds_json_t` tree belongs to none
  ([IARC.1.11]). The integrator **must not** pass an engine a
  handle another engine handed out, a fact or a schema, nor a
  fact handle whose fact is not live ([IDAT.3.1]). Either is
  undefined behaviour: libds owes no check for it, and a caller
  **must not** take any status as reporting it. A schema is a handle like any other here,
  whether or not this engine holds a schema of the same name.

*see also:* [IARC.1.11](#IARC-1-11), [IDAT.3.1](#IDAT-3-1)

(IDAT-1-7)=
- [IDAT.1.7] **`const char *` strings are caller-owned unless
  stated otherwise.** libds does not copy string
  arguments defensively; callers keep ownership for
  the lifetime documented per-function. For strings
  libds returns in result structs, libds owns the
  pointer and guarantees stability for a documented
  lifetime (usually "until the next call on this
  engine").

---

(IDAT-2)=
## Core result types [IDAT.2]

(IDAT-2-1)=
### ds_status_t [IDAT.2.1]

(IDAT-2-1-1)=
[IDAT.2.1.1] A status is a plain integer: `0` for success, negative for an
error; no status is positive ([NERR.1.3]).

**The assignments live in [IERR.2], and only there.** This clause introduces
the type; it does not restate the dictionary. A second copy of a dictionary
cannot be kept honest, because its entire content is the numbers — drift does
not merely date such a copy, it makes it wrong about the one thing that is
normative ([STYL.2.13.3]), which is what [STYL.2.13.2] clause (b) rules out.

The type is declared in `runtime/include/libds.h`.

*see also:* [IERR.2](#IERR-2), [NERR.1.3](#NERR-1-3)

(IDAT-2-1-2)=
[IDAT.2.1.2] The table above is illustrative; the full canonical
list is the `ds_status_t` taxonomy, [IERR.2].

*see also:* [IERR.2](#IERR-2)

(IDAT-2-3)=
### ds_result_t [IDAT.2.3]

(IDAT-2-3-1)=
[IDAT.2.3.1] The universal return type: a status a caller branches on, paired
with an optional detail string for a human ([NERR.1.1]). Two words, and the
sizing follows from that -- 16 bytes on 64-bit
platforms; fits in registers under SysV x86-64
(RAX:RDX) and AAPCS64 alike.

`ds_result_t` is declared in `runtime/include/libds.h`.

*see also:* [NERR.1.1](#NERR-1-1)

(IDAT-2-3-2)=
[IDAT.2.3.2] Because the return type is a pair rather than a scalar
([IDAT.2.3.1]), every return site would otherwise spell out a compound
literal. Two macros keep that from drowning the code: one names the success
value, which carries no detail and is by far the most common thing any
function returns, and one pairs a status with a detail string.

They are a convenience of this implementation, not part of the contract. What
crosses the boundary is the value; how a call site spelled it is invisible to
the caller.

*see also:* [IDAT.2.3.1](#IDAT-2-3-1)

(IDAT-2-3-3)=
[IDAT.2.3.3] Callers check `.status` against `DS_OK` and either
propagate the result or extract `.detail` for
logging. When `.detail` may be `NULL` is
[IERR.3.3]'s.

*see also:* [IERR.3.3](#IERR-3-3)

(IDAT-3)=
## Opaque types index [IDAT.3]

(IDAT-3-1)=
[IDAT.3.1] The integrator-visible opaque types of [IDAT.1.2], and the stream
event, a borrowed callback payload: their owning module, their creation /
destruction APIs, and their lifetime class.

| Type              | Owning module | New / free                               | Lifetime class             |
|-------------------|---------------|------------------------------------------|----------------------------|
| `ds_engine_t`     | `engine`      | `ds_engine_new()` or `ds_engine_clone()` / `ds_engine_free()` | Engine (integrator-owned)  |
| `ds_fact_t`       | `wm`          | Library-owned; returned by `ds_engine_assert()`'s out-parameter and `ds_engine_fact_find()`, handed to a `ds_engine_for_each_fact()` visitor and in a stream event's payload, and read from a fact-reference slot with `ds_fact_get_slot()` | WM-bound; invalid once its fact leaves working memory ([NFCT.6.2]) |
| `ds_schema_t`     | `schema`      | Library-owned; registered at load, returned by `ds_engine_schema_find()`, `ds_engine_schema_at()` and `ds_fact_get_schema()`, and read as a slot's `schema_ref` with `ds_schema_get_slot()` | Engine |
| `ds_stream_ev_t`  | `recorder`    | Library-owned; borrowed by the stream callback | Valid during the stream callback only |
| `ds_json_t`       | `json`        | Integrator: `ds_json_parse()` / `ds_json_clone()` / `ds_json_new_*()` → `ds_json_free()`; also delivered as library-owned callback-payload borrows | **Dual** — see [IDAT.3.3] |

*see also:* [IDAT.1.2](#IDAT-1-2), [IDAT.3.3](#IDAT-3-3), [NFCT.6.2](#NFCT-6-2)

(IDAT-3-2)=
[IDAT.3.2] "Library-owned" means integrators receive non-owning
pointers through callbacks; they must not `free()`
them. "Integrator-owned" means the integrator calls
both new and free. The distinction is load-bearing;
violating it corrupts heap state.

(IDAT-3-3)=
### ds_json access and construction [IDAT.3.3]

(IDAT-3-3-1)=
[IDAT.3.3.1] `ds_json_t` is opaque ([IDAT.1.2]): integrators
inspect and build trees only through the accessor / builder API in
`libds.h`, never by field-walking the layout. The full signatures
live in the header (the header is the ABI); their normative
contract is [IDAT.3.3.2]–[IDAT.3.3.12]. libds's own modules — and
white-box impl tests ([ITST]) — may include `internal/json.h` and
field-walk directly; nothing reachable from `libds.h` alone may.

*see also:* [IDAT.1.2](#IDAT-1-2), [IDAT.3.3.2](#IDAT-3-3-2), [IDAT.3.3.12](#IDAT-3-3-12)

(IDAT-3-3-2)=
[IDAT.3.3.2] **Reads borrow.** Every accessor that yields a
`const ds_json_t *` or `const char *` — `ds_json_get_string`,
`ds_json_array_at` / `_object_get` / `_object_at`, and
`ds_json_get_path` — returns a pointer INTO the source tree,
valid for that tree's lifetime and never freed by the caller.

(IDAT-3-3-3)=
[IDAT.3.3.3] **Builders own.** Each `ds_json_new_*` yields a
freshly owned node in its out-param. The caller must dispose of it
exactly once, one of three ways: `ds_json_free` it; transfer it
into a parent via `ds_json_array_append` / `ds_json_object_set`;
or hand it to the engine as a `DS_SLOT_JSON` slot value — the
engine deep-clones it on assert ([NFCT.2.4]), so the caller still
owns and must free its built tree afterward.

*see also:* [NFCT.2.4](#NFCT-2-4)

(IDAT-3-3-4)=
[IDAT.3.3.4] **Transfer is single and success-only.** On a
successful `ds_json_array_append` / `ds_json_object_set` the
container takes ownership of the child: freeing the container
frees it, and freeing the child again is a double-free. On error
ownership does NOT move — the child is not consumed and the
container is left unchanged, so the caller must free the child.
This makes error cleanup deterministic. `ds_json_object_set`
copies its key, and when the key is already present it replaces
the value (freeing the old), so a built object holds one value per
key. A parsed one does too: `ds_json_parse` refuses text that
repeats a key in one object ([LGRA.5.8.7]).

*checks:* `alloy×4`  —  *see also:* [LGRA.5.8.7](#LGRA-5-8-7)

(IDAT-3-3-5)=
[IDAT.3.3.5] **Typed getters are strict.** A typed getter requires
the node to be exactly the requested kind; JSON's distinct `INT`
and `FLOAT` are never coerced. A kind mismatch returns
`DS_ERR_INVAL` with a detail naming the actual and requested kinds — a
caller programming error, recovered by checking `ds_json_get_kind`
first. A NULL node or out-param returns `DS_ERR_INVAL` with a detail
naming the argument.

(IDAT-3-3-6)=
[IDAT.3.3.6] **Miss semantics.** `ds_json_array_at` (index out of
range) and `ds_json_object_get` (key absent) return
`DS_ERR_NOT_FOUND` with `*out = NULL`: a miss is exceptional for a
direct lookup. This is deliberately distinct from `ds_json_get_path`,
whose path-miss is lenient — `DS_OK` with `*out = NULL`.

A read writes its out-parameters on success and on these misses, and
nowhere else. After any other error status the caller **must not** read
an out-parameter.

*ratified*

(IDAT-3-3-10)=
[IDAT.3.3.10] **Path syntax.** A path `ds_json_get_path` takes is a `json_path`,
as this clause's `ebnf` check gives it. `ds_json_get_path` **must** judge
the whole path before it reads the tree, and **must** return `DS_ERR_INVAL` for a
path the production does not admit, whatever the tree holds. So the empty path,
an empty key, a leading `.`, an index with a sign or white space, and `a[0]b` are
malformed on every tree.

A key step reads the object member whose key is the step's bytes. An index step
reads the array element at that decimal number, from zero. A step on a node of
another kind, a key the object does not hold, and an index past the array's end,
however large the number, are each a miss ([IDAT.3.3.6]), and the walk ends
there. A member whose key is empty, or holds `.` or `[`, has no path:
`ds_json_object_get` reads it.

*ratified*  —  *see also:* [IDAT.3.3.6](#IDAT-3-3-6)

(IDAT-3-3-11)=
[IDAT.3.3.11] **Object position order.** `ds_json_object_at` **must** give an
object's members in the order they entered it: text order for a parsed object,
and the order of first insertion for a built one. `ds_json_object_set` on a key
already present keeps that key's position, and `ds_json_clone` keeps every
position. This order is not `ds_json_serialize`'s, which sorts members by key.

*ratified*

(IDAT-3-3-7)=
[IDAT.3.3.7] **String model.** A string a JSON value holds contains no NUL
byte, because a `String` holds no U+0000 ([LSTR.1.1]), and libds refuses one
where it would enter ([LSTR.1.5]). `ds_json_new_string` must refuse `len`
bytes that hold a NUL with `DS_ERR_INVAL`, and `ds_json_object_set` must refuse
such a key the same way; the parser refuses a `\u0000` escape or a raw NUL as
malformed text. Built and returned strings are NUL-terminated, so
`ds_json_get_string`'s `*out_len` is the string's length in bytes, which
`strlen` also gives.

*see also:* [LSTR.1.1](#LSTR-1-1), [LSTR.1.5](#LSTR-1-5)

(IDAT-3-3-9)=
[IDAT.3.3.9] **Float model.** A float a JSON value holds is finite
([LGRA.5.8.10]). `ds_json_new_float` must refuse a `v` that is `±Inf` or a NaN
with `DS_ERR_JSON_NONFINITE` and leave `*out` `NULL`, and `ds_json_parse` must
refuse a number literal past the largest finite double with `DS_ERR_PARSE`, as
malformed text. So no tree an integrator parses or builds holds a non-finite
float, and none reaches the engine as a `DS_SLOT_JSON` slot value or a call's
response. `ds_json_serialize` **must** still refuse a tree holding one with
`DS_ERR_JSON_NONFINITE` ([LDET.3.2.7]), which libds's own writers rely on and
no `libds.h` caller meets.

*ratified*  —  *see also:* [LDET.3.2.7](#LDET-3-2-7), [LGRA.5.8.10](#LGRA-5-8-10)

(IDAT-3-3-12)=
[IDAT.3.3.12] **A tree across threads.** `ds_json_get_kind`, the typed getters,
`ds_json_array_len`, `ds_json_array_at`, `ds_json_object_len`,
`ds_json_object_get`, `ds_json_object_at` and `ds_json_get_path` **must not**
write to the tree or to any state another call shares. So several threads may
make these calls on one integrator-owned tree at once, provided no thread is
changing or freeing it. libds takes no lock on a tree: the integrator **must**
hold a tree exclusively across `ds_json_array_append`, `ds_json_object_set` and
`ds_json_free`. A tree the engine lends is the engine's, and the rules
for the call that lent it bind ([IDAT.3.3.8]).

*see also:* [IDAT.3.3.8](#IDAT-3-3-8)

(IDAT-3-3-8)=
[IDAT.3.3.8] **Dual ownership shape.** `ds_json_t` is the one type
that is both integrator-owned and library-owned depending on
provenance. A tree the integrator built (`ds_json_parse` /
`ds_json_new_*`) is integrator-owned and integrator-freed. A tree
delivered to a record / cache callback as a `const ds_json_t *`
payload is a library-owned borrow, valid only for the callback's
duration ([IDAT.10.3]). A tree read from a fact's `Json` slot
with `ds_fact_get_slot` is a library-owned borrow too, valid until
that fact is retracted ([NFCT.6.2]). The engine's deep-clone-on-assert
([NFCT.2.4]) is what keeps the two disjoint — a built tree handed
to the engine and the engine's stored copy are independent trees,
each freed by its own owner.

---

*see also:* [IDAT.10.3](#IDAT-10-3), [NFCT.2.4](#NFCT-2-4), [NFCT.6.2](#NFCT-6-2)

(IDAT-4)=
## Fact representation [IDAT.4]

(IDAT-4-1)=
[IDAT.4.1] `ds_fact_t` is the working-memory fact record: DS-level
metadata, a pointer to the paired Rete fact (`rete_fact`,
a `ds_rete_fact_t *`), and the fact's slot values
unpacked into a trailing flexible-array member at
allocation time.

`struct ds_fact` is declared in `runtime/src/libds/wm.h` — internal to the reference runtime, which is what this tree describes ([STYL.2.13.6]).

(IDAT-4-1-1)=
[IDAT.4.1.1] Allocation is a single zeroed `DS_CALLOC` ([IALC.2.1]) sized
`sizeof(ds_fact_t) + n_slots * sizeof(ds_slot_value_t)`.
One allocation per fact; good cache locality; slot
access is plain array indexing with no NULL check.

*see also:* [IALC.2.1](#IALC-2-1)

(IDAT-4-2)=
[IDAT.4.2] Facts are allocated on assertion (by
`ds_wm_fact_new`), freed on retraction. Retraction invalidates the wrapper: any
pointer held externally is dangling the moment the
retraction event crosses the recorder. Callbacks
that deliver `ds_fact_t *` document whether the
pointer is valid only during the callback or for
longer.

(IDAT-4-3)=
[IDAT.4.3] A fact's identity is its schema and its identity
key ([LFAC.1.7]); two facts are equal when all their slot
values are ([RARC.5.2.3]). `fact_id` is a per-engine counter, numbered as
[RFCS.6.9] states, used for ordering, tracing, and stream
correlation; it is not a persistent ID across
engine restarts.

*ratified*  —  *checks:* `alloy`  —  *see also:* [LFAC.1.7](#LFAC-1-7), [RARC.5.2.3](#RARC-5-2-3), [RFCS.6.9](#RFCS-6-9)

(IDAT-4-4)=
[IDAT.4.4] For `logical` schemas, no-op reassertion preserves
the existing `ds_fact_t` (same pointer, same
`fact_id`). A meaningful-change reassertion is a
retract + assert; the old wrapper is freed and a
new one is allocated. Integrator callbacks see this
as an assert event followed by a retract event: the
arriving assert comes before the withdrawal it causes
([RFCS.6.7]). A consumer pairs the retract with the
fact it removes by `fact_id`, never by identity, since
the replacement shares the identity and is already live
when the retract arrives.

*ratified*  —  *checks:* `alloy×4`  —  *see also:* [RFCS.6.7](#RFCS-6-7)

(IDAT-4-5)=
[IDAT.4.5] Slot unpacking happens once at fact creation, inside
the `wm` module's assertion path. The fact record plus
its slot array is allocated as a single block via the
flexible-array pattern ([IDAT.4.1.1]). Slot access is
plain array indexing: `f->slots[i]`. No NULL checks, no
deferred materialisation, no hidden allocations on read.
The `wm` module tracks facts in a hash table keyed by
the `rete_fact` pointer; the paired Rete fact's `id` is
the stable key the network uses for alpha-memory
membership, token references, and TMS dependencies
([IRET.4.4]).

*see also:* [IDAT.4.1.1](#IDAT-4-1-1), [IRET.4.4](#IRET-4-4)

(IDAT-4-6)=
### Slot values [IDAT.4.6]

(IDAT-4-6-1)=
[IDAT.4.6.1] Tagged union. Sized for the largest payload
(typically 16 bytes); total struct is 24 bytes
with the discriminator and padding.

`ds_slot_value_t` and `ds_slot_kind_t` are declared in `runtime/include/libds.h`.

*ratified*  —  *see also:* [IDAT.4.7](#IDAT-4-7)

(IDAT-4-6-2)=
[IDAT.4.6.2] **`ds_slot_kind_t` is the runtime tag, not the
schema-declared type.** The two are separate enums ([IDAT.5.3]), and
[NFCT.2.3]'s table pairs them. A `Time`, `Date` or `Duration` slot carries
`DS_SLOT_INT`. A `Json` slot carries `DS_SLOT_JSON`, whatever its tree holds:
a node inside the tree has a `ds_json_kind_t`, which is not a slot kind. A null
value, in a slot declared `T?` ([LNUL.3.1]), carries `DS_SLOT_NULL`, and a
`Json` value whose root is `null` is that null ([LNUL.3.4]).

*ratified*  —  *see also:* [IDAT.5.3](#IDAT-5-3), [LNUL.3.1](#LNUL-3-1), [LNUL.3.4](#LNUL-3-4), [NFCT.2.3](#NFCT-2-3)

(IDAT-4-7)=
[IDAT.4.7] `DS_SLOT_STRING` / `DS_SLOT_BYTES` values are interned
in the engine's per-engine string table ([IRET.1.4]) as
**counted** entries: reference-counted by the number of live
committed fact slots holding the value and freed when the last
holder retracts — a **reclaimable-refcount** lifetime, not an
engine lifetime. Structural strings (schema / slot / rule
names, compile-time literals) are **pinned** (engine-lifetime).

Every string entering working memory — whether from a compiled
fact, an integrator-provided slot value (`ds_engine_assert`), a
rule-RHS emit, or an adapter — is passed through the intern
boundary (`acquire` at commit), returning the canonical pointer
stored in `ds_slot_value_t.v.s`.

**Stored** equality is pointer comparison (Rete alpha / beta /
identity — [IDAT.4.4] still holds: equal stored strings share a
pointer). **Value** equality (eval `==`, no-op reassertion) is
by **content** ([LFAC.2]) — interning is a non-observable
implementation detail. Fact teardown **releases** its
`String`/`Bytes` slot references (`release` at retract); a
counted value frees when its last holder retracts, a pinned
value at engine destroy.

**Borrower rule.** Anything that
retains a fact's string past the fact's life must not dangle
against a now-reclaimable counted value:

- a **retains-past-life** borrower (a series / cache backend that
  samples a slot into its own state) **copies** the bytes;
- a **co-lifetime mirror** (the DS-layer `ds_fact_t` wrapper,
  whose lifetime tracks the fact) takes a **lock-step intern
  reference** — acquire when it copies the slot, release when the
  wrapper is freed.

Both keep the invariant *refcount = live fact-lifecycle holders*;
neither widens it to a non-fact holder, and copying in the
co-lifetime case would needlessly double every fact's string
storage.

---

*see also:* [IDAT.4.4](#IDAT-4-4), [IRET.1.4](#IRET-1-4), [LFAC.2](#LFAC-2)

(IDAT-5)=
## Schema representation [IDAT.5]

(IDAT-5-1)=
[IDAT.5.1] One `ds_schema_t` per declared type (`Hass`,
`Motion`, `Person`, …). Allocated at rule-load
time; freed at engine teardown.

`ds_schema_t` and `ds_schema_lifecycle_t` are declared in `runtime/include/libds.h`.

(IDAT-5-2)=
[IDAT.5.2] Schema registry is a `ds_engine_t`-owned array plus
a name-to-schema hash map. Lookup by type name is
O(1) amortised; by schema pointer is free
(already-resolved reference).

*ratified*

(IDAT-5-3)=
### Slot descriptor [IDAT.5.3]

One descriptor describes one slot: what it is called, what type it holds, and
whatever markers its declaration attached to it. A schema's descriptors sit in
an array in declaration order, and a slot's **index in that array is its
identity** -- the name map ([IDAT.5.1]) exists to get from a name to an index,
and every value tuple is positional against the same order ([NFCT.2.1]).

The type set is closed, and one member differs in kind from the rest: a slot
holding a reference to another schema has to say *which*, so the schema
reference is populated **exactly when** the type is the schema type. The
compiler writes no other shape, and a load does not judge it ([IDAT.5.5]).

Everything else is a per-slot marker carried through from the declaration.
Tolerance is the one with a subtlety of its own ([IDAT.5.4]).

`ds_slot_desc_t` and `ds_slot_type_t` are declared in `runtime/include/libds.h`.

*see also:* [IDAT.5.1](#IDAT-5-1), [IDAT.5.4](#IDAT-5-4), [IDAT.5.5](#IDAT-5-5), [NFCT.2.1](#NFCT-2-1)

(IDAT-5-3-1)=
[IDAT.5.3.1] **`ds_slot_type_t` is the statically-declared schema
type, not the runtime value tag.** [IDAT.4.6.2] states the runtime tag
(`ds_slot_kind_t`) and how the two pair.

*see also:* [IDAT.4.6.2](#IDAT-4-6-2)

(IDAT-5-4)=
[IDAT.5.4] `tolerance` being `double` regardless of slot
integer / float type keeps the struct POD-shaped
and simplifies comparison code paths. `has_tolerance`
distinguishes "`tolerance 0`" (explicit exact-
equality marker) from "no tolerance declared."

(IDAT-5-5)=
[IDAT.5.5] Test obligations: `spec/test_schema_registry_spec`
covers, black-box, the IDAT.5 surface an integrator reaches, every schema
loaded from a compiled artefact ([NFCT.1.1]): find returns the loaded
schema's borrow, the same on every lookup; a lookup miss returns DS_OK with
*out=NULL; schema_count counts the registered schemas, the declared ones and
the engine's built-in ones ([NDBG.2.2]), and is unaffected by find;
`ds_engine_schema_at` gives each index below the count and DS_ERR_NOT_FOUND
past it; per-engine registries are independent; a second
`ds_engine_load_dsc` → DS_ERR_STATE with the schemas, borrows and count
unchanged ([NFCT.1.1]), and a load after a failed one → DS_ERR_ENGINE_HALTED
([RDSC.9.8]); NULL engine
and NULL type_name rejected on every public entry per IDAT.10.5.

A schema's slot descriptors, its lifecycle and TTL, its `schema_ref` and
`tolerance` markers have no public entry that could refuse them: the compiler
refuses what is wrong in them, and the artefact that carries them is trusted
([RDSC.9.9]).

---

*ratified*  —  *see also:* [IDAT.10.5](#IDAT-10-5), [IDAT.5](#IDAT-5), [NDBG.2.2](#NDBG-2-2), [NFCT.1.1](#NFCT-1-1), [RDSC.9.8](#RDSC-9-8), [RDSC.9.9](#RDSC-9-9)

(IDAT-6)=
## Activations [IDAT.6]

(IDAT-6-2)=
### Activations [IDAT.6.2]

An activation is a rule together with the particular facts that matched it: a
firing that is owed but has not happened yet. It is internal to libds: no
public function takes or returns one ([IARC.6.1]).

The ownership split inside one is what matters. The activation holds a
**non-owning borrow** of each fact it matched, and of its rule, which a
registry that outlives every activation owns. An activation therefore cannot
outlive the facts it matched -- which is why retracting one of them destroys
the activation rather than leaving it holding a dangling reference
([IDAT.6.2.1]).

The agenda orders activations by their rule's ordinal, then their entry order,
the tie-break within a single rule when several partial matches have completed
([RARC.5.4.7], [LDET.5.5]). The fired flag is the refraction state
([IDAT.6.2.2]) and is no ordering key: an activation carrying it is suppressed,
not sorted ([LDET.5.3]).

*see also:* [IARC.6.1](#IARC-6-1), [IDAT.6.2.1](#IDAT-6-2-1), [IDAT.6.2.2](#IDAT-6-2-2), [LDET.5.3](#LDET-5-3), [LDET.5.5](#LDET-5-5), [RARC.5.4.7](#RARC-5-4-7)

(IDAT-6-2-1)=
[IDAT.6.2.1] Activations are allocated by the agenda module
when the Rete network completes a pattern match, and
freed when that match ends: a fact it matched is
retracted, or a test it passed no longer admits it.
Firing does not free one. A fired activation stays,
carrying the fired flag, until its match ends
([IDAT.6.2.2]), so an activation is not bounded by the
pump that made it.

*see also:* [IDAT.6.2.2](#IDAT-6-2-2)

(IDAT-6-2-2)=
[IDAT.6.2.2] The `fired` flag implements refraction per
[LDET.5.3]: once an activation fires, it stays on
the agenda with `fired = true` until the LHS
changes, preventing re-fire on the same binding
tuple.

---

*checks:* `idris×51`  —  *see also:* [LDET.5.3](#LDET-5-3)

(IDAT-7)=
## Stream events [IDAT.7]

(IDAT-7-1)=
[IDAT.7.1] Recorder-observed events. Every module hands its
events to the recorder through the emit helper for the
event's kind ([IARC.3.6.1]).

The event union and its `ds_stream_ev_kind_t` discriminant are declared in `runtime/include/libds.h`.

*ratified*  —  *see also:* [IARC.3.6.1](#IARC-3-6-1)

(IDAT-7-2)=
[IDAT.7.2] Tagged union: consumers switch on `kind` and access
the matching union member (`ev->p.fact_assert.fact`,
`ev->p.rule_fire_end.timetag`, …). Compiler-checked
access; no `void *` casts. Struct size is bounded by
the largest variant; every
event pays that size regardless of kind, but events
flow through the recorder and do not accumulate.

*ratified*

(IDAT-7-3)=
[IDAT.7.3] The per-kind payload shapes above are the in-memory shapes and
nothing more. [LFST.6] owns the semantic contract — what each event kind
means; this document commits only to the layout the recorder holds them in.

*see also:* [LFST.6](#LFST-6)

(IDAT-9)=
## Engine state [IDAT.9]

(IDAT-9-1)=
[IDAT.9.1] Top-level composition. Owned registries live
directly in `ds_engine_t`; sub-module state
pointers are inline.

`struct ds_engine` is declared in `runtime/src/libds/engine.h` — internal to the reference runtime ([STYL.2.13.6]).

*see also:* [IDAT.4.7](#IDAT-4-7)

(IDAT-9-2)=
[IDAT.9.2] No thread synchronization primitives in this
struct — `ds_engine_pump()` is the only writer
([IARC.1.10] / [IARC.3.2.2]).

---

*see also:* [IARC.1.10](#IARC-1-10), [IARC.3.2.2](#IARC-3-2-2)

(IDAT-10)=
## Ownership and lifetime conventions [IDAT.10]

(IDAT-10-1)=
[IDAT.10.1] **Argument ownership.** By default, arguments
passed by pointer are borrows — the callee reads
them, does not take ownership, does not retain the
pointer beyond the call. A few functions do take
ownership: `ds_json_array_append()` and `ds_json_object_set()`
adopt `child` on success and leave it with the caller
on error. **The name does not tell you** — every one of
these reads like a borrow — so the header comment is
the normative statement of ownership, and a function
that takes ownership of any argument MUST carry one.

(IDAT-10-2)=
[IDAT.10.2] **Return ownership.** A function returning a struct
by value transfers ownership (the caller owns the
returned struct). A pointer returned through
`ds_result_t.detail` or another out-parameter is, by
default, a borrow from libds state, with the lifetime its
declaration states.

An out-parameter through which libds transfers ownership
returns one of two things: a handle the caller owns and frees
as [IDAT.3.1]'s table states (an engine from `ds_engine_new()`
or `ds_engine_clone()`; a `ds_json_t` from `ds_json_parse()`,
`ds_json_clone()` or a `ds_json_new_*()`), or an owned raw
buffer the caller frees with `ds_free()` ([IALC.4.3]). As for
arguments ([IDAT.10.1]), the name does not tell a transfer from
a borrow, so the header comment is the normative statement, and
a function that transfers ownership through an out-parameter
**must** carry one.

*see also:* [IALC.4.3](#IALC-4-3), [IDAT.10.1](#IDAT-10-1), [IDAT.3.1](#IDAT-3-1)

(IDAT-10-3)=
[IDAT.10.3] **Callback-delivered pointers.** Integrator
callbacks that receive opaque pointers
(`ds_fact_t *`) are passed
borrows. They must not `free()` them, must not
retain them past the callback unless the callback's
documentation explicitly says the pointer remains
valid (e.g. "the fact remains valid until the
matching retract event").

(IDAT-10-5)=
[IDAT.10.5] **NULL handling.** Public API entry points check
for `NULL` arguments where documented and return
`DS_ERR_INVAL`. Internal functions may assume
non-NULL where that invariant is upheld by the
call graph (asserted in debug builds, not in
release).

---

*ratified*

(IDAT-11)=
## Structure commitments [IDAT.11]

(IDAT-11-2)=
[IDAT.11.2] **TTL bookkeeping structure.** libds keeps the structure the
program's capabilities call for: a per-schema FIFO queue in deadline order
without `dynamic_ttl` ([LDTL.3.1]), and a deadline min-heap with it
([LDTL.4.2]).

*see also:* [LDTL.3.1](#LDTL-3-1), [LDTL.4.2](#LDTL-4-2)

(IDAT-12)=
## Layout commitments [IDAT.12]

(IDAT-12-2)=
[IDAT.12.2] **Slot unpacking.** Eager unpacking into
a flexible-array-member at fact-allocation time. One
malloc per fact; slot access is array indexing with
no NULL checks, no deferred allocations. See
[IDAT.4.1] / [IDAT.4.5].

*see also:* [IDAT.4.1](#IDAT-4-1), [IDAT.4.5](#IDAT-4-5)

(IDAT-12-3)=
[IDAT.12.3] **String-interning convention.** A single
per-engine string table interns schema / slot / rule
names and `String`-typed slot values ([IRET.1.4]).
Every string entering working memory is funneled
through the intern function at the boundary.
Pointer-equality comparison and one canonical pointer per
distinct string. A structural name lives as long as the
engine; a slot value lives as long as the facts that hold it
([IDAT.4.7]).

*see also:* [IDAT.4.7](#IDAT-4-7), [IRET.1.4](#IRET-1-4)

(IDAT-12-4)=
[IDAT.12.4] **Stream-event payload shape.** Tagged
union inline in `ds_stream_ev_t` (not `void *`, not
FAM). One allocation per event, compiler-checked
access, best cache locality. Pays ~48 bytes per
event for the largest-variant size, acceptable at
v1 event rates. See [IDAT.7.1].

*see also:* [IDAT.7.1](#IDAT-7-1)

