DS C Rete — architecture

Contents

DS C Rete — architecture#

Prefix IRET.

The design of a purpose-built Rete network implementation in C that targets only the features DS uses. This is not a general-purpose production-system engine; every design decision is constrained by the DS feature set and the DS workload profile (tens to hundreds of rules, 100–1000 live facts per engine instance).

The implementation lives at runtime/src/libds/rete/ and is the sole rule-evaluation engine. The compiled network travels in the DSC artefact as the RETP atom set — the AlphaNode / BetaNode / TerminalNode atoms, which carry their own expression and action trees; the loader assembles the in-memory node graph from them at init time.

What this is not#

  • Not a general-purpose production-system engine. No module system, no object/instance facts, no scripting or runtime rule-definition surface.

  • Not a compiler. Expression trees and network topology arrive pre-compiled in the RETP atom set; the runtime assembles the in-memory graph from that description.

  • Not a wire-format spec. The RETP atom encodings live in [RDSC] (the AlphaNode / BetaNode / TerminalNode atoms).


Engine commitments [IRET.1]#

  • [IRET.1.1] DS features only. The network supports exactly the pattern forms, expression operators, and action verbs that DS's lowering spec ([RLOW]) can emit. No facility is added speculatively for features DS doesn't use.

  • [IRET.1.2] No runtime text parsing. The Rete network topology and all expression trees arrive in binary form, as the artefact's AlphaNode, BetaNode and TerminalNode atoms ([RDSC.4a]). The loader assembles in-memory node graphs from that description; no textual rule language is parsed at runtime.

see also: RDSC.4a

  • [IRET.1.3] The evaluator's value kinds. A fact slot carries one of the slot-value kinds [RFCS.23.2] defines. The evaluator's value (rete/val.h) holds those, keeps a Time as an instant with its zone offset, and adds three kinds no slot stores: an unbound marker for a let slot not yet bound, an exact ratio that currency conversion yields and rounding consumes ([LUNI.13.5]), and a Json borrowed from the working-memory wrapper that owns it. The set is closed ([IRET.3.1]).

see also: IRET.3.1, LUNI.13.5, RFCS.23.2

  • [IRET.1.4] Interned strings (refcounted fact-slot values). The per-engine string table holds two entry classes in one pointer space: pinned — schema/slot/rule names and compile-time literals, interned at load, engine-lifetime, never freed; and counted — String/Bytes slot values, reference-counted by the number of live committed fact slots holding the string and freed when the last such slot retracts. Four operations: find (non-mutating lookup, for no-op / dedup), acquire (find-or-insert + refcount++, once per String/Bytes slot at fact commit), release (refcount--, free + remove at 0, once per slot at fact retract), pin (insert saturated). The open-addressing table supports deletion (tombstones) so a freed counted entry is reclaimed. A value equal to a pinned literal shares the literal's pointer (stays pinned).

    Every other dynamic string the engine computes but does not store in a fact slot — an interpolated string, gensym, json→string, cache-get value, where-predicate operands — is never interned: it lives in a fire-scoped bump arena ([IRET.1.4a]) and is copied into a counted entry only if it is emitted into a fact slot. This bounds the table to live facts + structural vocabulary (seals SI1 oversized-at-destroy and SI2 unbounded computed-string growth).

    Rete structural comparisons (alpha EQ/NEQ, beta join, identity hash / equal) stay pointer-equality: they only ever see stored (interned) slot values, and equal stored strings still share one pointer. Eval-level == / < / > on strings is a length-aware content comparison — a computed arena operand is not interned, so an equal-content value has a different pointer and must still compare equal (and content order is deterministic, unlike pointer order).

see also: IRET.1.4a

  • [IRET.1.4a] Fire-scoped arena. Transient computed strings live in a per-engine slab-chain bump arena, reset at pump entry (bounded per pump; the always-runs choke, independent of how the prior pump exited). Each dup takes a distinct span (no clobber between two live computed strings); growth chains a new slab, so a live pointer is never moved. An emitted computed string is interned counted at the emit-commit, before the reset. ds.intern.arena_high_water_bytes ([NMET.4]) bounds it.

see also: NMET.4

  • [IRET.1.4b] Counted-string storage: recycling freelist (Rung γ, x-ref [RTCT.1] / [NRTM.1]). A counted String/ Bytes block is drawn from a size-classed recycling freelist (classes 8 … 4096 bytes) and returned to it on release, so a steady-state assert / retract cycle reuses blocks: zero steady-state allocation, bounded by the peak live count per class. This restores the realtime steady-state-zero-malloc property. A per-size-class warmup allocation (and any oversized-string allocation) remains — a one-time, bounded event before steady state; it is tolerated, not a hard failure (String/Bytes facts function in RT, bounded by the intern contract caps [RTCT.7.1]; go_live does not forbid it). Eliminating the warmup entirely (a freelist presz before go_live) is an optional further refinement where a contract requires a strictly allocation-free pump. The freelist changes only the allocation source, never the refcount semantics ([IRET.1.4]), so reclamation balance is identical with or without it.

see also: IRET.1.4, NRTM.1, RTCT.1, RTCT.7.1

  • [IRET.1.4c] Enforcement. Two guards. (1) The refcount-underflow assertion in release (double-free / lifecycle imbalance) — load-bearing. (2) The pinned-set freeze: after setup a new PINNED insert is a hard error. It is armed at the setup→runtime boundary (first pump). The freeze's trigger ("zero runtime pinned inserts") is exact once the small, program-structure-bounded first-pump sentinel set — "" (a live fact's corr on a hydration target) and $ClockTick (ds_rete_engine_tick_clock), which the engine interns pinned lazily at first pump rather than at load — is pre-pinned before the freeze arms. That set is verified complete by enumeration across the asserts-on surfaces. Boundedness is additionally observable via the SI3 pinned watermark (ds.intern.pinned_entries, [NMET.4]), which stays flat under value churn.

see also: NMET.4

  • [IRET.1.5] Fixed-width fact value arrays. A fact's slot values are stored in a flat array of ds_rete_val_t sized at schema-definition time. No per-fact heap allocation for non-Json slots. Json slots hold a separately-allocated UTF-8 blob; its pointer is stored in the value array.

  • [IRET.1.6] Token as flat array of fact pointers. A partial match (token) is an array of ds_rete_fact_t * with one entry per pattern in the rule, in pattern-declaration order. Variable bindings are implicit: to read binding s in pattern position i, slot j, evaluate token->facts[i]->slots[j]. Tokens carry a creation_timetag — a stamp monotone in completion order, assigned when the token is completed and ordered as [LDET.5.5] defines — for agenda ordering.

see also: LDET.5.5

  • [IRET.1.7] Alpha dispatch by schema index. Every schema is assigned a compact integer ID at load time. The alpha dispatch table is a flat array indexed by schema ID; each entry is the list of alpha nodes registered for that schema. Dispatch on a new/retracted fact is O(1) index + O(alpha_count_for_schema) iteration; no linear scan of all patterns.

checks: idris×11

  • [IRET.1.8] TMS via refcount + dependency table. Truth maintenance tracks logical-emit justifications as reference counts on derived facts. A dependency table maps each in-flight activation's ID to the list of logical facts it supports. When the activation ends (token retracted), each supported fact's refcount decrements; at zero the fact is retracted. Multiple activations supporting the same logical fact are the natural refcount > 1 case.

  • [IRET.1.9] Agenda sorted by (terminal ordinal ASC, creation_timetag ASC). The ordinal is the rule's index in canonical source order ([RLOW.14.3]) and decides between any two rules; the creation timetag ascends with completion order and decides only among activations of ONE rule. No hash-order dependence in agenda selection, and no dependence on completion order between rules ([RARC.5.4.7]).

checks: idris×3 — see also: RLOW.14.3, RARC.5.4.7, IRET.8, IRET.11.1

  • [IRET.1.10] Expression evaluation by recursive tree walk. Expression nodes are tagged C structs forming a tree; evaluation is a recursive function taking an evaluation context (current token + engine state). This is the simplest correct implementation; profiling gates any move to stack bytecode.

  • [IRET.1.11] One builtin table for every call node. Every builtin a call node names — math, string, time, Json and series reads among them — is registered in the op-indexed dispatch table [IRET.13.1] describes, and expression evaluation dispatches through it. No builtin is hard-coded in the evaluator.

see also: IRET.13.1

  • [IRET.1.12] Mockable clock source. Two clock function pointers per engine, sharing one context, supply the monotonic and the wall sample ([IRET.14]); no subsystem reads a platform clock directly. Live mode uses CLOCK_MONOTONIC and CLOCK_REALTIME; test / replay mode uses harness-controlled counters.

see also: IRET.14

  • [IRET.1.13] Rule-fire events for recording integration. Before and after each activation fires, the engine emits DS_EV_RULE_FIRE_BEGIN / DS_EV_RULE_FIRE_END stream events carrying the rule name (recorder.c::ds_recorder_emit_rule_fire_{begin,end}; the event payload is { const char *rule_name; }). The recorder's before/after machinery consumes these — there is no separate firing-token hook.

  • [IRET.1.14] No internal threads. The engine is single-threaded per instance, consistent with IARC.1.10. The integrator drives the pump; the engine does not spawn background work.


see also: IARC.1.10

Feature scope [IRET.2]#

What the C Rete implements [IRET.2.1]#

Derived from [RLOW]: every Rete feature the compiler can emit must be supported:

DS feature

Rete mechanism

Schema / slot types

Schema descriptors, typed value arrays of the kinds [IRET.3.1] lists

Simple pattern (Schema s)

Alpha node, all-slots bind

Inline equality constraint (where slot == literal)

Alpha test: slot == literal

Regex constraint (where slot ~ /…/)

Alpha test: regex match on slot

Where clause

Test CE: beta-level predicate over bound variables

no Schema (negation)

NOT node in beta network

within <dur>

Test CE over the monotonic sample minus the fact's assert_ns ([IRET.4.3])

then ... within (sequence)

Multi-pattern join + test CE on ts ordering

latest modifier

NOT sub-pattern excluding older anchors

Refraction

Per-rule refraction table keyed by token identity (hash pre-filter + fact-id tuple, [IRET.11.3])

emit X (plain)

RHS assert action

emit X logical

RHS assert action + TMS registration

let pure

Inlined at compile time; no Rete mechanism needed

let sync-impure (now(), monotonic_ns())

Bind-once in RHS expression context

let async

Desugared to request + response rules; no Rete primitive

Cooldown gate

The terminal's fire_guard, or a call site's gate, calling FN_RATE_ALLOW ([IRET.10.4])

Action verbs (log, call, publish, cache)

RHS expression nodes → builtin dispatch

Series aggregation in where clause

Test CE calling the FN_SERIES_* builtins ([IRET.13.2])

$ClockTick

Schema with no slots; assert/retract drives time-bound tests

String interpolation

one InterpExpr node: a linear sequence of FormatPrims — literal text, a value under a numeric or string spec, a time field (RLOW.6.4)

Json path access

json_path expression node → builtin

Truth maintenance (logical facts)

TMS: refcount + dependency table

TTL fact expiry

Deadline in fact; swept once per pump, before anything fires ([IRET.19.3])

No-op reassertion suppression

Slot equality check (with per-slot tolerance) at assert time

scope activation facts (LSCP.2.4)

Schema descriptor with DS_RETE_SCOPE_ACTIVATION; lifetime tied to the firing activation

scope logical ambient facts (LSCP.2.5)

Schema descriptor with DS_RETE_SCOPE_AMBIENT; plain working memory with ambient-write restriction enforced at compile time

see also: IRET.10.4, IRET.13.2, IRET.19.3, IRET.3.1, IRET.4.3, IRET.11.3, LSCP.2.4, LSCP.2.5, RLOW.6.4.3, RLOW.8.4

Value system [IRET.3]#

Types [IRET.3.1]#

A slot value is a tagged union — a kind discriminant plus exactly one payload. Its storage differs by kind in a way that matters:

Kind

Payload

Storage

Int

64-bit signed

inline

Float

double

inline

Bool

boolean

inline

Time

UTC nanoseconds and a zone offset

inline

Null

none

inline

String, Bytes

pointer and length

interned, not owned by the value

FactRef

the target's fact id, never a pointer

inline

Json

UTF-8 document tree

heap-allocated, owned; or borrowed from the wrapper that owns it

Unbound, Ratio

none; numerator and denominator

inline; evaluator-only ([IRET.1.3])

Three kinds reach outside the value. A String or Bytes is a borrowed view into the intern table, so copying a value never copies string bytes and comparing two interned strings can be a pointer comparison. Json is the one kind that owns heap memory, which is why it is the kind the bounded-memory dialects restrict ([LNLS.3.1]). A FactRef holds an id, so a target that leaves working memory leaves no dangling pointer.

The explicit length on String and Bytes means a value is not NUL-terminated by contract; a reader must use the length rather than scanning.

see also: IRET.1.3, LNLS.3.1

[IRET.3.2] A String/Bytes fact-slot value is interned counted at fact commit ([IRET.1.4]): the intern returns the canonical pointer, stable while at least one live fact holds the value and freed when the last holder retracts. Pinned structural strings are stable for the engine's lifetime. Two stored equal strings share a pointer (Rete comparisons use ==); eval-level string equality is by content, so a transient (arena, un-interned) computed operand still compares equal to a byte-equal stored value.

see also: IRET.1.4

[IRET.3.3] Json slots hold a ds_rete_json_t *: a length-prefixed UTF-8 blob plus a lazily-parsed path cache. Json slot values are not interned. Equality on Json slots uses structural comparison (deep equal on the parsed value). tolerance is not legal on Json slots (compile-time rejected).

[IRET.3.4] Slot equality with tolerance. At fact-assert time, the working memory dedup path compares the incoming fact against any existing fact with the same schema and identity-key slot value. For each slot:

  • Slots without tolerance: memcmp on the 8-byte union content (safe for int/float/bool/interned-ptr). String slots compare pointer (interned equality).

  • Slots with tolerance T > 0: only legal on Int and Float; the values are equal when abs(new - old) <= T, a change of exactly T included ([RLOW.3.7.4]).

  • Json slots: structural deep equality.

If all slots compare equal under their per-slot rule, the incoming assertion is suppressed (no-op).


see also: RLOW.3.7.4

Fact representation [IRET.4]#

Slot descriptor [IRET.4.1]#

One descriptor per slot of a schema, carrying everything the network needs about that slot without consulting the schema again:

Field

Holds

name

the slot name, interned

index

its position in a fact's value array

type

the slot's value kind

tolerance

0.0 = exact match; a positive value, in the slot's base unit ([LUNI.7.4]), is held only for a slot whose tolerance [LGRA.5.9.4], [LGRA.5.9.5] and [LGRA.5.9.10] admit, so a mutable slot of a logical schema whose value kind is Int or Float: a unit-typed slot's value kind is its dimension's storage ([LUNI.7.2])

sampled

whether absorbed samples are forwarded for this slot

retained

whether the slot's value is retained

identity_role

KEY or MUTABLE on a logical schema ([LFAC.1.7]); unspecified otherwise

Identity is a declared role per slot, never inferred from position. It mirrors the DSC IdentityRole ([RDSC.5.5.7]), so the compiled form and the in-memory form agree by construction.

see also: LFAC.1.7, LGRA.5.9.10, LGRA.5.9.4, LGRA.5.9.5, LUNI.7.2, LUNI.7.4, RDSC.5.5.7

Schema descriptor [IRET.4.2]#

One descriptor per registered schema: its name (interned), a compact index used for alpha dispatch, its slot count, its scope, a default TTL (meaningful only under ttl scope, otherwise zero), and a flat array of slot descriptors ([IRET.4.1]).

Five scope values: the four lifecycles the language declares, and ambient, which libds keeps as a value of its own for a logical schema that carries the ambient modifier ([LSCP.2.5]):

Scope

Source form

plain

scope explicit

logical

scope logical

ttl

scope ttl <dur>

activation

scope activation ([LSCP.2.4])

ambient

scope logical ambient ([LSCP.2.5])

Two of them carry runtime semantics that the scope value alone does not convey:

Activation scope. Every activation-scoped fact emitted during a rule firing is retracted when that activation ends — at the end of a synchronous RHS, and on every async completion path, so no path leaks them. The sweep is keyed by (fact, activation), through the same dependency table logical facts use, but it is unconditional: unlike a logical fact it does not wait for a justification count to reach zero.

Ambient scope. Working memory treats an ambient fact exactly as a plain one. The restriction that only ambient-declared rules may emit ambient facts is a compile-time check and is deliberately not re-checked at runtime.

checks: idris×2 — see also: IRET.4.1, LSCP.2.4, LSCP.2.5

Fact [IRET.4.3]#

A fact carries its identity, its schema, two timestamps, its truth-maintenance refcount, and its slot values:

Field

Holds

id

monotonically assigned, never reused within a session ([IRET.4.4])

schema

the schema this fact instantiates

assert_ns

the fact's entry stamp: the monotonic clock's sample when it entered working memory ([LTIM.2.8.6])

deadline_ns

the expiry instant for a TTL fact; 0 means no deadline

justif_count

the number of active justifications; non-zero only on logical facts, and reaching zero is what retracts one ([IRET.4.5])

slots

the values, one per slot the schema declares

The slot values are stored inline with the fact, sized from the schema's slot count, rather than behind a pointer — one allocation per fact, and slot access is an offset rather than an indirection.

checks: idris×26 — see also: LTIM.2.8.6, IRET.4.4, IRET.4.5

[IRET.4.4] id is assigned by a monotonic counter in the engine; it is never reused within a session. Fact IDs are used as stable keys in alpha memories, token arrays, and the TMS dependency table.

checks: idris×36

[IRET.4.5] justif_count is non-zero only for logical-scoped facts. When it reaches zero the fact is retracted by the TMS path.


checks: idris

Schema registry [IRET.5]#

[IRET.5.1] The schema registry is populated at load time from the artefact's schema atoms and its AlphaNode atoms ([RDSC.8.1]). It maps:

  • Schema name (interned) → ds_rete_schema_t *

  • Schema ID (uint16) → list of alpha nodes for that schema

see also: RDSC.8.1

[IRET.5.2] The alpha node list per schema ID is a flat array; during fact assert/retract the engine iterates this array and evaluates each alpha node's tests against the fact. With O(10_s) of alpha nodes per schema in typical DS rulesets this is unconditionally fast.

[IRET.5.3] Schema IDs are assigned consecutively starting from 0 during RETP loading. The maximum schema count per engine is 65535 (uint16 constraint). DS rulesets in practice have O(10_s) of schemas.


Alpha network [IRET.6]#

Alpha node [IRET.6.1]#

An alpha node represents one pattern-schema participation in the network. It holds:

  • A reference to the schema it matches.

  • A list of inline alpha tests (constraints that can be checked on the fact alone, without joining against other patterns).

  • An alpha memory: the set of facts currently satisfying this node's tests.

  • A list of downstream beta inputs to notify on memory changes.

ds_rete_alpha_node_t is declared in runtime/src/libds/rete/alpha.h.

checks: idris×9

Alpha tests [IRET.6.2]#

Alpha tests are predicates over a single fact's slot values. Three kinds cover all DS-lowered patterns:

The test record and its ds_rete_alpha_test_kind_t discriminant are declared in runtime/src/libds/rete/alpha.h.

[IRET.6.2.1] linear_scan: false overlay — alpha tests over known types. When the loaded DSC was compiled with linear_scan: false, all DS_RETE_ALPHA_EQ and DS_RETE_ALPHA_CMP tests operate on scalar or interned-string types. The engine may use an optimized comparison path for these types that avoids the cmp_vals switch statement when the type is known at node-creation time. Specifically:

  • DS_RETE_VAL_INT: direct int64_t comparison.

  • DS_RETE_VAL_FLOAT: direct double comparison.

  • DS_RETE_VAL_BOOL: direct bool comparison.

  • DS_RETE_VAL_STR: pointer equality (interned) for EQ/NEQ.

  • DS_RETE_VAL_STR for CMP (single-pattern only): strncmp bounded by the slot's capacity ([LSTR.11.1]): N codepoints, at most 4N bytes.

The comparison path is a may, and libds does not take it: every alpha test goes through the general cmp_vals comparison. DS_RETE_ALPHA_REGEX tests are only present when capacity is declared, and RE2 is linear in the input length ([LREG.8.1]), so a regex test costs O(capacity × P) with both factors compile-time constants — the property linear_scan: false needs.

This supplements, and does not replace, the base [IRET.6.2] behaviour.

see also: IRET.6.2, LREG.8.1, LSTR.11.1

[IRET.6.3] Regex pre-compilation. Regex alpha tests compile the pattern string at RETP load time, not at match time. The compiled regex object is stored in the alpha node; pattern evaluation calls RE2 through ds_re2_match. There is no backend to choose: the regex syntax is RE2 ([LREG.8.1]), so a swappable engine would change which patterns compile ([IRET.23.1]).

see also: IRET.23.1, LREG.8.1

[IRET.6.4] Alpha test evaluation. On fact assert, the engine evaluates all alpha tests for every alpha node registered for fact->schema->id. Tests short-circuit: the first failing test skips the fact for that node. A fact that passes all tests is inserted into the alpha memory and the downstream beta inputs are notified.

Short-circuiting is sound because every alpha test is decided: it answers true or false and cannot raise, the only conjuncts the compiler may take out of a where (RLOW.5.5). Rejecting a fact on one therefore cannot change what the where yields ([LNUL.4.2]), for an artefact that does not lie ([LDET.1.11]).

Two alpha tests are not decided: one whose slot_index names no slot of the fact's schema ([RDSC.4a.9.1]), and a REGEX test whose subject is not a String ([RDSC.4a.6.2]). Each faults. The engine must not short-circuit on either. The fact is rejected if another test of the node answers false, and the fault is raised only if none does.

checks: alloy×5 k idris×29 — see also: LDET.1.11, LNUL.4.2, RDSC.4a.6.2, RDSC.4a.9.1

[IRET.6.5] Alpha memory. The memory is a hash set keyed by fact->id. Insert and remove are O(1) average. The set supports iteration (for beta network left-memory join on fresh right memory).

checks: idris×18

Sharing alpha nodes [IRET.6.6]#

Two rules that have identical patterns on the same schema with identical tests share one alpha node. The compiler is responsible for deduplication; the RETP atom encodes the node graph, including shared references. The loader respects shared nodes — one in-memory ds_rete_alpha_node_t may appear as the right input to multiple beta nodes.


checks: alloy×6 idris×8

Beta network [IRET.7]#

Token [IRET.7.1]#

A token is one partial match travelling the beta network: the facts bound so far, one per LHS pattern position, in pattern order.

Field

Holds

fact_count

how many pattern positions are bound

facts

the bound facts, indexed by pattern position

creation_timetag

a monotonic stamp; this is what orders the agenda ([LDET.5.5])

hash

a cached hash of the fact-id tuple

next

links the token into a beta memory

Three of these are performance decisions with observable consequences. The timetag is not a timestamp — it is a stamp monotone in completion order, compared as [LDET.5.5] defines, so agenda order is deterministic and independent of the clock. The hash is cached because a token is hashed far more often than it is built, and it is over the fact-id tuple, so two tokens binding the same facts in the same positions hash alike. The list link is intrusive, so adding a token to a beta memory allocates nothing.

checks: idris — see also: LDET.5.5

[IRET.7.2] Tokens grow left-to-right as the beta network deepens. A token at a node with n patterns contains n fact pointers. The last pattern's fact is always facts[n-1]; earlier patterns are carried forward from the left parent.

checks: idris×7

[IRET.7.3] hash is the XOR-rotation hash of the fact IDs in the token. It is used as the O(1) pre-filter for duplicate detection and refraction table lookups; it is not the key. Hash collisions are disambiguated by token identity — tokens_equal (pointer / fact-id equality) for duplicate detection, and the fact-id tuple for refraction ([IRET.11.3]).

see also: IRET.11.3

Beta (join) node [IRET.7.4]#

A beta node joins a stream of tokens arriving on its left with a stream of facts arriving on its right, and passes what matches to its children. Its state divides three ways:

Inputs. A left parent — another beta node, or nothing at all, which marks this as the first pattern and makes working memory the left source. A right alpha node supplying candidate facts. A list of cross-pattern join predicates. And a flag marking the node negative, which inverts the test: a NOT node propagates when the join finds nothing.

Memory. Only the left side is remembered. Tokens accumulate in the left memory; the right side is not stored here, because the alpha node already holds those facts.

Outputs. Two child lists, kept separate: further beta nodes, and terminal nodes. A node may feed both.

ds_rete_beta_node_t is declared in runtime/src/libds/rete/beta.h.

checks: alloy idris×48

Join tests [IRET.7.5]#

Join tests are predicates over the token (left side) and the new fact (right side, the candidate for the current pattern). They implement DS's where clause predicates and within / then...within temporal constraints.

ds_rete_join_test_t is declared in runtime/src/libds/rete/beta.h.

checks: idris×14

[IRET.7.5.1] linear_scan: false overlay — the equality anchor is extracted at load. When the loaded DSC was compiled with linear_scan: false, every positive beta node's join-test list contains at least one EQ test of the form BINOP(EQ, VAR(left, i, j), VAR(right, k)). For a positive node, the beta node loader must:

  1. Extract (fact_idx=i, left_slot=j, right_slot=k) from this test and store it in the beta node's lmem_idx_* and ralpha_idx_* fields.

  2. Compile a specialized comparator over (token, fact) that performs a direct typed comparison on slots t->facts[i]->slots[j] and f->slots[k] without calling the expression evaluator.

  3. Use this comparator in place of join_tests_pass for the equality- anchor check during index probe. Remaining join tests still use join_tests_pass.

An EQ join test of that form is a legal anchor, wherever it stands in the list, when it is decided: both slots are non-nullable and the comparison cannot raise by their declared types. A decided anchor answers only true or false, and join tests combine as an absorbing and ([IRET.7.6], [LNUL.4.2]), so probing on it first changes neither whether the pair passes nor the fault the pair yields. An anchor that could answer null or raise could change both — for a negated join, whether it blocks — so the loader must not probe on one. The guarantee is for an artefact that does not lie about a slot's type ([LDET.1.11]).

The loader takes the first such test as the anchor. A negated node has no anchor and no index ([LNLS.5.8]).

This reduces the join-test hot-path cost from O(E) to O(1) for the equality anchor. [LNLS.5.1]'s both-directions O(1) bound needs more than this: an index over a whole composite identity, and one on negated nodes.

This supplements, and does not replace, the base [IRET.7.5] behaviour. It is a must on the reference engine's loader, naming this engine's own fields, so the implementation tree is where it belongs.

checks: alloy×2 k idris×16 — see also: IRET.7.5, IRET.7.6, LDET.1.11, LNLS.5.1, LNLS.5.8, LNUL.4.2

[IRET.7.6] Join tests may be evaluated in any order, and combine as [LNUL.4.2]'s absorbing and: a test returning false rejects the pair whatever another test raises — a trap, a TypeError or an EngineError — and that fault reaches no surface ([LERR.1.4.11]). When no test is false and several fault, the pair yields the one fault [LNUL.4.2]'s order selects. A token + candidate fact pair passes the join only if all join tests return true. The expression evaluation context provides access to all fact pointers in the current (extended) token plus the candidate fact in the "right" slot.

checks: alloy×2 k idris×32 — see also: LERR.1.4.11, LNUL.4.2

Join algorithm [IRET.7.7]#

On right-activation (new fact added to alpha memory):

  1. Iterate the beta node's left memory.

  2. For each token in left memory: build the candidate extended token (left token + new fact).

  3. Evaluate all join tests. If all pass: propagate the extended token to all beta children and terminal children.

On left-activation (new token arrives from left parent):

  1. Iterate the beta node's right alpha memory.

  2. For each fact in the alpha memory: build the candidate extended token (left token + fact).

  3. Evaluate all join tests. If all pass: propagate.

On right-retraction (fact removed from alpha memory):

  1. Iterate left memory; find all tokens whose facts[k] (for the relevant pattern index k) equals the retracted fact.

  2. For each such token: send a retraction downstream.

No join test is evaluated: a retraction ends these pairs, and a pair it ends records no fault ([LERR.1.4.12]).

On left-retraction (token removed from left parent):

  1. For each extended token that was built from this token: send retraction downstream.

checks: idris×89 — see also: LERR.1.4.12

[IRET.7.8] Token retraction propagates depth-first to terminal nodes. At a terminal node, retraction removes the corresponding activation from the agenda (if not yet fired) and ends the activation, withdrawing whatever justifications its firing recorded ([IRET.12.2]).

checks: idris×24 — see also: IRET.12.2

NOT (negative) nodes [IRET.7.9]#

A NOT node implements the no Schema s pattern. Its semantics: a token passes through the NOT node only if the join produces zero matches in the right memory.

checks: idris×28

[IRET.7.9.1] On left-activation (new token from left parent):

  • Count matches in right alpha memory using join tests.

  • If count == 0: propagate the token as-is downstream (the absence is "matched").

  • If count > 0: do not propagate; record that this token is blocked by count facts.

checks: idris×29

[IRET.7.9.2] On right-activation (new fact in alpha):

  • For each token in left memory: re-evaluate join tests with this new fact.

  • For each token that now matches: increment its block count. If block count was 0 before: retract the downstream token (the absence no longer holds).

checks: tla×2 idris×17

[IRET.7.9.3] On right-retraction:

  • For each left token the retracted fact blocks, as the index of [IRET.7.9.4] records it: decrement its block count. No join test is evaluated.

  • Each token whose block count drops to 0 propagates downstream (the absence holds again). Its wave derives the pairs below it ([LERR.1.4.12]).

checks: tla idris×13 — see also: IRET.7.9.4, LERR.1.4.12

[IRET.7.9.4] Block count tracking. A token's block count at a NOT node is the number of right facts its left-token join index records as blocking that token, keyed by token identity ([IRET.7.3]). There is no separate count structure, so the count and the blockers cannot disagree. Right-activation and right-retraction update the index. A token with no recorded blocker holds no entry.

checks: idris×9 — see also: IRET.7.3

[IRET.7.9.5] NOT nodes do not produce extended tokens. The passing token carries only the left-side facts; the "right" slot is conceptually the absence. Downstream nodes see fact_count unchanged.

then ... within temporal chain structure [IRET.7.10]#

[IRET.7.10.1] A then ... within sequence compiles to a linear left-associative chain of join nodes plus test CEs (RLOW.5.6). A two-step sequence A then B within T produces:

alpha(A) → beta_join_1 → alpha(B) → beta_join_2(test: ts_B - ts_A < T) → terminal

Each additional then C within T2 appends one more join node; the within constraint becomes a test CE on the immediately preceding event pair (RLOW.5.6.3). The chain is linear, not a DAG.

checks: idris — see also: RLOW.5.6, RLOW.5.6.3

[IRET.7.10.2] latest modifier (RLOW.5.6.5). When the anchor pattern is prefixed with latest, the compiler adds a NOT sub-node immediately after the sequence's last join, where the anchor and every follower are on the token. For an anchor at ts_a and a first follower at ts_b within window T, the NOT node's join test blocks the match whenever a fact f of the anchor's schema has ts_a < f.ts < ts_b, ts_b − f.ts < T, and none of the anchor's where and the followers' wheres, with f in the anchor's place and the followers on the token unchanged, answers false ([RLOW.5.6.5.2], [LTHE.2.5.3], [LNUL.4.7]).

Only the first follower's window and ordering involve f: each later within is measured from the step before it ([LTHE.2.3.1]), never from the anchor. A follower where that does not read the anchor already holds of the token whichever anchor is in place, so the compiler may omit it from the test. In a two-pattern sequence the last join is the first follower's.

This reduces the activation set to the single latest qualifying anchor per match of the followers. latest applies only to the first (anchor) pattern in a sequence; the compiler rejects it on interior patterns (RLOW.5.6.5.4). The NOT sub-node is a standard is_negative = true beta node; no new node type is required.


checks: idris×4 — see also: LNUL.4.7, LTHE.2.3.1, LTHE.2.5.3, RLOW.5.6.5, RLOW.5.6.5.4, RLOW.5.6.5.2

Terminal nodes [IRET.8]#

A terminal is where a fully-matched token becomes a firing. It holds the rule's name (interned), its ordering weight and its RHS action list. It holds no truth-maintenance flag: whether a firing records a justification is decided per action ([IRET.8.3]).

The terminal ordinal is the agenda's FIRST key. It is the rule's zero-based index in the artefact's terminal sequence, which is canonical source order ([RLOW.14.3]) — so the comparator reads it directly and no per-rule annotation or lookup is needed. [LDET.5.4] is the normative statement.

ds_rete_terminal_t is declared in runtime/src/libds/rete/terminal.h.

see also: IRET.11.1, IRET.8.3, LDET.5.4, LTES.12.9, RLOW.14.3

[IRET.8.1] Activation. When a terminal node receives a token (from its parent beta node), it creates an activation and inserts it into the agenda. When the token is retracted, the corresponding activation is removed.

checks: tla×4 idris×81

[IRET.8.2] Refraction. A terminal node maintains a refraction table: the set of token identities for which an activation has already fired and not been re-created, keyed by token hash (pre-filter) plus the fact-id tuple (the key); see [IRET.11.3] for the full contract and the identity-tiebreak rationale. On activation fire, the token identity is added to the refraction table. On re-activation (same token, after the fact that caused it changed), refraction state for that identity is cleared ([IRET.11.3.2]).

ratified — checks: idris×5 — see also: IRET.11.3, IRET.11.3.2

[IRET.8.3] Justification is the emit's, not the rule's. A firing records its activation as a justification for the fact each of its logical emits asserts (ACTION_LOGICAL_ASSERT, [IRET.12.1]). An explicit emit (ACTION_ASSERT) records none, whatever else the rule does, and no field of the terminal changes either.


checks: idris×2 — see also: IRET.12.1

[IRET.8.4] logical: false overlay — the retraction path. terminal_left_retract is the engine function that runs when a rule's supporting token is retracted. Normally it:

  1. Copies TMS IDs to a local stack array (re-entrancy safety).

  2. Withdraws from the TMS to retrieve the logical fact IDs.

  3. For each ID, retracts the WM fact — potentially triggering further alpha/beta retractions (cascade).

  4. Frees the scratch buffer if caller_must_free.

Under logical: false, steps 1–4 are absent. terminal_left_retract only removes the terminal token from the token pool. No WM retraction is triggered from the TMS path.

This is the mechanism by which [LNOG.4.2]'s no-cascade guarantee holds: the observable consequence — a supporting token's retraction withdraws nothing else — stays in [LNOG.4.2]; the named steps of this engine's function are implementation.

checks: idris×2 — see also: IRET.8, LNOG.4.2

Expression evaluation [IRET.9]#

Expression node kinds [IRET.9.1]#

An expression is a tree of nodes, each of one kind:

Kind

Node is

literal

an Int, Float, String or Bool constant, or null ([LNUL.2.1])

var

a fact slot reference — (pattern position, slot index)

binop

binary arithmetic, comparison, logical or bitwise

unop

unary not, bitwise-not, or negate

call

a builtin invocation — op plus arguments ([IRET.13.1])

interp

an interpolated string: literal text, values under their specs, time fields ([RLOW.6.4])

now

reads the clock source

json-path

traversal of a Json value by path

if

a conditional

bind / bind-ref

a let binding and a reference to one

coalesce

left ?? right, evaluating left once ([LNUL.8.9])

is-test

x is <subject>, a total tag test ([LNUL.4.9])

entry-stamp

the entry stamp of the fact bound at a pattern position ([LTIM.2.8.6])

Two of these are narrower than their names suggest, and the narrowing is deliberate:

Var is positional, naming a pattern position and a slot index rather than a name. Name resolution happens at lowering, so evaluation never performs a lookup.

Bind exists because a let may be sync-impure. A pure let folds at lowering and leaves no node behind; the bind/bind-ref pair is what remains when it cannot.

see also: IRET.13.1, LNUL.2.1, LNUL.4.9, LNUL.8.9, LTIM.2.8.6, RLOW.6.4

Evaluation context [IRET.9.2]#

Everything an expression evaluation may read, gathered into one value so evaluation itself is a pure function of its context:

Field

Holds

token

the current partial match — how a slot reference resolves

right_fact

the fact arriving on the right, during join evaluation

bind_frame

the let bindings in scope

bind_count

how many are bound

engine

reached only for builtin dispatch and the clock

Two properties are load-bearing:

right_fact is absent when evaluating a RHS action. That is what distinguishes the two evaluation sites — a join test evaluates against a candidate fact, an action evaluates after the match is settled and there is no candidate. Its absence is the signal, not an error.

The bind frame is stack-allocated. let bindings live for exactly one evaluation, so they cost no allocation and need no freeing — which is what lets let be used freely under constspace and in LIVE mode.

[IRET.9.3] VAR nodes: pattern_index < token->fact_count reads from token->facts[i]->slots[j]. When pattern_index == DS_RETE_VAR_RIGHT_FACT, the value comes from ctx->right_fact->slots[j] (used in join tests when evaluating the candidate right fact).

[IRET.9.4] BIND nodes: evaluate expr, store the result in ctx->bind_frame[bind_index], return the value. BIND_REF reads from the same frame. The bind frame is zeroed and stack-allocated at RHS evaluation entry.

[IRET.9.5] Evaluation order. and / or may evaluate their operands in any order and may stop once the result is decided, but the result must be [LNUL.4.2]'s absorbing one. An operand that faults — a trap, a TypeError, or an EngineError raised by evaluating it — does not end the evaluation: the evaluator holds the fault, evaluates the remaining operands, and a false (true for or) among them decides the result and discards every held fault. When nothing decides, the expression yields the one fault [LNUL.4.2]'s order selects. A held fault that is discarded or not selected reaches no fault surface ([LERR.1.4.11]).

checks: alloy×5 k idris×15 — see also: LERR.1.4.11, LNUL.4.2

[IRET.9.6] Ill-typed operations and renderings split three ways, and null is the first test. Arithmetic on wrong types (e.g. adding a String to an Int) yields no value, and so does a format spec the value it is given cannot render (a numeric spec over a Json leaf holding a string). Both raise, and which fault they raise depends on the operand:

  • An operand is null — TypeError. A null in a slot declared T? is a value the artefact declared, so absence is data and is never evidence that the artefact lied. The activation is abandoned. This arm is reached only where an operation refuses a null at all, which is a narrow set: a conversion yields null for a null source rather than raising, and null propagates through arithmetic and comparison ([LNUL.4.1]). What remains is the builtins that demand a value of a particular kind — and a T? slot cannot reach one, because a builtin's receiver and its arguments are both concrete-value positions ([LNUL.5.1]) and an un-narrowed nullable is refused there at compile time. The route that remains is a Json projection whose leaf is a present JSON null ([LNUL.8.4]) — a value rather than absence, carried by a slot whose shape is not schema-committed, and so not refused before it runs. A narrowed T? ([LNUL.5.4]) meets this arm only when the conjunct it narrows is evaluated before its guard; the guard is then false, and absorbs the TypeError ([LNUL.4.2]).

  • Neither operand is null, and one derives from a Json slot — TypeError. A wrong-typed Json value is data, whether it is a leaf a projection reached or the whole slot read directly. Json is the one slot type whose shape is not schema-committed ([LADP.5.5.3]), so this is expected in normal operation and attributable to a node. The activation is abandoned.

  • Otherwise — EngineError. The load-time shape said one thing and the value is another, so the artefact lied and nothing about it is trustworthy. The tier halts.

Each disposition is that of a fault the expression yields. A deciding operand of and / or absorbs any of the three ([LNUL.4.2]): an absorbed TypeError abandons nothing, an absorbed EngineError does not halt the tier, and neither reaches a surface ([LERR.1.4.11]). An EngineError the expression yields halts the tier, and that run is outside the determinism guarantee ([LDET.1.11]).

The order of the first two tests is normative, not an implementation detail. A null reaching an operation through a Json projection is both null and tainted, and both orderings classify it TypeError. The rule is that absence decides before provenance, because absence is data whatever carried it, and provenance is only the question of whether a present value's type can be trusted.

Provenance starts at every read of a Json slot, a bare slot read as well as a projection. Provenance is transitive — (j.a + 1) > 5 buries the projection a level down — and a raising site sees only a tag and a union. So provenance is computed by the compiler and lowered onto the node as Expr.json_tainted (proto/rete_expr.proto); the evaluator reads it, it does not derive it.

Taint flows through a let and clears at a :: cast and at ??: both establish the type and carry their own disposition, so a later ill-typed operation on the far side means something else is wrong — the EngineError criterion exactly. Taint is rule-local; a value reaching a slot has passed through emit into a schema-committed slot, so provenance ends at the fact boundary.

An absent flag means clean: proto3 has no presence for a scalar.

An interpolation segment carries the flag like any other node. A segment reading a Json value is tainted, so a format spec that cannot render it abandons the activation rather than halting the tier — the same disposition the same value gets one operator away ([LADP.5.5.3]). A null or absent value is not this case: it renders as the empty string ([LGRA.2.9.6.2]) and raises nothing.

⚠ Json path traversal is NOT one of these. [LNUL.8.4] governs it: an unresolved path reads as null, and a path resolving to a JSON null reads as null as a present value. Both are null; has(path) is what tells them apart, and it is the only absence test. An unresolved path is absence, not an ill-typed operation, and it does not abandon the activation.

ratified — checks: alloy×2 k idris×3 — defined in: proto/rete_expr.proto#Expr — see also: LADP.5.5.3, LDET.1.11, LERR.1.4.11, LGRA.2.9.6.2, LNUL.4.1, LNUL.4.2, LNUL.5.1, LNUL.5.4, LNUL.8.4

Binary operator table [IRET.9.7]#

DS

Node kind

Operand types

+ - * /

BINOP / ARITH

Int×Int→Int, Float×Float→Float, Int×Float→Float

// %

BINOP / INT_ARITH

Int×Int→Int

== != < > <= >=

BINOP / CMP

numeric, String (interned ptr), Bool

and or

BINOP / LOGICAL

Bool×Bool→Bool

& | ^ << >>

BINOP / BITWISE

Int×Int→Int

~

UNOP / BIT_NOT

Int→Int

not

UNOP / LOGICAL_NOT

Bool→Bool

negate (-x)

UNOP / NEGATE

Int→Int, Float→Float


linear_scan: false — expression kinds unreachable in the pump path [IRET.9.8]#

When the loaded DSC was compiled with linear_scan: false, the following expression kinds are unreachable in the pump path:

Kind

Why unreachable

DS_RETE_EXPR_JSON_PATH

No json slots ([LNLS.3.1])

DS_RETE_EXPR_INTERP producing novel strings

Blocked by [LNLS.3.2]

All remaining expression kinds are bounded and operate as specified in the base [IRET.9] definition.

This is a consequence of the exclusions rather than an independent obligation, and it is stated because an implementer sizing the evaluator needs to know which arms cannot be entered.

see also: IRET.9, LNLS.3.1, LNLS.3.2

Actions [IRET.10]#

RHS actions are evaluated in order when an activation fires. Each action is an expression that may have side effects via builtin calls.

The action record is ds_rete_action_t, declared in runtime/src/libds/rete/action.h.

[IRET.10.1] Emit action. emit Schema slot: val ... lowers to an assertion action. The action node carries the schema ID and a list of (slot_index, expr) pairs. At fire time the evaluator builds a ds_rete_fact_t with the evaluated slot values and calls ds_rete_wm_assert.

[IRET.10.2] Logical emit. Same as plain emit but registers the asserted fact's ID in the TMS dependency table under the current activation's ID.

checks: idris×9

[IRET.10.3] Builtin actions. All other action verbs (ds-log, ds-call, etc.) are CallIssued expression nodes in the action list. The evaluator dispatches to the named builtin.

[IRET.10.4] Rate gate. A rule's cooldown lowers to its terminal's fire_guard ([IRET.16.6]), evaluated before the action loop: a false result skips every action. A call site's cooldown gates that call alone ([RLOW.4.6.6.1]).

Either gate calls the rate-allow builtin (FN_RATE_ALLOW), which receives (name, key_1, ..., key_N, cooldown_ns): a tracker name (the rule's, or a call site's <rule>#call<N>, [IRET.25.5.1]), then the activation key's components, which [LCDB.3.3.3] composes from the bound facts, then the window in nanoseconds. The window is always the last argument. The builtin maintains per-engine state keyed by (name, activation_key):

  • Cooldown (RLOW.4.6.2): state value is last_fire_ns. Returns true (allow) when now_ns - last_fire_ns >= cooldown_ns. On allow, updates last_fire_ns = now_ns.


checks: k idris×5 — see also: IRET.16.6, IRET.25.5.1, LCDB.3.3.3, RLOW.4.6.2, RLOW.4.6.6.1

[IRET.10.5] Withdraw action. withdraw b lowers to an ACTION_WITHDRAW whose withdraw_pattern_index is b's position in the activation token ([RDSC.4a.8]). At fire time the engine must retract the fact at that position as an engine retraction: the fact leaves working memory, the retraction propagates through the network as any other does ([IRET.7.8]), and the stream records it as a FactWithdraw with cause AUTHOR_WITHDRAWN ([RFCS.7a.2]). If the fact is no longer live when the action runs, the action does nothing.

The action does not end the firing. The actions after it run, and none of them refers to the withdrawn fact, because the compiler refuses one that would ([LGRA.10.1.3]).

ratified — see also: IRET.7.8, LGRA.10.1.3, RDSC.4a.8, RFCS.7a.2

[IRET.10.6] An action kind the engine does not execute is refused at load. The loader must check each Action.kind against the kinds the engine executes, and refuse an artefact carrying any other with DS_ERR_DSC_SEMANTIC ([NERR.8.1]). An unknown kind left to the action loop is executed as whichever action its value happens to fall through to, which does something the artefact never asked for.

ratified — see also: NERR.8.1

[IRET.10.7] Withdraw in a nested body: by identity. A withdraw b in a nested body ([LGRA.10.1.4]) cannot use a pattern position, because the rule that runs the body is the synthetic sibling, whose activation token does not hold b's fact. It lowers instead to an ACTION_WITHDRAW_BY_ID, whose withdraw_fact_id reads a reference to the withdrawn fact from the fact that carries the body's captured values: the capture fact, or for a timeout body its timer ([LCCO.7.2]).

  • The compiler must add to the capture fact ([LCCO.5.2], [LTAC.3.5]) one slot per binding a nested body withdraws, typed by that binding's schema ([LGRA.5.7a.2]) and holding a reference to the fact the outer rule bound to it when the rule fired, and the same slot to a timeout clause's timer when its body withdraws the binding. A capture fact that carries such a slot has something to capture, so [LCCO.5.6] and [LTAC.3.6] do not omit it.

  • The engine must, at fire time, resolve that reference and, when it names a live fact, retract that fact exactly as for ACTION_WITHDRAW ([IRET.7.8]), recorded as a FactWithdraw with cause AUTHOR_WITHDRAWN ([RFCS.7a.2]). A reference names one fact by its id, and an id is never reused ([IRET.4.4]), so once that fact has left working memory the reference names nothing and the action does nothing. A fact replaced by a meaningful change is a new fact ([LFAC.2.5.3]), so its replacement is never matched.

A runtime that does not execute this kind refuses the artefact at load ([IRET.10.6]).

see also: IRET.10.6, IRET.4.4, IRET.7.8, LCCO.5.2, LCCO.7.2, LGRA.10.1.4, LGRA.5.7a.2, LCCO.5.6, LFAC.2.5.3, LTAC.3.5, LTAC.3.6, RFCS.7a.2

Agenda [IRET.11]#

An activation is a matched rule waiting to fire: which rule, which token satisfied it, when the match was made, and whether it has already fired.

Field

Holds

rule

the terminal whose LHS matched

token

the match itself

creation_timetag

when the match was made — the SECOND key, within one rule

fired

whether this activation has already fired

Ordering comes from two places and never from arrival: the activation's terminal ordinal ([IRET.8]) is the first key, and the creation timetag orders the activations of ONE rule against each other ([LDET.5.4], [LDET.5.5]).

Refraction is the flag on the activation. A fired activation stays on its terminal's list, carrying the flag, and is not selected again while its match lasts ([IDAT.6.2.2]), so asking whether a match has fired cannot drift out of step with the activation it describes. Two per-terminal structures back the flag where a match is formed again without having ended: the refraction table ([IRET.11.3]) and the edge-once set for clock-driven matches ([IRET.11.3.5]). The identity both key on is the (rule, token) pair — see [IRET.11.3.3] for why the token's fact-id tuple, and not its hash, is what makes that identity safe.

checks: idris×12 — see also: IDAT.6.2.2, IRET.11.3, IRET.11.3.3, IRET.11.3.5, IRET.8, LDET.5.4, LDET.5.5

Ordering [IRET.11.1]#

The agenda is a min-heap (or sorted structure) ordered by the comparison key (terminal ordinal, creation_timetag) — lower ordinal first, and among activations of the SAME rule, earliest-created first. Both keys are read directly off the activation and its terminal; neither needs a lookup.

Two keys suffice, and neither has to be assumed unique. The ordinal is unique per rule, so it separates activations of different rules outright. Two activations of one rule share an ordinal but cannot share a timetag, because a timetag is assigned per token and a token reaches exactly one terminal.

The timetag never decides between two rules, and that is the point: which match completed first is a property of propagation order, and [LTES.12.9] requires the firing order to be spec-defined rather than implementation-defined.

checks: idris×26 — see also: IRET.8, LDET.5.4, LTES.12.9

[IRET.11.2] The agenda does not use hash-based ordering at any level. The total order is deterministic given a deterministic creation_timetag — a stamp monotone in completion order, compared as [LDET.5.5] defines.

ratified — see also: LDET.5.5

Refraction [IRET.11.3]#

Refraction is a property of the activation, the flag [LDET.5.3] describes ([IRET.11]). Each terminal node also keeps a refraction table of the token identities that fired in the engine's current cycle generation. The generation advances on every working-memory assert and retract and once per pump; an entry of an earlier generation is stale and matches nothing, so the table empties without being walked. The table catches an activation formed again for an identity that already fired before any change to working memory, and so before the match could have ended ([IRET.11.3.2]). The token identity is the activation's tuple of participating fact ids; the 32-bit token hash is a pre-filter, not the key. An entry matches only when both its token hash and its fact-id tuple match (refract_identity_match, terminal.c).

checks: alloy×9 tla×2 idris×88 — see also: IRET.11, IRET.11.3.2, LDET.5.3

[IRET.11.3.1] Refraction is applied at selection, to the activation selected ([LDET.5.3]). A fired activation is not selected again: it left the agenda when it fired and stays on its terminal's list with the flag set. An activation selected whose token identity has an entry in the current generation's table is discarded unfired. When an activation fires, its token identity (hash + fact-id tuple) is entered in the table at the current generation.

ratified — checks: tla×3 idris×32 — see also: LDET.5.3

[IRET.11.3.2] A fired match stays refracted until its activation is re-created: its token re-asserted under a new wrapper, retracted, released by a negated condition of its rule, or ended by a time-dependent test that went false and made again when the test goes true ([LTIM.2.5.1]). Nothing else releases it — not an unrelated assert or retract, not a pump boundary, and not a clock tick under which its match persists ([LDET.5.8]). A match blocked and released within one pump is re-created and may fire again.

The flag carries this, not the table. A generation's turnover — every working-memory assert and retract, and each pump — leaves every table entry stale, but releases no match: an activation the change did not reach keeps its flag and is not selected again, and one it did reach is re-created. The table's entries matter only within one generation; a clock-driven match formed again on every tick is held by the edge-once set ([IRET.11.3.5]).

ratified — checks: tla×2 idris×9 — see also: IRET.11.3.5, LDET.5.8, LTIM.2.5.1

[IRET.11.3.3] The identity tiebreak is required for confluence. Keying refraction by token hash alone lets two distinct activations whose tokens collide on the 32-bit hash cross-suppress: the second is wrongly treated as already-fired and its RHS never runs. Because a from-scratch (batched) build restarts fact ids at 0 — so its small ids yield small, collision-prone hashes, while the incremental engine's spread ids rarely collide — this made the batched result derive fewer facts than the incremental one, violating the batched-equals-incremental determinism contract ([LDET.5]). The fact-id tiebreak restores it.

The tiebreak applies under every capability setting, the pooled strategy of constspace and realtime included ([LDET.1.12]). There the runtime captures the fact-id tuple in a fixed-size buffer: a token's fact count is bounded by the network, so capturing it allocates nothing.

ratified — checks: alloy idris×4 — see also: LDET.1.12, LDET.5

[IRET.11.3.5] The edge-once set. A clock-driven match — a token that joins $ClockTick for a time-dependent test ([IRET.19.5]) — is formed again on every tick, with a new token. Each terminal keeps a set of the fact ids whose clock-driven match has fired. A re-formed activation for a fact in the set is suppressed, tick after tick, until the match ends: the engine must remove the fact's id when the time-dependent test goes false, so that the next true is a new match and fires ([LTIM.2.5.1]), and when the fact leaves working memory. A fact that is upserted takes a new id, which the set does not hold. Unlike the table ([IRET.11.3]), the set survives a generation's turnover.

checks: idris — see also: IRET.11.3, IRET.19.5, LTIM.2.5.1

Firing loop [IRET.11.4]#

ds_rete_run(engine, max_fires, fires_out):

  1. While the agenda is non-empty and fires_out < max_fires: a. Pop the highest-priority non-refracted activation. b. Call before_fire hook. c. Evaluate the activation's RHS actions in order. d. Call after_fire hook. e. Mark the activation's token identity (hash + fact-id tuple) as refracted in the terminal's refraction set. f. Increment fires_out.

  2. Return DS_OK (agenda drained) or DS_ERR_BUDGET_EXCEEDED.

checks: idris×179

[IRET.11.5] max_fires = 0 means unlimited (run until empty). The existing ds_engine_pump contract maps to ds_rete_run(engine, 0, NULL).


checks: tla×2 idris×43

Truth maintenance [IRET.12]#

checks: alloy×3 tla×14 idris×74

[IRET.12.1] Justification. When a firing runs an ACTION_LOGICAL_ASSERT ([RLOW.7.1.3]) and so emits a logical fact F ([LLOG.15.1]), the engine:

  1. Asserts F into working memory (may be a no-op if F already exists with matching slot values).

  2. Increments F->justif_count.

  3. Records the pair (activation_id → fact_id) in the dependency table.

ratified — checks: idris×15 — see also: LLOG.15.1, RLOW.7.1.3

[IRET.12.2] Justification withdrawal. The engine must retract exactly the logical facts [LLOG.2.5] leaves unsupported: a logical fact survives while it has a well-founded justification, one that does not rest on the fact itself.

On every program [LCYC.3.1.1] admits, support is acyclic — no SCC both emits and matches a schema — so a count of live justifications decides it, and libds maintains one. When an activation ends (its token is retracted because a supporting fact in the LHS was retracted or a NOT condition became unsatisfied):

  1. Look up all logical facts this activation supports in the dependency table.

  2. For each: decrement justif_count.

  3. For each where justif_count == 0: retract the fact from working memory (generating a fact_retract stream event). The retraction may cascade through the Rete network if other rules pattern-match on F.

  4. Remove the activation's entry from the dependency table.

An activation can end inside its own firing ([LLOG.15.1]), when an action of the firing retracts a fact its token holds. The steps run at that action, and the firing goes on. The engine must not enter a logical fact the firing asserts after that action in the dependency table against the ended activation. It must retract that fact as it is asserted, unless another live justification already holds it.

The clock tick's turnover ends no match. The tick is not a supporting fact: a match that persists across ticks is one match ([IRET.19.5]), so the engine must not run these steps when the only change to its token is the tick. The activation formed again with the new tick takes over the justifications of the one the tick's retraction removed (carry_across_tick, terminal.c). The activation ends, and its justifications are withdrawn, on the tick at which its time-dependent test goes false ([LTIM.2.7.2]).

The count is correct only because support is acyclic. On a support cycle it keeps every member's count above zero with no well-founded justification left, and [LLOG.2.5] retracts them. So admitting emit-and-read cycles — the shape a +recursive admission would license — requires replacing the count with a mechanism that finds unfounded sets, and must not land without one.

ratified — checks: alloy×2 tla×3 souffle×6 idris×189 — see also: IRET.19.5, LCYC.3.1.1, LLOG.15.1, LLOG.2.5, LTIM.2.7.2

[IRET.12.3] Multiple justifiers. A logical fact F asserted by two activations A1 and A2 has justif_count = 2. When A1 ends, justif_count drops to 1; F is not retracted. When A2 also ends, justif_count drops to 0 and F is retracted.

ratified — checks: alloy tla idris×26

[IRET.12.4] Dependency table. An oa map ([IRET.28]) keyed by the justifying activation's creation timetag, which no two activations share. Each value holds the activation's rule name and the ids of the logical facts it justifies: up to 16 inline, overflow in a heap list.


checks: idris×27 — see also: IRET.28

Builtin dispatch [IRET.13]#

All builtins are ours — there is no user-extension surface. A CALL expression node (rete CallExpr) carries a numeric BuiltinFn op on the wire (proto/builtin_fn.proto); the runtime dispatches by that op through a global, op-indexed array — no builtin name strings, no hashing, no interning.

The builtin signature is ds_fn_t, declared in runtime/src/libds/fn.h.

defined in: proto/builtin_fn.proto#BuiltinFn

[IRET.13.1] Dispatch is an O(1) index into ds_builtin_dispatch[] by the CALL node's op (ds_lookup_fn(op)). The table is global and shared across engines (builtins are fixed), zero-initialised in .bss (every op starts unregistered), and populated once, idempotently at engine init by the module register functions. An op that is zero, out of range, or has no registered handler is refused at load with DS_ERR_FN_NOT_FOUND ([RDSC.4a.9.3]), so evaluation never meets one in a loaded artefact; eval_call raises an artefact fault (DS_FAULT_ARTEFACT) for one it meets in a network built by hand. Cross-file registration is first-registrant-wins (a duplicate op re-registers identically; where two modules could register the same op — e.g. FN_REGEX_MATCH — the one that inits first owns it).

see also: RDSC.4a.9.3

[IRET.13.2] The op registry is enum BuiltinFn (proto/builtin_fn.proto; C mirror runtime/src/libds/builtin_fn.h as enum ds_builtin_fn / DS_FN_*), reached through the native-rete CallExpr.op. Op values are a registry: assigned once, never reused. A reserved number has no handler and is never emitted; proto/builtin_fn.proto lists them, among them the belief candset (42,43), the byte/string conversions (68,71-74, [LSTR.4.6]) and the string distances (38,39, [LEXP.5.6]). Representative op groups and their handlers:

Op group

Handlers (register site)

Actions FN_EMIT / FN_LOG / FN_CALL / FN_PUBLISH / FN_CACHE_SET / FN_CACHE_GET / FN_CACHE_DELETE / FN_RATE_ALLOW / FN_RETRACT_CORR / FN_RETRACT_TOKEN_FACT

rete/adapters.c (RT-safe)

Math / rounding FN_ABS / FN_ROUND / FN_FLOOR / FN_FLOOR_TIME / FN_CEIL / FN_TRUNC / FN_SIGN / FN_SQRT / FN_POW / FN_MIN / FN_MAX / FN_DEGREES / FN_RADIANS; bitwise FN_BIT_*; distances FN_EUCLIDEAN_2D … FN_COSINE_3D; FN_REGEX_MATCH / FN_JSON_PATH / FN_JSON_HAS / FN_STR_LENGTH / FN_NOW

builtins.c

Series reads FN_SERIES_MEAN … FN_SERIES_ONSET_RATE, FN_SERIES_PERCENTILE

engine_rete_adapters.c (op → agg-kind)

String/time/json adapters FN_TO_STRING / FN_CALENDAR_TIME / FN_CALENDAR_DATE / FN_TIME_DATE / FN_UTC / FN_LOCAL / FN_MONOTONIC_NS / FN_JSON_BUILD / FN_JSON_VALUE / FN_GENSYM

rete/adapters.c

defined in: proto/builtin_fn.proto#BuiltinFn — see also: LEXP.5.6, LSTR.4.6

[IRET.13.3] RT-safety. A builtin registered via ds_register_fn_rt is flagged rt_safe (O(1)/bounded, no allocation). The action adapters register RT-safe; the general math/string builtins register via ds_register_fn (rt_safe defaults false).

The refusal belongs at load ([RTCT.7.8]): an artefact whose rules can reach a non-rt_safe op under constspace: true — and so under realtime, which requires it — is rejected with DS_ERR_RT_UNSAFE before any fact is processed. An op that could fault in the pooled strategy and succeed in the ordinary one would otherwise change a result by setting ([LDET.1.12]).

In the pooled strategy the CALL evaluator additionally rejects a non-rt_safe op before invoking it. That check is defence in depth, not the contract — reaching it means an artefact got past the load gate, which is a defect in the gate rather than a condition an author can produce. It is retained because the evaluator cannot verify that the gate ran.

see also: LDET.1.12, RTCT.7.8

[IRET.13.4] Adding a builtin requires: (a) a new BuiltinFn op (append at the next free value; never reuse a tombstone), (b) a registered handler, (c) the compiler emitting the op. No change to the evaluator's dispatch loop.


defined in: proto/builtin_fn.proto#BuiltinFn

Clock integration [IRET.14]#

The engine does not read a clock. It is given its two ([LTIM.2.8.1]): a monotonic function returning nanoseconds, and a wall function writing UTC nanoseconds and answering false while it has no reading, sharing one opaque context pointer handed back on each call. The engine calls them only at the sample points [LTIM.2.8.4] names.

That indirection is what makes determinism testable rather than merely intended. The same engine takes wall time in production and a mock clock under test, with no code path that differs between them — so a recorded run replays against the recorded ClockAdvance values and reproduces exactly ([LFST.9.2.1]). An engine that called a system clock directly could not offer that.

The context pointer means the clock needs no globals, so two engines in one process may run on entirely independent clocks.

The setters are ds_rete_set_clock, which takes the monotonic function and the context, and ds_rete_set_wall_clock, which takes the wall function, both declared in runtime/src/libds/rete/engine.h. Each returns ds_result_t and refuses a NULL function with DS_ERR_INVAL.

see also: LTIM.2.8.1, LTIM.2.8.4, LFST.9.2.1

[IRET.14.1] NOW expression nodes read the engine's held wall-clock sample directly, and monotonic_ns() nodes its held monotonic sample; neither calls the clock function, which runs only at a sample point ([LTIM.2.8.4]). This is not a builtin call (it would be hot path in time-bound rules); it is a direct field read in the evaluator.

checks: idris×3 — see also: LTIM.2.8.4

[IRET.14.2] The now and monotonic_ns builtins in the builtin table are thin wrappers that read the same held samples. It exists so CALL expression nodes for now() in contexts where the compiler emits a builtin call also work.

[IRET.14.3] clock_gettime(CLOCK_MONOTONIC) and clock_gettime(CLOCK_REALTIME) are the live-mode implementation, read together. The test harness sets controlled counters via this hook. No code outside the clock source reads wall time.


Module integration [IRET.15]#

Wiring into libds [IRET.15.1]#

The C Rete engine is one subsystem of ds_engine_t. ds_engine_new creates it (ds_rete_engine_create, stored as engine->rete_engine), registers the built-in callable functions (ds_register_builtins), and calls ds_engine_wire_rete_adapters, which populates the engine's ds_rete_adapter_config_t with the action-verb callbacks (log, call, publish, emit, cache). The Rete engine is libds's only rule-evaluation substrate, and nothing selects it.

libds drives the engine through these entry points:

libds operation

ds_rete_* entry point

Create engine

ds_rete_engine_create(&rete_engine)

Destroy engine

ds_rete_engine_destroy(rete_engine)

Load compiled network

ds_rete_load(engine, atom bodies)

Before-fire hook

ds_rete_set_before_fire(engine, hook, ctx)

After-fire hook

ds_rete_set_after_fire(engine, hook, ctx)

Assert a fact

ds_rete_wm_assert(engine, …)

Retract a fact

ds_rete_wm_retract(engine, fact)

Run the agenda

ds_rete_run(engine, max_fires, fires_out)

Register a callable

ds_register_fn / ds_register_fn_rt

Agenda ordering

built into the agenda (no API)

DSC loader [IRET.15.2]#

The loader reads the RETP atom set — the AlphaNode / BetaNode / TerminalNode atoms — and calls ds_rete_load, which assembles the in-memory node graph. There is one load path; the loader does not branch on a backend flag.


The RETP atom set — AlphaNode / BetaNode / TerminalNode [IRET.16]#

[IRET.16.1] The compiled Rete network for one source module is carried as a set of per-node DSC atoms — one AlphaNode atom per alpha node, one BetaNode per beta node, one TerminalNode per terminal node ([RDSC.4a]). There is no single top-level container message. The set carries the full node graph and the expression trees for all tests and actions; schema descriptors arrive separately via the SCHEMA atom family (below).

see also: RDSC.4a

[IRET.16.2] Per-node atom shapes (proto/{alfa,beta,term}.proto) — each node is its own atom keyed by a node_id:

The three node messages are proto/alfa.proto#AlphaNode, proto/beta.proto#BetaNode and proto/term.proto#TerminalNode. [RDSC.4a.6] and its siblings tie the DSC format to the same messages; this clause does not restate them ([STYL.2.15.5]).

see also: RDSC.4a.6

[IRET.16.3] Schema descriptors are not carried here. Schema name, slot descriptors (name, type, tolerance, flags), scope, and default TTL arrive via the SCHEMA atom family (SchemaTtl/SchemaLogical/Slot/SchemaDef/SchemaSource) and register into the rete schema reg (dsc/loader.c::dsc_register_rete_schemas) before the AlphaNode/BetaNode/TerminalNode atoms load.

[IRET.16.4] The AlphaNode atom encodes its node_id, the schema_name it filters, and a list of alpha test descriptors (kind, slot index, op, literal value or compiled-regex pattern string). Downstream beta inputs reference this node by node_id.

checks: idris×4 — defined in: proto/alfa.proto#AlphaNode

[IRET.16.5] The BetaNode atom encodes its node_id, right_alpha_id, left_parent_id (0 = WM root), the join-test expression trees, and the negative flag. Parents are referenced by node_id.

checks: idris×6 — defined in: proto/beta.proto#BetaNode

[IRET.16.6] The TerminalNode atom encodes its node_id, parent_beta_id, rule_name, bind_count, the RHS actions (as expression trees), and an optional fire_guard (a time-dependent condition, the cooldown's rate gate, or both, [RDSC.4a.8.2]).

checks: idris×3 — defined in: proto/term.proto#TerminalNode — see also: RDSC.4a.8.2

[IRET.16.7] Expression trees are protobuf messages with a top-level oneof over expression kinds; recursive child expressions are embedded messages. This is the standard protobuf pattern for trees; the loader recursively constructs ds_rete_expr_t nodes from the protobuf tree. A CALL expression (proto/rete_expr.proto#CallExpr) carries a numeric BuiltinFn op (field 3; the former builtin-name field 1 is reserved) — the loader stores the op directly on the CALL node for O(1) op dispatch ([IRET.13]); no name is interned.

defined in: proto/rete_expr.proto#CallExpr — see also: IRET.13

[IRET.16.8] Node cross-references use the node_id field (a uint32 assigned per node), not array positions — e.g. a beta node names its left_parent_id / right_alpha_id, a terminal its parent_beta_id. The loader validates that every referenced node_id resolves before constructing pointers; an unresolvable reference is DS_ERR_RETP_INDEX_OOB.


Performance characteristics [IRET.17]#

[IRET.17.1] Target workload: tens to hundreds of rules; 100–1,000 live facts; engine pump driven at 10–100 Hz in typical deployments. At this scale, even O(n×r) algorithms are fast. The design targets correctness and simplicity first; profiling gates optimizations.

[IRET.17.2] Alpha dispatch: O(1) schema ID index + O(alpha_count_for_schema) test evaluation. With O(10) schemas and O(5) alpha nodes per schema, this is always fast.

[IRET.17.3] Beta join: worst case O(left_memory × alpha_memory) per join node on a right-activation. With 1,000 facts and typical DS rules matching 2–3 patterns, left memory sizes are small (often single-digit). The typical case is fast; pathological cartesian-product joins are a risk inherent to any Rete network.

[IRET.17.4] Agenda: with O(100) rules and O(1,000) activations, even a simple sorted array or binary heap is fast. The agenda size is bounded by (rules × live facts).

[IRET.17.5] Memory layout v1: standard malloc/free allocations. A later optimization pass can use arena allocation (facts in one arena, tokens in another, expressions in a read-only static arena populated at load time). This is a profiling-gated optimization.

[IRET.17.6] No speculative optimization. v1 indexes partial matches only where [IRET.7.5.1] requires it, on a beta node's equality anchor under linear_scan: false. It does not implement alpha-memory hash-partitioning by slot value, join-order reordering, or compilation of expression trees to arch-specific code.


see also: IRET.7.5.1

Engine lifecycle [IRET.18]#

Engine create and destroy [IRET.18.1]#

ds_rete_engine_create initialises subsystems in this order:

  1. String intern table — an open-addressing hash set with tombstone deletion ([IRET.1.4]): pinned structural strings interned at load and never freed, counted String/Bytes slot values individually allocated and reclaimed on last-holder retract. All subsequent intern calls land here.

  2. Schema registry — name→ds_rete_schema_t * map plus the flat schema-ID → alpha-node-list array. Empty until the load ([IRET.18.2]) populates it.

  3. Agenda — empty binary heap.

  4. TMS dependency table — empty map keyed by the justifying activation's timetag ([IRET.12.4]).

  5. Builtin table — the global op-indexed table ([IRET.13.1]); the module register functions populate it, idempotently, before any load. See [IRET.13.2].

  6. Clock — two function pointers sharing one context, the monotonic clock and the wall clock ([IRET.14]), defaulting to clock_gettime(CLOCK_MONOTONIC) and clock_gettime(CLOCK_REALTIME).

  7. Fire hooks — before_fire and after_fire pointers, initialised to NULL (no-op).

ds_rete_engine_destroy runs teardown in reverse order. Any in-flight tokens and activations are freed; all interned strings are released with the intern-table slab; schema descriptors, node graphs, and expression trees are freed.

On mid-init failure, ds_rete_engine_create frees every subsystem that successfully initialised before returning the error — no partial engine is returned to the caller.

see also: IRET.1.4, IRET.12.4, IRET.13.1, IRET.13.2, IRET.14, IRET.18.2

Load [IRET.18.2]#

The artefact loader (dsc/rete_loader.c) decodes the AlphaNode / BetaNode / TerminalNode atom bodies (IRET.16), and ds_rete_load_network builds the in-memory node graph from them. Steps, in order:

  1. Decode each AlphaNode / BetaNode / TerminalNode atom body via the chosen protobuf library (IRET.23.6). Return DS_ERR_DSC_DECODE on decode failure, before any other check of the body ([RDSC.11.4]).

  2. Validate all node_id cross-references resolve before constructing any pointer (IRET.16.8). Return DS_ERR_RETP_INDEX_OOB on first violation.

  3. Schemas are already registered — the SCHEMA atom family (SchemaTtl/SchemaLogical/Slot/SchemaDef/SchemaSource) loads and registers into the rete schema reg (dsc_register_rete_schemas) before the network atoms.

  4. Construct alpha nodes from the AlphaNode atoms — compile regex test patterns (IRET.6.3); wire into the schema's alpha-dispatch entry.

  5. Construct beta nodes from the BetaNode atoms — allocate join-test expression trees recursively; set is_negative; wire left-parent and right-alpha links by node_id.

  6. Construct terminal nodes from the TerminalNode atoms — allocate RHS action expression trees.

  7. Wire all downstream links (beta children, terminal children, beta inputs on alpha nodes) using the node_id references encoded in the atoms.

If any step fails, the load returns the error and sets the halt latch: a failed load spends the engine ([RDSC.9.8]). The loader undoes nothing it applied. There is no reload: an engine loads one artefact for its life ([RARC.10.1]).


checks: idris×4 — see also: IRET.16, IRET.16.8, IRET.23.6, IRET.6.3, RARC.10.1, RDSC.11.4, RDSC.9.8

[IRET.18.2.1] logical: false overlay — the TMS table is not allocated. When the DSC loader configures an engine for a logical: false program, the TMS table is not initialised and its entry array is left NULL. No memory is allocated for TMS entries, withdraw_scratch, or heap_ids overflow buffers. The RT table pre-sizing step that would normally allocate the TMS scratch is skipped, and the TMS capacity is left zero.

This is the mechanism by which [LNOG.4.1]'s allocation guarantee holds: the guarantee — that a logical: false program allocates nothing for truth maintenance — is observable and stays in [LNOG.4.1]; the field names by which this engine achieves it are implementation.

see also: IRET.18.2, LNOG.4.1

Working memory operations [IRET.19]#

checks: idris×4

Assert [IRET.19.1]#

ds_rete_wm_assert(engine, schema_id, slots, fact_out):

  1. Determine the schema's identity key — the slots whose identity_role is KEY (IRET.4.1, [LFAC.1.7]). Search working memory for an existing fact of the same schema whose KEY-slot tuple matches exactly. Key = ∅ (no KEY slot) is a singleton: any existing fact of the schema matches. Key = all slots is a relation: only an identical tuple matches.

  2. If found: compare the MUTABLE slots under per-slot tolerance rules (IRET.3.4) — the KEY slots already matched exactly. If all compare equal: suppress the assertion (no-op); set *fact_out to the existing fact; return DS_OK.

  3. If found but a MUTABLE slot differs (update): retract the old fact (IRET.19.2), then fall through to insert.

  4. Allocate a new ds_rete_fact_t with a fresh monotonic ID. Populate assert_ns with the held monotonic sample ([LTIM.2.8.6]).

  5. For TTL-scoped schemas: set deadline_ns = assert_ns + schema->default_ttl_ns.

  6. For logical-scoped schemas: initialise justif_count = 0.

  7. For each alpha node registered for schema_id: evaluate all alpha tests against the new fact (IRET.6.4). On pass: insert the fact into the alpha memory and left-activate each downstream beta input.

  8. Emit DS_EV_FACT_ASSERT stream event.

  9. Set *fact_out; return DS_OK.

checks: alloy×4 idris×56 — see also: IRET.19.2, IRET.3.4, IRET.4.1, IRET.6.4, LFAC.1.7, LTIM.2.8.6

Retract [IRET.19.2]#

ds_rete_wm_retract(engine, fact):

  1. For each alpha node whose memory contains this fact: remove it and right-retract each downstream beta input (IRET.7.7 right-retraction path).

  2. Token retraction propagates depth-first to terminal nodes (IRET.7.8). At each terminal, pending activations for the retracted token are removed from the agenda.

  3. For logical-scoped facts: the TMS path handles justif_count bookkeeping (IRET.12). Plain retract of a logical fact (not via TMS) is allowed; it acts as an unconditional removal.

  4. Emit DS_EV_FACT_RETRACT stream event.

  5. Free the fact.

checks: idris×38 — see also: IRET.12, IRET.7.7, IRET.7.8

TTL sweep [IRET.19.3]#

The engine must sweep expired facts once per pump, against the pump's monotonic sample now_ns ([LTIM.2.8.2]), before any activation fires ([IRET.19.4]):

  1. Iterate all live facts with deadline_ns > 0.

  2. For each fact where now_ns >= deadline_ns: call ds_rete_wm_retract. The retraction cascades through the Rete network and may enqueue new activations on the agenda (rules that fire on absence of the expired fact).

  3. Continue until all expired facts are retracted.

The order in which expired facts are retracted is [LDTL.6.1] and [LDTL.6.2]'s.

checks: idris×28 — see also: IRET.19.4, LDTL.6.1, LDTL.6.2, LTIM.2.8.2

[IRET.19.4] The engine must tick exactly once per ds_engine_pump, before the pump's firing loop ([IRET.11.4]), and must not tick between two firings of one pump. The tick is the TTL sweep ([IRET.19.3]) and the $ClockTick turnover ([IRET.19.5]). ds_rete_run does not tick: a caller that runs the firing loop outside the pump gets no tick.

ratified — see also: IRET.11.4, IRET.19.3, IRET.19.5

$ClockTick schema [IRET.19.5]#

$ClockTick is an engine-internal schema with no slots and a synthetic name ([LLEX.10.6.1]). Its assert/retract cycle drives reevaluation of within <dur> test CEs, which compare the monotonic clock's sample against the fact's entry stamp ([LTIM.2.7.1]), and of every other time-dependent test ([LTIM.2.4.1]). A then … within test compares two facts' ts values ([LTHE.2.2.2]) and is not re-evaluated by the tick.

The consumption loop (engine.c, not the integrator) drives the clock cycle once on every ds_engine_pump call ([IRET.19.4]):

  1. Sampling both clocks as the pump begins ([LTIM.2.8.4]).

  2. The TTL sweep ([IRET.19.3]) against the pump's monotonic sample ([LTIM.2.8.2]).

  3. Retracting the previous $ClockTick fact, if any, and asserting a new one. The turnover ends no match that persists (below, [IRET.12.2]).

  4. Calling ds_rete_run to fire any activations that became ready because time advanced.

The integrator does not manage $ClockTick directly; it is an engine-internal fact driven by ds_engine_pump. The clock source (IRET.14) is the only external input.

The tick lives outside working memory ([LDET.5.8]). libds asserts it into the Rete network's own fact store, not the engine's working-memory table: it is not counted by the fact count, it is not delivered to the fact callbacks or the stream as a fact event, and cycling it never makes a new match of one that persists. A token that joins the tick is formed again on every tick, with the new tick's fact. For as long as its time-dependent test stays true, those are one match: refraction holds it through the edge-once set ([IRET.11.3.5]), keyed by the matched fact rather than the tick, and its justifications carry over ([IRET.12.2]). A test that goes false ends the match, and one that goes true again makes a new one ([LTIM.2.5.1]).

Rules that use within <dur> pattern-match on $ClockTick as their time-advancement trigger. The assert of a new tick causes those rules' beta joins to reevaluate their time-window test CEs with the clocks as sampled for that pump ([LTIM.2.8.4]).


checks: idris×129 — see also: IRET.11.3.5, IRET.12.2, IRET.14, IRET.19.3, IRET.19.4, LDET.5.8, LLEX.10.6.1, LTHE.2.2.2, LTIM.2.4.1, LTIM.2.5.1, LTIM.2.7.1, LTIM.2.8.2, LTIM.2.8.4

Memory ownership [IRET.20]#

The Rete engine follows libds's single-ownership discipline (IARC.1.13). Every heap allocation has exactly one owner; ownership transfer happens only at explicitly-named APIs.

Object

Owner

Lifetime

ds_rete_engine_t

Caller of ds_rete_engine_create

Until ds_rete_engine_destroy

ds_rete_schema_t + slot descriptors

Engine

Engine lifetime; freed on ds_rete_engine_destroy

Alpha / beta / terminal node graphs

Engine

From the load until ds_rete_engine_destroy; there is no reload ([RARC.10.1])

ds_rete_expr_t expression trees

Engine

Read-only after the load; freed with node graphs

Interned strings

Engine intern table

Structural names, engine lifetime; slot values, as long as the facts holding them ([IDAT.4.7])

ds_rete_fact_t

Engine working memory

From ds_rete_wm_assert until ds_rete_wm_retract

ds_rete_token_t

Beta node left memory

From join creation until retraction propagation frees depth-first

ds_rete_activation_t

Agenda

From terminal-node activation until its match ends ([IDAT.6.2.1])

see also: IARC.1.13, IDAT.4.7, IDAT.6.2.1, RARC.10.1

[IRET.20.1] Token ownership on retraction. When a token is retracted, the engine frees all downstream extended tokens it created before freeing the token itself (depth-first, post-order). No token is freed while a downstream token still holds a reference to it.

[IRET.20.2] Expression tree allocation. In v1, expression nodes are individually malloc'd at load time.

[IRET.20.3] Json slot ownership. Json-typed slot values hold a heap-allocated ds_rete_json_t *. The fact that owns the slot owns the Json blob. On fact retraction, the engine frees the Json blob before freeing the fact. builtins that receive a Json value as an argument receive a borrow; they must not free it.

Error codes [IRET.21]#

Rete-specific status codes, extending the libds ds_status_t taxonomy ([IERR]):

Code

Meaning

DS_ERR_RETP_INVALID

An AlphaNode / BetaNode / TerminalNode atom carries node_id 0 or a node_id another already holds ([RDSC.11.1]). A body that fails decode is DS_ERR_DSC_DECODE ([RDSC.11.4]).

DS_ERR_RETP_INDEX_OOB

A node cross-reference (node_id — a beta parent / alpha / terminal parent) did not resolve to a loaded node (IRET.16.8).

DS_ERR_FN_NOT_FOUND

At load, a CallExpr carries a BuiltinFn op that is zero, out of range, or has no handler registered in ds_builtin_dispatch[] ([RDSC.4a.9.3], IRET.13.1).

DS_ERR_BUDGET_EXCEEDED

ds_rete_run exited because max_fires > 0 was reached before the agenda drained (IRET.11.4).

see also: IRET.11.4, IRET.13.1, IRET.16.8, RDSC.11.1, RDSC.11.4, RDSC.4a.9.3

[IRET.21.1] Incompatible operand types do not produce a value. There is no value-level marker for them and nothing propagates: an ill-typed operation raises TypeError or EngineError on the provenance of its operands ([IRET.9.6]). No operation yields a sentinel that takes part in further computation as though it were data.

A TypeError abandons the activation and reaches the fault surfaces ([LERR.9.1]); the enclosing ds_rete_run returns DS_OK unless a separate hard error occurred. An EngineError halts the tier.

see also: IRET.9.6, LERR.9.1

[IRET.21.2] The numeric values of the codes above are the ds_status_t enum's ([IERR]).


Test obligations [IRET.22]#

Each item below corresponds to a required test group.

[IRET.22.1] Alpha dispatch. Schema match/non-match; EQ, CMP, and REGEX alpha tests; multiple alpha nodes per schema; a fact that fails one alpha node's tests but passes another's; regex pre-compilation at load time.

[IRET.22.2] Beta join. Left-activation path (new token, iterate right alpha memory) and right-activation path (new fact, iterate left memory); join test pass/fail; multi-pattern join (≥ 3 patterns); fact retraction removes all downstream tokens.

[IRET.22.3] NOT nodes. Token blocked on right-activation (new blocking fact); token propagated on right-retraction (block count drops to zero); token retracted on right-activation when it was previously propagated; multiple blocking facts (block_count > 1).

checks: idris

[IRET.22.4] Agenda and refraction. Higher-salience activation fires before lower; within equal salience, earlier creation_timetag fires first; an activation does not refire in the same cycle (refraction); refraction cleared when working memory changes (new cycle); max_fires budget terminates run with DS_ERR_BUDGET_EXCEEDED.

[IRET.22.5] Truth maintenance. Single justifier: logical fact retracted when activation ends. Multiple justifiers: logical fact survives until all activations end. justif_count accurately tracks the number of live activations supporting a fact.

[IRET.22.6] TTL sweep. Fact not retracted before its deadline; fact retracted at or after deadline by the next pump's TTL sweep ([IRET.19.3]); cascade: retraction of a TTL fact propagates through the beta network and may trigger new activations.

checks: tla idris×6 — see also: IRET.19.3

[IRET.22.7] $ClockTick. A rule using within <dur> does not fire before the window elapses; fires after a $ClockTick assert that advances time past the window boundary.

[IRET.22.8] Token hash collisions. Construct two tokens with equal hash but different fact-pointer tuples; verify pointer-equality fallback in refraction and retraction paths correctly distinguishes them.

[IRET.22.9] Engine isolation. Two independent engine instances in the same process share no working memory, schema registry, agenda, or string intern table. Facts asserted in one do not appear in the other.

[IRET.22.10] Builtin dispatch. Registered builtin called with correct args and arg_count; an artefact naming an unregistered op fails the LOAD with DS_ERR_FN_NOT_FOUND — dispatch is by numeric op ([IRET.13]) and the table is fully populated at ds_engine_new, so a miss is a bad or forward-versioned artefact and must be rejected, not silently skipped; builtin returning an error propagates through the engine's pending-error slot.


see also: IRET.13

Implementation commitments [IRET.23]#

  1. [IRET.23.1] Regex engine: RE2. The regex syntax is RE2 ([LREG.8.1]) — a commitment of the language, not a property of what this runtime links — so there is no backend to choose and no swap flag to offer: a build option that changed which patterns compile, among patterns the runtime accepts at all, would make .ds source non-portable between conforming runtimes. That claim is about swapping engines, not about linking one at all — a build carrying no regex engine and refusing every DSC that needs one ([IRET.23.7]) does not compile a different set of patterns than a conforming build with RE2 linked; it compiles none.

    PCRE and PCRE2 are excluded: they are backtracking engines, and linear-time evaluation is part of what RE2 buys.

    RE2 is linked on both sides: the runtime matches through ds_re2_compile / ds_re2_match, and the compiler validates every pattern with the google-re2 binding, so the two agree on what compiles by construction rather than by inspection.

see also: LREG.8.1, IRET.23.7

  1. [IRET.23.3] Left-memory indexing for NOT nodes. A NOT node's left-token join index, keyed by token identity, records the right facts blocking each token. A token's block count is the size of its entry ([IRET.7.9.4]). A flat hash map is the structure.

see also: IRET.7.9.4

  1. [IRET.23.4] Refraction table implementation: a generation-stamped array. Each terminal's table ([IRET.11.3]) is an open-addressing array of entries (token hash, generation, fact-id tuple), probed linearly. An entry stamped with an earlier generation counts as empty, so a generation's turnover empties the table in O(1) without visiting it, which oa's per-entry delete ([IRET.28]) cannot. It and the intern table ([IRET.1.4]) are the two Rete tables that are not oa tables. The edge-once set ([IRET.11.3.5]) is an oa set keyed by fact id.

see also: IRET.1.4, IRET.11.3, IRET.11.3.5, IRET.28

  1. [IRET.23.6] Protobuf library choice for RETP decoding. RETP decoding uses protobuf-c, the same library the runtime uses for DSC atom decoding ([IARC.7.4]) — one dependency, consistent with the existing loader path. A target with no malloc may substitute nanopb.

see also: IARC.7.4

  1. [IRET.23.7] A build without the regex capability links no RE2. A target that never loads a regex-using artefact builds against a stub source in place of ds_re2.cc: the ds_re2_compile / ds_re2_match symbols still resolve, but ds_re2_compile always returns failure and nothing of RE2 is linked. Such a build omits regex from the capabilities it reports ([LCAP.1]), and refuses a DSC whose requires lists regex with DS_ERR_DSC_CAPABILITY_ABSENT before decoding any body ([RDSC.16.2.7]).

    This check reads the artefact's requires, which the compiler computes from content, never its settings, so it refuses a regex-carrying DSC whatever its regex setting ([LNRE.4.2]). Neither this build choice nor its absence changes what a pattern means when regex support is present at all — that is [IRET.23.1], unaffected.


see also: IRET.23.1, LCAP.1, LNRE.4.2, RDSC.16.2.7

Per-fire evaluation state and the call cooldown gate [IRET.25]#

Native-Rete evaluator behaviour.

DS_RETE_EXPR_NOW reads the held sample [IRET.25.4]#

[IRET.25.4.1] DS_RETE_EXPR_NOW nodes read the held wall-clock sample ([IRET.14.1]). The sample does not change between two sample points ([LTIM.2.8.4]), so nothing is cached and every encounter in a pump returns one value. That is how [LTIM.2.1.3]'s activation atomicity is delivered.

checks: idris×9 — see also: IRET.14.1, LTIM.2.1.3, LTIM.2.8.4

The call cooldown gate [IRET.25.5]#

[IRET.25.5.1] The cooldown gate for call actions wraps the ds-call builtin in a ds-rate-allow IF expression ([IRET.10.4]). The compiler emits that structure into the terminal's expression tree; the loader sees it as ordinary Expr nodes and builds no gate of its own:

  1. A CallExpr targeting ds-rate-allow with args (tracker_lit, key_0, ..., key_N, cooldown_ns): the call site's tracker name <rule>#call<N>; then a VarExpr for each declared key slot of each logical fact the activation binds, in pattern-declaration order ([LCDB.3.3.1]); then the declared window in nanoseconds.

  2. A CallExpr targeting ds-call with the service, correlation, and kwarg expressions from the call action, or targeting the hydration builtin for a hydration call ([LHYD.11.2]), which is gated the same way.

  3. Both wrapped in an IfExpr: condition = step 1, then-branch = step 2, else-branch = NULL (no-op).

see also: IRET.10.4, LCDB.3.3.1, LHYD.11.2

[IRET.25.5.2] When the call action carries cooldown_ns = 0 (nocooldown), steps 1 and 3 are skipped: the ds-call CallExpr stands alone with no IfExpr wrapper.

[IRET.25.5.3] The rate-allow state is maintained per-engine. The gate key is the rule name followed by the activation key ([LCDB.3.3.3], [IRET.10.4]), compared with the identity RLOW.4.6.2.1 states: component by component, representation and value, exact and whole. libds must not render a key lossily — no rounding of a Float, no truncation of a component or of the whole, no separator a component can contain — and holds no key-length limit of its own.


checks: idris×21 — see also: IRET.10.4, LCDB.3.3.3, RLOW.4.6.2.1

Arch-specific code hooks [IRET.26]#

Deferred: not binding in this edition.

[IRET.26.1] When a CompiledCode atom is loaded for a node, the runtime wires a compiled function pointer directly into the node's struct. The node remains a data structure — its memories, indexes, and topology are unchanged — but evaluation and execution bypass the interpreter for that node.

Function pointer fields [IRET.26.2]#

[IRET.26.2.1] Three optional function pointer fields are added to the node structs: alpha_fn on the alpha node, join_fn on the beta node, and rhs_fn on the terminal.

[IRET.26.2.2] All three fields are initialised to NULL. NULL means "use the interpreter path." A non-NULL pointer was set by the CompiledCode atom loader and points into an mmap'd, executable, read-only memory region.

Hot-path fallback dispatch [IRET.26.3]#

[IRET.26.3.1] Alpha test evaluation ([IRET.6.4] callsite) consults alpha_fn; when it is NULL the node evaluates its own alpha tests.

see also: IRET.6.4

[IRET.26.3.2] Join test evaluation ([IRET.7.7] callsite) consults join_fn; when it is NULL the node evaluates its own join tests.

see also: IRET.7.7

[IRET.26.3.3] Terminal RHS execution ([IRET.11.4] step c) consults rhs_fn, passing the engine, the token and engine->dispatch_table ([IRET.26.3.5]); when it is NULL the terminal interprets its action trees.

see also: IRET.11.4, IRET.26.3.5

[IRET.26.3.4] The two-level fallback (CompiledCode → interpreted, [RAOT.10.1]) applies per-terminal. A terminal may have a rhs_fn set (CompiledCode path) even if its parent beta nodes have no join_fn set (interpreted path for joins). Each node's path is independent.

see also: RAOT.10.1

[IRET.26.3.5] engine->dispatch_table is the ds_dispatch_t struct initialised at ds_engine_new with the live function addresses of the dispatcher entry points ([IDSP.14.4]).


see also: IDSP.14.4

Action-verb dispatch [IRET.27]#

[IRET.27.5] Each RHS action verb invokes the dispatcher operation below directly — there is no intervening interpretation step — with the operands named. Every verb but emit reaches the terminal as a builtin op on a CallExpr ([RDSC.4a.9.3]); emit is an action kind of its own, ACTION_ASSERT or ACTION_LOGICAL_ASSERT ([RDSC.4a.8]).

Verb

BuiltinFn op

Dispatcher operation

Operands

emit

none: ACTION_ASSERT / ACTION_LOGICAL_ASSERT

assert into working memory

schema, slots, logical flag, token

publish

FN_PUBLISH

publish

schema, slots

call

FN_CALL

issue a call

service, correlation, typed arguments ([RLOW.7.3.1]), cooldown_ns

cache

FN_CACHE_SET

cache set

key, value_json, ttl_ns

cache_delete

FN_CACHE_DELETE

cache delete

key

log

FN_LOG

log

level, rule_name, message

A logical emit additionally passes the firing activation token as the TMS justifier ([IRET.12]); the engine retracts the emitted fact when the justifying activation ends.

see also: RDSC.4a.9.3, IRET.12, RDSC.4a.8, RLOW.7.3.1

[IRET.28] Unified open-addressing map (oa)#

The hash tables of the C Rete and its working memory are oa tables ([IRET.28.2]): one tested structure, so that a probe, delete or grow defect is fixed in one place. The engine must route every such table through oa, with two exceptions, each for its stated reason: the intern table, whose pinned and counted entries share one pointer space and delete by tombstone ([IRET.1.4]), and each terminal's refraction table, which a generation stamp empties in O(1) ([IRET.23.4]). oa also provides iteration, over its dense arrays ([IRET.28.6.6]).

see also: IRET.1.4, IRET.23.4, IRET.28.2, IRET.28.6.6

[IRET.28.0.1] Goals. The structure:

  • must be a single data structure that every table of [IRET.28.2] uses.

  • must centralize the probe, backward-shift delete, grow, and load machinery so the bug class is fixed in one tested place.

  • must keep the hot path (the alpha join scan) a flat dense-array walk with no per-element indirection, and must keep probing cache-friendly.

  • must be deterministic and bit-identical across runs and platforms ([IRET.28.10], [LDET.3.4]). Its iteration order must not feed timetag assignment ([LDET.5.5]).

  • must support pre-sizing and a grow-forbidden ("locked") mode for real-time use ([IRET.28.11], [RTCT]).

  • must be exhaustively property / fuzz / invariant tested ([IRET.28.16]).

checks: idris×5 — see also: IRET.28.10, IRET.28.11, IRET.28.16, IRET.28.2, LDET.3.4, LDET.5.5

[IRET.28.0.2] Non-goals. The structure:

  • is not thread-safe and must not be shared across threads without external synchronization. The engine pump is single-threaded.

  • does not provide insertion-stable iteration order across deletes. Order is deterministic — a function of the operation sequence — but delete uses swap-remove, so it is not insertion-stable.

  • is not a general-purpose container library. Its scope is the runtime's needs only.

Terminology [IRET.28.1]#

  • slot — an entry of the slots[] probe array (a u32).

  • dense index — an index into the packed dkeys/dvals/… arrays, range [0, len).

  • key bytes — the ksize-byte value the caller passes as the key. For handle keys this is a pointer (rete_fact*/token*); the hash/eq callbacks dereference it to the logical key. For value keys (ds_rete_val_t, ds_slot_value_t) it is the value itself, stored inline.

  • mix — oa_mix64, the table's final hash mixer ([IRET.28.5]).

see also: IRET.28.5

Coverage — the tables [IRET.28.2]#

The engine's oa tables, by the number [IRET.28.13] and the code's comments cite. A number no table holds stays unused.

#

table (field, file)

key

hash / eq

value

1

table (ds_wm_state_t, wm.c)

rete_fact*

pointer

ds_fact_t*, owning

2

—

3

id_map (ds_rete_schema_t, wm_rete.c)

ds_rete_val_t*, the fact's identity-key slots

the slots' content

rete_fact*

4

wm_map (ds_rete_engine_t, wm_rete.c)

u32 fact id

int

rete_fact*

5

ridx_map (beta node, beta.c)

u32 fact id

int

oa_list<token*>

6

lmem_idx_map (beta node, beta.c)

ds_rete_val_t

lmem_idx_oa_hash / _eq

oa_list<token*>

7

ralpha_idx_map (beta node, beta.c)

ds_rete_val_t

as #6

oa_list<fact*>

8

ltok_idx_map (beta node, beta.c)

token*

pointer

oa_list<fact*>

9

—

10

lmem_map (beta node, beta.c)

token*

token->hash / tokens_equal

token*

11

map (the TMS table, tms.c)

i64 timetag

int

ds_tms_just_t

12

memory.map (alpha node, alpha.c)

u32 fact id

int

rete_fact*

13

act_map (terminal, terminal.c)

token*

token->hash / tokens_equal

activation*

14

by_id (ds_wm_state_t, wm.c)

u64 fact id

wm_id_hash / wm_id_eq

ds_fact_t*

15

oneshot (terminal, terminal.c)

u32 fact id

oneshot_oa_hash / _eq

none ([IRET.11.3.5])

16

map (cache, cache.c)

char*, owned

cache_hash / cache_eq

ds_cache_entry_t

17

zones (zone index, wm_rete.c)

tz_zone_key_t

the zone key

tz_node_t*, a tree's root

Tables #1, #4 and #12 are iterated, #12 on the hot join scan. A clone ([IARC.11.1]) and a replay build further oa maps that live only for that operation.

see also: IARC.11.1, IRET.11.3.5, IRET.28.13

[IRET.28.2.1] Variation across the tables is handled by: generic hash/eq callbacks (key kind), vsize plus the oa_list adapter (value kind), the dense vector (iteration), and locked + ds_oa_reserve (RT). No table-specific structure remains.

Representation [IRET.28.3]#

The table is open-addressed with a dense payload: a probe array of indices, and the keys and values packed contiguously beside it.

The probe array holds indices, not entries. A slot is either empty or points at a position in the dense arrays. So probing touches a compact array of integers rather than striding over key-value pairs, and the payload stays packed in [0, len) with no holes.

Two side arrays make the packing maintainable. A cached hash per dense entry allows probe comparison and rehashing without re-reading — or re-hashing — the key. A reverse map from dense index back to probe slot is what makes deletion O(1): the last entry swaps into the freed position and its slot is repaired directly, with no scan.

Invariants. Capacity is zero or a power of two, so the probe index is a mask rather than a modulo. Live count is strictly less than capacity — the table never reaches 100% load, which is what guarantees a probe terminates. cap is u32 and bounded at 2³¹; no runtime table approaches that, and the bound is asserted at grow.

Three behaviours are configured per table. A growth threshold (default 70%). A lock flag which, under real-time mode, forbids growth so an insert fails rather than allocating. And a value destructor called when an entry leaves the map — on delete, clear and free, but never on growth, because growth moves values rather than destroying them. That asymmetry is the one a caller most easily gets wrong.

The open-addressing table is oa_t, declared in runtime/src/libds/oa.h.

[IRET.28.3.1] dcap == cap. The dense arrays are sized to cap. Because len < cap always (load < 100 %), dense index [0,len) always fits. The implementation must grow slots and the dense arrays together on one growth path. The cost is a (1 - load)·cap unused dense tail (≤ 30 % at 70 % load); see [IRET.28.14].

see also: IRET.28.14

Representation invariant (RI) [IRET.28.4]#

After every public operation returns, all of the following must hold, and the ds_oa_check verifier ([IRET.28.15]) must assert them:

  • RI-1 cap == 0 (empty, lazily allocated) or cap is a power of two.

  • RI-2 len < cap when cap > 0; and len ≤ cap · load_pct / 100 except transiently inside ds_oa_put before a grow.

  • RI-3 for each slot i: slots[i] == 0 (empty) or slots[i]-1 ∈ [0, len).

  • RI-4 bijection: for each dense index d ∈ [0,len), slots[dslot[d]] == d+1; and for each non-empty slot i, dslot[slots[i]-1] == i.

  • RI-5 findability (the backward-shift invariant): for each d ∈ [0,len), probing from mix(hash(dkeys[d])) & mask reaches dslot[d] without crossing an empty slot. Equivalently, no occupied slot has an empty slot strictly between its home slot and its actual slot (cyclically).

  • RI-6 no duplicate keys: eq(dkeys[a], dkeys[b]) is false for all a ≠ b.

  • RI-7 dhash[d] == (uint32_t) mix(hash(dkeys[d])) for all d ∈ [0,len).

see also: IRET.28.15

Hashing & slot mapping [IRET.28.5]#

The callback returns a u64; the table must apply a final mixer so callbacks need not be perfectly distributed (low-bit masking is otherwise fragile).

checks: saw

  • [IRET.28.5.1] The slot of a key with mixed hash H is H & (cap - 1).

  • [IRET.28.5.2] The stored dhash[d] is (uint32_t)H, used to skip most eq calls and to rehash on grow without recomputing hash.

  • [IRET.28.5.3] The hash callback must be a pure function of the logical key. It may depend on pointer values (handle keys): this affects probe location only, never iteration order (which comes from the dense vector, [IRET.28.10]), so determinism holds.

see also: IRET.28.10

Core operations [IRET.28.6]#

Complexity is amortized; "probe" is expected O(1) under the load bound. Helper macros: dkey(d) = dkeys + (size_t)d*ksize, dval(d) = dvals + (size_t)d*vsize.

Lifecycle [IRET.28.6.1]#

Four operations, and the distinction between the last two is the one that matters.

Init configures a table without allocating: key and value sizes, the growth threshold, the hash, equality and value-destructor callbacks, and the context handed to all three. Reserve pre-allocates for an expected count — the operation a real-time deployment performs before locking, so that no later insert needs to grow.

Clear empties the table: the value destructor runs on every live value, the length drops to zero, and the capacity and arrays are kept. Free does everything clear does, then releases the arrays and zeroes the table.

So clear is the reuse path and free is the teardown path. Clearing a table that will be refilled costs no reallocation, which is why these are two operations rather than one with a flag.

  • [IRET.28.6.1.1] ds_oa_init zeroes t and records params. load_pct == 0 selects the default 70. It allocates nothing (cap = 0); the first ds_oa_put/ds_oa_reserve allocates. ds_oa_init must not fail.

  • [IRET.28.6.1.2] ds_oa_reserve ensures capacity for at least n live entries without a later grow: it sets cap to the smallest power of two with n ≤ cap · load_pct / 100, rehashing extant entries. It is the RT presize step before entering locked mode. On allocation failure it returns DS_ERR_OOM and leaves the table unchanged.

oa_find (internal) [IRET.28.6.2]#

Lookup is linear probing over the mixed hash, returning the dense index of the key or a not-found marker. Four properties define it:

  1. The hash is mixed before use. The caller supplies an already-mixed value, so a caller-provided hash function with poor low bits cannot degrade probing.

  2. The start position is a mask, not a modulo, which the power-of-two capacity invariant ([IRET.28.3]) guarantees is legitimate.

  3. An empty slot terminates the search as absent. This is the load invariant doing its work: because the table never reaches full, a probe always meets an empty slot rather than looping. There are no tombstones to skip — deletion repairs the probe chain instead.

  4. The cached hash is compared before equality is called. Only when the 32-bit cached hashes match does the (possibly expensive) caller-supplied equality run, so a probe collision costs one integer comparison rather than a callback.

see also: IRET.28.3

[IRET.28.6.2.1] The loop terminates because len < cap guarantees at least one empty slot (RI-2). eq is called only on a 32-bit hash match.

ds_oa_get [IRET.28.6.3]#

Lookup by key, yielding a pointer into the table's own value storage or nothing when the key is absent.

The pointer is a borrow, not a copy, so a caller may read or mutate the stored value in place. It is valid only until the next operation that may move the dense arrays — an insert that grows, or a delete, which relocates the last entry ([IRET.28.3]). A caller holding one across either has a dangling pointer.

see also: IRET.28.3

  • [IRET.28.6.3.1] Returns a pointer to the value (dval(d)) if present, else NULL.

  • [IRET.28.6.3.2] Pointer validity (P1). The returned pointer is invalidated by the next ds_oa_put/ds_oa_del/ds_oa_reserve/ds_oa_clear/ ds_oa_free on t. Callers must not retain it across a mutating call. This is critical for the oa_list adapter: get → mutate the list → done, before any other op.

ds_oa_put (+ grow) [IRET.28.6.4]#

  1. H = oa_mix64(t->hash(key, ctx)). If d = oa_find(t, key, H) is not OA_NONE: set *out_val = dval(d), *is_new = false, return DS_OK_R.

  2. Else a new entry is needed. If cap == 0 or (len+1)·100 > cap·load_pct: if t->locked, return DS_ERR_RT_UNSAFE (table unchanged); else oa_grow(t) (×2, or OA_INIT_CAP from empty). DS_ERR_OOM propagates (table unchanged).

  3. Append: d = len++; copy key into dkey(d); dhash[d] = (u32)H; zero dval(d); probe from H & mask to the first empty slot i; slots[i] = d+1; dslot[d] = i. Set *out_val = dval(d), *is_new = true, return DS_OK_R.

[IRET.28.6.4.1] P2 (zero-init). New values must be zero-initialized, so a count starts at 0 and an oa_list starts empty with no extra step.

[IRET.28.6.4.2] oa_grow allocates a new zeroed slots' (2·cap or OA_INIT_CAP) and resized dense arrays, moves the dense arrays by memcpy, and re-seats the slot array only: for each d ∈ [0,len), probe from dhash[d] & mask' to the first empty slots' and set slots'[i] = d+1, dslot[d] = i. It makes no hash/eq calls (it uses cached dhash) and must not call val_dtor.

[IRET.28.6.4.3] P3 (move-safety). Values must be relocatable by memcpy (no internal self-pointers). oa_list satisfies this (POD plus one owned heap pointer).

ds_oa_del (+ backward-shift) [IRET.28.6.5]#

  • [IRET.28.6.5.1] The dense swap-remove moves the last entry into the hole — identical to the current occ[] swap-remove — so migrated iteration order is bit-identical ([IRET.28.10]).

see also: IRET.28.10

  • [IRET.28.6.5.2] slots[s] = 0 comes before the scan: slots[scan] != 0 terminates when scan wraps back to the now-empty s, even at maximal load. The implementation must clear first unconditionally.

  • [IRET.28.6.5.3] on_path is the standard cyclic test gap ∈ [nat, scan); it preserves RI-5.

  • [IRET.28.6.5.4] ds_oa_del must not shrink cap (no hysteresis thrash); ds_oa_clear/ds_oa_free reclaim.

  • [IRET.28.6.5.5] dslot sync (RI-4). Each time the backward-shift relocates a slot entry (slots[gap] = slots[scan]), it must update the moved dense entry's dslot to its new slot (dslot[slots[gap]-1] = gap) before clearing slots[scan]. Omitting this leaves dslot stale, violates the slots ↔ dslot bijection (RI-4), and causes a later ds_oa_del swap-remove repoint (slots[dslot[d]] = d+1) to corrupt the wrong slot. The ds_oa_check RI-4 assertion ([IRET.28.15]) gates against regression.

see also: IRET.28.15

Iteration [IRET.28.6.6]#

Iteration is over the dense arrays by index, not over probe slots: a live count, and key and value accessors taking a position in [0, len).

Because the payload is packed with no holes ([IRET.28.3]), a full walk visits exactly len entries and skips nothing — an iteration costs the number of live entries, not the capacity. This is why working-memory walks do not degrade after a table has been heavily deleted from.

Iteration order carries no meaning and must not be relied on. It is deterministic ([IRET.28.10.1]), but it reflects insertion and deletion history — a delete moves the last entry into the freed position — so it is neither insertion order nor stable across mutation. Anything requiring a defined order sorts explicitly.

Mutating during iteration invalidates it, for the same reason: an insert may grow and a delete relocates an entry, so indices shift beneath the walk.

see also: IRET.28.10.1, IRET.28.3

  • [IRET.28.6.6.1] Iteration is O(len) and cache-tight (it walks dvals directly — the hot alpha scan).

  • [IRET.28.6.6.2] P4. Mutating the table during iteration invalidates indices (swap-remove reorders). The delete-while-iterating idiom is high→low: for (i = oa_len(t); i-- > 0;) { ... maybe oa_del_at(t,i) ... } — deleting i swaps last into i, which has already been visited.

Value lifecycle [IRET.28.7]#

  • [IRET.28.7.1] Owned value resources (e.g. an oa_list heap) must be freed by val_dtor, invoked on ds_oa_del (before the swap overwrites the entry), ds_oa_clear, and ds_oa_free.

  • [IRET.28.7.2] Grow and ds_oa_reserve move values by memcpy and must not call val_dtor (P3).

  • [IRET.28.7.3] For plain pointer / u32 / POD values, val_dtor is NULL.

oa_list — the multimap value adapter [IRET.28.8]#

oa_list is the oa value for the multimap tables (ridx, lmem_idx, ralpha_idx, ltok_idx: key → set of element pointers). It mirrors today's inline-array + heap-overflow scheme so small per-key fan-out stays allocation-free. The inline count OA_LIST_INLINE must match DS_RIDX_INLINE (= 8, beta.h): a smaller value would spill to heap sooner and, in RT-locked mode where heap growth is forbidden ([IRET.28.11.2]), would regress allocation-free fan-out capacity below the pre-oa tables.

see also: IRET.28.11.2

  • [IRET.28.8.1] ds_oa_list_add under rt_locked must fail rather than grow heap (RT bound).

  • [IRET.28.8.2] Element order within a list is not stable (swap-remove). Today's consumers iterate for set membership / counts, which is order-insensitive; a consumer needing determinism over a list must sort or key it.

  • [IRET.28.8.3] ds_oa_list_free is the val_dtor for every multimap table.

Determinism & bit-identity [IRET.28.10]#

This section is normative. Iteration order is deterministic, as cross-platform bit-identity requires ([LDET.3.4]), and it does not decide rule-firing order: [LDET.5.5] orders a rule's activations by a key computed from the match and working memory, so the engine must not derive a timetag from the order in which it traverses these tables ([LDET.5.9]).

checks: idris — see also: LDET.3.4, LDET.5.5, LDET.5.9

  • [IRET.28.10.1] Iteration order is the dense-vector order: append on insert, last-into-hole on delete. It is a pure function of the operation sequence, independent of cap, pointer values, and platform, and is therefore deterministic.

checks: idris×5

  • [IRET.28.10.2] For the iterated tables (alpha_mem, wm_bucket, wm_table) the dense order must be insertion order, and a removal must move the last entry into the hole it leaves. Entries inserted in the same sequence then iterate in the same order on every platform. The conformance bit-identity / replay-determinism tests are the gate ([IRET.28.16]).

see also: IRET.28.16

  • [IRET.28.10.3] oa_mix64 and H & mask use only callback hash bits; they affect probe location, never iteration order, so platform-varying pointer hashes are safe.

Real-time / bounded memory [IRET.28.11]#

This section is normative; it composes with [RTCT].

  • [IRET.28.11.1] When locked == true, ds_oa_put must not allocate; it returns DS_ERR_RT_UNSAFE if a grow would be required. Integrators presize via ds_oa_reserve before the RT-locked region (mirrors ds_rete_engine_presz_rt_tables).

  • [IRET.28.11.2] ds_oa_list_add(rt_locked = true) must not grow heap.

  • [IRET.28.11.3] No operation other than oa_grow / ds_oa_reserve allocates.

[IRET.28.11.4] libds holds sixteen slot values inline on the assert path. A fact of a schema with at most 16 slots asserts without allocating; above that the assert path allocates its slot-value array on the heap, which a realtime engine must not do ([LCSP.1]).

A compiler whose artefacts libds executes must therefore, when realtime resolves, refuse a schema of more than 16 slots with DS_VALIDATE_RT_SCHEMA_TOO_WIDE, naming the schema, its slot count and the bound.

The bound is libds's, not the language's. It is the width of one runtime's inline buffer; a runtime that asserts without one has no such limit or declares its own, and the language commitment is only that realtime admits no unbounded per-assert allocation. The program is refused at compile time rather than tolerated because the alternative is an artefact whose steady state allocates, which is what realtime exists to exclude, and an author can act on a compile error.

Deferred: not binding in this edition.

see also: LCSP.1

Error model [IRET.28.12]#

oa uses ds_result_t per the libds convention (NERR.1 / IERR). The codes are existing taxonomy members — oa introduces no new code:

Code

Condition

DS_OK_R

success.

DS_ERR_OOM

allocation failed (grow/reserve); structure unchanged.

DS_ERR_RT_UNSAFE

a grow would be required while locked; structure unchanged.

see also: NERR.1

  • [IRET.28.12.1] ds_oa_get / ds_oa_del cannot fail; they return NULL / bool.

  • [IRET.28.12.2] On any error the structure must remain a valid map satisfying the RI ([IRET.28.4]).

see also: IRET.28.4

Per-table behaviour [IRET.28.13]#

What a table of [IRET.28.2] keeps beyond its key, value and hash, by its number there:

  • #1, #4 are iterated (ds_oa_val_at), #4 under bit-identity ([IRET.28.10]).

  • #5–#8 are multimaps: each value is an oa_list, freed by ds_oa_list_free, and grown through ds_oa_list_add, which honours a locked table.

  • #10's doubly-linked left_head list stays beside it: the list gives ordered traversal, the map lookup.

  • #12 is iterated on the hot join scan (ds_oa_val_at loop), under bit-identity ([IRET.28.10]).

  • #13's discard path finds an activation by act->token, then checks the stored value is that activation. The activation's doubly-linked list stays beside it.

A negated join's block count has no table of its own: it is the number of right facts a token's ltok_idx_map entry lists ([IRET.7.9.4]).

see also: IRET.28.10, IRET.28.2, IRET.7.9.4

[IRET.28.13.1] A table keyed by a handle whose logical identity is content (#3, #10, #13 of [IRET.28.2]) hashes and compares the content the handle names, never the pointer.

see also: IRET.28.2

Complexity & memory [IRET.28.14]#

  • [IRET.28.14.1] get/put/del are expected O(1); del's backward-shift is O(probe-run); iterate is O(len).

  • [IRET.28.14.2] Memory at slot capacity cap: slots 4·cap plus dense (ksize+vsize+8)·cap (the +8 is dhash 4 + dslot 4). Versus a hypothetical inline table this adds ~8 bytes per slot (~11 bytes per live entry at 70 % load), in exchange for free O(len) cache-tight iteration (subsuming occ[]) and u32 probing. This is acceptable at Rete table sizes (10²–10⁴ entries, per [IRET.17]).

see also: IRET.17

  • [IRET.28.14.3] For the multimap tables ([IRET.28.8]) the per-entry vsize is sizeof(oa_list), which carries OA_LIST_INLINE (= 8) inline element pointers — 8·8 = 64 bytes plus the heap/n/heap_cap fields. This is the same inline footprint as the pre-oa tables (DS_RIDX_INLINE = 8), so the migration is memory- and RT-neutral for those tables; the only delta is the oa per-slot overhead above.

see also: IRET.28.8

  • [IRET.28.14.4] Escape hatch, bounded. If a specific hot table regresses against the perf guard ([IRET.28.16.6]), the same algorithm may be macro-specialized inline for that table alone. This is a last resort, not the default: the point of oa is one tested algorithm, and each specialization is a copy of it that can rot separately.

see also: IRET.28.16.6

ds_oa_check invariant verifier [IRET.28.15]#

void ds_oa_check(const oa_t *t) (compiled under DS_DEBUG, and called after every op in tests) must assert RI-1..RI-7 ([IRET.28.4]). Concretely it must:

  • count non-empty slots == len; assert each slots[i]-1 < len;

  • verify the slots ↔ dslot bijection (RI-4);

  • for every d, assert oa_find(t, dkey(d), mix(hash(dkey(d)))) == d (RI-5 findability + RI-6 no-dup);

  • assert dhash[d] == (u32)mix(hash(dkey(d))) (RI-7);

  • assert cap is 0 or a power of two, and len < cap.

see also: IRET.28.4

[IRET.28.15.1] Engine-level invariants compose with ds_oa_check: per negation node, a token's block count — the facts its ltok_idx_map entry lists ([IRET.7.9.4]) — equals the number of ridx_map lists containing it; ridx_map and ltok_idx_map are mutual inverses; lmem_map's size equals left_count; every act_map value is a live activation also on the activation list.

see also: IRET.7.9.4

Test obligations [IRET.28.16]#

These extend [IRET.22].

see also: IRET.22

  • [IRET.28.16.1] Unit. Each operation's contract: empty-table get/del, lazy first insert, reserve-then-locked, zero-init of new values, dtor on del/clear/free, grow correctness, OA_NONE paths.

  • [IRET.28.16.2] Model-based property test. Random put/get/del/ iterate streams over a small key domain against a reference dict (sorted assoc array); assert membership/value/len equivalence and ds_oa_check after every op. Domains must include collision storms (cap ≪ domain) and grow-boundary crossings (insert exactly to each grow threshold).

  • [IRET.28.16.3] Regression cases (explicit, named): full-table delete loop; long backward-shift chains; delete-then-reinsert storms; grow exactly at the boundary; tiny-cap collision storms; pointer-key + simulated slab reuse (free a key, reuse the address); oa_list heap overflow under locked.

  • [IRET.28.16.4] Standalone fuzzer. An oa analogue of rete_churn_fuzz (specs/conformance/harness/rete_churn_fuzz.py): seeded, deterministic, minimizing on failure, model + ds_oa_check, many seeds / keys, including the oa_list multimap and count adapters.

  • [IRET.28.16.5] Differential migration gate. Migrate one table per change; each change must keep libds (impl + spec), conformance (including bit-identity / replay determinism), and rete_churn_fuzz green, under valgrind/ASan.

  • [IRET.28.16.6] Perf guard. A micro-benchmark for the hot alpha scan and beta probe, so a migration regressing the hot path is caught against the pre-migration baseline ([IRET.17]).

see also: IRET.17