# Dispatcher contract — verbs, callbacks, stream events

libds's action-verb dispatch layer. For each DS action verb the dispatcher must:

- Receive the verb's RHS arguments as typed values from
  the Rete action adapter.
- Run the verb's primary effect (assert a fact, route
  to an integrator callback, emit telemetry, etc.).
- Emit the matching `DS_EV_ACTION_*` stream event after
  the primary effect succeeds.
- Surface errors via the engine pending slot per
  [IARC.1.12] / [IARC.2.3].

This doc is the runtime-side dual of [NCBK].
That doc tells integrators *what they can register*;
this doc tells the libds implementation *what it must
do* with each registration.

## What this is not

- Not a tutorial. See [NCBK] for the
  integrator's view.
- Not a compiler-side lowering spec. The DS source
  text → action-atom lowering is per
  [RLOW];
  this doc picks up where a rule's RHS fires an action.

---

(IDSP-1)=
## Cross-cutting rules [IDSP.1]

(IDSP-1-1)=
[IDSP.1.1] **One adapter per verb.** Each action verb is
routed by the Rete action adapters
(`engine_rete_adapters.c`). At engine startup
`ds_engine_wire_rete_adapters` installs one `bridge_<verb>`
callback per verb into the engine's
`ds_rete_adapter_config_t` (via `ds_rete_register_adapters`);
when a rule's RHS fires verb `X`, the Rete evaluator invokes
`bridge_X`. The integrator-supplied callbacks themselves
live in the per-engine `ds_dispatcher_state_t` table
(`call_cb`, the
`cache_*_cb`s); each bridge reads the matching one and
invokes it.

(IDSP-1-2)=
[IDSP.1.2] **Typed arguments — no trampoline.** There is no
builtin trampoline and no argument-by-index decode. The Rete
evaluator produces each action's arguments as typed values
and hands the adapter a request struct (e.g.
`ds_rete_call_request_t { service, correlation, args, arg_count }`);
the bridge forwards them as the typed C parameters of the
public callback request type and of `ds_dispatcher_<verb>`.
Arg arity and types are fixed by the `Action` the compiler
emits in the rule's `TerminalNode` atom ([RDSC.4a.8]), not
re-validated at dispatch.

*see also:* [RDSC.4a.8](#RDSC-4a-8)

(IDSP-1-3)=
[IDSP.1.3] **Error stash, not return.** The Rete eval path
runs an action for its side effects and discards the result
value, so a verb's `ds_result_t` cannot return up the eval
stack. Essential-verb failures — and unregistered essential
callbacks — are stashed on the engine pending slot via
`ds_engine_set_pending`; `ds_engine_pump`
drains it with `ds_engine_take_pending` after `ds_rete_run`
and returns the first error to its caller. Observational
verbs (log) deliberately do not stash — their
failure leaves the pump `DS_OK`.

*ratified*

(IDSP-1-4)=
[IDSP.1.4] **The engine's part decides; the integrator's does
not.** Every `DS_EV_ACTION_*` event is emitted once the engine's
own part of the verb has succeeded — its arguments decoded, its
write applied — and **before** any integrator callback the verb
invokes. A verb that fails in the engine emits no action event.
An integrator callback never decides whether the event is
emitted: not by failing, and not by being unregistered. Its
failure reaches the caller as the returned status ([NCBK.1.5]).

The recorded stream is therefore a function of the engine's
inputs, which a replay reproduces, and not of what the
integrator's callbacks answered, which it does not. A
subscriber's count of `DS_EV_ACTION_*` events matches the verbs
the engine carried out.

*ratified*  —  *see also:* [NCBK.1.5](#NCBK-1-5)

(IDSP-1-5)=
[IDSP.1.5] **NULL-callback policy is per-verb.** The
universal default is "silent drop, callback's
absence is not an error." Per-verb sections below
override this when the verb is essential
([IARC.1.14]) — e.g., `call` cannot silently drop
because the caller's rule expects a response fact.

*see also:* [IARC.1.14](#IARC-1-14)

(IDSP-1-6)=
[IDSP.1.6] **Pending-slot save/restore at re-entrant
boundaries.** Verbs that call back into libds (e.g.,
`emit` calls `ds_engine_assert`) must use the
save-and-restore pattern so first-error-wins is preserved
across sibling RHS actions. See `wm.c` for the canonical
implementation.

---

(IDSP-2)=
## ds-log [IDSP.2]

(IDSP-2-2)=
[IDSP.2.2] Dispatcher entry: `ds_dispatcher_log(engine,
level, rule_name, message)` — arguments arrive as typed
values:

| Arg | DS type | Notes |
|---|---|---|
| level    | `ds_log_level_t` | One of DEBUG / INFO / WARNING / ERROR / CRITICAL — bad value → `DS_ERR_INVAL` |
| category | String           | the rule / category name, verbatim |
| message  | String           | verbatim |

*ratified*

(IDSP-2-3)=
[IDSP.2.3] Primary effect: invoke
`ds_telemetry_emit_log(engine, &event)` with the
decoded `ds_log_event_t`. NULL log callback is silent
drop per [IARC.1.14] (log is non-essential). A registered
callback that returns an error does not fail the pump: log is
an observational verb, so its failure is not stashed and the
pump returns `DS_OK` ([IDSP.1.3]).

*ratified*  —  *see also:* [IARC.1.14](#IARC-1-14), [IDSP.1.3](#IDSP-1-3)

(IDSP-2-4)=
[IDSP.2.4] Stream event:
`ds_recorder_emit_action_log(engine, level, category, message)`
fires **before** the typed callback so a stream
subscriber sees the log even if the typed cb returns
an error. The
stream is the audit trail, the typed callback is the
routing. ACTION_LOG fires whether or not a typed log
callback is registered. ACTION_LOG does NOT fire on
arg-decode failures (bad level, wrong arg count) per
[IDSP.1.4].

*ratified*  —  *see also:* [IDSP.1.4](#IDSP-1-4)

(IDSP-3)=
## ds-emit [IDSP.3]

(IDSP-3-2)=
[IDSP.3.2] Action arguments: `(type-name, slot1, slot2, ...)`,
arriving as typed values:

| Arg | DS type | Notes |
|---|---|---|
| type-name | String | Look up the schema in the engine's schema registry |
| slot1..N  | per slot's declared DS type | Int/Float/String/Bool/Json; SCHEMA-ref returns DS_ERR_UNSUPPORTED until E6 |

*ratified*

(IDSP-3-3)=
[IDSP.3.3] Errors:
- Unknown schema: `DS_ERR_SCHEMA_UNKNOWN`
- Slot-arg count ≠ schema's slot count: `DS_ERR_INVAL`
- Wrong slot arg type: `DS_ERR_SLOT_TYPE_MISMATCH`
- JSON parse failure: `DS_ERR_PARSE`
- SCHEMA-ref slot type: `DS_ERR_UNSUPPORTED`

(IDSP-3-4)=
[IDSP.3.4] Primary effect: `ds_engine_assert(engine,
schema, values, n, &fact)`. Caller-owned JSON trees
parsed during decode are freed AFTER the assert (the
assert copies them into working-memory storage and does
not retain).

*ratified*

(IDSP-3-5)=
[IDSP.3.5] **An emit's stream events.** When a rule's `emit` asserts a fact, libds
**must** deliver an `ACTION_EMIT` stream event
(`proto/stream_event_kind.proto#StreamEventKind`) after that assert's `FACT_ASSERT`
event, inside the firing's `RULE_FIRE_BEGIN` … `RULE_FIRE_END`. The `ACTION_EMIT`
**must** carry the same fact the `FACT_ASSERT` carried. Each firing that emits delivers its
own pair. The order within one firing:

```
RULE_FIRE_BEGIN
FACT_ASSERT
ACTION_EMIT
...
RULE_FIRE_END
```

In libds the `FACT_ASSERT` comes from the working-memory listener and the `ACTION_EMIT`
from `ds_recorder_emit_action_emit`, later in the same call stack, with the same fact
wrapper.

*ratified*

(IDSP-4)=
## ds-publish [IDSP.4]

(IDSP-4-2)=
[IDSP.4.2] Action arguments: `(type-name, slot1, slot2, ...)`
— same shape as ds-emit.

(IDSP-4-4)=
[IDSP.4.4] Primary effect: none in working memory ([LTIE.4.3]). Once the values
are judged ([LTIE.4.8]), the dispatcher must record the publish action through
`ds_recorder_emit_action_publish`, carrying a view of the published fact and its
`FactExternal` encoding ([NCBK.10.1]).

*ratified*  —  *see also:* [LTIE.4.3](#LTIE-4-3), [LTIE.4.8](#LTIE-4-8), [NCBK.10.1](#NCBK-10-1)

(IDSP-4-5)=
[IDSP.4.5] Why a separate verb from ds-emit: the
ACTION_PUBLISH stream event is the cross-tier
replication marker. Cross-tier subscribers gate on
ACTION_PUBLISH (not every FACT_ASSERT) so they
forward only the facts the rule author marked for
propagation. See [NCBK.10].

*ratified*  —  *see also:* [NCBK.10](#NCBK-10)

(IDSP-4-6)=
[IDSP.4.6] **A publish's stream events.** When a rule's `publish` runs, libds **must**
deliver an `ACTION_PUBLISH` stream event
(`proto/stream_event_kind.proto#StreamEventKind`), inside the firing's
`RULE_FIRE_BEGIN` … `RULE_FIRE_END`, and **must not** deliver a `FACT_ASSERT` or an
`ACTION_EMIT` for it: a publish is not an emit. The order within one firing:

```
RULE_FIRE_BEGIN
ACTION_PUBLISH
...
RULE_FIRE_END
```

*ratified*

(IDSP-6)=
## ds-call [IDSP.6]

(IDSP-6-1)=
[IDSP.6.1] LCRS is authoritative here (see LCRS.3 + LCRS.7).
A call's correlation is its `as` value, or, for a call
with none, one generated per activation from the
engine's correlation counter ([LCRS.3.1], [LCCO.3.4]).
Either way it is evaluated before the dispatcher is
entered. Timeouts are adapter-side. The dispatcher does
not allocate correlation IDs, sweep deadlines, or
synthesise timeout responses.

*see also:* [LCCO.3.4](#LCCO-3-4), [LCRS.3](#LCRS-3), [LCRS.3.1](#LCRS-3-1), [LCRS.7](#LCRS-7)

(IDSP-6-2)=
[IDSP.6.2] Dispatcher entry: `ds_dispatcher_call(engine,
service, correlation, args, arg_count, cooldown_ns)` — arguments
arrive as typed values:

| Arg | DS type | Notes |
|---|---|---|
| service     | String | "domain.method" string from the lowered `call <domain>.<method>` |
| correlation | String | the call's `as` value, or the per-activation value generated for a call with none ([LCRS.3.1]); never `null` or empty; flows verbatim to the answer's `corr` slot |
| args        | typed arguments | one per kwarg the call supplies, sorted by name ([RLOW.7.3.1], [NCBK.6.10]) |

*see also:* [LCRS.3.1](#LCRS-3-1), [NCBK.6.10](#NCBK-6-10), [RLOW.7.3.1](#RLOW-7-3-1)

(IDSP-6-3)=
[IDSP.6.3] Primary effect, in this order:
1. Arguments arrive typed from the action adapter
   (`bridge_call`); no per-arg decode step. A NaN `Float`
   argument refuses the call with `DS_ERR_NAN_REJECTED`
   ([LEXP.4.2]).
2. The call supersedes its earlier answers ([LCRS.6.2.1]).
3. Emit `DS_EV_ACTION_CALL` with the request payload, before
   any callback ([IDSP.6.5], [IDSP.1.4]).
4. In a replay, invoke no callback ([IDSP.6.4]).
5. Look up the registered call callback. NULL →
   `DS_ERR_STORAGE_UNAVAILABLE` (the verb is a
   service request, storing a fact included, and the
   storage-unavailable category fits).
6. Construct a `ds_call_request_t { service,
   correlation, args, arg_count }`, encoding each fact
   argument as a `FactExternal` ([NCBK.6.10]), and
   invoke the typed callback. The integrator's cb does whatever the
   call needs (sync, async, deferred to a thread
   pool) and returns `ds_result_t`.
7. On cb error, propagate verbatim per IDSP.1.3.

*ratified*  —  *see also:* [IDSP.1.3](#IDSP-1-3), [IDSP.1.4](#IDSP-1-4), [IDSP.6.4](#IDSP-6-4), [IDSP.6.5](#IDSP-6-5), [LCRS.6.2.1](#LCRS-6-2-1), [LEXP.4.2](#LEXP-4-2), [NCBK.6.10](#NCBK-6-10)

(IDSP-6-4)=
[IDSP.6.4] **NULL callback policy: ESSENTIAL.** NULL-cb returns
`DS_ERR_STORAGE_UNAVAILABLE` (not `DS_ERR_ACTION_FAILED`
— that code is reserved for "cb ran but reported
failure"). A calling rule that registered no call
callback gets a pump-time error.

A replay is the exception. It hands no re-derived call to the call callback
([LFST.9.2], [NDET.8.2]), so a replaying engine with none raises no error for
it.

*ratified*  —  *see also:* [LFST.9.2](#LFST-9-2), [NDET.8.2](#NDET-8-2)

(IDSP-6-5)=
[IDSP.6.5] Stream event: `DS_EV_ACTION_CALL` once the
arguments evaluate, **before** the typed callback runs. Payload
carries `{ service, correlation, args, arg_count }`. An argument
that fails to evaluate, or is refused (a NaN, [LEXP.4.2]), does NOT
emit `ACTION_CALL`; the callback's outcome, and whether one is
registered, do not decide it, per [IDSP.1.4].

*ratified*  —  *see also:* [IDSP.1.4](#IDSP-1-4), [LEXP.4.2](#LEXP-4-2)

(IDSP-6-6)=
[IDSP.6.6] **No engine-side per-call deadline.** Per
LCRS.7.3, adapters time out, not the engine.
Authors who care about adapter latency write
absence matchers over the response schema
([LCRS.7.1]). The engine never synthesises a
response fact or a `CallError`; the integrator asserts
them via `ds_engine_assert` when the external operation
completes or fails, and never from inside the callback
([NCBK.6.4], [RARC.13.16]).

*see also:* [LCRS.7.3](#LCRS-7-3), [LCRS.7.1](#LCRS-7-1), [NCBK.6.4](#NCBK-6-4), [RARC.13.16](#RARC-13-16)

(IDSP-6-7)=
[IDSP.6.7] **No correlation table.** The correlation
string ([IDSP.6.1]) flows through to the
response fact's `corr` slot per LCRS.3 and is
matched by sibling rules via standard rule
patterns. The engine does not maintain an in-
flight-calls table. Supersede-on-correlation
([LCRS.6.2.1]) needs none: it is a sweep of
working memory by `corr` that the engine runs
while evaluating the call, before the dispatcher
is entered ([RLOW.7.3.8]).

*see also:* [IDSP.6.1](#IDSP-6-1), [LCRS.3](#LCRS-3), [LCRS.6.2](#LCRS-6-2), [LCRS.6.2.1](#LCRS-6-2-1), [RLOW.7.3.8](#RLOW-7-3-8)

(IDSP-6-8)=
[IDSP.6.8] Cooldown ([LCRS.8]) is enforced engine-side. The compiler lowers
`cooldown: <DUR>` on a `call` to an inline `FN_RATE_ALLOW` gate inside the
`ACTION_CALL` action's `expr` in the rule's `TerminalNode` atom ([RDSC.4a.8]),
as [IRET.25.5.1] lays out; the engine tracks the window per call site and key ([LCRS.8.2])
and the gate suppresses the call when it has not elapsed. An integrator does not implement cooldown in the call
callback.

*see also:* [IRET.25.5.1](#IRET-25-5-1), [LCRS.8](#LCRS-8), [LCRS.8.2](#LCRS-8-2), [RDSC.4a.8](#RDSC-4a-8)

(IDSP-7)=
## ds-cache-{get,set,delete} [IDSP.7]

(IDSP-7-2)=
[IDSP.7.2] Forms — `cache-get` is a value-returning read
(expression position), served **from the engine's own
in-engine cache map** ([LSTO.4.7], no callback);
`cache-set` / `cache-delete` are statement actions
(`ds_dispatcher_cache_set` / `ds_dispatcher_cache_delete`)
that mutate the engine's cache and optionally persist it:

```
cache-get(key)                      → JSON-text on hit, null on miss
cache-set(key, value-json, ttl-ns)  ; ttl-ns 0 = no expiry
cache-delete(key)
```

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

(IDSP-7-3)=
[IDSP.7.3] Args (typed values from the adapter):

| Verb | Arg | DS type |
|---|---|---|
| cache-get    | key        | String |
| cache-set    | key        | String |
|              | value      | String (JSON-text) |
|              | ttl_ns     | Int (≥0) |
| cache-delete | key        | String |

(IDSP-7-4)=
[IDSP.7.4] The read path has **no callback** — the engine
answers `cache-get` from its own map. `cache-set` /
`cache-delete` first mutate the engine's cache, then route
to **two optional write-through persistence callbacks**
registered as a bundle with one shared user pointer:

The setter keeps the name `ds_engine_cache_callbacks` (no
`set_` prefix): the two persistence ops are one durability
surface. `runtime/include/libds.h` gives its signature.

(IDSP-7-5)=
[IDSP.7.5] **NULL callback policy: OPTIONAL, per-op.** The
persistence callbacks are not essential — a NULL `set_cb`
/ `delete_cb` is not an error. The verb still mutates the
engine's cache; the write is simply not persisted (a
volatile cache, [LSTO.4.3.2]). An integrator wires either,
both, or neither; `cache-get` needs no callback at all. No
cache verb ever returns `DS_ERR_STORAGE_UNAVAILABLE`.

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

(IDSP-7-6)=
[IDSP.7.6] Stream events:
- `DS_EV_ACTION_CACHE_GET` is **not emitted** — a
  `cache-get` is a pure internal engine read
  ([RARC.5.7.9]), reserved-but-not-emitted ([NCBK.2.4]).
- `DS_EV_ACTION_CACHE_SET` after the engine applies the
  write to its cache (independent of any persistence
  callback); payload `{ key, value, ttl_ns }`.
- `DS_EV_ACTION_CACHE_DELETE` after the engine removes the
  key; payload `{ key }`.

Failed verbs do NOT emit (per [IDSP.1.4]).

**A TTL expiry emits nothing.** `DS_EV_ACTION_CACHE_DELETE`
denotes the *verb* — a rule acting — and no rule acts when a
deadline passes. The expiry sweep ([NSTG.2.4.2]) therefore
fires `delete_cb` and emits no stream event, which is not an
omission: the stream already records the clock, and expiry is
a function of the clock and a TTL both sides already have, so
replay re-derives it. Recording it would put a second source
of truth beside a derivable fact, and the two could disagree.

The asymmetry is worth stating plainly because it is easy to
trip over: a **callback** consumer sees every removal, a
**stream** consumer sees only the verb ones.

*ratified*  —  *see also:* [IDSP.1.4](#IDSP-1-4), [NCBK.2.4](#NCBK-2-4), [NSTG.2.4.2](#NSTG-2-4-2), [RARC.5.7.9](#RARC-5-7-9)

(IDSP-7-7)=
[IDSP.7.7] cache-get rule-visible return. Unlike the other
verbs, `cache-get` is a value-returning read used in
expression position (a `let` / bind), not a statement:
- Hit (the key is present in the engine's cache): the
  engine returns its stored value as JSON-text (a String),
  so `let v = cached("key")` binds the JSON-text and `v`
  is usable anywhere a String is.
- Miss (the key is absent): the read yields `null` (absent,
  [LSTO.4.3.1a]) — it renders `""` under interpolation
  ([LGRA.2.9.6.2]) and propagates in a comparison.

cache-get is the only verb that returns a value into the
rule; the statement verbs (log, emit, publish,
call, cache-set, cache-delete) produce no
expression result.

*see also:* [LGRA.2.9.6.2](#LGRA-2-9-6-2), [LSTO.4.3.1a](#LSTO-4-3-1a)

(IDSP-7-8)=
[IDSP.7.8] Lifetime:
- get: no allocation crosses a boundary — the engine
  serializes its own stored value into the rule.
- set_cb (persistence, optional): the engine has already
  stored the value; it then hands the value to the
  integrator as a borrow for the callback's duration and
  frees it after the callback returns.

(IDSP-7-9)=
[IDSP.7.9] Errors are [NCBK.7.5]'s. The dispatcher adds two
defensive refusals no compiled program reaches, each `DS_ERR_INVAL`:
a negative TTL, and a value that is not JSON text. The
interpreted path makes them where the author's value is
still visible, in the cache-set adapter, and the
ahead-of-time slot makes them on entry, so the two paths
agree on identical input.

*see also:* [NCBK.7.5](#NCBK-7-5)

(IDSP-7-10)=
[IDSP.7.10] A conforming implementation must exercise the engine-owned-cache
contract: a volatile-cache round-trip (set, then `cached()` returns the
JSON-text with **no** callback wired); a miss returning FALSE
distinguishably from a hit; the optional persistence callbacks invoked on
set / delete when wired and skipped without error when NULL;
`ACTION_CACHE_SET` / `_DELETE` firing on the engine write while
`ACTION_CACHE_GET` is not emitted; per-verb arity / type rejection; negative
ttl and bad JSON rejected; and a wired persistence callback's error
propagating without rolling back the engine cache.

---

*ratified*

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

*Deferred: not binding in this edition.*

(IDSP-9-1)=
[IDSP.9.1] Hydration is delivered by the `ds-call` verb plus the integrator
call callback. Per [LHYD.2.1], hydration is
invoked **on the RHS** as a normal `call` action against an adapter's
`hydrate_*` endpoint, whose `retain:` arrives as an argument ([RLOW.7.3.1]).

*see also:* [LHYD.2.1](#LHYD-2-1), [RLOW.7.3.1](#RLOW-7-3-1)

(IDSP-9-2)=
[IDSP.9.2] No new dispatcher infrastructure is needed. The integrator's call
callback (registered via `ds_engine_set_call_callback`, [IDSP.6]) handles
`hydrate_facts` and `hydrate_samples`, or any adapter's
`hydrate_*` service ([LHYD.2.3.1]), and asserts what it finds as [NCBK.9.2]
states: each result with the call's correlation as its `corr` and the `retain`
duration as its TTL, then a `HydrationComplete` ([LHYD.5.1]). Stored facts
enter through `ds_engine_assert_external` ([NCBK.10.4]); no dispatcher state is
held between the call and the results.

*see also:* [IDSP.6](#IDSP-6), [LHYD.2.3.1](#LHYD-2-3-1), [LHYD.5.1](#LHYD-5-1), [NCBK.10.4](#NCBK-10-4), [NCBK.9.2](#NCBK-9-2)

(IDSP-9-3)=
[IDSP.9.3] **NULL callback policy** is the call cb's
NULL policy: returns `DS_ERR_STORAGE_UNAVAILABLE` per
IDSP.6.4 because the calling rule expects a response.

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

(IDSP-9-4)=
[IDSP.9.4] **A hydration emits `DS_EV_ACTION_CALL`.** That
`DS_EV_ACTION_CALL` (emitted from D6) is the
audit marker for the hydration request itself; each
hydrated row arrives as a normal `FACT_ASSERT`
event; `HydrationComplete` is itself a `FACT_ASSERT`.

(IDSP-13)=
## FN_JSON_VALUE [IDSP.13]

(IDSP-13-2)=
[IDSP.13.2] Form: `FN_JSON_VALUE(value)` — one argument, returning a String
that holds the value's JSON text.

| Arg | DS type | Notes |
|---|---|---|
| value | any | Per [IDSP.13.4] type mapping |

*see also:* [IDSP.13.4](#IDSP-13-4)

(IDSP-13-3)=
[IDSP.13.3] **Purpose.** The compiler wraps the value of every `cache` action in
`FN_JSON_VALUE` (RLOW.7.4), whatever the expression, literal or runtime
([LSTO.4.2.1]). The cache wire is JSON text ([IDSP.7]), and this builtin
produces it. A literal takes the same path as any other value, so there is one
encoding to keep right.

*see also:* [IDSP.7](#IDSP-7), [LSTO.4.2.1](#LSTO-4-2-1)

(IDSP-13-4)=
[IDSP.13.4] **Value type mapping.** The engine must render `FN_JSON_VALUE`'s argument
as this table gives:

| DS value | JSON text |
|---|---|
| `null` | `null`: a `null` is stored, not refused ([LNUL.11.1]) |
| `Int` | a JSON number, the integer in decimal |
| `Float`, finite | a JSON number, in the canonical form of [LDET.3.2.7] |
| `Bool` | `true` or `false` |
| `String` | a JSON string: `"` and `\` escaped, `\n` `\r` `\t` for those three, `\u00XX` for any other character below U+0020, and every other character as itself |
| `Time` | a JSON number, the instant's UTC nanoseconds since the Unix epoch |
| `Date` | a JSON number, the days since 1970-01-01 |
| `Duration` | a JSON number, the nanoseconds |
| `Json` | the JSON text [LGRA.5.8.7a] gives the document |

**A value with no JSON form is refused.** A non-finite `Float`, a `Bytes` value,
a fact reference and a `Ratio` have none. For each, the engine must raise a
`ComputationError` of kind `NOT_REPRESENTABLE` ([LERR.1.4.9]) and abandon the
activation, so the `cache` write does not happen. It must not write a
placeholder, `null` included. A non-finite `Float` is also the hard error
[LDET.3.2.7] names for the JSON data plane.

*see also:* [LDET.3.2.7](#LDET-3-2-7), [LERR.1.4.9](#LERR-1-4-9), [LGRA.5.8.7a](#LGRA-5-8-7a), [LNUL.11.1](#LNUL-11-1)

(IDSP-13-5)=
[IDSP.13.5] **NULL-callback policy:** N/A — pure builtin.

(IDSP-13-6)=
[IDSP.13.6] **Other failures** are `EngineError`s and halt the tier
(`proto/engine_fault.proto#EngineFault`):
- A call with no argument is the artefact disagreeing with the arity it
  declares: `ENGINE_FAULT_ARTEFACT_LIED`. The compiler always passes one.
- An allocation failure while the text is built: `ENGINE_FAULT_ALLOCATION`.

(IDSP-10)=
## Implementation responsibilities table [IDSP.10]

(IDSP-10-1)=
[IDSP.10.1] What every verb implementation must wire
up. Use as a checklist when adding a verb.

| Step | Concrete action |
|---|---|
| Register adapter | Wire `bridge_<verb>` into `ds_rete_adapter_config_t` in `ds_engine_wire_rete_adapters`; `ds_rete_register_adapters` installs it on the Rete engine. |
| Receive args | The bridge receives typed values in the verb's request struct (e.g. `ds_rete_call_request_t`); no per-arg decode. Arity / type are fixed by the `Action` in the rule's `TerminalNode` atom ([RDSC.4a.8]). |
| Look up callback | Read `engine->dispatcher.<verb>_cb` and `<verb>_user`. NULL handling per the verb's policy ([IDSP.2] silent drop vs [IDSP.6-8] essential). |
| Invoke primary effect | Call the typed callback (or run inline if local-only). Save/restore pending slot if the effect re-enters libds (assert/retract). |
| Emit stream event | Once the engine's own part of the verb succeeds, and before any callback, call `ds_recorder_emit_action_<verb>` ([IDSP.1.4]). A verb whose engine part fails does NOT emit; the callback's outcome does not decide it. |
| Surface errors | Essential-verb failures stash via `ds_engine_set_pending` (the bridge's `essential_fail`); `ds_engine_pump` drains and returns them after `ds_rete_run`. |
| Add a public setter | `ds_engine_set_<verb>_callback` (or `_callbacks` for cache). Lives in `dispatcher.c`. Stores into `engine->dispatcher.<verb>_cb / _user`. |
| Update `ds_dispatcher_state_t` | Add the `<verb>_cb` and `<verb>_user` fields in `dispatcher.h`. Init to NULL in `ds_dispatcher_init`. |
| Add a stream-event union member | If it carries a typed payload (e.g., `ds_call_request_t`-shaped event), add to `ds_stream_ev`'s union in `libds.h`. |
| Add a recorder helper | `ds_recorder_emit_action_<verb>` in `recorder.{h,c}`. |
| Write per-verb test | `test_dispatcher_<verb>` covering registration, decode happy-path, NULL-cb policy, error paths, callback-error propagation. |
| Update `test_action_events` | New scenario verifying the verb emits ACTION_<verb> once its engine part succeeds, whatever the callback answers, and not when its engine part fails. |

---

*see also:* [IDSP.1.4](#IDSP-1-4), [IDSP.2](#IDSP-2), [IDSP.6](#IDSP-6), [RDSC.4a.8](#RDSC-4a-8)

(IDSP-11)=
## Dispatcher commitments [IDSP.11]

(IDSP-11-2)=
[IDSP.11.2] **cache-delete event payload: carries
the key.** `DS_EV_ACTION_CACHE_DELETE`'s payload is
`{ key }`, matching libds.h's `action_cache_delete`
union member and dispatcher.c.

(IDSP-11-3)=
[IDSP.11.3] **A hydration is audited through the existing events.**
`DS_EV_ACTION_CALL` (emitted from D6, [IDSP.9.4]) is the
audit marker for the hydration request; per-row hydrated facts arrive as
normal `FACT_ASSERT` events; `HydrationComplete` is
itself a `FACT_ASSERT`.

*Deferred: not binding in this edition.*

*see also:* [IDSP.9.4](#IDSP-9-4)

(IDSP-11-4)=
[IDSP.11.4] **Cache callbacks: one setter, two optional
persistence callbacks.**
`ds_engine_cache_callbacks(engine, set_cb, delete_cb,
user)` ([IDSP.7.4]). The engine owns the cache state and
read path ([LSTO.4.7]); the set / delete callbacks are optional
write-through persistence hooks, NULL ⇒ a volatile
in-engine cache.

---

*see also:* [IDSP.7.4](#IDSP-7-4), [LSTO.4.7](#LSTO-4-7)

(IDSP-14)=
## ds_dispatch_t — arch-specific code dispatch table [IDSP.14]

*Deferred: not binding in this edition.*

*checks:* `alloy×4`

(IDSP-14-1)=
[IDSP.14.1] `ds_dispatch_t` is a fixed C struct that
provides compiled RHS functions (`CompiledCode` atoms) with direct
access to the dispatcher entry points (the same
`ds_dispatcher_<verb>` functions the Rete action adapters
call).  Its field layout matches the slot
table embedded at the front of every `CODE_KIND_RHS` blob
body (RAOT.6); the `CompiledCode` atom loader populates the in-blob
slot table by copying live function addresses from
`engine->dispatch_table` at mmap time.

*see also:* `RAOT.6`

(IDSP-14-2)=
[IDSP.14.2] The table is the entire boundary between compiled RHS code and
the engine. Six VERB entry points, and nothing else a blob can effect: assert into
working memory, publish, call a service, set a cache entry, delete one, log.
Slot 5 is reserved: it holds no entry and its number is never reissued
([STYL.2.8.7]). The membership of that list is therefore a **capability
list** -- anything outside it is not merely unimplemented for compiled code,
it is unreachable from it.

**Slot 7 is not a verb, and the table is one entry longer than the capability
list.** `fmt_float` is a formatting service the engine lends to compiled code:
the freestanding AOT `.text` carries no libc, so the generated C routes every
float render through it. It performs no effect, reaches no registry and
is observable only in a string the caller already owns, so it is inside the ABI
and outside the capability list. The two counts differ by exactly this entry and
that is deliberate — a blob can *format* without being able to *do* anything.

Two properties keep the boundary stable. Every entry takes the engine as its
first argument and reports through the universal result type, so a blob holds
no state of its own. And the things it names -- a schema, a cache key, a
service -- cross as **names** rather than as resolved handles, so a blob
carries no pointer into a registry and needs to know nothing about how one is
laid out.

The slot numbering is not commentary. It is the contract with the slot table
at the front of the blob itself ([IDSP.14.1], [IDSP.14.3]).

```c
typedef struct ds_dispatch_t {
    /* Slot 0 */ ds_result_t (*wm_assert)      (struct ds_engine *,
                                 const char *schema_name,
                                 ds_rete_val_t *slots,
                                 uint32_t slot_count,
                                 bool is_logical,
                                 ds_rete_token_t *justifier);
    /* Slot 1 */ ds_result_t (*publish)        (struct ds_engine *,
                                 const char *schema_name,
                                 ds_rete_val_t *slots,
                                 uint32_t slot_count);
    /* Slot 2 */ ds_result_t (*call)           (struct ds_engine *,
                                 const char *service,
                                 const char *correlation,
                                 const ds_arg_t *args,
                                 uint32_t    arg_count,
                                 uint64_t    cooldown_ns);
    /* Slot 3 */ ds_result_t (*cache_set)      (struct ds_engine *,
                                 const char *key,
                                 const char *value_json,
                                 int64_t     ttl_ns);
    /* Slot 4 */ ds_result_t (*cache_delete)   (struct ds_engine *,
                                 const char *key);
    /* Slot 5 */ void        *reserved5;      /* reserved — no entry */
    /* Slot 6 */ ds_result_t (*log)            (struct ds_engine *,
                                 ds_log_level_t  level,
                                 const char     *rule_name,
                                 const char     *message);
    /* Slot 7 */ void        (*fmt_float)      (char *buf, size_t cap,
                                 double v);   /* NOT a verb — see above */
} ds_dispatch_t;
```

*see also:* [IDSP.14.1](#IDSP-14-1), [IDSP.14.3](#IDSP-14-3)

(IDSP-14-3)=
[IDSP.14.3] **Field order is load-bearing.**  The table
has eight slots, 0–7, and their order must match RAOT.6 exactly; slot 7 is a
formatting service, not an action verb ([IDSP.14.2]).  Any change to
field order or count is a breaking change requiring a
minor release ([LDET.1.10]) and recompilation of all `CompiledCode`
atom blobs.

*checks:* `alloy×3`  —  *see also:* [IDSP.14.2](#IDSP-14-2), [LDET.1.10](#LDET-1-10), `RAOT.6`

(IDSP-14-4)=
[IDSP.14.4] **Initialisation.** The table is filled in `ds_engine_new`,
by `ds_dispatcher_init_dispatch_table(engine)`.

(IDSP-14-5)=
[IDSP.14.5] `ds_dispatch_t` is stored by value in
`ds_engine_t` (not a pointer).  Its address is stable
for the engine's lifetime and is passed by const pointer
to every compiled RHS function.

(IDSP-14-6)=
[IDSP.14.6] **No separate registration step.**
`ds_dispatch_t` is not a plugin table.  All eight
functions are first-party dispatcher entry points that
exist unconditionally.  Integrators do not add to or
replace entries in `ds_dispatch_t`; integrator callbacks
are wired through the existing per-verb callback tables
(IDSP.5–9), which the dispatcher entry points call into.

