# Storage: wiring backends through the typed callbacks

How an integrator wires a storage backend (SQLite,
Redis, Postgres, an in-process map, an HA-recorder
DB, anything) into libds via the cache callbacks and the
sample callbacks.
Pairs with the language-side contract
([LSTO])
which describes what authors see; this doc is what
the integrator implements.

The libds surface is callback-only — there is no
embedded storage backend, no wire to a storage adapter,
no protobuf. Each integrator picks a backend that
fits their deployment and writes a thin adapter
between libds's typed callbacks and the backend's
API.

## What this is not

- Not a backend recommendation. Pick whatever fits
  your deployment.
- Not a backend implementation. libds doesn't
  ship one.
- Not the language-side surface. See LSTO for the
  three-plane model + author contract.
- Not a runtime implementation guide for the planes.
  Code under `runtime/src/libds/` documents itself
  via the public header (`libds.h`) and the
  contract docs (`IDSP`, `IARC`); this doc covers
  the integrator-facing surface.

---

(NSTG-1)=
## The three planes [NSTG.1]

(NSTG-1-1)=
[NSTG.1.1] Per LSTO.1 the language commits to three
storage planes, each tuned to a different question. The facts and samples
planes are deferred ([NSTG.3], [NSTG.5]); in this edition the libds wiring is
the cache plane's:

| Plane | Question | libds callback | Loss semantics |
|---|---|---|---|
| **Cache**   | "what is the current value?"    | engine-owned ([LSTO.4.7]); `ds_engine_cache_callbacks` (C3) is **optional** write-through persistence | in-session must-not-lose (engine); cross-restart via the optional hook |

*see also:* [LSTO.1](#LSTO-1), [LSTO.4.7](#LSTO-4-7), [NSTG.3](#NSTG-3), [NSTG.5](#NSTG-5)

(NSTG-1-2)=
[NSTG.1.2] Cache dispatches through the dispatcher ([IDSP.7]). The series
aggregation backends are a separate surface, specified under NSBK: libds ships
every one, and an integrator registers none ([NSBK.2.3]).

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

(NSTG-1-3)=
[NSTG.1.3] **Hydration crosses planes.** Per LHYD,
`call hydrate_facts` brings stored facts back
into working memory; `call hydrate_samples`
does the same for samples. Hydration rides on the
call callback. See §NSTG.5.

---

*Deferred: not binding in this edition.*

*see also:* [NSTG.5](#NSTG-5)

(NSTG-2)=
## Cache plane (C3) [NSTG.2]

(NSTG-2-1)=
### Setter [NSTG.2.1]

(NSTG-2-1-1)=
[NSTG.2.1.1] **The engine owns the cache** ([LSTO.4.7]); `cached()`
reads engine-resident memory with no callback. The setter registers
only the **optional** write-through persistence hooks — `set_cb` /
`delete_cb` — so a `cache` write survives a restart.

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

(NSTG-2-1-2)=
[NSTG.2.1.2] The two cbs share one user pointer — typically a
backing-store handle. A NULL `set_cb` / `delete_cb` is **not** an
error: the write still lands in the engine's cache and is simply not
persisted (a volatile cache, [LSTO.4.3.2]). Registering neither (the
default) is a fully working volatile cache.

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

(NSTG-2-2)=
### The read path — no callback [NSTG.2.2]

(NSTG-2-2-1)=
[NSTG.2.2.1] **`cached()` reads engine memory.** The rule uses
`let v = cached("key")`; the engine answers from its own in-engine
cache ([LSTO.4.7.1]) — there is **no get callback**. The read is
synchronous and cannot block or fail for want of a registered
callback; per LSTO.1.1 it is still the **only** sync storage
affordance.

*see also:* [LSTO.1.1](#LSTO-1-1), [LSTO.4.7.1](#LSTO-4-7-1)

(NSTG-2-2-2)=
[NSTG.2.2.2] **Hit / miss.** On a hit the engine returns its stored
value to the rule as JSON-text (usable anywhere a String is,
IDSP.7.7). On a miss the read yields `null` (absent, [LSTO.4.3.1a]) —
it renders `""` under interpolation and propagates in a comparison; a
miss is never an error, and never `DS_ERR_STORAGE_NOT_FOUND`.

*see also:* [IDSP.7.7](#IDSP-7-7), [LSTO.4.3.1a](#LSTO-4-3-1a)

(NSTG-2-3)=
### set_cb [NSTG.2.3]

Fires **after** the engine has applied a cache write, so the integrator
can persist it. It is a write-*through* notification, not a write
authority: the engine's own cache is already updated when the callback
runs, and returning an error does not undo it ([LSTO.4.7]).

It receives the engine, a `const` pointer to the write, and the `user`
pointer registered alongside it, the shape every registered callback has
([NCBK.1.1]). The write is a payload struct, borrowed for the callback's
duration, with these members:

| Member | Meaning |
|---|---|
| key | the cache key written |
| value | the value, as a parsed JSON tree — **borrowed for the callback's duration only** |
| ttl_ns | the entry's lifetime in nanoseconds; **zero means no expiry** |

The value being borrowed is the contract most easily got wrong: an
integrator that needs it after returning must copy it. Registering no
callback at all is legal and leaves the cache purely volatile.

The payload struct is `ds_cache_write_t` and the callback signature is
`ds_cache_set_cb_t`, both declared in `runtime/include/libds.h`. A member a
later edition adds to the struct appends to it and breaks no registration,
as [NSTG.2.4] gives the reason for the delete callback's payload.

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

(NSTG-2-3-1)=
[NSTG.2.3.1] **Borrowed tree.** The engine has already applied the
write to its own cache; it then hands the value tree to the cb so you
can persist it. The cb serializes it into the backing store (JSON,
msgpack, blob) or walks it directly. After the cb returns, libds frees
the tree. **Do not retain `value` past callback return.**

(NSTG-2-3-2)=
[NSTG.2.3.2] **TTL semantics.** `ttl_ns == 0` means no expiry: the
entry lives until an explicit `cache_delete`, and nothing else removes
it. A write that would breach the cache cap fails rather than making
room ([RTCT.7.1]), so a capped cache never evicts to accept a new key.
Non-zero means *expire after this duration*. The engine tracks the deadline for its own cache; a
persistence cb should mirror it into the backing store (set the
store's TTL field, schedule eviction) so a hydrate re-seeds a
consistent view. A hydrate seeds each entry with the lifetime it has left,
which counts from the new engine's first sample ([NLFC.9.4]).

*see also:* [NLFC.9.4](#NLFC-9-4), [RTCT.6.8](#RTCT-6-8), [RTCT.7.1](#RTCT-7-1)

(NSTG-2-3-3)=
[NSTG.2.3.3] **Persistence failure is reported, not rolled back.** A
NULL `set_cb` is a volatile cache (the write lands in the engine,
nothing persists) — not an error. A wired `set_cb` that returns
`DS_ERR_STORAGE_*` propagates to the calling rule, but the engine's
cache is **already** mutated and is not rolled back ([LSTO.4.7.2]) —
rolling back would make cache state depend on external success.

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

(NSTG-2-4)=
### delete_cb — optional write-through persistence [NSTG.2.4]

The deletion counterpart of [NSTG.2.3], and **optional independently of
it**: an integrator may persist writes without persisting deletes,
though the result is a store that outlives its keys.

It receives the key and **why the key is gone** — there is no value,
because the entry has already left the engine's cache by the time the
callback runs. As with the setter, this is notification rather than
authority: returning an error does not restore the entry.

**Both exits notify.** An entry leaves the cache by an explicit
`cache_delete` or by its TTL elapsing ([NSTG.2.4.2]), and each fires this
callback — so it means *this key is gone from the engine's cache*, not
*someone called the delete verb*. An integrator therefore receives
deletions never requested, including for entries their own store may
already have expired, so **the delete path must be idempotent**
([NSTG.2.4.1]).

| Reason | What happened | What a persisting store should do |
|---|---|---|
| the delete verb | a rule asked for it | drop the row |
| TTL expiry | the value is no longer valid | drop the row |

**A full cache refuses the write.** A write that would breach `cap_keys` or `cap_bytes` **fails**, and the
cache is left unchanged ([RTCT.7.1]) — the engine does not make room by
dropping something else. So no entry is ever removed for want of space,
and the callback has no such reason to carry.

That is a determinism property rather than an implementation detail.
[LDET.2.1] lists what a run depends on — compiled rule set, event trace,
adapter contract, starting state, platform signature — and memory
pressure is not among them. A cache that evicted under pressure would
make the same event trace produce different output depending on how full
it was, which is exactly the input the guarantee cannot admit. Failing
the write keeps the pressure visible and the run reproducible.

The reason enum is `ds_cache_removal_reason_t`, the payload struct is
`ds_cache_removal_t`, and the callback signature is
`ds_cache_delete_cb_t` — all declared in `runtime/include/libds.h`.

**The reason arrives in a payload struct rather than a fourth
parameter.** Adding an argument breaks every existing registration, and
so would the next reason after these two; a `const` payload pointer
matches the shape of every registered callback ([NCBK.1.1]), and absorbs a
third reason without breaking a registration. The set callback's payload is a
struct for the same reason ([NSTG.2.3]).

**Registration is version-gated.** The registering call carries a
callback-ABI version ([NCBK.7.2]), and a mismatch is refused with
`DS_ERR_BACKEND_ABI_VERSION` rather than accepted. This is not
ceremony: an integrator built against a header whose callbacks take other
arguments would be handed a struct pointer where it expects a `const char *`,
and would read it as a string. Refusing the registration is what turns that
from a silent misread into an error at the point of wiring.

*ratified*  —  *see also:* [LDET.2.1](#LDET-2-1), [NCBK.1.1](#NCBK-1-1), [NCBK.7.2](#NCBK-7-2), [NSTG.2.3](#NSTG-2-3), [NSTG.2.4.1](#NSTG-2-4-1), [NSTG.2.4.2](#NSTG-2-4-2), [RTCT.7.1](#RTCT-7-1)

(NSTG-2-4-1)=
[NSTG.2.4.1] The engine has already removed the key from its own
cache; the cb persists the removal to the backing store. Idempotent:
deleting a missing key returns `DS_OK`, not `DS_ERR_STORAGE_NOT_FOUND`.
A NULL `delete_cb` is a volatile delete (engine only), not an error; a
wired cb's failure is reported, not rolled back ([NSTG.2.3.3]).

*see also:* [NSTG.2.3.3](#NSTG-2-3-3)

(NSTG-2-4-2)=
[NSTG.2.4.2] **Expiry happens at a defined instant: the sweep at pump
entry.** A pass over the cache removes every entry past its deadline and
fires `delete_cb` for each, alongside the fact-TTL sweep that runs at the
same point ([NTST.3.4]).

The alternative — expiring an entry only when something next reads it —
cannot satisfy [NSTG.2.4], and the failure is in exactly the case the
callback exists for: a key written once, its TTL elapsing, nothing ever
reading it again. Under lazy expiry that entry never leaves, its callback
never fires, and a persisting store holds the row for ever. Lazy expiry
does not remove the drift; it makes the drift depend on read traffic.

A read encountering an expired entry must still not return it, so the
read path removes it as a backstop — **and fires the callback when it
does**. Without that, whether an integrator hears about an entry depends
on whether a reader or the sweep reached it first, which is
non-determinism in an observable ([LDET.1.1]), not merely an
inconsistency.

Two consequences worth stating rather than discovering:

- **The order is: fact sweeps, then the cache sweep, then the run.**
  Both sweeps fire callbacks at pump entry, so which goes first is part
  of what an integrator sees, and it is fixed here rather than left to
  an implementation. Facts go first because the fact sweep changes what
  the rules about to run will match against; the cache sweep is
  notification-only and alters nothing the agenda sees, so running it
  first could only move callbacks earlier without changing any
  decision. **Both sweeps read the same instant** — one clock value for
  the whole of pump entry, so no entry can be live for one sweep and
  expired for the other.
- **The sweep costs pump time.** It walks up to the configured key cap
  every pump ([RTCT.7.1]), which the WCET bound must account for rather
  than absorb silently ([RTCT.12.1]).

The sweep is also what makes the behaviour testable: set a short TTL,
advance the clock past it, pump, observe the callback. Before it there
was no instant at which anything was obliged to happen.

*ratified*  —  *see also:* [LDET.1.1](#LDET-1-1), [NSTG.2.4](#NSTG-2-4), [NTST.3.4](#NTST-3-4), [RTCT.12.1](#RTCT-12-1), [RTCT.7.1](#RTCT-7-1)

(NSTG-2-4-3)=
[NSTG.2.4.3] **The removal reasons are the registry `specs/registry/cache_removal_reason.ebnf`.**
`ds_cache_removal_reason_t` must mirror it name for name and value for value.
A reason's stable name is its name without the `DS_CACHE_REMOVED_` prefix, in
lower case: `delete` for the delete verb, `ttl` for TTL expiry ([NSTG.2.4.2]).
A binding must name a reason by its stable name, and must name a value that is
not a member `unknown`.

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

(NSTG-2-5)=
### A complete cache integration [NSTG.2.5]

(NSTG-2-5-1)=
[NSTG.2.5.1] The default cache needs **no wiring at all** — omit the
setter and `cache` / `cached()` work against the engine's volatile
in-engine cache. Durability is opt-in: register `set_cb` and
`delete_cb` together via `ds_engine_cache_callbacks`, declared in
`runtime/include/libds.h`. On restart, the integrator seeds the engine
cache from the backing store with `ds_engine_cache_seed`, before the
engine's first stream event ([NLFC.9.1]).

*see also:* [NLFC.9.1](#NLFC-9-1)

(NSTG-2-5-2)=
[NSTG.2.5.2] The engine serves `cached()` itself. Production backings (Redis, the HA recorder DB,
SQLite) differ only in the persistence code; the libds contract —
argument types, lifetime rules, the volatile-on-NULL default — is
identical.

(NSTG-2-6)=
### Bounding the cache [NSTG.2.6]

(NSTG-2-6-1)=
[NSTG.2.6.1] `ds_engine_set_cache_cap(engine, cap_keys, cap_bytes)` sets
[LSTO.4.7.5]'s two bounds: `cap_keys` on the live keys and `cap_bytes` on the
total value bytes. `0` leaves that bound unset. The integrator should call it
before the artefact is loaded, and before any cache seed ([NSTG.9.1]) that the
bound is to count.

A later call is accepted. It binds the writes and seeds that follow it and
evicts nothing: a cache already past a new, lower bound keeps its entries, and
refuses each write of a new key until it is back under the bound. A call from
inside a callback is re-entry and is refused with `DS_ERR_STATE`, so a bound
never changes during a pump.

A rule's write past a bound is refused as [LSTO.4.7.5] states, and the
`ds_engine_pump` that ran it returns `DS_ERR_CONTRACT_BREACH`. A
`ds_engine_cache_seed` past a bound returns `DS_ERR_CONTRACT_BREACH` and stores
nothing. A null `engine` is `DS_ERR_INVAL`.

The bounds are a setting a replaying engine must be given as the recording one
had them, a later change included, between the same two inputs ([NDET.8.1]).

---

*ratified*  —  *see also:* [LSTO.4.7.5](#LSTO-4-7-5), [NDET.8.1](#NDET-8-1), [NSTG.9.1](#NSTG-9-1)

(NSTG-3)=
## Facts plane [NSTG.3]

*Deferred: not binding in this edition.*

(NSTG-3-1)=
### The write [NSTG.3.1]

A rule stores a fact by calling `record_fact` ([LSTO.2.2.1]), so the
facts plane rides on the call callback ([NCBK.6]). The call's one argument is the fact, of kind `DS_ARG_ENCODED_FACT`
([NCBK.6.10]). The store reads it back to the engine only through a hydration
([NSTG.4.3]).

*see also:* [LSTO.2.2.1](#LSTO-2-2-1), [NCBK.6](#NCBK-6), [NCBK.6.10](#NCBK-6-10), [NSTG.4.3](#NSTG-4-3)

(NSTG-3-1-1)=
[NSTG.3.1.1] A `call` with no callback registered returns
`DS_ERR_STORAGE_UNAVAILABLE` ([IDSP.6.4]), so a program that stores facts on an
engine with no call callback fails loudly rather than dropping the write.

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

(NSTG-3-2)=
### What the store keeps [NSTG.3.2]

The store keeps each record as the bytes it received and never decodes or
rewrites them ([LSTO.2.1]). Beside each it keeps what it selects by: the schema
name and `asserted_at`, the instant the fact entered working memory. The
argument carries both beside the bytes ([NCBK.6.10]), so the store indexes
without reading inside the record.

The store must keep every record it is given. It must not merge, replace or
drop a record because another resembles it: a fact recorded twice is two
records, and a hydration returning both is resolved by the engine
([RFCS.23.7]).

A hydration selects by schema and by `asserted_at` within the window, up to the
limit, and returns the bytes unchanged ([NSTG.4.3]). An integrator that needs
to find records by content keeps a record of its own beside DS's, keyed to it.

*see also:* [LSTO.2.1](#LSTO-2-1), [NCBK.6.10](#NCBK-6-10), [NSTG.4.3](#NSTG-4-3), [RFCS.23.7](#RFCS-23-7)

(NSTG-3-2-1)=
[NSTG.3.2.1] **Success is silence; a lost write is a `CallError`.**
`record_fact` declares `no response` ([LSTO.13.1]): the callback returns
`DS_OK` and asserts nothing for a write it makes durable. For a write it cannot
make durable it must assert a `CallError` carrying the call's correlation,
whenever it learns of the failure ([LSTO.2.4.1], [LCRS.17.1]).

*see also:* [LCRS.17.1](#LCRS-17-1), [LSTO.13.1](#LSTO-13-1), [LSTO.2.4.1](#LSTO-2-4-1)

(NSTG-3-2-2)=
[NSTG.3.2.2] **Borrowed bytes.** The encoded fact's bytes, like every other
argument, are the dispatcher's and valid for the callback's duration
([NSTG.6.1]). The callback must copy what it keeps before it returns.

*see also:* [NSTG.6.1](#NSTG-6-1)

(NSTG-3-2-4)=
[NSTG.3.2.4] **Must-not-lose.** The callback must not drop a record
silently. A backend that cannot make a write durable at once (a network store, a
transient outage) may queue it and retry; a write it gives up on, a full queue
included, is a lost write and is reported as one ([NSTG.3.2.1]).

*see also:* [NSTG.3.2.1](#NSTG-3-2-1)

(NSTG-3-3)=
### A complete storage integration [NSTG.3.3]

Guidance, not a required shape, on top of [NSTG.3.2]'s obligations: keep
the backing-store handle behind the registered `user` pointer rather
than a global, copy the borrowed bytes before returning, index by the
`asserted_at` the argument carries rather than a wall-clock reading taken at
write time, and report an I/O failure as an error result (`DS_ERR_IO`) rather
than swallowing it.

*see also:* [NSTG.3.2](#NSTG-3-2)

(NSTG-3-3-1)=
[NSTG.3.3.1] More common backends: SQLite (one row
per record), an OpenTelemetry log pipeline, an HA
recorder DB extension, an object store. The shape
is the same — the cb's job is to make the record
durable per the backend's contract.

---

(NSTG-4)=
## Hydration via D6+C2 [NSTG.4]

*Deferred: not binding in this edition.*

(NSTG-4-1)=
[NSTG.4.1] Per LHYD, hydration is invoked on the RHS
as a normal `call` action (`call hydrate_facts
schema: ... window: 24_h as "..."`). It rides on the
existing call callback registered via
`ds_engine_set_call_callback`.

(NSTG-4-2)=
[NSTG.4.2] The integrator's call cb dispatches by
service prefix; storage-hydration handlers live next\nto other call handlers.

(NSTG-4-3)=
[NSTG.4.3] **Hydration writes facts back into the engine.** The handler
selects the matching records and asserts each, in ascending `asserted_at`
order, with the call's correlation as its `corr` and the call's `retain` duration as its TTL ([NCBK.9.2]): a stored
fact by handing its bytes to `ds_engine_assert_external` unchanged
([NCBK.10.4]), a sample as a `HydratedSample` ([LHYD.4.3.1]) via
`ds_engine_assert_with_ttl`. It then asserts the call's `HydrationComplete`
([LHYD.5.1]).

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

(NSTG-4-4)=
[NSTG.4.4] **Async hydration.** For backends with
non-trivial query latency, the cb queues the work
onto its own runtime and returns DS_OK without
asserting. The hydrated facts arrive later when the
queued work completes; the integrator's runtime then
calls `ds_engine_assert` from the pump thread. Same
async-marshal-back-to-pump-thread caveat as the
general call pattern.

(NSTG-4-5)=
[NSTG.4.5] **Per-emit TTL.** Per LHYD, the call's
`retain: 10_min` clause caps a hydrated fact's lifetime
regardless of the schema's default ttl_ns. Assert each
hydrated row with `ds_engine_assert_with_ttl`, passing the call's
retain budget as `ttl_ns_override`; the engine retracts
the row at the per-emit deadline (LHYD.6.2 /
LHYD.10.5.1) even on a LOGICAL schema. A `0` override
falls back to the schema default.

---

*see also:* [LHYD.10.5.1](#LHYD-10-5-1), [LHYD.6.2](#LHYD-6-2)

(NSTG-5)=
## Samples plane (C6 + C7) [NSTG.5]

*Deferred: not binding in this edition.*

(NSTG-5-1)=
[NSTG.5.1] The samples plane forwards each absorbed series
sample to an integrator-supplied callback per [LSER.8.3].
Two callbacks compose:

- **C6 — sample emission.** Fires once per absorbed sample
  during fact assertion, after the firing decision lands
  per [LSER.8.6].
- **C7 — series declaration.** Fires at DSC load time
  once per persisted series (i.e., series with `persist:`
  declared), giving the integrator the manifest needed to
  provision backend storage before any sample arrives.

Both callbacks are independent. An integrator may register
neither (NULL = silent drop matching drop-oldest framing),
one, or both. C7 is for backends that need pre-arrival
setup — relational TSDB hypertables, retention policies,
column-type validation. Without it, the integrator's C6 cb
learns about `(schema, slot)` pairs lazily as samples
arrive (which works for client libraries that auto-create
metrics on first observation: Prometheus, InfluxDB).

*see also:* [LSER.8.3](#LSER-8-3), [LSER.8.6](#LSER-8-6)

(NSTG-5-2)=
### Sample setter [NSTG.5.2]

Registers the **C6** sample callback ([NSTG.5.3]) and the user pointer
handed back on every invocation. One per engine; registering again
replaces. Registering none is legal and drops samples silently, matching
the drop-oldest framing of a bounded backing.

Independent of the declaration callback ([NSTG.5.4]) — either may be
registered without the other.

*see also:* [NSTG.5.3](#NSTG-5-3), [NSTG.5.4](#NSTG-5-4)

(NSTG-5-2-1)=
[NSTG.5.2.1] Single setter. NULL cb is permitted and means
"silent drop" matching [LSTO.3.5]'s drop-oldest framing.
Operators monitor sample loss via the
`ds.samples.dropped_total{schema, slot, reason="no_cb"}`
metric.

*see also:* [LSTO.3.5](#LSTO-3-5)

(NSTG-5-3)=
### Sample callback [NSTG.5.3]

Fires **once per absorbed sample**, during fact assertion and after the
firing decision has landed ([LSER.8.6]) — so a sample is delivered only
when the assertion that produced it survived, never speculatively.

Each sample identifies itself fully, so a receiver needs no prior state:

| Field | Meaning |
|---|---|
| schema_name / slot_name | which declared series this belongs to |
| identity_slot_name / identity_value | which series instance — **both empty under `by: none`**, where the series is not partitioned |
| ts_ns | the engine clock at absorption |
| value | the sampled value, typed to match the slot |

Two things follow. The empty-identity convention means a receiver must
treat empty as *unpartitioned* rather than as a missing field. And
because the timestamp is the **absorption** instant from the engine
clock, samples stay correctly ordered and replay-reproducible however the
integrator batches the writes.

The callback signature will be `ds_sample_cb_t` and the sample struct
`ds_sample_t`, declared in `runtime/include/libds.h` when this section binds.
Nothing declares them in this edition.

*see also:* [LSER.8.6](#LSER-8-6)

(NSTG-5-3-1)=
[NSTG.5.3.1] **Per-sample call.** One cb invocation per
absorbed sample. Engine-side batching is not provided;
integrator-side batching rides on the client library
(Prometheus / InfluxDB / TimescaleDB clients all batch
internally) or a hand-rolled buffer in the cb.

(NSTG-5-3-2)=
[NSTG.5.3.2] **Drop-oldest semantics.** Cb returning a
non-OK `ds_result_t` does not propagate to rules. The
dispatcher emits
`ds.samples.dropped_total{schema, slot, reason="cb_error"}`
and a log line carrying the cb's detail string; the rule
that triggered the sample-emitting fact assertion returns
`DS_OK`. Integrator backends that need durability handle
their own queueing or retry inside the cb.

(NSTG-5-3-3)=
[NSTG.5.3.3] **Caller-keeps-its-strings.** Strings inside
`ds_sample_t` are engine-interned per [NSTG.6.2]; valid for
the cb's duration only. The integrator copies before
retaining.

*see also:* [NSTG.6.2](#NSTG-6-2)

(NSTG-5-3-4)=
[NSTG.5.3.4] **`identity_slot_name` and `identity_value`
both empty** indicates a `by: none` series (one global
allocation per `(schema, slot, module)` per [LSER.7.6.2]).
Backends with named columns can route this to a special
"global" key; backends labelling by identity fold the
empty values into a `total` aggregation.

*see also:* [LSER.7.6.2](#LSER-7-6-2)

(NSTG-5-4)=
### Declaration setter [NSTG.5.4]

Registers the **C7** series-declaration callback ([NSTG.5.5]), which
fires at DSC load rather than at sample time.

It exists for backends needing setup *before* any sample arrives —
provisioning a hypertable, installing a retention policy, validating
column types. Without it an integrator still works, but learns of each
`(schema, slot)` pair lazily, when its first sample turns up.

*see also:* [NSTG.5.5](#NSTG-5-5)

(NSTG-5-4-1)=
[NSTG.5.4.1] Single setter. NULL cb is permitted and means
"no manifest"; the integrator falls back to lazy-create
from sample arrivals via [NSTG.5.3]. Most simple
integrations (Prometheus client, InfluxDB line protocol)
work fine without C7.

*see also:* [NSTG.5.3](#NSTG-5-3)

(NSTG-5-5)=
### Declaration callback [NSTG.5.5]

Fires at DSC load, **once per persisted series** — a series without
`persist:` never reaches this callback. It is the manifest a backend
needs to provision storage before the first sample arrives.

| Field | Meaning |
|---|---|
| schema_name / slot_name | which series is being declared |
| identity_slot_name | how it partitions; **empty under `by: none`**, matching [NSTG.5.3] |
| storage_mode | accumulator, or ring buffer |
| element_type | the element's type; always float for an accumulator |
| window_ns | the window; **zero means unwindowed** |
| persist_ns | the retention, always positive — it is what made this series persisted at all |

The storage mode is the field that decides provisioning: an accumulator
keeps one running value per instance, a ring buffer keeps a bounded
sequence, and those want different backing shapes. The enum is
deliberately open for future modes, so a receiver should reject an
unrecognised mode rather than assume one of the two.

The callback signature will be `ds_series_declared_cb_t`, the declaration
struct `ds_series_declaration_t`, and the storage-mode enum
`ds_series_storage_mode_t` (`DS_SERIES_ACCUMULATOR` /
`DS_SERIES_RING_BUFFER`), declared in `runtime/include/libds.h` when this
section binds. Nothing declares them in this edition.

*see also:* [NSTG.5.3](#NSTG-5-3)

(NSTG-5-5-1)=
[NSTG.5.5.1] **Fires at DSC load.** Each
`ds_engine_load_dsc` invocation fires C7 once per
persisted series in the loaded module, before any sample
emission for that module begins. Order within a module
follows [RDSC.8] emission order.

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

(NSTG-5-5-2)=
[NSTG.5.5.2] **Re-load semantics.** Re-loading a DSC fires
C7 again with the same metadata; the integrator's cb
idempotently re-creates state. Unloading a DSC does not
fire a separate signal in v1; integrators treat their
backend state as monotonic-add.

(NSTG-5-5-3)=
[NSTG.5.5.3] **Caller-keeps-its-strings.** Same as
[NSTG.5.3.3].

*see also:* [NSTG.5.3.3](#NSTG-5-3-3)

(NSTG-5-5-4)=
[NSTG.5.5.4] **The storage modes are the registry `specs/registry/series_storage_mode.ebnf`.**
`ds_series_storage_mode_t` must mirror it name for name and value for value. A
mode's stable name is its name without the `DS_SERIES_` prefix, in lower case:
`accumulator`, `ring_buffer`. A binding must name a mode by its stable name,
and must name a value that is not a member `unknown`.

(NSTG-5-6)=
### Loss semantics [NSTG.5.6]

(NSTG-5-6-1)=
[NSTG.5.6.1] Samples are drop-oldest per [LSER.8.3] /
[LSTO.3.5] / [LSTO.6.3]. The engine never propagates
sample-emission failures to rules; the only feedback loop
is via the `ds.samples.dropped_total` metric. Integrators
needing visibility into drop rates wire their metrics
callback (per the runtime's metric-emission surface) to
scrape or forward that counter.

*see also:* [LSER.8.3](#LSER-8-3), [LSTO.3.5](#LSTO-3-5), [LSTO.6.3](#LSTO-6-3)

(NSTG-5-6-2)=
[NSTG.5.6.2] **NULL sample cb is a config issue, not a
runtime contract violation.** A `persist:`-declared series
with no sample callback registered drops every sample
silently (modulo the metric). Operators should alarm on
`ds.samples.dropped_total{reason="no_cb"}` to catch
forgotten registration.

(NSTG-6)=
## Ownership + lifetime [NSTG.6]

(NSTG-6-1)=
[NSTG.6.1] Across all storage callbacks, the
ownership / lifetime rules:

| Pointer | Owner | Valid for |
|---|---|---|
| the write (`ds_cache_write_t`) on cache set | dispatcher | callback duration |
| `key` (cache) | dispatcher | callback duration |
| `value` on cache | dispatcher | callback duration |
| `removal` on cache delete | dispatcher | callback duration |
| Service, correlation and every argument (name and value, including an encoded fact's bytes) on call | dispatcher | callback duration |

(NSTG-6-2)=
[NSTG.6.2] **Caller-keeps-its-strings is the default.**
Strings and bytes the dispatcher hands the cb (key, service,
argument names and values, etc.) are engine-interned, valid for the
callback's duration. The integrator copies before
retaining.

(NSTG-6-3)=
[NSTG.6.3] **No storage callback transfers ownership.** Every tree and
string a storage callback receives — the cache key and value, a cache
removal, a `Json` call argument — is dispatcher-allocated and
dispatcher-freed; the callback borrows it for the call. `cached()` reads the
engine's own cache ([NSTG.2.2.1]), so no callback returns a value libds
takes.

---

*see also:* [NSTG.2.2.1](#NSTG-2-2-1)

(NSTG-7)=
## Errors [NSTG.7]

(NSTG-7-1)=
[NSTG.7.1] Per IERR.2.7 the storage code range:

| Code | Cause |
|---|---|
| `DS_ERR_STORAGE_UNAVAILABLE` | NULL cb registered (engine-emitted) OR backend unreachable from cb (integrator-emitted) |
| `DS_ERR_STORAGE_QUERY_FAILED` | backend executed the query but returned an error |
| `DS_ERR_STORAGE_NOT_FOUND` | backend reported "no such key" (distinguishable from generic NOT_FOUND) |

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

(NSTG-7-2)=
[NSTG.7.2] **Detail strings are advisory.** Pass
`DS_ERR_R(DS_ERR_STORAGE_QUERY_FAILED, "redis: connection refused")`
or similar; libds propagates the detail through the
pending slot. Authors write rules against the
status code; operators read the detail in logs.

(NSTG-7-3)=
[NSTG.7.3] **Cb-error propagation.** Per IDSP.1.3
the cb's `ds_result_t` flows verbatim through the
engine's pending slot. The calling rule's pump
returns the cb's status. The author can write a
sibling rule matching `CallError` or react to the rule-level error directly.

---

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

(NSTG-9)=
## Cache restore [NSTG.9]

(NSTG-9-1)=
[NSTG.9.1] **The seed is the read-back half of write-through persistence.** The
`ds_engine_cache_callbacks` write-through hooks ([NSTG.2.1.1], [LSTO.4.5.2])
mirror each `cache` write to a durable store so it survives a restart; they do
**not** read anything back. On the next startup the integrator restores the
saved entries into the fresh engine's cache with `ds_engine_cache_seed`
([IARC.12]) — one call per persisted `key` → `value`, before the engine's first
stream event ([NLFC.9.1]). The two are a matched pair: `set_cb` / `delete_cb` persist outward,
the seed hydrates inward.

Because they are a pair, every delete notification is one to act on: both
reasons the callback can carry — the verb and TTL expiry ([NSTG.2.4]) — mean
the value is genuinely finished, so the store drops the row in each case and
the seed has nothing it should have restored.

That is only true because a cache write past its cap **fails** rather than
evicting ([LSTO.4.7.5]). Were it otherwise there would be a third reason meaning
*still valid, could not hold it*, and a store acting on it would destroy under
memory pressure precisely what the durable copy existed to survive.

*see also:* [IARC.12](#IARC-12), [LSTO.4.5.2](#LSTO-4-5-2), [LSTO.4.7.5](#LSTO-4-7-5), [NLFC.9.1](#NLFC-9-1), [NSTG.2.1.1](#NSTG-2-1-1), [NSTG.2.4](#NSTG-2-4)

(NSTG-9-2)=
[NSTG.9.2] **Restore is setup arrange, not replay.** A restored entry is starting
state, not a cache write ([RARC.5.7.10]): the seed emits no stream
event and drives no callback, so restoring the cache neither re-persists it nor
re-fires write-through. A recording carries each restored entry in its prelude
([RFCS.26.1]), so a replay starts from the restored cache without the
integrator restoring it again. The integrator parses each persisted JSON value to a
`ds_json_t` and passes it to the seed; the engine re-serialises canonically, so a
restored value is byte-identical to the value the running engine originally wrote
([IARC.12.2]).

*see also:* [IARC.12.2](#IARC-12-2), [RARC.5.7.10](#RARC-5-7-10), [RFCS.26.1](#RFCS-26-1)

