# Facts: assert, retract, observe

How an integrator gets data into and out of libds's working memory: declaring
schemas, asserting facts, reading them back, observing what the engine emits,
and retracting. Companion to [NLFC] (engine
create / free / pump) and [NCBK] (the action-verb side).

## What this is not

- Not the language spec for facts. Author-side semantics live in
  [LFAC] — `logical` vs `ttl` lifecycles, no-op reassertion discipline, mixing
  categories in one rule.
- Not the schema-design guide. Designing schema shapes is a language-level
  concern; this doc covers the **registration mechanics** the integrator drives.

---

(NFCT-1)=
## Registering a schema [NFCT.1]

(NFCT-1-1)=
[NFCT.1.1] A schema reaches the engine from a compiled artefact, and in no
other way: `ds_engine_load_dsc` registers every schema (and rule) the `.ds`
source declared, with the schemas of the built-in module ([LIMP.12.2]). A fact
type an adapter supplies is declared in the program, as an `ambient` schema
where rules only read it ([LADP.2.1.1]). See [NGST.4].

**Registration is setup-phase only.** Every schema an engine holds must be
registered before the engine emits its first stream event, and the engine must
refuse a load after that with `DS_ERR_STATE`. A host
assert, a retract and a pump each emit one, so registration comes before the
first of them; loading an artefact and seeding the cache ([NLFC.9.1]) emit none.
The schema set is therefore fixed before anything on the stream can name a
schema, which is what lets an encoder announce all of it at the head of a
stream ([RFCS.5.1]).

A single `.dsc` load is everything assert
needs — the engine builds its own
matching working-memory and Rete state internally.

**An engine holds one artefact.** After a
successful `ds_engine_load_dsc`, the engine must refuse a second load, of the
same artefact or of another, with `DS_ERR_STATE`, and leave its state
unchanged. A recording's header names one rule set by its hash ([LFST.4.7]),
and a replay loads that one artefact ([RFCS.4.5]), so an engine holding two
would run a program no recording describes. A load that failed spent the engine
([RDSC.9.8]), so that engine takes no other load.

*ratified*  —  *see also:* [LADP.2.1.1](#LADP-2-1-1), [LFST.4.7](#LFST-4-7), [LIMP.12.2](#LIMP-12-2), [NGST.4](#NGST-4), [NLFC.9.1](#NLFC-9-1), [RDSC.9.8](#RDSC-9-8), [RFCS.4.5](#RFCS-4-5), [RFCS.5.1](#RFCS-5-1)

(NFCT-1-4)=
### Slot descriptors and markers [NFCT.1.4]

(NFCT-1-4-1)=
[NFCT.1.4.1] Each slot is a `ds_slot_desc_t`. Beyond `name` and `type`:

| Field | Meaning |
|---|---|
| `identity_role`       | `DS_IDENTITY_KEY` / `DS_IDENTITY_MUTABLE` / `DS_IDENTITY_ENGINE` — the slot's identity role on a `logical` schema: `KEY` slots form the identity tuple (assert upserts on it), `MUTABLE` slots are payload ([LFAC.1.7] / [NFCT.4.4]), and `ENGINE` is `ts`'s alone ([LFAC.9.1]). **Required on every slot of a `logical` schema** (require-all, [LGRA.5.10]); omitted on TTL / event schemas. No slot is privileged by position, and none by name except `ts`. |
| `schema_ref`          | Non-NULL **iff** `type == DS_SLOT_TYPE_SCHEMA`: the referenced schema (a borrow) for a fact-pointer slot. |
| `has_tolerance` / `tolerance` | Numeric reassertion tolerance — widens the dedup comparison on this slot ([NFCT.4.4]). |
| `sampled` / `retained` | Per-slot markers the artefact's `Slot` carries, read back for tooling. The compiler writes `sampled` false in this edition: the samples plane is deferred ([NSTG.5]). |
| `hydration_eligible`  | True when a `Hydration` atom in the artefact names the slot, false otherwise. The compiler writes no `Hydration` atom in this edition: hydration is deferred ([NCBK.9]). |
| `docstring`           | Optional human-readable string; may be NULL. |

*see also:* [LFAC.1.7](#LFAC-1-7), [LFAC.9.1](#LFAC-9-1), [LGRA.5.10](#LGRA-5-10), [NCBK.9](#NCBK-9), [NFCT.4.4](#NFCT-4-4), [NSTG.5](#NSTG-5)

(NFCT-1-4-5)=
[NFCT.1.4.5] **`ds_identity_role_t` mirrors `proto/slot.proto#IdentityRole`.**
It must carry the same members at the same values, `DS_IDENTITY_` for
`IDENTITY_ROLE_`, `UNSPECIFIED` at zero included ([STYL.5.9.7]), so the role an
integrator declares and the role an artefact carries ([RDSC.5.5.7]) are one
vocabulary.

*defined in:* [proto/slot.proto#IdentityRole](#proto-slot-proto-IdentityRole)  —  *see also:* [RDSC.5.5.7](#RDSC-5-5-7)

(NFCT-1-4-6)=
[NFCT.1.4.6] **A slot that names a unit converts a host's number.** A slot names
a unit when its declared type is a unit symbol ([LUNI.7.1]). Each call below
evaluates that slot's conversion ([RDSC.5.5.9]), taking `const ds_schema_t *`,
a `uint32_t` slot index, and a `const ds_slot_value_t *` and a
`ds_slot_value_t *` of the kind [NFCT.2.3] pairs with the slot's type:

- `ds_schema_slot_to_stored` writes the stored number ([LUNI.7.6]) of a number
  in the unit the slot names. It computes what `x::<unit>` computes ([LUNI.8.5]).
- `ds_schema_slot_from_stored` writes a stored number expressed in the unit the
  slot names. It computes what a kwarg of that unit receives ([LADP.8.5.3]).

Neither call changes the engine, records an event or asserts a fault fact, save
for an `EngineError` the conversion raises. The artefact has then lied
([RDSC.4a.9.3], [RDSC.4a.9.6]), and the call halts the engine and reports it as any
public call that raises one does ([NCBK.2.8], [NCBK.2.9]).
Neither is a `ds_engine_*` call, so [RARC.13.16] does not refuse one made from a
callback. After an EngineError each returns `DS_ERR_ENGINE_HALTED`, as the schema
accessors do ([NCBK.2.9]).

Each must return the status of the first of these that holds, and must write
`*out` only on `DS_OK`:

| Condition | Status |
|---|---|
| a `NULL` pointer | `DS_ERR_INVAL` |
| an EngineError has halted the engine | `DS_ERR_ENGINE_HALTED` |
| the index names no slot of the schema | `DS_ERR_NOT_FOUND` |
| the slot names no unit | `DS_ERR_INVAL` |
| the value's kind is not the one [NFCT.2.3] pairs with the slot's type | `DS_ERR_SLOT_TYPE_MISMATCH` |
| the value is a NaN | `DS_ERR_NAN_REJECTED` |
| the conversion raises an `EngineError` ([LERR.1.4.7]) | `DS_ERR_ENGINE_HALTED` |
| the conversion raises any other fault where a rule's evaluation would ([LERR.1.4]), or its result is NaN | `DS_ERR_NOT_REPRESENTABLE` |

*ratified*  —  *see also:* [LADP.8.5.3](#LADP-8-5-3), [LERR.1.4](#LERR-1-4), [LERR.1.4.7](#LERR-1-4-7), [LUNI.7.1](#LUNI-7-1), [LUNI.7.6](#LUNI-7-6), [LUNI.8.5](#LUNI-8-5), [NCBK.2.8](#NCBK-2-8), [NCBK.2.9](#NCBK-2-9), [NFCT.2.3](#NFCT-2-3), [RARC.13.16](#RARC-13-16), [RDSC.4a.9.3](#RDSC-4a-9-3), [RDSC.4a.9.6](#RDSC-4a-9-6), [RDSC.5.5.9](#RDSC-5-5-9)

(NFCT-1-4-2)=
[NFCT.1.4.2] A loaded schema's slots, as its declaration states them, are the
enforced slot-type contract ([NFCT.1.1]). The introspection accessors
(`ds_schema_get_name` / `_get_slot_count` / `_get_slot` / `_get_lifecycle` /
`_get_ttl_ns`) read the contract back, each slot as a `ds_slot_desc_t`
([NFCT.1.4.1]). A schema's name, in `ds_engine_schema_find` and
`ds_schema_get_name` and every binding's lookup, is its own name ([LIMP.13.1]):
`plant.sensors.Reading`, for a schema of that library, and never an alias.

---

*ratified*  —  *see also:* [LIMP.13.1](#LIMP-13-1), [NFCT.1.1](#NFCT-1-1), [NFCT.1.4.1](#NFCT-1-4-1)

(NFCT-2)=
## Asserting [NFCT.2]

(NFCT-2-1)=
[NFCT.2.1] Asserting is how a fact enters working memory. The call takes the
schema the fact is an instance of, the values that fill its slots, and how many
there are.

The values are **positional**: the i-th value fills the i-th slot the schema
declared ([NFCT.1.4.1]). A value carries no name, so position is the only thing
that could bind it to a slot -- which is why the count must equal the schema's
slot count exactly ([NFCT.2.2]), and why each value's kind is checked against
the type declared *at that position* ([NFCT.2.3]). An integrator assembling
values from a keyed source is the one responsible for ordering them.

Nothing the caller passes is retained. Every buffer reachable from the values
is borrowed for the duration of the call ([NFCT.2.4]), and the optional
out-parameter is the only thing that outlives it ([NFCT.2.5]).

Asserting also fires nothing. The fact lands in working memory and whatever it
activates waits on the agenda until the engine is pumped ([NLFC.2.1]).

*see also:* [NFCT.1.4.1](#NFCT-1-4-1), [NFCT.2.2](#NFCT-2-2), [NFCT.2.3](#NFCT-2-3), [NFCT.2.4](#NFCT-2-4), [NFCT.2.5](#NFCT-2-5), [NLFC.2.1](#NLFC-2-1)

(NFCT-2-2)=
[NFCT.2.2] `n_values` must equal the schema's slot count exactly — too few or
too many is `DS_ERR_INVAL`.

(NFCT-2-3)=
[NFCT.2.3] Each `ds_slot_value_t.kind` must match the slot's declared
`ds_slot_type_t`. There is **no implicit conversion**; a mismatch is
`DS_ERR_SLOT_TYPE_MISMATCH` (IDAT.4.6):

| Schema slot type | Required value kind | Union member |
|---|---|---|
| `DS_SLOT_TYPE_INT`    | `DS_SLOT_INT`      | `v.i` |
| `DS_SLOT_TYPE_FLOAT`  | `DS_SLOT_FLOAT`    | `v.f` |
| `DS_SLOT_TYPE_STRING` | `DS_SLOT_STRING`   | `v.s` (non-NULL) |
| `DS_SLOT_TYPE_BOOL`   | `DS_SLOT_BOOL`     | `v.b` |
| `DS_SLOT_TYPE_JSON`   | `DS_SLOT_JSON`     | `v.json` (non-NULL parsed tree) |
| `DS_SLOT_TYPE_SCHEMA` | `DS_SLOT_FACT_REF` | `v.ref` (a live fact whose schema equals the slot's `schema_ref`) |
| `DS_SLOT_TYPE_BYTES`  | `DS_SLOT_BYTES`    | `v.bytes` (`ds_bytes_view_t` data+len) |
| `DS_SLOT_TYPE_TIME`   | `DS_SLOT_INT`      | `v.i` (UTC nanoseconds, [RDSC.5.5.8]) |
| `DS_SLOT_TYPE_DATE`   | `DS_SLOT_INT`      | `v.i` (epoch days, [RDSC.5.5.8]) |
| `DS_SLOT_TYPE_DURATION` | `DS_SLOT_INT`    | `v.i` (nanoseconds, [RDSC.5.5.8]) |

A negative `v.i` for a `DS_SLOT_TYPE_DURATION` slot is stored as `0`: a
`Duration` is never negative ([LTIM.1.3.1]). That is a value the engine
stores, not a kind it converts, and it is not an error.

The number a host gives a slot typed by a unit or a dimension is the slot's
stored number ([LUNI.7.6]).

A host's reference **must** name a live fact of the slot's `schema_ref`. One that
names a live fact of another schema, or no live fact, is
`DS_ERR_SLOT_TYPE_MISMATCH`, judged at its slot's place in [NFCT.2.11]'s
step 4, on working memory as the call finds it. A `libds.h` caller does not meet
the second: its reference is a handle, and a handle whose fact is not live is
undefined behaviour ([IDAT.1.6]). A runtime whose host names a fact by its id does
meet it, and its engine **must** judge it, because the recording of such an assert
inlines each referenced live fact ([RFCS.24.1]). A target that leaves after the
assert does not undo it: a read of the slot then finds the target gone.
A delivery's references are [RFCS.23.7]'s: it judges them once, on working memory
as the call finds it, and a target the delivery's own asserts remove is this case
too.

This is the host-boundary statement of a working-memory invariant, not a
property of this API: [RARC.5.2.6] binds every path into working memory to the
same rule, so a rule-fired `emit` is held to this table exactly as a host
assertion is.

*ratified*  —  *see also:* [IDAT.1.6](#IDAT-1-6), [IDAT.4.6](#IDAT-4-6), [LTIM.1.3.1](#LTIM-1-3-1), [LUNI.7.6](#LUNI-7-6), [NFCT.2.11](#NFCT-2-11), [RARC.5.2.6](#RARC-5-2-6), [RDSC.5.5.8](#RDSC-5-5-8), [RFCS.23.7](#RFCS-23-7), [RFCS.24.1](#RFCS-24-1)

(NFCT-2-8)=
[NFCT.2.8] **The slot types are the registry `specs/registry/slot_type.ebnf`.**
`ds_slot_type_t` must mirror it name for name and value for value. It is the
type `ds_schema_get_slot` reads back for a loaded schema's slot ([NFCT.1.4.1])
and the type [NFCT.2.3] pairs a value's kind with. Its numbers are its own: it
is not a mirror of the artefact's `proto/slot.proto#SlotKind`.

*see also:* [NFCT.1.4.1](#NFCT-1-4-1), [NFCT.2.3](#NFCT-2-3)

(NFCT-2-10)=
[NFCT.2.10] **The host supplies `ts`.** Where the schema declares a slot named
`ts` ([LFAC.9.1]), the integrator must supply its value like any other slot's: a
`DS_SLOT_INT` of UTC nanoseconds ([NFCT.2.3]), the instant the source observed
the fact ([LFAC.9.2]). The engine must not fill it and must not read the wall
clock for it. A `DS_SLOT_NULL` in `ts` is a null in a slot that is not
nullable, and `ds_engine_assert` must refuse it with
`DS_ERR_SLOT_TYPE_MISMATCH`.

*ratified*  —  *see also:* [LFAC.9.1](#LFAC-9-1), [LFAC.9.2](#LFAC-9-2), [NFCT.2.3](#NFCT-2-3)

(NFCT-2-11)=
[NFCT.2.11] **Where one assert breaks several refusals, the first in this order
decides.** `ds_engine_assert` **must** return the
status of the first of these steps that refuses:

1. The engine is halted: `DS_ERR_ENGINE_HALTED` ([NCBK.2.9]).
2. The schema is not one the engine holds: `DS_ERR_SCHEMA_UNKNOWN` ([NFCT.1.1]).
3. The value count is not the schema's slot count: `DS_ERR_INVAL` ([NFCT.2.2]).
4. A value its slot does not admit: a `null` in a slot not declared `T?`
   ([LNUL.3.1]), a kind [NFCT.2.3]'s table does not pair with the slot's type, or
   a reference that clause does not admit, is `DS_ERR_SLOT_TYPE_MISMATCH`. A pointer that table requires to be
   non-`NULL` and that is `NULL` is `DS_ERR_INVAL`, at its slot's place in this
   step.
5. A NaN `Float`: `DS_ERR_NAN_REJECTED` ([LEXP.4.2]).
6. A `Json` value over one of its limits: `DS_ERR_JSON_LIMIT` ([LGRA.5.8.6]).
7. Text that is not well-formed UTF-8: `DS_ERR_ENCODING` ([LSTR.8.5]).
8. A `Date` outside its range: `DS_ERR_TIME_RANGE` ([LTIM.1.2.2]).
9. A malformed `TimeZoneOffset` fact: `DS_ERR_INVAL` ([LTIM.10.9]).
10. A TTL deadline outside the `Time` range: `DS_ERR_TIME_RANGE` ([RFCS.6.7]).
11. A held seed's deadline, which this call's sample would fix, outside the
    `Time` range: `DS_ERR_TIME_RANGE` ([NLFC.9.5]).

A step that judges slot values judges every slot, in declaration order, before
the next step begins, and the first slot it refuses decides. So a NaN in the
first slot beside a `Json` value over a limit in the second is
`DS_ERR_NAN_REJECTED`, and either beside a kind mismatch in any slot is
`DS_ERR_SLOT_TYPE_MISMATCH`. A `NULL` engine is `DS_ERR_INVAL` before step 1, and
a `NULL` schema is `DS_ERR_INVAL` after step 1 and before step 2.

The order judges values. A `Json` slot given as JSON text is judged as text
first, and a refusal of the text comes before step 1 ([LSTR.8.5]).

`ds_json_t` is opaque, and `ds_json_parse` and the builders refuse a tree over a
limit or holding ill-formed text before it exists ([LGRA.5.8.6], [LSTR.8.5]). So
a `libds.h` caller meets neither step 6 nor, for a `Json` slot, step 7. The
engine **must** judge both all the same: a runtime whose host builds a value
another way meets them.

Step 2 stands on the same footing. Every schema handle `libds.h` hands out names
a schema its engine holds, and any other handle is undefined behaviour
([IDAT.1.6]), so a `libds.h` caller does not meet step 2. A runtime whose host
names a schema another way does. A reference that names no live fact, in
step 4, stands on it too ([NFCT.2.3]).

Every step is an argument check. A call any of them refuses is not a step
([LTIM.2.8.4]): it changes nothing and records nothing ([RFCS.6.7]). A refusal
the engine makes after it samples, such as a `String` over its slot's capacity
([LSTR.11.3]) or an `initial` block over a cache cap ([LGRA.24.3]), answers a
call that passed all eleven.

*ratified*  —  *see also:* [IDAT.1.6](#IDAT-1-6), [LEXP.4.2](#LEXP-4-2), [LGRA.24.3](#LGRA-24-3), [LGRA.5.8.6](#LGRA-5-8-6), [LNUL.3.1](#LNUL-3-1), [LSTR.11.3](#LSTR-11-3), [LSTR.8.5](#LSTR-8-5), [LTIM.1.2.2](#LTIM-1-2-2), [LTIM.10.9](#LTIM-10-9), [LTIM.2.8.4](#LTIM-2-8-4), [NCBK.2.9](#NCBK-2-9), [NFCT.1.1](#NFCT-1-1), [NFCT.2.2](#NFCT-2-2), [NFCT.2.3](#NFCT-2-3), [NLFC.9.5](#NLFC-9-5), [RFCS.6.7](#RFCS-6-7)

(NFCT-2-4)=
[NFCT.2.4] **Value lifetimes — the engine copies.** All call-site value
storage is borrowed for the duration of the `ds_engine_assert` call only:

- **String** (`v.s`): non-NULL; libds copies the content into the engine's
  interned string table. Free your buffer after the call returns.
- **JSON** (`v.json`): a tree from `ds_json_parse` (or the builder API); the
  caller keeps ownership. libds **deep-clones** it (via `ds_json_clone`, into
  independent engine-owned trees) and returns; free your tree afterward
  (including when the assert errors before the clone step).
- **Bytes** (`v.bytes`): the engine copies `len` bytes from `data`.
- **Fact-ref** (`v.ref`): a non-owning borrow of a live fact; it must outlive
  the assert and must match the slot's declared `schema_ref`.

(NFCT-2-9)=
[NFCT.2.9] **The Json node kinds are the registry `specs/registry/json_kind.ebnf`.**
`ds_json_kind_t`, the kind `ds_json_get_kind` reports for a node of a Json tree
([NFCT.2.4]), must mirror it name for name and value for value.

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

(NFCT-2-5)=
[NFCT.2.5] **`out_fact` is optional.** Pass NULL if you do not need the wrapper
handle. Pass non-NULL to retract later (you need the pointer) or to correlate
with the `DS_EV_FACT_ASSERT` stream event (whose `fact` pointer is the same
wrapper returned here).

(NFCT-2-7)=
[NFCT.2.7] **One kind number space for slots and call arguments.**
`ds_kind_t` holds the value kinds a slot and a call argument share, at the
numbers `ds_slot_kind_t` already uses. `ds_slot_kind_t` is those plus
`DS_SLOT_FACT_REF`; `ds_arg_kind_t` is those plus `DS_ARG_ENCODED_FACT`. A
common kind has one number everywhere, so converting between the types is the
identity; a number belonging to one subtype is reserved in the other.

The value unions follow the same shape: `ds_value_t` holds the common members,
and `ds_slot_value_t` and `ds_arg_value_t` each repeat them under the same names
and offsets and add their own. All three enumerations and their member lists are
generated from `proto/fact_external.proto#Kind` ([RFCS.23.2]), never written by
hand ([STYL.5.9.7]).

*defined in:* [proto/fact_external.proto#Kind](#proto-fact_external-proto-Kind)  —  *see also:* [RFCS.23.2](#RFCS-23-2)

(NFCT-4)=
## Lifecycle categories: LOGICAL vs TTL [NFCT.4]

(NFCT-4-1)=
[NFCT.4.1] Every schema has one lifecycle, which its declaration states and
the artefact carries ([NFCT.1.1]):

- `DS_SCHEMA_LIFECYCLE_LOGICAL` — the fact stays in working memory until it is
  retracted: by your manual retract, by a rule-side retract action, or by the
  engine's truth-maintenance machinery when a logical justifier ends.
  `ttl_ns` is `0`.
- `DS_SCHEMA_LIFECYCLE_TTL` — the fact carries a per-fact deadline
  (`assert_clock + ttl_ns`); the pump's
  TTL sweep retracts it once the deadline passes. `ttl_ns` is `> 0`.

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

(NFCT-4-5)=
[NFCT.4.5] **The lifecycles are the registry `specs/registry/schema_lifecycle.ebnf`.**
`ds_schema_lifecycle_t` must mirror it name for name and value for value. A
lifecycle says how a fact of the schema leaves working memory ([NFCT.4.1]), and
`INTERNAL` marks a schema the engine owns ([NDBG.2.2]). It is not the scope an
artefact declares (`proto/schema_logical.proto#SchemaLifecycle`): a schema the
artefact declares `explicit`, `logical` or `activation` reads as `LOGICAL`.

*see also:* [NDBG.2.2](#NDBG-2-2), [NFCT.4.1](#NFCT-4-1)

(NFCT-4-2)=
[NFCT.4.2] **LOGICAL** suits entity-state facts (current sensor state, a
retained MQTT value, derived state). **TTL** suits event facts (event-bus
events, detections, non-retained publishes, fading alerts).

(NFCT-4-3)=
[NFCT.4.3] If one concept carries both intents (a state *and* an entry event),
split it into two schemas rather than conflating (LFAC.1.5.11).

*see also:* [LFAC.1.5.11](#LFAC-1-5-11)

(NFCT-4-4)=
### Reassertion, identity, and dedup [NFCT.4.4]

(NFCT-4-4-1)=
[NFCT.4.4.1] A LOGICAL schema's identity is its declared **`KEY`** slots
([LFAC.1.7]; every slot is `KEY` or `MUTABLE`, [LGRA.5.10]). Assert is
**upsert** keyed on the `KEY` tuple: asserting a fact whose `KEY`-slot values
match a live fact *replaces* it — the new one, carrying its updated `MUTABLE`
payload, is asserted and the old fact retracted. The stream shows the arriving
`DS_EV_FACT_ASSERT` first and the old fact's `DS_EV_FACT_RETRACT` after it
([RFCS.6.7]). Exactly one live LOGICAL fact exists per `KEY`
tuple. There is **no slot-0 default and no privileged slot name**.

*see also:* [LFAC.1.7](#LFAC-1-7), [LGRA.5.10](#LGRA-5-10), [RFCS.6.7](#RFCS-6-7)

(NFCT-4-4-2)=
[NFCT.4.4.2] The width of the key sets the behaviour. **Key = ∅** (every slot
`MUTABLE`) is a singleton — one live fact, latest payload wins. **Key = all
slots** is a relation — asserting a tuple that already exists is a **no-op in
working memory** (LFAC.2.5.1): `out_fact` returns the existing wrapper and
`fact_count` is unchanged; a different tuple is a different fact. The no-op is
a **working-memory discipline, not a recording one** — the assert still
arrived, so the `FactAssert` is written and `DS_EV_FACT_ASSERT` **does** fire
([RFCS.6.7]). The key-subset cases (entity-state, composite key) sit between.

*see also:* [LFAC.2.5.1](#LFAC-2-5-1), [RFCS.6.7](#RFCS-6-7)

(NFCT-4-4-3)=
[NFCT.4.4.3] The **`KEY`-tuple comparison is always exact**. On a `MUTABLE`
numeric slot a per-slot `tolerance` ([NFCT.1.4]) widens the *meaningful-change*
test — a within-tolerance payload change is a no-op and the live fact is kept.
`tolerance` is admissible only on `MUTABLE` slots; on a `KEY` slot it is a
compile error ([LGRA.5.9]) — identity is exact.

*see also:* [LGRA.5.9](#LGRA-5-9), [NFCT.1.4](#NFCT-1-4)

(NFCT-4-4-4)=
[NFCT.4.4.4] **TTL schemas do not dedup.** Each assert is a distinct fact with
its own deadline; identical TTL events accumulate (LFAC.1.3).

*see also:* [LFAC.1.3](#LFAC-1-3)

(NFCT-4-4-5)=
[NFCT.4.4.5] The integrator pattern for LOGICAL state is "always re-assert with
the latest values" — the engine upserts the changed ones and no-ops the
unchanged ones; you need not filter at the source for correctness (adapters MAY
suppress redundant asserts to cut call volume).

---

(NFCT-3)=
## Retracting [NFCT.3]

(NFCT-3-1)=
[NFCT.3.1] `ds_engine_retract(e, f)` removes a fact from working memory.

(NFCT-3-2)=
[NFCT.3.2] `f` must be a handle this engine handed out, whose fact is still
live: from `ds_engine_assert`, `ds_engine_fact_find`, a
`ds_engine_for_each_fact` visitor, a stream event's `fact` payload, or a
fact-reference slot read with `ds_fact_get_slot` ([IDAT.3.1]).

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

(NFCT-3-3)=
[NFCT.3.3] **After return the pointer is invalid** — libds freed the wrapper.
Do not dereference, compare, or pass it to any further libds call.

(NFCT-3-4)=
[NFCT.3.4] **Double-retract is undefined behaviour**; NULL the pointer after. A
caller holding only a fact's id looks it up first ([NFCT.6.4]): a fact no longer
live is not found, so nothing is retracted twice.

*see also:* [NFCT.6.4](#NFCT-6-4)

(NFCT-3-5)=
[NFCT.3.5] You usually do **not** retract LOGICAL facts manually — upsert /
no-op reassertion ([NFCT.4.4]) covers ordinary state churn. Manual retract is
appropriate when the source reports an entity deleted, or when an adapter
shuts down and cleans up its facts.

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

(NFCT-3-6)=
[NFCT.3.6] TTL facts retract automatically at their deadline ([NFCT.4]).
Manual retract of a TTL fact before its deadline is allowed but unusual.

---

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

(NFCT-6)=
## Reading working memory [NFCT.6]

(NFCT-6-1)=
[NFCT.6.1] **Counts:**

- `ds_engine_fact_count(e, &n)` — live facts in working memory.
- `ds_engine_schema_count(e, &n)` — registered schemas.

(NFCT-6-2)=
[NFCT.6.2] **Per-fact accessors.** A `ds_fact_t *` is opaque; read it through:

| Accessor | Returns |
|---|---|
| `ds_fact_get_id`             | engine-assigned monotonic id (a new id after retract→reassert; identity is not preserved across retraction) |
| `ds_fact_get_schema`         | the schema this fact instantiates (borrow, engine-lifetime) |
| `ds_fact_get_asserted_ns`    | the fact's entry stamp, on the monotonic clock ([LTIM.2.8.6]) |
| `ds_fact_get_ttl_deadline_ns`| TTL deadline (0 for LOGICAL / untracked) |
| `ds_fact_get_slot_count`     | slot count |
| `ds_fact_get_slot`           | the i-th slot's name (borrow) and tagged-union value |

Each returns `DS_OK` with the out-pointer set, `DS_ERR_INVAL` on NULL,
`DS_ERR_NOT_FOUND` on out-of-range index. `ds_fact_get_slot` takes `NULL` for
either out-pointer, and `DS_ERR_INVAL` answers both being `NULL`. Pointers are
valid until the fact is retracted (TTL sweep, explicit retract, justifier-end);
holding a `ds_fact_t *` across pumps risks use-after-free unless you subscribe
to `DS_EV_FACT_RETRACT` and clear your reference there. A `v.json` read from a
fact is the fact's own tree, a borrow the caller must not free or change
([IDAT.3.3.8]).

*see also:* [IDAT.3.3.8](#IDAT-3-3-8), [LTIM.2.8.6](#LTIM-2-8-6)

(NFCT-6-3)=
[NFCT.6.3] **Iteration.** `ds_engine_for_each_fact(e, schema, visitor, user)`
visits every live fact (or, with a non-NULL `schema`, every fact of that
schema). The engine must not visit, by schema or unfiltered, or count in
`ds_engine_fact_count` ([NFCT.6.1]), a fact the lowering creates for its own
use, an `after` clause's timer or capture fact ([RFCS.6a.5]), or a fact the
engine synthesises, the clock tick ([LDET.5.8]), as the stream carries none of
them ([NCBK.2.6]). A pending `after` deadline is therefore not read through the
fact API. The visitor receives a borrowed
read-only fact pointer; return `DS_OK_R` to continue or any non-OK result to abort (which becomes the call's
return). Every `ds_engine_*` call the visitor makes on the engine being
walked, a read included, returns `DS_ERR_STATE` and does nothing
([RARC.13.17]): capture into `user` and act after iteration returns. A call on
a different engine is unaffected. Order is unspecified (hash-keyed); sort
captured results if you need stability.

---

*ratified*  —  *see also:* [LDET.5.8](#LDET-5-8), [NCBK.2.6](#NCBK-2-6), [NFCT.6.1](#NFCT-6-1), [RARC.13.17](#RARC-13-17), [RFCS.6a.5](#RFCS-6a-5)

(NFCT-6-4)=
[NFCT.6.4] **Looking a fact up by id.** `ds_engine_fact_find(e, fact_id,
&out)` answers whether the fact with that id ([NFCT.6.2]'s `ds_fact_get_id`)
is still live. If it is, the call returns `DS_OK` with `*out` set to it, a
pointer with [NFCT.5.3]'s lifetime. If no live fact has the id — it was
retracted, expired, superseded, or never assigned — the call returns
`DS_ERR_NOT_FOUND` and sets `*out` to `NULL`.

An id is never reassigned, so a caller holding only an id can tell whether its
fact is still live without mirroring the stream: look it up, then retract the
pointer the lookup returned ([NFCT.3.1]). The lookup reads working memory, so a
halted engine refuses it with `DS_ERR_ENGINE_HALTED` ([NCBK.2.9]).

*ratified*  —  *see also:* [NCBK.2.9](#NCBK-2-9), [NFCT.3.1](#NFCT-3-1), [NFCT.5.3](#NFCT-5-3), [NFCT.6.2](#NFCT-6-2)

(NFCT-5)=
## Observing: the stream callback [NFCT.5]

(NFCT-5-1)=
[NFCT.5.1] Every fact lifecycle event passes through the stream callback
(`ds_engine_set_stream_callback`; [NCBK.2]):

| Kind | Fires when | Payload |
|---|---|---|
| `DS_EV_FACT_ASSERT`  | an assert arrived ([RFCS.6.7]): a new fact entered working memory; or an upsert's replacement did, and the old fact's `DS_EV_FACT_RETRACT` follows; or a no-op reassertion left the live fact in place; or the engine refused the assert, and its `DS_EV_BOUNDS_ERROR` follows | `event->p.fact_assert.fact` |
| `DS_EV_FACT_RETRACT` | a fact left working memory (your retract, the TTL sweep, a rule-side retract, or upsert replacement) | `event->p.fact_retract.fact` |

The payload of a refused assert's `DS_EV_FACT_ASSERT` is valid only for the
callback, and is not a working-memory handle: the fact never entered.

`DS_EV_FACT_MODIFY` is reserved in the enum and **not emitted** — an upsert
surfaces as a `FACT_ASSERT` followed by a `FACT_RETRACT`, not a modify. A `switch` over
the kind still needs the case: the member is in the public enum. The full event catalogue is in [NCBK.2].

*ratified*  —  *see also:* [NCBK.2](#NCBK-2), [RFCS.6.7](#RFCS-6-7)

(NFCT-5-2)=
[NFCT.5.2] Every event carries `seq` (per-engine monotonic; strictly
increasing, LFST.7.1.1) and `clock_ns` (engine clock at emit).

*see also:* [LFST.7.1.1](#LFST-7-1-1)

(NFCT-5-3)=
[NFCT.5.3] **Pointer lifetime:** the `FACT_ASSERT` `fact` is valid until that
fact is retracted; the `FACT_RETRACT` `fact` is valid only for the callback's
duration (libds frees the wrapper right after the callback returns).

(NFCT-5-4)=
[NFCT.5.4] No-op LOGICAL reassertions ([NFCT.4.4.2]) **do** emit `FACT_ASSERT`.
A `FactAssert` records an assert ARRIVING, not a fact entering working memory
([RFCS.6.7]); the suppression is a working-memory discipline and never reaches
the recorder. Each successful retract emits exactly one `FACT_RETRACT`; the TTL
sweep emits one per expired fact. Within one rule firing these events take the
order [NCBK.2.6] states.

---

*see also:* [NCBK.2.6](#NCBK-2-6), [NFCT.4.4.2](#NFCT-4-4-2), [RFCS.6.7](#RFCS-6-7)

(NFCT-7)=
## Common patterns [NFCT.7]

(NFCT-7-1)=
### Adapter mirror loop [NFCT.7.1]

(NFCT-7-1-1)=
[NFCT.7.1.1] Source reports a state change → translate to slot values → assert.
Upsert / no-op discipline ([NFCT.4.4]) means re-asserting unchanged values is\nfree.

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

(NFCT-7-2)=
### Manual retract on entity removal [NFCT.7.2]

(NFCT-7-2-1)=
[NFCT.7.2.1] Keep the wrapper from the original assert (or capture it from the
stream callback), and retract it when the source reports the entity gone.

(NFCT-7-3)=
### Bursty events with TTL [NFCT.7.3]

(NFCT-7-3-1)=
[NFCT.7.3.1] Use a TTL schema whose window matches how long downstream rules
react; each message is an assert, and the sweep retracts it automatically.

---

(NFCT-8)=
## Errors reachable from the fact path [NFCT.8]

(NFCT-8-1)=
[NFCT.8.1] Full taxonomy in [NERR]. The codes the
assert path produces:

| Code | Cause |
|---|---|
| `DS_ERR_INVAL`               | NULL engine / schema, n_values mismatch, NULL string / JSON / fact-ref value |
| `DS_ERR_SLOT_TYPE_MISMATCH`  | value `kind` ≠ declared slot type; or a fact-ref whose schema ≠ the slot's `schema_ref`, or that names no live fact ([NFCT.2.3]) |
| `DS_ERR_OOM`                 | allocation failed |

*see also:* [NFCT.2.3](#NFCT-2-3)

(NFCT-8-2)=
[NFCT.8.2] Every error result but `DS_ERR_OOM` carries a non-NULL, non-empty
`detail` string identifying the problem ([IERR.3.3]), valid as [NERR.2.1]
states.

---

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

