Engine lifecycle and the pump#
Engine create / destroy / pump conventions for integrators. Covers the async-first contract, multi-engine coexistence, and the mock clock. Companion to [NFCT] (asserting / observing facts) and [NCBK] (the action-verb surface).
What this is not#
Not a full API reference. Signatures live in
runtime/include/libds.hwith docstrings; this doc explains why each call exists and when to call it.Not the realtime doc. RT-mode configuration is [NRTM], which states per clause what binds.
Not a deployment guide. Production sizing and observability are integrator concerns out of scope.
Engine creation [NLFC.1]#
[NLFC.1.1] Creating an engine is the only allocation an integrator has to make explicitly. Everything else in libds hangs off the handle it returns.
The call takes a configuration ([NLFC.1.2]) and yields the handle through an out-parameter, because the return channel carries the status ([NLFC.7.1]). Read the handle only once that status says the call succeeded.
What comes back is a complete but empty engine: defaults chosen, no schemas, no rules, no callbacks registered, clock live ([NLFC.1.4]), and no state shared with any other engine in the process ([NLFC.1.3]). The caller owns it from here until teardown ([NLFC.6]).
see also: NLFC.1.2, NLFC.1.3, NLFC.1.4, NLFC.6, NLFC.7.1
[NLFC.1.2] ds_engine_config_t carries:
run_id— a string identifying the run this engine belongs to, orNULL.tier_id— a string identifying this engine's tier, orNULL.
run_id and tier_id are the integrator's. Either may be given without the
other, and an empty string is the same as NULL. The engine copies them at
ds_engine_new and reads them only to derive event_id ([LFST.5.6]) and to
record them in the stream header ([RFCS.4.3], [RFCS.4.4]); what they mean, and
whether they are unique, is the integrator's to decide. With neither given, an
event_id is distinguished by seq alone. ds_engine_get_run_id and
ds_engine_get_tier_id return them, NULL when absent.
Each must be well-formed UTF-8 ([LSTR.8.5]): the stream header
writes them as protobuf string fields, and event_id hashes their bytes.
ds_engine_new must refuse a run_id or tier_id that is not with
DS_ERR_ENCODING, and create no engine.
The struct is additive — new fields append; passing NULL selects all defaults.
ratified — see also: LFST.5.6, LSTR.8.5, RFCS.4.3, RFCS.4.4
[NLFC.1.3] Each ds_engine_t is wholly self-contained. Its subsystems — the
Rete network, schema registry, clock, working memory, telemetry — are
all per-engine. There is no global state in libds. You can instantiate as
many engines as you like in one process; they are fully independent ([NLFC.4]).
see also: NLFC.4
[NLFC.1.4] After ds_engine_new succeeds:
The engine is in live clock mode: its monotonic clock reads the host's monotonic clock and its wall clock the host's UTC clock ([LTIM.2.8.1]). Test harnesses switch to mock immediately ([NLFC.5]).
No callbacks are registered; stream events, metrics, and logs silently drop until you set them ([NCBK.1]).
No schemas or rules exist yet. Load them via
ds_engine_load_dsc— see [NFCT.1] and [NGST.4].
see also: LTIM.2.8.1, NCBK.1, NFCT.1, NGST.4, NLFC.5
The pump [NLFC.2]#
[NLFC.2.1] The pump is how rules fire. Until you call ds_engine_pump,
asserted facts sit in working memory and matched activations sit on the agenda
untouched.
[NLFC.2.2] ds_engine_pump takes the engine and nothing else, and runs the
agenda to exhaustion — every activation that can fire, fires — before it
returns. No argument bounds the work one pump does. A pump is an in-process call
on the integrator's own stack ([IARC.1.10]), so nothing outside it can stop it
part-way.
checks: tla×16 — see also: IARC.1.10
[NLFC.2.4] Pump returns ds_result_t:
DS_OK— pump completed; the agenda is drained.DS_ERR_INVAL— NULL engine.Other codes — an action verb fired during rule execution and stashed an error through the engine's pending slot (e.g. a
callwith no registered callback returnsDS_ERR_STORAGE_UNAVAILABLE; a type mismatch on a fact a rule's RHS asserted). The error is a one-shot report, and the engine remains functional ([NERR.15.1]).DS_ERR_ENGINE_HALTED— anEngineErrorhalted the tier during this pump or before it, and the engine refuses every later call but the few [NCBK.2.9] names.
See [NCBK] and [NERR].
Async-first: the integrator drives, libds never spawns [NLFC.3]#
[NLFC.3.1] libds ships zero threading primitives — no internally-spawned threads, no background timers, no thread-local state, no sleeping. The pump is the only place rules fire, and the integrator decides when it runs.
[NLFC.3.2] Integration patterns:
Pattern |
Pump call site |
|---|---|
Single-threaded async loop (asyncio, tokio, libuv, an event loop) |
A periodic timer plus event-driven nudges when new facts arrive. |
Dedicated worker thread |
A loop calling |
Thread pool, one engine per worker |
Fine — each engine is independent, no cross-engine state. |
CLI / one-shot |
Set up, assert inputs, single pump, read results, free. |
[NLFC.3.3] Constraints:
Pump is the only writer. Do not call
ds_engine_*functions concurrently on the same engine from multiple threads. libds does not lock; the integrator serialises externally. Concurrent pump + assert on one engine is undefined behaviour.Multiple engines in different threads is fine — each is independent.
Do not block inside callbacks. Callbacks fire on the pump thread; a blocking callback blocks the pump. Push discovered work onto a queue the runtime services later.
Do not call back into the engine that called you. A callback holds a live handle and runs on the pump's stack, so re-entry is easy to write by accident; every
ds_engine_*call on that engine returnsDS_ERR_STATE([RARC.13.16]). This covers reads as well as writes — a read mid-pump is a torn snapshot. The same holds inside the callback an enumerating read invokes once per item, such asds_engine_for_each_fact's visitor ([RARC.13.17]). Calling into a different engine is the intended cross-tier pattern and is fine.
checks: tla×6 — see also: RARC.13.16, RARC.13.17
[NLFC.3.4] libds provides no synchronous wrapper and no thread-lifecycle helper; the integrator supplies any thread management.
Multi-engine [NLFC.4]#
[NLFC.4.1] Multiple engines in one process is a first-class deployment — real integrators run several DS contexts simultaneously (per-tier, per-room). Each engine has its own Rete network, schema registry, clock (independently live or mocked), recorder / telemetry / callback registrations, and pump state.
[NLFC.4.2] Coordinating across engines is the integrator's concern. There is no
built-in pub/sub, fact replication, or shared state. To propagate facts between
engines, subscribe to the source engine's stream (gate on DS_EV_ACTION_PUBLISH),
encode the fact, and ds_engine_assert it on the destination ([NCBK.10]).
see also: NCBK.10
Mock clock for tests [NLFC.5]#
[NLFC.5.1] Time-driven behaviour (TTL retraction, dwell, cooldown,
a single pattern's within, series windows) reads the engine's monotonic
clock, and now() its wall clock ([LTIM.2.8.1]). A then … within sequence
reads neither: it compares its facts' ts values ([LTIM.2.8.2]). Live tests are flaky; deterministic
tests use the mock clock, which drives both.
see also: LTIM.2.8.1, LTIM.2.8.2
[NLFC.5.2] A test's first act after creating an engine should be to take the clock off live.
The engine starts in live mode ([NLFC.1.4]). The switch puts the monotonic clock at 0 and leaves the wall clock unset ([NLFC.5.4]), and the test then sets the timeline it wants explicitly ([NLFC.5.3]), so every time-driven effect is under its control from the first input on.
Switching later is refused: once the engine has sampled its clock, which an
input does and a pump does with no input, the switch to mock returns
DS_ERR_STATE ([NLFC.5.4]). Anything time-driven that ran
before it would have run against wall time and would not reproduce
([NLFC.5.1]).
see also: NLFC.1.4, NLFC.5.1, NLFC.5.3, NLFC.5.4
[NLFC.5.3] Drive time explicitly:
ds_engine_clock_set / _advance move the monotonic clock, _advance moves
the wall clock by the same interval, and ds_engine_wall_clock_set sets the
wall clock alone ([NTST.3.1]). All three return DS_ERR_STATE in live mode.
In live mode the wall clock comes from the host or, on a microcontroller, from
the board's optional wall-clock shim ([IARC.3.11.2]). An integrator gives a
clockless board its wall clock by implementing that shim, not by calling
ds_engine_wall_clock_set.
see also: IARC.3.11.2, NTST.3.1
[NLFC.5.4] The clock source is substituted, not switched back and forth. The mechanism is the runtime's (RTIM.3): live reads the host's monotonic and UTC clocks (RTIM.3.1.2), the harness clock returns the values the harness most recently set (RTIM.3.1.3), and selecting the mock mode puts one in place of the other (RTIM.3.1.4).
Going live → mock fixes both origins; it reads nothing from the host. The
mock monotonic clock starts at 0, and the mock wall clock starts unset until
the test sets it with ds_engine_wall_clock_set ([NTST.3.1]). Neither depends
on when the run started, so two identical runs record identical clock values.
The switch must come before the clock is first sampled. Once the engine has
sampled its clock, which a pump does whether or not an input has arrived,
ds_engine_clock_set_mode refuses the switch to mock with DS_ERR_STATE: the
monotonic clock never decreases ([LTIM.2.8.2]), and the held sample is by then
past the mock origin. It is the same refusal a backward
ds_engine_clock_set gets ([NTST.3.1]).
Going mock → live continues from the mock time. The engine must continue the monotonic clock from the mock clock's current value, advancing with the host's from there, so it never decreases ([LTIM.2.8.2]). The wall clock reads the host's again. The engine does not return to the live timeline it left: a test that set mock time explicitly ([NLFC.5.3]) has moved the monotonic clock off it, and there is no correspondence to return to. Do not build a test on switching back mid-run.
checks: alloy tla×3 — see also: LTIM.2.8.2, NLFC.5.3, NTST.3.1, RTIM.3, RTIM.3.1.2, RTIM.3.1.3, RTIM.3.1.4
[NLFC.5.6] The clock modes are the registry specs/registry/clock_mode.ebnf.
ds_clock_mode_t must mirror it name for name and value for value
([NLFC.5.4]).
see also: NLFC.5.4
Teardown [NLFC.6]#
checks: alloy×4 tla×9
[NLFC.6.1] ds_engine_free tears down all libds-owned state in reverse of init
order: working memory (frees fact wrappers) → schema registry (frees schemas) →
recorder → telemetry → the Rete engine.
checks: tla
[NLFC.6.2] After ds_engine_free returns:
The
ds_engine_t *is invalid.Every
ds_fact_t */ds_schema_t *obtained from this engine is invalid.No registered callback will be invoked again.
checks: alloy×2 tla×3
[NLFC.6.3] Calling ds_engine_free twice on the same engine is undefined\nbehaviour.
[NLFC.6.4] Teardown fires no callback. ds_engine_free must not
invoke any callback the integrator registered: it emits no stream event and no
metric or log, and hands nothing to the cache persistence callbacks. The engine
holds each registered user pointer until ds_engine_free returns, so an
integrator whose callback context owns resources frees them after that, not
before.
ratified
Error handling overview [NLFC.7]#
[NLFC.7.1] Every libds entry point reports the same way: one returned value carrying a machine-readable status and an optional human-readable detail. That follows from libds holding no global state at all ([NLFC.1.3]), and it is what keeps two engines in one process independent in their error reporting as well as their data.
Field |
Meaning |
|---|---|
status |
the outcome; zero is success, errors are negative, and the taxonomy is [NLFC.7.4] |
detail |
a message for a human -- a log line, a fault report. May be absent, and is borrowed when present ([NLFC.7.2]) |
The split is the point: branch on the status, never on the text. detail
exists to make a failure diagnosable and is free to change wording, so a
caller that parses it has coupled itself to something that carries no
guarantee. A caller that formats it must also tolerate its absence.
see also: NLFC.1.3, NLFC.7.2, NLFC.7.4
[NLFC.7.2] detail is valid until the next libds call on the same engine; copy
it to retain the message.
[NLFC.7.3] Treat the result as a unit — check .status, then propagate or
log + recover. A single failed call does not invalidate the engine unless\ndocumented otherwise.
[NLFC.7.4] The full status taxonomy and per-code recovery is [NERR]; the canonical range scheme is [IERR.2].
see also: IERR.2
Engine clone [NLFC.8]#
[NLFC.8.1] ds_engine_clone produces an independent engine identical to the
source at call time.
The contract is behavioural equivalence + full independence, not a memory
layout. Equivalence is over engine state: working memory, the agenda, the
clocks, series and the cache. A clone starts with no callbacks ([NLFC.8.3]), so
once the integrator has registered callbacks on it that behave as the source's
do, any subsequent input sequence applied identically to src and to the clone
produces byte-identical observable output from both (the LDET stream,
[LDET.2.2b]); and the two share no mutable state — an operation on
one never affects the other, and either may be freed first. How the impl
achieves this (share-immutable / deep-copy-mutable) is [IARC.11]. Clone is a
runtime API over in-memory state — no wire format and no atom — and it is
not rollback: a discarded clone's events never enter the
source's event trace (speculation is off-trace, [IARC.11.3]).
see also: IARC.11, IARC.11.3, LDET.2.2b, NLFC.8.3
[NLFC.8.2] Clone requires a quiescent engine.
Condition |
Result |
|---|---|
|
|
called mid-pump / mid-callback |
|
|
|
allocation fails |
|
Clone mints no new error codes; it reuses the existing taxonomy ([NLFC.7.4]). This edition has no realtime entry point, so no engine an integrator holds is in RT mode ([NRTM.9.1]).
see also: NCBK.2.9, NLFC.7.4, NRTM.9.1, RARC.13.16
[NLFC.8.3] A clone starts with no callbacks registered. ds_engine_clone
must return the clone with every callback empty and no user pointer
copied: the stream, call, log and metric callbacks and both cache
hooks. The integrator registers what the
clone needs before pumping it, as on a new engine. An essential verb with no
handler registered fails the clone's pump as it would a new engine's
(DS_ERR_STORAGE_UNAVAILABLE, [NERR.7]). So until the integrator wires it,
nothing a clone does reaches the source's host state.
For the shadow-engine speculate / commit / discard use case, the integrator registers effect-buffering wrappers on the clone before pumping it. The reads-live / writes-buffered split and the single-pump scope limit are an integrator-guide how-to, not part of this contract.
ratified — see also: NERR.7
Cache seed [NLFC.9]#
[NLFC.9.1] When to seed: at setup, before the first stream event. After
creating an engine ([NLFC.1]) and before the engine emits its first stream
event, the integrator may seed the engine-owned cache with
ds_engine_cache_seed ([IARC.12]) — one call per entry — to restore a cache
snapshot persisted by the write-through hooks ([NSTG.9]). The window is a
load's ([NFCT.1.1]): a host assert, a retract and a pump ([NLFC.2]) each emit a
stream event, so a seed comes before the first of them, and a load or a seed
emits none. A seed establishes starting state, not a running-phase input, and
every seed is made before an encoder writes the head of the engine's stream
([RFCS.5.1]).
ratified — see also: IARC.12, NFCT.1.1, NLFC.1, NLFC.2, NSTG.9, RFCS.5.1
[NLFC.9.2] After the first stream event it is refused. Once the engine
has emitted a stream event ([NLFC.9.1]), the engine must refuse a seed with
DS_ERR_STATE and leave the cache unchanged. The cache is thereafter mutated
only by rule cache / cache_delete writes ([LSTO.4.7.2]); restoring state
mid-run is not a supported operation. Like clone ([NLFC.8]), the seed mints no
new error codes.
see also: LSTO.4.7.2, NLFC.8, NLFC.9.1
[NLFC.9.3] A seed outlasts the ruleset's initial block. The loaded
artefact's initial block applies at the engine's first step ([LGRA.24.3]), or
at the next one where a bounds refusal refused it. A key the integrator seeded
before the block applies keeps the seeded value: the block's cache item for the
same key does not overwrite it. A seed made after the block applies, where
[NLFC.9.2] still admits one, overwrites the key as any seed does.
[NLFC.9.4] A seed's TTL counts from the engine's first sample. A
seed is made before the engine has sampled its clocks ([NLFC.9.1]), so there is
no reading of the monotonic clock to count a TTL from ([LTIM.2.8.4]), and the
clock's zero means nothing ([LTIM.2.8.2]). The engine therefore holds a seed's
non-zero ttl_ns as a duration until it takes its first sample ([LTIM.2.8.5]).
When it takes that sample, the engine must give each seeded entry still held
as a duration the deadline of that sample plus its ttl_ns. It does so before
it records the sample, before the step applies the initial block
([LGRA.24.3]), and before it consumes the step's input. From then on the entry
expires at its deadline, as a rule's cache … ttl: write does ([NSTG.2.4.2]).
So an entry restored with a remaining lifetime ([NSTG.9.1]) keeps that lifetime from the engine's first step. Neither where the host set a mock clock before that step ([NTST.3.3]) nor how long the integrator took between creating the engine and its first input changes it. A clone made before the first sample holds the same durations ([NLFC.8.1]), and its own first sample fixes its deadlines.
ratified — see also: LGRA.24.3, LTIM.2.8.2, LTIM.2.8.4, LTIM.2.8.5, NLFC.8.1, NLFC.9.1, NSTG.2.4.2, NSTG.9.1, NTST.3.3
[NLFC.9.5] A seed whose deadline would fall outside the Time range is
refused, as a host assert's is ([LTIM.1.1.5], [RFCS.6.7]). The engine
must refuse with DS_ERR_TIME_RANGE a seed whose ttl_ns is greater than
$2^{63} - 1$, which no Duration holds, and leave the cache as it was.
Where a seed's deadline, fixed at the first sample ([NLFC.9.4]), would fall
outside the range, the engine must refuse with DS_ERR_TIME_RANGE the call
that would take that sample, and leave the engine as it was before the call:
neither clock moves, no sample is recorded, no seed's deadline is fixed, nothing
enters working memory, and a pending initial block stays pending
([LGRA.24.3]). The call is not a step ([LTIM.2.8.4]), so the seeding window
stays open ([NLFC.9.2]), and the host may seed the key again ([NLFC.9.1]).
ratified — see also: LGRA.24.3, LTIM.1.1.5, LTIM.2.8.4, NLFC.9.1, NLFC.9.2, NLFC.9.4, RFCS.6.7
[NLFC.9.6] Where one seed breaks several refusals, the first in this order
decides. ds_engine_cache_seed must return
the status of the first of these that refuses, and leave the cache as it was:
The engine is halted:
DS_ERR_ENGINE_HALTED([NCBK.2.9]).The engine has emitted a stream event:
DS_ERR_STATE([NLFC.9.2]).ttl_nsis greater than $2^{63} - 1$:DS_ERR_TIME_RANGE([NLFC.9.5]).The value is over one of its limits:
DS_ERR_JSON_LIMIT([LGRA.5.8.6]).The key, or a string or object key in the value, is not well-formed UTF-8:
DS_ERR_ENCODING([LSTR.8.5]).Storing it would breach a bound
ds_engine_set_cache_capset:DS_ERR_CONTRACT_BREACH([LSTO.4.7.5]).
A NULL engine, key or value is DS_ERR_INVAL before step 1. An allocation
that fails is DS_ERR_OOM at whichever step needs it, and leaves the cache as
it was.
The order judges a value. A seed given as JSON text is judged as text first,
and a refusal of the text comes before step 1 ([LSTR.8.5]). For the reason
[NFCT.2.11] gives, a libds.h caller meets neither step 4 nor, for what is in
the value, step 5.
ratified — see also: LGRA.5.8.6, LSTO.4.7.5, LSTR.8.5, NCBK.2.9, NFCT.2.11, NLFC.9.2, NLFC.9.5
Capabilities and admission [NLFC.10]#
Every artefact records its program's resolved capability settings and the capabilities its content requires ([RDSC.16.2]). Two things decide whether a build and an integration can run it: which capabilities the build has code for, and which settings the integration admits.
see also: RDSC.16.2
[NLFC.10.1] The build's capabilities. libds must provide a public
query returning the capabilities it was built with, as values of
proto/capabilities.proto#Capability. It needs no engine. An integrator may
compare an artefact's requires against it before loading; a load of an
artefact requiring a capability the build lacks fails with
DS_ERR_DSC_CAPABILITY_ABSENT ([RDSC.16.2.7]).
ratified — see also: RDSC.16.2.7
[NLFC.10.2] The admission policy. An integrator may give an engine an
admission policy before loading an artefact into it: for each capability,
the settings the integration admits — true only, false only, or either.
libds must enforce it: loading an artefact whose resolved setting for some
capability the policy does not admit fails with
DS_ERR_BND_DIALECT_MISMATCH, and the detail names the capability. With no
policy given, every setting is admitted.
The policy is checked after the build's capabilities and before binding
([RDSC.16.2.9]). It is policy, where DS_ERR_DSC_CAPABILITY_ABSENT is
physical: an integration that cannot support a program's settings refuses
it here, with the capability named, whether or not the build has the code.
A policy set after a load is refused. An engine takes one load
([NFCT.1.1]), and its policy has judged it. Once ds_engine_load_dsc has
succeeded, ds_engine_set_admission must return DS_ERR_STATE and leave
the policy as it was, rather than accept a policy that would judge nothing. On
an engine a failed load spent, it is refused with DS_ERR_ENGINE_HALTED, as
every call there is ([RDSC.9.8], [NCBK.2.9]).
ratified — see also: NCBK.2.9, NFCT.1.1, RDSC.16.2.9, RDSC.9.8
[NLFC.10.4] The admission policies are the registry specs/registry/admission.ebnf.
ds_admission_t must mirror it name for name and value for value
([NLFC.10.2]).
see also: NLFC.10.2
[NLFC.10.3] Integrator configuration never selects a strategy. The
engine executes under the artefact's recorded settings and nothing else
([RDSC.16.2.1]). Sizing calls, such as setting the cache bounds
([NSTG.2.6.1]), supply capacities; they must not switch the engine between
strategies. In this edition every artefact has constspace: false
([LCAP.2.1.5]), and there is no working-memory bound ([NRTM.3.1]).
ratified — see also: LCAP.2.1.5, NRTM.3.1, NSTG.2.6.1, RDSC.16.2.1