# Integrator callback registry

The complete inventory of callbacks an integrator registers with libds. For
each: shape, when it fires, the lifetime of the pointers it receives,
return-value semantics, and what happens when it is not registered.

libds's entire surface to anything outside its own process is **typed C
callbacks plus structured event payloads**. If your integration must bridge libds across processes
or machines (cross-tier publish, remote storage, an external debugger), that
protocol is yours to design — libds hands you typed values; you encode them
however your stack likes.

## What this is not

- Not the first-time walk-through — see [NGST].
- Not the lifecycle guide — [NLFC] covers pump and
  threading; this doc assumes it.
- Not the storage / series detail — the samples-plane callbacks are summarised
  here ([NCBK.12]) and specified under NSTG / NSBK.

---

(NCBK-1)=
## Universal contract [NCBK.1]

(NCBK-1-1)=
[NCBK.1.1] Every callback an integrator registers on an engine (the stream,
metric, log and call callbacks, and the two cache callbacks) has the **same
three-argument shape and returns `ds_result_t`**. Only the payload type varies
between areas: the engine handle comes first, a `const` pointer to what
happened second, and the integrator's own context pointer third. The cache set
callback's payload is the write ([NSTG.2.3]).

That uniformity is what the rest of this section rests on. The argument roles
([NCBK.1.2]-[NCBK.1.4]), the meaning of a non-OK return ([NCBK.1.5]), the
lifetime of pointers reachable from the payload ([NCBK.1.6]), the thread the
call arrives on ([NCBK.1.7]), and how registration and replacement behave
([NCBK.1.9]) are stated **once, here**, and hold for every registered callback.
An integrator who has learned one signature has learned all of them.

A visitor that an enumerating read takes as an argument, and calls before it
returns, is not a registered callback, and has the shape its call declares:
the Rete visitors return nothing ([IARC.1.12]). The re-entry rule binds inside
a visitor as inside a callback ([RARC.13.17]).

The concrete type for each area is named in that area's own clause, and every one is declared in `runtime/include/libds.h`.

*see also:* [IARC.1.12](#IARC-1-12), [NCBK.1.2](#NCBK-1-2), [NCBK.1.4](#NCBK-1-4), [NCBK.1.5](#NCBK-1-5), [NCBK.1.6](#NCBK-1-6), [NCBK.1.7](#NCBK-1-7), [NCBK.1.9](#NCBK-1-9), [NSTG.2.3](#NSTG-2-3), [RARC.13.17](#RARC-13-17)

(NCBK-1-2)=
- [NCBK.1.2] **First arg is the engine handle.** Every public surface is
  engine-scoped, no globals ([IARC.1.11]). The handle names the engine that
  fired the callback; it is not a way back into that engine. Every
  `ds_engine_*` call on it from inside the callback, a read as well as a
  write, returns `DS_ERR_STATE` ([RARC.13.16]). A callback may call into a
  different engine.

*see also:* [IARC.1.11](#IARC-1-11), [RARC.13.16](#RARC-13-16)

(NCBK-1-3)=
- [NCBK.1.3] **Second arg is the event-specific payload**, always `const` —
  callbacks read, they do not mutate.

(NCBK-1-4)=
- [NCBK.1.4] **`void *user` is your context pointer**, exactly what you passed
  at registration; libds never touches it.

(NCBK-1-5)=
- [NCBK.1.5] **Return `ds_result_t`.** A non-OK status propagates to whoever
  invoked the libds call that fired the callback. Most callbacks log internally
  and return `DS_OK_R`. A typed verb callback's non-OK status keeps the meaning
  its verb's dispatcher contract gives it.

  For the **stream callback** ([NCBK.2.1]):

  - **The engine does not depend on it.** A non-OK status from the stream
    callback must not change what the engine does. The call that fired it runs
    to completion: every remaining event is delivered, every firing's RHS runs,
    and a TTL sweep retracts every expired fact. The stream is an observer.
  - **The first status is the call's.** The first non-OK status the stream
    callback returns during a public libds call is that call's return value,
    unless the call fails for its own reason, whose status takes precedence.
    A later non-OK status in the same call is not reported, and none is carried
    into the next call.
  - **The outermost public call reports it.** A callback fired inside work an
    outer public call started — a truth-maintenance cascade, a pump's firings —
    is reported by that outer call.
  - **Fault events are included.** A stream event reporting a fault
    ([NCBK.2.8]) is delivered like any other, and a non-OK status from its
    delivery is reported under the same rule; where the call returns a status
    of its own for the fault, that status takes precedence.

  So a stream-callback error during a pump surfaces as the pump's return value,
  after the pump has done everything it would have done without it.

  The **metric** and **log** callbacks are fire-and-forget. The engine must
  drop a non-OK status from either: it changes nothing the engine does and is
  not the return status of any call. For the log callback this holds whatever
  produced the line, an author's `log` action or a message of the engine's
  own. This is the samples callback's rule ([NSTG.5.3.2]) applied to both. An
  integrator that must know its sink failed handles that inside its callback.

*see also:* [NCBK.2.1](#NCBK-2-1), [NCBK.2.8](#NCBK-2-8), [NSTG.5.3.2](#NSTG-5-3-2)

(NCBK-1-6)=
[NCBK.1.6] **Pointers in payloads are valid only during the callback unless
documented otherwise.** Do not retain a `ds_fact_t *` past the call; copy what
you need (slot values, schema pointer, fact id) into your own storage.

(NCBK-1-7)=
[NCBK.1.7] **A callback runs on the stack of the `ds_engine_*` call that fires
it**, synchronously and on the caller's thread: a pump, an assert or retract, a
clock set. libds starts no thread to deliver one ([IARC.1.10]). Callbacks must
be non-blocking and thread-free; push real work onto a queue the runtime
services later ([NLFC.3]).

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

(NCBK-1-8)=
[NCBK.1.8] **Unregistered (NULL) callbacks silently drop, except where the verb
is essential.** Default state at engine creation: nothing registered. A verb
whose contract requires delivery returns an explicit error when its callback is
unset — `call` returns `DS_ERR_STORAGE_UNAVAILABLE` ([IDSP.6.4]), including a
call that stores a fact. The cache verbs are **not** essential: `cached()` reads the
engine's own map, and `cache` / `cache_delete` fall back to a volatile in-engine
cache when no persistence callback is wired ([NCBK.7.3]).

*see also:* [IDSP.6.4](#IDSP-6-4), [NCBK.7.3](#NCBK-7-3)

(NCBK-1-9)=
[NCBK.1.9] **Replacement is a single setter call.** Calling a setter again
replaces the prior registration; libds no longer holds the previous user
pointer (you reclaim it). Pass `cb = NULL` to unregister.

---

(NCBK-2)=
## Stream sink [NCBK.2]

(NCBK-2-1)=
[NCBK.2.1] Receives every observable event the engine produces, in `seq` order,
with engine-clock timestamps. The stream is the foundation for replay,
debugging, and durable recording (LFST): a single stream subscriber can
reconstruct the engine's full activity — fact lifecycle, rule firing, every
action verb — without registering any typed verb callback below.

The callback type is `ds_stream_cb_t`, its payload `ds_stream_ev_t`, and it is registered by `ds_engine_set_stream_callback` — all declared in `runtime/include/libds.h`.

(NCBK-2-2)=
[NCBK.2.2] `ds_stream_ev_t` carries `seq` (per-engine monotonic, strictly
increasing — LFST.7.1.1), `clock_ns` (engine clock at emit), `kind`, and a
per-kind payload union `p`. The per-kind members are declared in `runtime/include/libds.h`.

*checks:* `tla×2`  —  *see also:* [LFST.7.1.1](#LFST-7-1-1)

(NCBK-2-3)=
[NCBK.2.3] **Kinds emitted by the current runtime**:

| Kind | When | Payload member |
|---|---|---|
| `DS_EV_FACT_ASSERT`        | an assert arrived, before anything its evaluation produces ([RFCS.6.7]); the cases are [NFCT.5.1]'s | `p.fact_assert.fact` |
| `DS_EV_FACT_RETRACT`       | a fact left working memory (retract / TTL sweep / upsert replacement) | `p.fact_retract.fact` |
| `DS_EV_RULE_FIRE_BEGIN`    | just before a rule's RHS runs | `p.rule_fire_begin.{rule_name,timetag}` |
| `DS_EV_RULE_FIRE_END`      | after a rule's RHS returns | `p.rule_fire_end.{rule_name,timetag}` |
| `DS_EV_RULE_LHS_FACTS`     | immediately before `RULE_FIRE_BEGIN`, when the firing matched ≥ 1 fact — the resolved matched facts; absent for a factless firing ([NCBK.2.6]) | `p.rule_lhs_facts.{rule_name,timetag,facts,fact_count}` |
| `DS_EV_ACTION_EMIT`        | after an `emit` asserted a fact (local-only) | `p.action_emit.fact` |
| `DS_EV_ACTION_PUBLISH`     | a `publish` ran ([LTIE.4.3]; cross-tier marker) | `p.action_publish.{fact,external,external_len}` — a view of the fact valid for the callback only ([NCBK.2.5]), and its `FactExternal` encoding ([NCBK.10.1]) |
| `DS_EV_ACTION_LOG`         | a `log` action ran — before the log callback | `p.action_log.{level,category,message}` |
| `DS_EV_ACTION_CALL`        | a `call` action ran — before the call callback, whatever it returns | `p.action_call.{service,correlation,args,arg_count,timetag,rule_name}` ([NCBK.6.2]) |
| `DS_EV_ACTION_CACHE_SET`   | after the engine applied a `cache` write (independent of any persistence callback) | `p.action_cache_set.{key,value,ttl_ns}` |
| `DS_EV_ACTION_CACHE_DELETE`| after the engine applied a `cache_delete` (independent of any persistence callback) | `p.action_cache_delete.key` |
| `DS_EV_TICK`               | an input or a pump took a clock sample ([LTIM.2.8.5], [NTST.3.3]); `clock_ns` is the monotonic sample | `p.tick.{wall_set,wall_ns}` |
| `DS_EV_PUMP`               | a host pump began, after its sample and its `DS_EV_TICK`, whether or not it fires anything ([RFCS.22]); `clock_ns` is the pump's sample | (no payload) |
| `DS_EV_TIMER_ARMED`        | a `cooldown` rule fired and armed its suppression window | `p.timer_armed.{rule_name,timetag,kind,window_ns,fire_at_ns}` |

`DS_EV_ACTION_RECORD`'s number is reserved and never reissued ([STYL.2.8.7]).

*see also:* [LTIE.4.3](#LTIE-4-3), [LTIM.2.8.5](#LTIM-2-8-5), [NCBK.10.1](#NCBK-10-1), [NCBK.2.5](#NCBK-2-5), [NCBK.2.6](#NCBK-2-6), [NCBK.6.2](#NCBK-6-2), [NFCT.5.1](#NFCT-5-1), [NTST.3.3](#NTST-3-3), [RFCS.22](#RFCS-22), [RFCS.6.7](#RFCS-6-7)

(NCBK-2-12)=
[NCBK.2.12] **One firing, one `timetag`.** Every `timetag` in [NCBK.2.3] is the
firing activation's identity ([RFCS.15]). The engine **must** set it to the
same value on every event one firing produces: `RULE_LHS_FACTS`, the
`RULE_FIRE_BEGIN` / `RULE_FIRE_END` bracket, `ACTION_CALL` and `TIMER_ARMED`.
A consumer joins them to their firing by that key, and **should not** join them
by position in the stream or by `rule_name`. Every one of these events is
produced inside a firing, so its `timetag` is never `0`, and `0` is never a
valid timetag.

The value is the engine's own and identifies the firing within this engine's
stream only ([RFCS.11.2]). A consumer **must not** compare it with a `timetag`
from another engine.

`RULE_LHS_FACTS` and `TIMER_ARMED` have no recorded form, so their `timetag`
reaches the stream callback only.

*ratified*  —  *see also:* [NCBK.2.3](#NCBK-2-3), [RFCS.11.2](#RFCS-11-2), [RFCS.15](#RFCS-15)

(NCBK-2-13)=
[NCBK.2.13] **The event kinds are `proto/stream_event_kind.proto#StreamEventKind`.**
`ds_stream_ev_kind_t` must mirror it member for member and value for value:
`DS_EV_<X>` is `STREAM_EVENT_KIND_<X>`. A number the enumeration reserves is
reserved in the mirror too, and is never reissued ([STYL.2.8.7]).

A kind's **stable name** is its member name without the `STREAM_EVENT_KIND_`
prefix, in lower case: `fact_assert`, `rule_fire_begin`, `pump`. A binding must
name a kind by its stable name. A binding must name a value that is not a
member `unknown`, so an event from a newer engine is reported rather than
misread.

*defined in:* [proto/stream_event_kind.proto#StreamEventKind](#proto-stream_event_kind-proto-StreamEventKind)

(NCBK-2-4)=
[NCBK.2.4] **Reserved but not emitted** (handle the `default` case — adding a
producer later is ABI-additive):

| Kind | Note |
|---|---|
| `DS_EV_FACT_MODIFY`       | an upsert surfaces as a `FACT_ASSERT` followed by a `FACT_RETRACT` ([NFCT.5.1]), not a modify |
| `DS_EV_ACTION_CACHE_GET`  | a `cached()` read is a pure internal engine read ([LSTO.4.7.1] / [RARC.5.7.9]); it dispatches no callback, so no action event is emitted |
| `DS_EV_TIMER_FIRED` (20) | a cooldown-gated rule's later firing is seen through its ordinary firing events, joined to its `DS_EV_TIMER_ARMED` by `timetag` ([NCBK.2.12]); the value is never reissued ([STYL.2.8.7]) |

**Enum values 10, 11, 13, 14 and 17 are permanently vacant**, as
`proto/stream_event_kind.proto#StreamEventKind` reserves them, and none is ever
reissued: recorded streams in the wild carry them, so an undocumented hole is
safer than a recycled meaning. 10 held `DS_EV_ACTION_RECORD`, 11
`DS_EV_ACTION_ALERT`, 13 and 14 the
peer-connect pair, and 17 the DIFFERENTIAL backend's divergence event
([STYL.2.8.7]).

*see also:* [LSTO.4.7.1](#LSTO-4-7-1), [NCBK.2.12](#NCBK-2-12), [NFCT.5.1](#NFCT-5-1), [RARC.5.7.9](#RARC-5-7-9)

(NCBK-2-8)=
[NCBK.2.8] **Every fault is a stream event.** The four fault classes reach the integrator through the
stream callback like any other observable event, in `seq` order, and take four
kinds of their own:

| Kind | Value | Raised when |
|---|---|---|
| `DS_EV_TYPE_ERROR`   | 21 | a value is present and the operation is invalid at that site; the activation is abandoned |
| `DS_EV_BOUNDS_ERROR` | 22 | a **declared** cap was reached; the operation is rejected and the engine is intact |
| `DS_EV_ENGINE_ERROR` | 23 | engine state is no longer trustworthy; the tier halts ([NCBK.2.9]) |
| `DS_EV_COMPUTATION_ERROR` | 24 | a well-typed operation has no answer — `DIVIDE_BY_ZERO`, `DOMAIN`, `NOT_REPRESENTABLE` ([LERR.1.4.9]); the activation is abandoned |

**Four kinds and not one**, because the recorded form is four atoms, and a single kind carrying a
discriminator would have a C consumer switching on a payload field where a
replayer switches on the atom. Two discriminators for one distinction is what
drifts.

**`ComputationError` takes a kind.** It is
a fault under the same rule as the other three and carries the same disposition
as a TypeError, so a vocabulary with a disposition and no kind would leave an
integrator able to observe one and not the other. The first sentence of this
clause admits no such exception: *every* fault is a stream event.

**The disposition is the kind.** A TypeError and a ComputationError always
abandon the activation, a BoundsError always leaves the engine intact, an
EngineError always halts — so none of the four carries a recoverability or
disposition field, and a consumer reads it off the kind.

⚠ **A fault reaching the callback does not mean it was persisted.** The engine
emits; whether the event reaches durable storage is the integrator's, and for a
recorder failure it by definition does not. The engine writes nothing itself
([IARC.1.14]), so this is a property of the integrator's sink rather than of the
event.

*see also:* [IARC.1.14](#IARC-1-14), [LERR.1.4.9](#LERR-1-4-9), [NCBK.2.9](#NCBK-2-9)

(NCBK-2-9)=
[NCBK.2.9] **`DS_EV_ENGINE_ERROR` is the last gasp: the integrator **must
not** resume service on that engine.** After it, the integrator **must not**
make any `ds_engine_*` call on that engine but the ones this clause names as
valid below — not a pump, not an assert or retract, not a load or a
registration, not a configuration or callback setter, not `ds_engine_clone`,
which would carry the halted state into an engine with no halt, and not a read
of working memory, a schema or the introspection surface. The tier has halted
([LERR.1.4.7]).

**The engine must refuse each such call with `DS_ERR_ENGINE_HALTED`, and must
not act on it.** The halt is a latch: the engine sets it when it raises the
`EngineError` and never clears it. The
refusal is the same code whatever caused the halt; the cause is the
`EngineError`'s payload ([NCBK.2.10]). Refusing consults the latch and nothing
else, so it is a guarantee an engine whose state is untrustworthy can still
honour.

**A failed load sets the latch too** ([RDSC.9.8]). A `ds_engine_load_dsc` that
fails once it has begun reading the artefact returns the error that stopped
it, delivers no event, and leaves the latch set: every later call is refused
as above, but the four this clause names. A load refused with `DS_ERR_INVAL`
or `DS_ERR_STATE`, or on an engine already halted, sets nothing.

**The call that raises the `EngineError` stops at it** ([LERR.1.4.7]). It
fires, propagates and records nothing after the `EngineError`, not even the
close of the activation that raised it (its end annotation and its
`scope activation` retractions). So the `EngineError` is the last stream
event the integrator receives from that engine.

**The call that raises the `EngineError` reports the halt too.** A public call during which the engine raises an
`EngineError` — a pump whose firing faults, an assert or retract whose
propagation does — **must** return `DS_ERR_ENGINE_HALTED`, ahead of any other
status the call would have returned ([NCBK.1.5]). The one exception is a halt
whose clause gives it a code of its own, which that call returns instead, and
the only such clause is deferred ([RTCT.7.3], [NERR.18]). So a host that reads only statuses
learns of the halt from the call that caused it, and is never told `DS_OK` by
it. A replay is outside this sentence: a halt it re-derives is the recording's
content, and its status says whether it reproduced the run ([RFCS.6.7]).

**A read of engine state is refused too.** After
the halt the engine's state is undefined ([LERR.1.4.7]), so a working-memory,
schema or introspection read has no answer an integrator could rely on. The
engine **must** refuse it with `DS_ERR_ENGINE_HALTED`, by consulting the latch,
as it refuses a mutation. A fact lookup by id ([NFCT.6.4]) is such a read.

**So is a read through a fact or schema handle, whenever the handle was taken.**
Its one window is the call that raises the
`EngineError`: the records that call delivers ahead of the `EngineError`
([RFCS.6.7]) carry handles the integrator reads to make sense of them. The
engine **must** answer a handle read until it has delivered the `EngineError`
or the call that raised it has returned, and **must** refuse it with
`DS_ERR_ENGINE_HALTED` from then on.

**Four calls remain valid, because none of them reads that state.** The engine
**must** answer each after the halt:

- `ds_engine_halted`, which reads the latch and the fault that set it
  ([NCBK.2.11]);
- `ds_engine_get_platform_signature` and `ds_engine_get_session_header`, which
  report what was fixed at load: the provenance a recording of the halted run
  is filed under ([NDET.2.1]);
- `ds_engine_free` (below).

`[LERR.1.4.7]` says the **engine** halts the tier, which is a statement about
what the engine does; this clause says what the integrator may no longer
do. An integrator reading only that clause would take "halted" to mean "stops
firing rules" and go on pumping, which is the reading the word invites.

**The callback may still complete its own work.** The obligation is on calls
**into** the engine, not on the callback body: an integrator may log the event,
flush their own sink, signal a supervisor, and return. What they may not do is
re-enter, and a read is re-entry too: inside the callback every call on that
engine returns `DS_ERR_STATE` ([RARC.13.16]). The calls above that remain valid
are valid once the callback has returned.

**Teardown is not a call into a running engine.** `ds_engine_free` remains valid
and remains the integrator's responsibility — otherwise a halted tier would leak
everything it holds. It is valid once the callback has returned, as the others
are: from inside a callback on that engine it returns `DS_ERR_STATE` and frees
nothing, since freeing there would free the stack the callback returns into
([RARC.13.16]). The engine **must** release everything it holds whatever
state the halt left it in.

*ratified*  —  *see also:* [LERR.1.4.7](#LERR-1-4-7), [NCBK.1.5](#NCBK-1-5), [NCBK.2.10](#NCBK-2-10), [NCBK.2.11](#NCBK-2-11), [NDET.2.1](#NDET-2-1), [NERR.18](#NERR-18), [NFCT.6.4](#NFCT-6-4), [RARC.13.16](#RARC-13-16), [RDSC.9.8](#RDSC-9-8), [RFCS.6.7](#RFCS-6-7), [RTCT.7.3](#RTCT-7-3)

(NCBK-2-10)=
[NCBK.2.10] **Each fault kind carries a payload, and its cause vocabulary is a
mirror of the wire enum.** `ds_stream_ev`'s union **must** carry one arm per
kind allocated by [NCBK.2.8]. Three of the four lead with a cause, and each
cause **must** be a C enum mirroring the protobuf enum that defines it — same
members, **same values**, per [STYL.5.9.7]:

| Kind | Union arm | Cause enum | Mirrors |
|---|---|---|---|
| `DS_EV_TYPE_ERROR` | `type_error` | *(none)* | `proto/type_error.proto#TypeError` |
| `DS_EV_BOUNDS_ERROR` | `bounds_error` | `ds_cap_name_t` (`DS_CAP_*`) | `proto/bounds_error.proto#CapName` |
| `DS_EV_ENGINE_ERROR` | `engine_error` | `ds_engine_fault_t` (`DS_ENGINE_FAULT_*`) | `proto/engine_fault.proto#EngineFault` |
| `DS_EV_COMPUTATION_ERROR` | `computation_error` | `ds_trap_kind_t` (`DS_TRAP_*`) | `proto/engine_error.proto#TrapKind` |

`clock_ns` and `seq` are on `ds_stream_ev` itself and **must not** be repeated
in an arm; the remaining fields of each protobuf message are the arm's members.

**Same values.** A cause enum carries the proto's `UNSPECIFIED` member at zero
rather than re-basing, and the reconciliation gate compares values, not only
names.

**A cause is an enum and never a bare integer** ([STYL.5.9.7]). Documenting the
values instead of enumerating them removes the compile error a consumer gets
when a member is added, and leaves nothing for the reconciliation to compare —
which is not a lighter registry but no registry.

⚠ **`DS_EV_TYPE_ERROR` and `DS_EV_ENGINE_ERROR` must ship together.** The engine's
ill-typed-operation site splits between them on whether the value came from
`Json` — the artefact-lied half is an `ENGINE_FAULT_ARTEFACT_LIED`
([`proto/engine_fault.proto`]) and the tainted half is a TypeError — so shipping
the TypeError arm alone leaves the other half still emitting nothing while its
sibling emits. A consumer then reads the stream and correctly concludes that no
EngineErrors occurred. That is worse than emitting nothing, because nothing is
legible as nothing and a half-populated vocabulary is not.

`DS_EV_COMPUTATION_ERROR` and `DS_EV_BOUNDS_ERROR` have no such partner.
`ds_cap_name_t` mirrors `CapName`, whose membership is [RTCT.7.1]'s cap table.

*see also:* [NCBK.2.8](#NCBK-2-8), [NCBK.2.9](#NCBK-2-9), [RTCT.7.1](#RTCT-7-1)

(NCBK-2-11)=
[NCBK.2.11] **The halt latch can be read.** `ds_engine_halted(e, &halted,
&fault)` reports whether the engine has halted ([NCBK.2.9]) and, if it has,
the cause: the `ds_engine_fault_t` the `DS_EV_ENGINE_ERROR` event carried
([NCBK.2.10]). On an engine that has not halted, `halted` is false and `fault`
is `DS_ENGINE_FAULT_UNSPECIFIED`. On an engine a failed load spent
([RDSC.9.8]), `halted` is true and `fault` is `DS_ENGINE_FAULT_UNSPECIFIED`: no
`EngineError` was raised, and the load's own status was the cause.

It reads the latch and nothing else, so it is one of the calls that remain
valid after the halt ([NCBK.2.9]). An integrator
that dropped the event, or learned of the halt only from a
`DS_ERR_ENGINE_HALTED` status, can still learn the cause.

*ratified*  —  *see also:* [NCBK.2.10](#NCBK-2-10), [NCBK.2.9](#NCBK-2-9), [RDSC.9.8](#RDSC-9-8)

(NCBK-2-5)=
[NCBK.2.5] **Pointer lifetime:**

- `p.fact_*.fact` and `p.action_emit.fact` are valid for the
  callback's duration; on `FACT_ASSERT` / `EMIT` the wrapper
  outlives the callback (treat it as valid until you observe its retract), but
  on `FACT_RETRACT` it is freed right after the callback returns. A refused
  assert's `FACT_ASSERT` is the exception: its fact never entered working
  memory, and its payload is valid for the callback only ([NFCT.5.1]).
- `p.action_publish.fact` is valid for the callback only. The fact is in no
  working memory ([LTIE.4.3]), so no id or lookup reaches it.
- `rule_lhs_facts.facts[]` is a borrowed array valid for the callback only.
- All strings (`rule_name`, `category`, `message`, `service`, `key`, …) are
  engine-interned; some are engine-lifetime-safe, but treat every payload
  pointer as callback-duration unless you have copied it.
- The recorder dispatches synchronously inside pump / assert / retract — your
  callback runs before they return. Snapshot what you need, return quickly,
  process later.

*ratified*  —  *see also:* [LTIE.4.3](#LTIE-4-3), [NFCT.5.1](#NFCT-5-1)

(NCBK-2-6)=
[NCBK.2.6] **Per-firing ordering.** Within one rule firing the seq order is:

```
RULE_LHS_FACTS   (if the firing matched ≥ 1 fact)
RULE_FIRE_BEGIN
  FACT_ASSERT      (if the RHS asserts)
  ACTION_<verb>    (per RHS action, after its primary effect)
  FACT_RETRACT     (if the RHS retracts)
RULE_FIRE_END
TIMER_ARMED      (if the rate gate admitted a `cooldown` rule's firing)
```

**`TIMER_ARMED` follows the bracket.** For a
firing of a `cooldown` rule that the rate gate admits ([RDSC.4a.8.2.3]), the
engine **must** emit `TIMER_ARMED` immediately after `RULE_FIRE_END`, with no
intervening event. For a firing the gate suppresses it **must not** emit one:
the gate records only the firings it admits ([LCDB.3.2.1]), so a suppressed
firing arms no window ([NCBK.2.3]). A consumer joins the event to its firing
by `timetag` ([NCBK.2.12]). The event belongs to the rule-level cooldown alone:
the engine **must not** emit one for the gate of a `cooldown:` on a `call`
([LCRS.8.2]), whether it admits the call or not.

`RULE_LHS_FACTS` is conditional like the body events: a **factless firing** —
a rule with no positive fact pattern (e.g. a pure timer/tick rule), or a
firing whose matched facts don't resolve to a live working-memory fact — emits
no `RULE_LHS_FACTS`; the `RULE_FIRE_BEGIN` bracket still opens. When present it
is emitted **immediately before** `RULE_FIRE_BEGIN` with no intervening event
(the two are produced atomically), and carries the resolved matched facts (≤
one per LHS pattern). An activation withheld before the bracket (a fire guard
whose condition is not `true`, [RDSC.4a.8.2.2]) emits neither.

**An `after` body's firing is factless.** The
follow-up rule that runs it ([LTAC.3]) matches only the compiler's timer,
tick and capture facts, and none of them is on the stream. The capture holds a
copy of the values the body reads, not the parent's facts ([LTAC.3.5]), so the
follow-up matched no fact of the parent firing and emits no `RULE_LHS_FACTS`.

Cross-tier bridges gate on `ACTION_PUBLISH`, not `FACT_ASSERT`: a `publish`
asserts nothing here, and an `emit` is local-only ([NCBK.10]).

*ratified*  —  *checks:* `alloy×12`  —  *see also:* [LCDB.3.2.1](#LCDB-3-2-1), [LCRS.8.2](#LCRS-8-2), [LTAC.3](#LTAC-3), [LTAC.3.5](#LTAC-3-5), [NCBK.10](#NCBK-10), [NCBK.2.12](#NCBK-2-12), [NCBK.2.3](#NCBK-2-3), [RDSC.4a.8.2.2](#RDSC-4a-8-2-2), [RDSC.4a.8.2.3](#RDSC-4a-8-2-3)

(NCBK-2-7)=
[NCBK.2.7] **Gotchas:**

- A callback cannot read the engine that fired it: `ds_engine_fact_count` and
  every other call on it return `DS_ERR_STATE` ([RARC.13.16]). A count is read
  between calls.
- Stream events precede metric / log emissions for the same logical event
  (recorder → telemetry), so a dual subscriber can correlate.
- A verb refused before its effect does **not** emit its `ACTION_*` event.
  `ACTION_CALL` is emitted before the call callback runs, so it appears
  whatever the callback returns ([IDSP.6.5]).

---

*see also:* [IDSP.6.5](#IDSP-6-5), [RARC.13.16](#RARC-13-16)

(NCBK-3)=
## Metric emission [NCBK.3]

(NCBK-3-1)=
[NCBK.3.1] Counters, gauges, and histograms libds emits about its own
operation. Map them to your metrics stack (Prometheus, StatsD, OpenTelemetry,
plain counters, nowhere).

The callback type is `ds_metric_cb_t`, its payload `ds_metric_t`, and it is registered by `ds_engine_set_metric_callback` — all declared in `runtime/include/libds.h`.

(NCBK-3-2)=
[NCBK.3.2] A metric emission is **self-describing**. One value carries
everything a receiver needs to route and fold the observation, with no prior
registration step and no schema to look up.

| Field | Meaning |
|---|---|
| name | the metric's dotted identifier, e.g. `ds.samples.dropped_total` |
| kind | how the receiver should fold `value` -- see below |
| value | the observation itself |
| labels / n_labels | optional dimensions; **`labels` is NULL whenever `n_labels` is 0** |

The kind is the field that decides aggregation: a **counter** contributes an
increment, a **gauge** replaces the previous reading, and a **histogram** is a
single observation the receiver buckets itself ([NCBK.3.3]). libds keeps
neither running totals nor bucket boundaries -- both live on the integrator's
side, which is what lets the one emission path serve stacks as different as
Prometheus and a plain array of counters.

Two consequences for a receiver. Because `labels` is absent rather than empty
when there are no dimensions, gate on `n_labels`, never on the pointer. And
because a single value field serves all three kinds it is floating-point, so
an integral counter delta is carried exactly only below 2^53.

The set libds emits is listed in [NMET.4.1] ([NCBK.3.4]). A receiver should
treat a name it does not know as a metric from a newer libds, not as an error.

The payload type is `ds_metric_t`, carrying `ds_metric_kind_t` and `ds_metric_label_t`, declared in `runtime/include/libds.h`.

*see also:* [NCBK.3.3](#NCBK-3-3), [NCBK.3.4](#NCBK-3-4), [NMET.4.1](#NMET-4-1)

(NCBK-3-3)=
[NCBK.3.3] Counters carry the **increment** in `value`, not the running total;
maintain totals on your side if your stack expects them. Histograms carry a
single observation per emit.

(NCBK-3-4)=
[NCBK.3.4] The metrics libds emits, with their kinds, labels and the events
that emit them, are listed in [NMET.4.1].

*see also:* [NMET.4.1](#NMET-4-1)

(NCBK-3-5)=
[NCBK.3.5] `metric->name` and the label `key`/`value` strings are valid only
during the callback; copy them to retain.

---

(NCBK-4)=
## Log emission [NCBK.4]

(NCBK-4-1)=
[NCBK.4.1] Operational events operators want to see — distinct from
`ds_result_t` errors (which travel as return values). Two sources flow through
this callback: engine-internal logs (wm, schema, dispatcher) and rule-author
`log` actions. They share one shape; the `category` string is the convention
that distinguishes them.

The callback type is `ds_log_cb_t`, its payload `ds_log_event_t`, and it is registered by `ds_engine_set_log_callback` — all declared in `runtime/include/libds.h`.

(NCBK-4-2)=
[NCBK.4.2] `ds_log_event_t` carries `level` (`DS_LOG_DEBUG` / `INFO` /
`WARNING` / `ERROR` / `CRITICAL`, mirroring Python `logging` per LGRA.10.1),
`category`, and `message`.

*see also:* [LGRA.10.1](#LGRA-10-1)

(NCBK-4-5)=
[NCBK.4.5] **A level's stable name.** The level is
`proto/log_level.proto#LogSeverity`, which `ds_log_level_t` mirrors member for
member and value for value ([NCBK.4.2]). A level's stable name is its member
name without the `LOG_SEVERITY_` prefix, as written: `DEBUG`, `INFO`, `WARNING`,
`ERROR`, `CRITICAL`. A binding must name a level by its stable name, and must
name a value that is not a member `UNKNOWN`.

*defined in:* [proto/log_level.proto#LogSeverity](#proto-log_level-proto-LogSeverity)  —  *see also:* [NCBK.4.2](#NCBK-4-2)

(NCBK-4-3)=
[NCBK.4.3] Representative log events:

| Source | Category | Level | When |
|---|---|---|---|
| engine | `wm`     | DEBUG   | a fact arrived for a schema not in the registry; fact ignored |
| engine | `wm`     | WARNING | slot-conversion failure during the assert path |
| rule author | (any) | (any) | a `log` action from a rule's RHS |

(NCBK-4-4)=
[NCBK.4.4] Logs are advisory — branch on `ds_result_t.status`, not on log text.
Strings may change between releases; messages are English (no i18n in v1).

---

(NCBK-6)=
## Call dispatch [NCBK.6]

(NCBK-6-1)=
[NCBK.6.1] The `call` action issues an async request to a service the integrator
owns (an HA service call, an MQTT publish, a weather request — anything a rule needs done outside libds that may yield a typed reply).

The callback type is `ds_call_cb_t`, its payload `ds_call_request_t`, and it is registered by `ds_engine_set_call_callback` — all declared in `runtime/include/libds.h`.

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

(NCBK-6-2)=
[NCBK.6.2] When a rule's `call` action fires, the dispatcher invokes this
callback with `{ service, correlation, args, arg_count, timetag, rule_name }`.
`correlation` is never NULL and never empty ([LCRS.3.1]). `args` holds one typed
argument per kwarg the call supplies ([NCBK.6.10]), sorted by name; an optional
kwarg the call omits is absent. `timetag` and `rule_name` are the firing
activation's identity, the pair that joins the call to its recorded `CallIssued`
and `RuleFireAnnotation` ([RFCS.21.1]). A `call` runs inside a firing, so `timetag`
is never `0` ([NCBK.2.12]) and `rule_name` is never NULL, here and on
`DS_EV_ACTION_CALL` ([NCBK.2.3]). Everything is engine-owned and borrowed for the
callback's duration.

*see also:* [LCRS.3.1](#LCRS-3-1), [NCBK.2.12](#NCBK-2-12), [NCBK.2.3](#NCBK-2-3), [NCBK.6.10](#NCBK-6-10), [RFCS.21.1](#RFCS-21-1)

(NCBK-6-3)=
[NCBK.6.3] **The correlation is opaque to the integrator, whoever wrote
it.** Where the rule writer supplies `as:` that string is the correlation
([LCRS.3.1]); where a `call` has no `as:`, the compiler and engine generate one
per activation ([LCCO.3.4]). Either way it reaches the
call callback as `correlation` and must flow **verbatim** to the `corr` slot of
the response fact ([LCRS.4.3.1]) or the `CallError` the integrator asserts. An integrator must not
parse it, derive anything from its shape, or substitute one of its own.

The engine does not track in-flight calls: it allocates the string and matches
it back, and nothing else about the call's progress is engine state.

*checks:* `tla` `idris`  —  *see also:* [LCCO.3.4](#LCCO-3-4), [LCRS.3.1](#LCRS-3-1), [LCRS.4.3.1](#LCRS-4-3-1)

(NCBK-6-4)=
[NCBK.6.4] **Async via fact assertion, not synchronous return.** The callback
dispatches the request (sync HTTP, queue, thread pool — your choice) and returns
`DS_OK_R`. The response arrives later: the integrator asserts a fact of the
service's response schema, or a `CallError`, via `ds_engine_assert`, setting its
`corr` slot to the correlation ([LCRS.4.3.1]); sibling rules match on `corr` to
consume it. For a service declaring `no response` the integrator asserts
nothing on success and a `CallError` on failure ([LCRS.17.1]).

*checks:* `idris×4`  —  *see also:* [LCRS.17.1](#LCRS-17-1), [LCRS.4.3.1](#LCRS-4-3-1)

(NCBK-6-5)=
[NCBK.6.5] **Adapter-side timeouts, not engine-side** (LCRS.7.3). libds does not
track per-call deadlines and never synthesises a response fact or a
`CallError`. Adapters assert `CallError` on timeout; authors react to absence
with a `timeout` continuation or a negated pattern over the response schema
bounded by `within` ([LCRS.7.1]).

*see also:* [LCRS.7.1](#LCRS-7-1), [LCRS.7.3](#LCRS-7-3)

(NCBK-6-6)=
[NCBK.6.6] **NULL callback is ESSENTIAL** — a `call` with no callback returns
`DS_ERR_STORAGE_UNAVAILABLE` through pump.

(NCBK-6-7)=
[NCBK.6.7] **Neither cooldown nor supersede is the integrator's.** The engine
suppresses a call inside its cooldown window ([LCRS.8.2]), and retracts the
prior response fact and `CallError` ([LCRS.6.2.1]), before the call reaches the
call callback. When the integrator asserts an answer, the engine retracts the
earlier live answer with the same correlation first ([LCRS.6.2.4]). A
response's lifetime is its schema's TTL ([LCRS.6.6.1]): the integrator asserts a
response with `ds_engine_assert` and supplies no TTL of its own.

*see also:* [LCRS.6.2.1](#LCRS-6-2-1), [LCRS.6.2.4](#LCRS-6-2-4), [LCRS.6.6.1](#LCRS-6-6-1), [LCRS.8.2](#LCRS-8-2)

(NCBK-6-8)=
[NCBK.6.8] Errors via the pending slot: NULL cb →
`DS_ERR_STORAGE_UNAVAILABLE`; a NaN `Float` argument →
`DS_ERR_NAN_REJECTED`, and nothing is issued ([IDSP.6.3]); a non-OK callback
result propagates verbatim.

A kwarg whose value is `null` prevents the call ([LNUL.11.1]): the engine emits
no `ACTION_CALL`, invokes no callback and reports no status, the firing's other
actions run, and `ds.calls.arg_error_total{service}` counts it ([NMET.4.1]).

A call's arity and argument types are the compiler's guarantee, so no status
reports them. A call whose operands its op does not admit is an `EngineError`
`ENGINE_FAULT_ARTEFACT_LIED`, and the tier halts ([RDSC.4a.9.3]).

*see also:* [IDSP.6.3](#IDSP-6-3), [LNUL.11.1](#LNUL-11-1), [NMET.4.1](#NMET-4-1), [RDSC.4a.9.3](#RDSC-4a-9-3)

(NCBK-6-9)=
[NCBK.6.9] `DS_EV_ACTION_CALL` fires before the callback is invoked, carrying the
same `{ service, correlation, args, arg_count, timetag, rule_name }`. It fires whether or not the
callback succeeds, and whether or not one is registered; a failure is the returned
status ([NCBK.1.5]).

---

*checks:* `idris×8`  —  *see also:* [NCBK.1.5](#NCBK-1-5)

(NCBK-6-10)=
[NCBK.6.10] **Arguments are typed.** Each argument is `{ name, kind, value }`:
`name` is the kwarg's name, `kind` a call-argument kind (`ds_arg_kind_t`,
[NFCT.2.7]), and `value` the member of `ds_arg_value_t` that kind names. A
`Json` argument is a parsed tree, as a `Json` slot value is ([NFCT.2.4]).

A kwarg whose value is a fact ([LADP.8.6.1]) is an argument of kind
`DS_ARG_ENCODED_FACT`: the bound fact's `FactExternal` encoding ([RFCS.23.1]) as
a byte string and its length, and beside them the fact's schema name and
`asserted_at` ([RFCS.23.5]), so the integrator can route the fact without
reading inside it. Nothing else is lifted out of the encoding. The integrator
may forward the bytes without decoding them; another tier's engine asserts them
through `ds_engine_assert_external` ([NCBK.10.4]).

A kwarg with no value prevents the call ([LNUL.11.1]), so no call callback
receives `DS_ARG_NULL`. `ds_arg_kind_t` holds the member because it holds every
common kind ([NFCT.2.7]).

*ratified*  —  *see also:* [LADP.8.6.1](#LADP-8-6-1), [LNUL.11.1](#LNUL-11-1), [NCBK.10.4](#NCBK-10-4), [NFCT.2.4](#NFCT-2-4), [NFCT.2.7](#NFCT-2-7), [RFCS.23.1](#RFCS-23-1), [RFCS.23.5](#RFCS-23-5)

(NCBK-7)=
## Cache surface [NCBK.7]

(NCBK-7-1)=
[NCBK.7.1] **The engine owns the cache** ([LSTO.4.7]); the integrator does not
provide it. `cached()` reads the engine's own in-engine map — there is **no
cache-read callback.** The only cache callbacks are **optional write-through
persistence hooks**: `cache_set` / `cache_delete` that carry a write onward to an
external store so the cache survives a restart. NULL ⇒ a volatile in-engine cache
(the write still mutates the engine's cache; nothing is persisted).

The callback types are `ds_cache_set_cb_t` and `ds_cache_delete_cb_t`, declared in `runtime/include/libds.h`. Unlike every other area both are registered in one call, `ds_engine_cache_callbacks`, rather than by a setter each. What each hook receives and when it fires is [NSTG.2.4].

*see also:* [LSTO.4.7](#LSTO-4-7), [NSTG.2.4](#NSTG-2-4)

(NCBK-7-2)=
[NCBK.7.2] **One setter, two persistence callbacks, one shared `user`** —
`ds_engine_cache_callbacks(engine, abi_version, set_cb, delete_cb, user)`. The
same external-store handle backs both, so they share context. The setter keeps
the name `ds_engine_cache_callbacks` (no `set_` prefix): the two persistence ops
are one durability surface, not independent registrations.

The caller passes the `DS_CACHE_CB_ABI_VERSION` it compiled against, which is
`3` in this edition. A mismatch is refused with `DS_ERR_BACKEND_ABI_VERSION`
and registers nothing, so a caller built against a header with other callback
signatures is never invoked with an argument it does not expect ([NCBK.7.4]).
The value is append-only ([STYL.2.8.7]): a change to either callback's
signature takes the next number, and no number is reissued.

*ratified*  —  *see also:* [NCBK.7.4](#NCBK-7-4)

(NCBK-7-3)=
[NCBK.7.3] **The persistence callbacks are OPTIONAL, independently.** A NULL
`set_cb` / `delete_cb` is not an error — the corresponding write still mutates
the engine's cache; it is simply not persisted (a volatile cache, [LSTO.4.3.2]).
An integrator that wants durability wires both; one wired and one NULL persists
only that op. Registering neither (the default) is a fully working volatile
cache. `cached()` reads work regardless — they never touch a callback.

*see also:* [LSTO.4.3.2](#LSTO-4-3-2)

(NCBK-7-4)=
[NCBK.7.4] **Lifetime / ownership:**

- `set_cb`: the engine has already applied the write to its own cache; it then
  hands you a `const ds_cache_write_t *`, borrowed for the callback, carrying the
  `key`, the `value` and the `ttl_ns` ([NSTG.2.3]). The struct and the value it
  points to are a **borrow for the callback only** (freed after you return), so
  you can persist the write. Inspect the value via `ds_json_get_path` / the
  `ds_json_*` accessors; copy whatever you persist. Do not retain either pointer.
- `delete_cb`: the entry has already left the engine's cache; persist the
  removal to the external store. It receives a `const ds_cache_removal_t *`,
  borrowed for the callback, carrying the `key` and the `reason` it left: an
  explicit `cache_delete` or a passed TTL deadline ([NSTG.2.4.2]).

*see also:* [NSTG.2.3](#NSTG-2-3), [NSTG.2.4.2](#NSTG-2-4-2)

(NCBK-7-5)=
[NCBK.7.5] Errors via the pending slot: a NULL persistence callback is **not** an
error (the write lands in the engine's cache and skips persistence); a write
that would breach a cache bound → `DS_ERR_CONTRACT_BREACH`, with a
`DS_EV_BOUNDS_ERROR`, and the cache is unchanged and the firing stops
([LSTO.4.7.5]); a non-OK result from a wired persistence callback propagates
verbatim — the engine's cache is already mutated, so a persistence failure is
reported, not rolled back (rolling back would make cache state depend on external
success, [LSTO.4.7.2]).

A value the write cannot store is a trap, not a status: a value over one of the
`Json` limits ([LGRA.5.8.6]), a non-finite `Float` in the value ([LCST.4.5.2]),
or a deadline outside the `Time` range ([LTIM.1.1.5]) abandons the activation
at the write with a `NOT_REPRESENTABLE` `ComputationError`, and the cache is
never touched ([LERR.1.4.10]).

The TTL and the value need no other check. A TTL is a `Duration`, which is never
negative ([LTIM.1.3.1]), and the value is the engine's own serialization.

*ratified*  —  *see also:* [LCST.4.5.2](#LCST-4-5-2), [LERR.1.4.10](#LERR-1-4-10), [LGRA.5.8.6](#LGRA-5-8-6), [LSTO.4.7.2](#LSTO-4-7-2), [LSTO.4.7.5](#LSTO-4-7-5), [LTIM.1.1.5](#LTIM-1-1-5), [LTIM.1.3.1](#LTIM-1-3-1)

(NCBK-7-6)=
[NCBK.7.6] Stream events: `DS_EV_ACTION_CACHE_SET` / `_CACHE_DELETE` fire after
the engine applies the write to its cache (independent of any persistence
callback). `DS_EV_ACTION_CACHE_GET` is **not emitted** — a `cached()` read
is a pure internal read ([LSTO.4.7.1], [RARC.5.7.9]), like a working-memory read,
and does not surface as an action event ([NCBK.2.4]).

---

*see also:* [LSTO.4.7.1](#LSTO-4-7-1), [NCBK.2.4](#NCBK-2-4), [RARC.5.7.9](#RARC-5-7-9)

(NCBK-9)=
## Hydration [NCBK.9]

*Deferred: not binding in this edition.*

*checks:* `tla`

(NCBK-9-1)=
[NCBK.9.1] Hydration injects facts from historical / external data into working
memory. It **rides on the call surface** (LHYD.2.1). A rule's RHS issues a `call` against an adapter's
`hydrate_*` endpoint; the call callback ([NCBK.6]) does the query and asserts
each row as a normal fact.

*see also:* [LHYD.2.1](#LHYD-2-1), [NCBK.6](#NCBK-6)

(NCBK-9-2)=
[NCBK.9.2] When `request->service` is a hydration endpoint
(an adapter's `hydrate_*` service), the call callback:

1. Reads the query from the arguments ([NCBK.6.10]) — the schema or sample
   source, the window, the limit, a `filter:` where the endpoint accepts one
   ([LHYD.8.1]) — and the `retain` argument, the duration the hydrated facts
   live ([LHYD.6.2]).
2. Queries the history backend.
3. Asserts each result with the call's correlation as its `corr` ([LHYD.4.1.7])
   and the `retain` duration as its TTL: a stored fact through
   `ds_engine_assert_external`, passing the correlation and the duration
   ([NCBK.10.4]); any other row through `ds_engine_assert_with_ttl`,
   with `corr` set.
4. Asserts the call's response fact, a `HydrationComplete` carrying the same
   correlation ([LHYD.5.1]); rules match it to learn the hydration ended.

*see also:* [LHYD.4.1.7](#LHYD-4-1-7), [LHYD.5.1](#LHYD-5-1), [LHYD.6.2](#LHYD-6-2), [LHYD.8.1](#LHYD-8-1), [NCBK.10.4](#NCBK-10-4), [NCBK.6.10](#NCBK-6-10)

(NCBK-9-3)=
[NCBK.9.3] The request is audited by
`DS_EV_ACTION_CALL`, and each hydrated row (and `HydrationComplete`) is a normal
`DS_EV_FACT_ASSERT`.

---

(NCBK-10)=
## Cross-tier publish bridging [NCBK.10]

(NCBK-10-1)=
[NCBK.10.1] **A published fact crosses as a `FactExternal`.** To propagate
`publish`ed facts to sibling engines across processes or machines:

1. Subscribe to the stream callback.
2. On `DS_EV_ACTION_PUBLISH`, take the event's `FactExternal` encoding
   ([RFCS.23.1]) — the bytes and their length — and copy them before the
   callback returns.
3. Ship them over any transport.
4. On the receiving engine, call `ds_engine_assert_external` with them
   ([NCBK.10.4]).

The bytes are self-describing; the integrator neither decodes nor re-encodes
them.

Where a failed allocation ([NERR.4]) kept the engine from building the encoding,
the event still arrives, with `external` null and `external_len` 0, and nothing
crosses.

*see also:* [NCBK.10.4](#NCBK-10-4), [NERR.4](#NERR-4), [RFCS.23.1](#RFCS-23-1)

(NCBK-10-2)=
[NCBK.10.2] Gate on `ACTION_PUBLISH`, not `FACT_ASSERT`: `emit` asserts and is
local-only; `publish` asserts nothing here and is the "this fact crosses tiers"
marker.

(NCBK-10-3)=
[NCBK.10.3] **An `event_id` stays on its engine.** The engine stamps every
`FactAssert` with its own `event_id` ([LFST.5.6]), a fact bridged from another
tier included, and offers no way to assert a fact under an `event_id` from
outside. An integrator bridging tiers does not carry `event_id`s across. To let
a tool or a rule recognise one fact on both tiers, the author declares an
identifying slot on the published schema and fills it ([LFST.7.2.4]).

---

*see also:* [LFST.5.6](#LFST-5-6), [LFST.7.2.4](#LFST-7-2-4)

(NCBK-10-4)=
[NCBK.10.4] **`ds_engine_assert_external(engine, bytes, len)`** asserts a
`FactExternal`, a published fact from another tier. The engine checks its
`schema_hash`, decodes it, and resolves its fact references as [RFCS.23.7]
states. Each fact it asserts gets this engine's own `event_id` ([NCBK.10.3])
and takes its lifetime from the receiving schema ([RFCS.23.6]).

The engine must refuse the whole `FactExternal`, asserting nothing, with:

| Status | When |
|---|---|
| `DS_ERR_PARSE` | the bytes are not a `FactExternal`, a text field at any depth holds U+0000 ([LSTR.1.5]) or is not well-formed UTF-8, a `Json` field's text does not parse, or its references nest deeper than [RFCS.23.4] allows |
| `DS_ERR_SCHEMA_UNKNOWN` | it names a schema the program does not declare |
| `DS_ERR_SCHEMA_HASH_MISMATCH` | its `schema_hash` differs from the program's schema of that name ([RFCS.23.3]) |
| `DS_ERR_FACT_REF_CONFLICT` | a nested reference meets a live fact with the same identity key and different values ([RFCS.23.7]) |
| `DS_ERR_SLOT_TYPE_MISMATCH` | a field's kind is not its slot's, a reference names another schema than its slot's ([NFCT.2.3]), `KIND_NULL` is in a slot not declared `T?` that holds no fact reference ([LNUL.3.1], [RFCS.23.7]), or a `Json` field's document is `null` at its root, in any slot: a `null` slot travels as `KIND_NULL` ([RFCS.23.4], [LNUL.3.4]) |
| `DS_ERR_NAN_REJECTED` | a `Float` field is a NaN ([LEXP.4.2]) |
| `DS_ERR_JSON_LIMIT` | a `Json` field is over one of its limits ([LGRA.5.8.6]) |
| `DS_ERR_TIME_RANGE` | a `Date` field is outside its range ([LTIM.1.2.2]), a fact's TTL deadline would fall outside the `Time` range ([RFCS.6.7]), or the call's sample would give a held seed a deadline outside it ([NLFC.9.5]) |
| `DS_ERR_INVAL` | a `TimeZoneOffset` fact it holds is malformed ([LTIM.10.9]) |
| `DS_ERR_CONTRACT_BREACH` | a field's value is longer than its slot's `capacity` ([LSTR.11.3]) |

Each holds at any depth. The engine must judge every row before the first assert
and before it takes the call's sample, so a refused call is not a step
([LTIM.2.8.4]). The status is the whole refusal: the engine records no event for
it, a `BoundsError` included ([RFCS.24.1]). `capacity` is outside `schema_hash`
([RFCS.23.3]), so two tiers can declare one slot with different capacities.

**Between its first assert and its last, only a failed allocation ([NERR.4]) or
a halt an assert raises ([LERR.1.4.7]) can stop a delivery.** The call returns
that status ([NCBK.2.9]) and the engine asserts nothing more. The engine must not
take back a fact it has already asserted: the stream has delivered its event.
After a failed allocation those facts stay live and the engine runs on. After a
halt the engine's state is what [LERR.1.4.7] says. A non-OK status from the
stream callback stops nothing ([NCBK.1.5]).

**A `FactExternal` is trusted input** ([RDSC.9.9]).
The integrator **must** accept one only from a tier it trusts, and the engine
does not examine it for malicious construction. The engine still refuses every
record the table above names, whatever its bytes, and is never corrupted by
one ([RDSC.9.9]).

*ratified*  —  *see also:* [LEXP.4.2](#LEXP-4-2), [LGRA.5.8.6](#LGRA-5-8-6), [LNUL.3.1](#LNUL-3-1), [LNUL.3.4](#LNUL-3-4), [LSTR.1.5](#LSTR-1-5), [LTIM.1.2.2](#LTIM-1-2-2), [NFCT.2.3](#NFCT-2-3), [RDSC.9.9](#RDSC-9-9), [RFCS.23.3](#RFCS-23-3), [RFCS.23.4](#RFCS-23-4), [RFCS.23.6](#RFCS-23-6), [RFCS.23.7](#RFCS-23-7), [NCBK.10.3](#NCBK-10-3), [LERR.1.4.7](#LERR-1-4-7), [LSTR.11.3](#LSTR-11-3), [LTIM.10.9](#LTIM-10-9), [LTIM.2.8.4](#LTIM-2-8-4), [NCBK.1.5](#NCBK-1-5), [NCBK.2.9](#NCBK-2-9), [NERR.4](#NERR-4), [NLFC.9.5](#NLFC-9-5), [RFCS.24.1](#RFCS-24-1), [RFCS.6.7](#RFCS-6-7)

(NCBK-11)=
## Samples-plane callbacks [NCBK.11]

(NCBK-11-1)=
[NCBK.11.1] Persisted series (`persist:` > 0) surface two callbacks; both are
specified under NSTG / NSBK and summarised here for the registry:

- **`sample_cb`** fires once per absorbed sample on a persisted series. NULL =
  silent drop (alarm on `ds.samples.dropped_total{reason="no_cb"}`). A non-OK
  return does not propagate to rules; it emits
  `ds.samples.dropped_total{reason="cb_error"}`.
- **`series_declared_cb`** fires once per persisted series at DSC-load time so
  the integrator can pre-provision backend storage. NULL = lazy-create from the
  first sample.

Series **backend** registration is not a callback, and v1 accepts no
integrator-supplied backend at all — see [NSBK.2.3].

---

*Deferred: not binding in this edition.*

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

(NCBK-12)=
## Registration ordering [NCBK.12]

(NCBK-12-1)=
[NCBK.12.1] Recommended startup order:

1. `ds_engine_new`
2. `ds_engine_clock_set_mode` if mocking
3. **Register all callbacks** before any work begins
4. Load rules and schemas (`ds_engine_load_dsc`)
5. Begin asserting and pumping

(NCBK-12-2)=
[NCBK.12.2] Callbacks registered after work starts miss earlier events. Register
early so the subscriber sees a complete history.

(NCBK-12-3)=
[NCBK.12.3] Each callback area registers through its own `ds_engine_set_<area>_callback`, named in that area's clause and declared in `runtime/include/libds.h`. The setters are not enumerated here; a second copy of the header's own list drifts and nothing reconciles it.

One area departs from the pattern. Cache persistence ([NCBK.7]) registers both
callbacks in one call, `ds_engine_cache_callbacks`, rather than one setter each.

*see also:* [NCBK.7](#NCBK-7), [NCBK.9](#NCBK-9)

