# Testing integrator code with libds

Patterns and APIs for writing deterministic tests of code
that links libds: mock-clock setup, event-trace
observation, callback wiring for tests, and how to
exercise rule-firing without flake.

## What this is not

- Not a libds-internal test guide. Implementation tests
  for libds itself live at
  `runtime/tests/libds/`;
  conventions for those sit in
  [ITST].
- Not a conformance-test harness spec. Cross-runtime
  conformance is
  [LCON].
- Not a tutorial — assumes you've read
  [NGST] and
  [NLFC].

---

(NTST-1)=
## Test discipline [NTST.1]

(NTST-1-1)=
[NTST.1.1] **Mock clock for everything time-related.**
libds exposes a mock clock via `ds_engine_clock_set_mode`,
`ds_engine_clock_set` / `_advance` and `ds_engine_wall_clock_set`. Use it
unconditionally in tests. Live wall-clock time has no
place in a unit test — TTL-driven retracts, cooldown
windows, `dwell` gates, per-emit TTL all become
non-deterministic if the clock advances on its own.

(NTST-1-2)=
[NTST.1.2] **One pump per scenario step.** A test step
typically: change inputs (assert facts, advance the
clock), call `ds_engine_pump`, assert that observable
state changed. Do not pump in a loop "until something
happens" — if the engine has nothing to do, pump returns
without firing rules and your test doesn't progress.

(NTST-1-3)=
[NTST.1.3] **Capture observability through callbacks.** The
stream callback (`ds_engine_set_stream_callback`) is the
test-friendly surface — every observable engine event
flows through it in `seq` order. Push received events
into a per-test ring buffer; assert against the contents
after pump returns.

---

(NTST-2)=
## The basic fixture [NTST.2]

(NTST-2-1)=
[NTST.2.1] A deterministic libds test has three moving parts: a clock the
test owns, a callback that records, and assertions made against what was
**observed** rather than against engine internals.

The stream is the observation surface. The test registers one callback with a
pointer to a buffer of its own, drives the engine, and then inspects that
buffer -- the engine is never interrogated about what it did. What the test
verifies is therefore exactly what a production integrator would see.

Both preparations happen before any schema is registered or any fact
asserted, and that ordering is a requirement rather than tidiness
([NTST.2.2]).

One practical caution: a bounded observation buffer that fills stops
recording, so a test that overruns one fails on a truncated
history instead of on the behaviour it meant to check. Size it for the events
the test expects, or make filling it a loud failure.

*see also:* [NTST.2.2](#NTST-2-2)

(NTST-2-2)=
[NTST.2.2] **Order of setup matters.** Switch to mock
clock and register the stream callback **before**
registering schemas / loading rules / asserting facts.
Registrations and loads emit events too; if the
callback isn't registered yet, those events are
silently dropped (per [NCBK.1.8]). Tests
that miss this see partial event histories.

---

*see also:* [NCBK.1.8](#NCBK-1-8)

(NTST-3)=
## The mock clock [NTST.3]

(NTST-3-1)=
[NTST.3.1] The mock clock moves only when the test moves it, and there are
two ways to move it: set it to an absolute instant, or advance it by a
duration. Both act on the monotonic clock ([LTIM.2.8.2]); an advance also moves
the wall clock by the same duration, and leaves a wall clock that has no value
without one. A third, `ds_engine_wall_clock_set`, sets
the wall clock alone, to any instant, earlier or later — the way a test
reproduces a host clock being stepped ([LTIM.2.8.3]).

The monotonic clock never decreases, so once the engine has taken its first
sample, from an input or a pump ([LTIM.2.8.4]), `ds_engine_clock_set` to a
value below the current one must return `DS_ERR_STATE` and leave both clocks as
they were, so nothing recorded goes backward. Before the first sample, it must
take any value in the clock's range, which is how a test fixes its epoch.

**A move never takes a clock out of its range.** On a mock clock,
`ds_engine_clock_set` and `ds_engine_clock_advance` must return
`DS_ERR_TIME_RANGE` and leave the engine as it was when the monotonic clock
would end above the top of its range ([LTIM.2.8.2]).
`ds_engine_clock_advance` must do the same when the wall clock has a value, and
that value plus the duration is greater than $2^{63} - 1$, outside the `Time`
range ([LTIM.1.1.5]).

A move that lands exactly on the top of a range is taken. A wall clock that
has no value limits nothing.

The set and the advance both exist because tests need each. An absolute set establishes an epoch,
which is what makes a computed deadline readable in the test's own text
([NTST.6.1]). A relative advance steps past a known interval without the test
having to know where the clock currently stands.

Neither is legal in live mode ([NTST.3.2]). Neither is a sample: the next
input or pump observes and records the value it left ([NTST.3.3]), and
neither on its own retracts anything, because time-driven work happens at the
next pump ([NTST.3.4]).

*ratified*  —  *checks:* `idris×10`  —  *see also:* [LTIM.1.1.5](#LTIM-1-1-5), [LTIM.2.8.2](#LTIM-2-8-2), [LTIM.2.8.3](#LTIM-2-8-3), [LTIM.2.8.4](#LTIM-2-8-4), [NTST.3.2](#NTST-3-2), [NTST.3.3](#NTST-3-3), [NTST.3.4](#NTST-3-4), [NTST.6.1](#NTST-6-1)

(NTST-3-2)=
[NTST.3.2] All three are legal only after
`ds_engine_clock_set_mode(e, DS_CLOCK_MOCK)`. Calling
any of them in `DS_CLOCK_LIVE` returns `DS_ERR_STATE`.

*ratified*

(NTST-3-3)=
[NTST.3.3] A mock-clock mutation sets the mock clock and is not itself a
sample ([LTIM.2.8.4]): it emits no event and records nothing. The next input
or pump samples the clock source, reads the value the mutation left, and
records it as a `ClockAdvance` carrying both clocks when it differs from the
previous sample ([LTIM.2.8.5], [RFCS.10.1]), with the `DS_EV_TICK` stream
event that sample drives. So a test writes the trace a live run through the
same clock values writes, and two mutations between samples leave one record.

*ratified*  —  *see also:* [LTIM.2.8.4](#LTIM-2-8-4), [LTIM.2.8.5](#LTIM-2-8-5), [RFCS.10.1](#RFCS-10-1)

(NTST-3-4)=
[NTST.3.4] **The pump's TTL sweep runs at pump entry.**

(NTST-3-5)=
[NTST.3.5] Fact-deadlines are computed at assert time
relative to the clock then. Mutating the clock after
assert affects whether the next sweep retracts; it
doesn't shift deadlines on already-asserted facts.

---

(NTST-4)=
## Wiring callbacks for tests [NTST.4]

(NTST-4-1)=
[NTST.4.1] Action-verb callbacks (call, cache) need
test-side stubs. The simplest pattern: register a
per-test observer via `ds_engine_set_call_callback` (or the cache
equivalent) that records what was called, then assert
against it after driving the rule under test.

(NTST-4-2)=
[NTST.4.2] **Strings in callback payloads are valid for
the callback duration only.** Copy via `snprintf` /
`strdup` inside the callback if the test asserts on
them after pump returns.

(NTST-4-3)=
[NTST.4.3] **Returning non-OK from a callback aborts the
pump.** Useful for "the callback observed bad input"
tests — return `DS_ERR_R(DS_ERR_INVAL, "...")` and
verify pump returns the same code.

---

(NTST-5)=
## Verifying rule-fire ordering [NTST.5]

(NTST-5-1)=
[NTST.5.1] Rule-fire events bracket each rule's RHS:
`DS_EV_RULE_FIRE_BEGIN` carries the rule name, then the
RHS's action events (`ACTION_LOG`, `ACTION_EMIT`, etc.),
then `DS_EV_RULE_FIRE_END`.

(NTST-5-3)=
[NTST.5.3] Per-rule metrics may also be emitted. Subscribe a
metric callback if your test asserts on them; metric
subscription is independent of the stream callback.

---

(NTST-6)=
## Testing TTL behaviour [NTST.6]

(NTST-6-1)=
[NTST.6.1] Testing a TTL means testing a boundary, so the test has to land on
both sides of it.

A fact's deadline is fixed when the fact is asserted -- the clock at that
moment plus the TTL -- and does not move afterwards ([NTST.3.5]). The
comparison against it is **inclusive**: a pump with the clock one tick short
of the deadline leaves the fact alive, and a pump with the clock exactly at
the deadline retracts it. A test that checks only the far side proves the fact
eventually dies, not that it dies when it should.

The retraction is the pump's work rather than the clock's ([NTST.3.4]), which
is why each half of the check is a clock move, then a pump, then a count.

*see also:* [NTST.3.4](#NTST-3-4), [NTST.3.5](#NTST-3-5)

(NTST-7)=
## Testing logical-fact truth maintenance [NTST.7]

(NTST-7-1)=
[NTST.7.1] A rule that emits a derived fact `logical` ties the derived
fact's lifetime to its premise: retracting the premise retracts the derived
fact through truth maintenance. A test of it asserts the premise, pumps,
observes the derived fact's `DS_EV_FACT_ASSERT`, retracts the premise, pumps
again, and observes its `DS_EV_FACT_RETRACT`. Justifier introspection
(`ds_engine_get_justifiers`, [NDBG.5]) lets a test assert *which* activation
supports the derived fact.

---

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

(NTST-8)=
## Testing DSC-loaded artefacts [NTST.8]

(NTST-8-1)=
[NTST.8.1] `ds_engine_load_dsc` consumes a byte slice that
contains a compiled `.dsc`. For tests, integrators
typically:

- Pre-build a known-good `.dsc` against test fixture
  source (compiled once, committed to the test tree).
- Load it during test setup and verify it registers the
  schemas / rules you expect by querying
  `ds_engine_schema_count`, `ds_engine_schema_find`,
  `ds_engine_rule_meta_find`.

(NTST-8-3)=
[NTST.8.3] DSC load errors are well-typed ([RDSC.11.1]). A failed load
spends the engine ([RDSC.9.8]), so a test that loads a corrupted artefact on
purpose gives it an engine of its own.

---

*see also:* [RDSC.11.1](#RDSC-11-1), [RDSC.9.8](#RDSC-9-8)

(NTST-9)=
## Multiple engines per test [NTST.9]

(NTST-9-1)=
[NTST.9.1] libds has no globals (per
[IARC.1.11]). Tests can
freely create multiple engines in a single process —
useful for replay-validation tests that run two engines
against identical inputs and compare event streams.

*see also:* [IARC.1.11](#IARC-1-11)

(NTST-9-2)=
[NTST.9.2] Each engine has its own clock, schema
registry, recorder seq, and callback registrations.
Registering a callback on one engine doesn't affect
the other.

---

(NTST-10)=
## Determinism contract [NTST.10]

(NTST-10-1)=
[NTST.10.1] Per [LDET],
two engines on the same platform with identical inputs
produce byte-equal stream events. Tests can rely on
this for hash-based comparison; just snapshot the
serialised stream after each pump and compare with
`memcmp`.

(NTST-10-2)=
[NTST.10.2] **Don't depend on incidental ordering.** The LDET
contract guarantees same inputs → same outputs on one platform
signature ([NDET]) — not a
particular agenda or hash-iteration order pinned across libds
versions. Tests that hard-code an expected event sequence may
need updating across engine releases; assert on the observable
outcome where you can.

---

(NTST-11)=
## Common gotchas [NTST.11]

| Symptom                                    | Likely cause                                                        |
|--------------------------------------------|---------------------------------------------------------------------|
| Test passes locally, flakes in CI          | Live clock somewhere; switch to mock.                               |
| Stream cb sees zero events                 | Registered after `assert` / `load`; register first.                 |
| `ds_engine_pump` returns `DS_ERR_STORAGE_UNAVAILABLE` | A rule fired an action verb you didn't wire a callback for.       |
| Asserting a fact yields no rule fire       | Pattern doesn't match (slot value off?), or rule already refracted. |
| TTL retract doesn't fire                   | Clock not advanced past deadline before pump.                       |
| Two engines disagree on event order        | LDET contract holds across pumps but each engine has own seq counter. |

---

(NTST-12)=
## Build / link [NTST.12]

(NTST-12-1)=
[NTST.12.1] Test binaries link as production does: `libds.a` and
`libprotobuf-c.a`, the row's platform libraries, and a C++ driver
([NGST.3.1]).

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

(NTST-12-2)=
[NTST.12.2] No additional test-only dependencies are
required — the public API is sufficient for full
black-box testing. If your test framework wants
mocks (cmocka, gmock-via-c shim), wire them on top
of the patterns above.

(NTST-12-3)=
[NTST.12.3] Internal headers (`engine.h`, `wm.h`, etc.)
are not on the integrator include path. Don't reach for
them; if you find a test gap that wants internals, the
public API surface should grow to cover the case —
file an issue.

(NTST-13)=
## Running a program's tests [NTST.13]

*Deferred: not binding in this edition.*

(NTST-13-1)=
[NTST.13.1] **The runtime runs an artefact's tests itself.** `ds_test_run(dsc, len, cfg, &report)` runs the test cases a compiled
artefact carries ([LTSL.2.4], [RLOW.17.1]) as [RTIM.14] states. For each
`TestCase` it creates an engine of its own, loads the artefact into it ([RTIM.14.3])
and drives the case on the mock clock ([RTIM.14.2]). It takes no engine of the
caller's and touches none. `cfg` selects every case, or the one whose `test_id`
it names; a `NULL` `cfg` selects every case. Both runtimes **must** provide it.

The call's status says whether the run happened, not whether the cases passed:

- `DS_OK`: every selected case ran, and `*report` holds the results ([NTST.13.2]),
  passing or failing.
- The load's own code ([RDSC.11.1]), when the artefact is refused before any case
  runs. `*report` is `NULL`.
- `DS_ERR_DSC_DECODE` or `DS_ERR_DSC_DANGLING`, when the artefact's test atoms
  cannot be read ([RTIM.14.15]). `*report` is `NULL`.
- `DS_ERR_NOT_FOUND`, when `cfg` names a `test_id` the artefact does not carry.
- `DS_ERR_INVAL` for a `NULL` `dsc` or `report`, and `DS_ERR_OOM`.

*see also:* [LTSL.2.4](#LTSL-2-4), [NTST.13.2](#NTST-13-2), [RDSC.11.1](#RDSC-11-1), [RLOW.17.1](#RLOW-17-1), [RTIM.14](#RTIM-14), [RTIM.14.15](#RTIM-14-15), [RTIM.14.2](#RTIM-14-2), [RTIM.14.3](#RTIM-14-3)

(NTST-13-2)=
[NTST.13.2] **The report.** `ds_test_run`'s report lists the cases it ran in
ascending `test_id`. For each it gives:

- the case's `test_id`, its name, and its module ([RDSC.4.7]);
- one result per `Oracle*` atom of the case, in atom order: the assertion's
  head, its position among the case's assertions, whether it is a `NEVER`
  assertion, how many occurrences the run observed, and whether that count
  satisfies it ([RTIM.14.7]);
- every failure the case met that is not an assertion's count ([NTST.13.3]),
  each with its kind and a detail text;
- every fault event the case's engine raised, in stream order, each with what
  [RTIM.14.16] names of it;
- whether the case passed: it **must** be reported passed exactly when every
  assertion's result is satisfied and it has no failure.

The report is the caller's until it passes it to `ds_test_report_free`, and
every string in it lives as long as the report.

*see also:* [NTST.13.3](#NTST-13-3), [RDSC.4.7](#RDSC-4-7), [RTIM.14.16](#RTIM-14-16), [RTIM.14.7](#RTIM-14-7)

(NTST-13-3)=
[NTST.13.3] **A case's failures are a closed set.** Besides an assertion whose
count does not satisfy it, a case fails for exactly these reasons, and the
report names each by its kind:

- an outbound call that no `TestResponse` stub answers ([RTIM.14.6]);
- a `Test*` or `Oracle*` atom the runtime did not understand or did not
  evaluate ([RTIM.14.9]);
- a step of the drive the engine refused without halting ([RTIM.14.14]), the
  step and its status in the detail;
- the engine halting during the case ([NCBK.2.9]), the fault in the detail;
- the case's own engine not created or not loaded, the status in the detail.

The kinds are a registry ([STYL.5.9.7]), allocated with the first runtime that
reports them.

*see also:* [NCBK.2.9](#NCBK-2-9), [RTIM.14.14](#RTIM-14-14), [RTIM.14.6](#RTIM-14-6), [RTIM.14.9](#RTIM-14-9)

(NTST-13-4)=
[NTST.13.4] **One driver per runtime.** pyds, @ds-lang/ds and mercury_ds **must**
each expose `ds_test_run` and its report ([NTST.13.2]). dsdb **must** run a
program's tests through that entry point and through no driver of its own, so a
test passes or fails by the runtime's verdict wherever it is run.

*see also:* [NTST.13.2](#NTST-13-2)

