Files
stefan-gorules 0083a66418 fix: v2 equality gaps (#577)
* fix(expression): copy values that read the node's own output on the compiled path

* fix(expression): match a date against every text cell naming it

* test(engine): cover the fixed version differences on every evaluation path

* fix(engine): keep the table index and compiled plan off tables whose cells read the last tested value

* fix(engine): give batch rows the node values and replaced fields a single row sees

* test(engine): cover the batch and table differences on every evaluation path

* fix(engine): read declared date inputs in the evaluation's time zone

* fix(engine): keep script dates right beyond 2099, at extreme years and for object arguments

* fix(engine): name script modules alike on every traced batch row

* fix(expression): keep typed batch results and errors equal to the row engine

* fix(engine): keep loop items, traced table fields and batch node values equal to version 1

* fix(engine): record table references in batch traces when a rule has a description

* fix(nodejs): convert decision results, policy traces and handler values without aborting on large integers

* fix(nodejs): reject fractional engine versions

* test(engine): cover null leaves in multi-row batches

* fix(engine): keep a null written under a missing or scalar parent in multi-row batches

A layer over an upstream patched shape treated every null leaf as absent,
so obj.a = null over a row without obj (or with obj = 1) never created
{obj: {a: null}} for downstream reads, and an all-null column was dropped
outright. A dotted null leaf now stays present on the rows whose parent
is not an object before the write, matching version 1's merge.

* fix(engine): merge a parent reached by duplicate edges once in multi-row batches

Version 1 merges a node's output onto itself as a no-op when two edges
from the same node meet at a target, so nested nulls survive. The batch
path gathered the parent twice as separate copies and re-applied the
patch, deleting those nulls and letting a dangling node's value win over
a null written on the twice-connected branch. Consecutive duplicate
parents now merge once.

* fix(engine): let a later table output replace an earlier one under it in batches

A rule writing res, res.k and then res again keeps only the last res in
version 1, because the final write replaces the object that res.k went
into. The compiled table folded the duplicate paths into one slot per
path and re-inserted res.k on top. Non-collect outputs that a later
non-collect output of the same rule replaces are now left out.

* fix(engine): share common ancestry when batch rows merge related parents

Version 1 merges parent outputs copy-on-write: a pass-through node shares
every subtree it did not change with its input, and merging two values
that share an object skips it. So a nested null written once and reached
through two branches survives the join, and an input null survives a
pass-through that changed nothing. The batch path rebuilt each parent's
rows separately, lost that sharing and deleted those nulls. When parents
share a base or leading layers and the merged parent can hold a null,
the join now derives their rows from the shared prefix with the same
copy-on-write merge; other joins stay columnar. Traced batch rows derive
pass-through outputs from their merged input the same way.

* fix(engine): keep one materialization per node so batch joins see shared rows

Gathering a node's rows for each consumer, and clearing a table's
unmatched rows before a pass-through, materialized the same node output
more than once, so a pass-through built from one copy no longer shared
objects with the copy merged at the join, and the version 1 rule that a
shared object merges as a no-op could not apply. Gathered copies of a
node on the same rows now share one materialization, a cleared copy
reuses its source's rows, layers keep their identity when picked to a
row subset, and input rows match by object identity. The final output
still materializes its own copy, since cleaning it mutates in place.

* test(engine): cover policy columns for a tested value that fails

* fix(engine): return column traces in the legacy format when it is requested

* fix(engine): return an error instead of building a cyclic value when an expression entry writes an object into itself on version 2

An entry such as `a.c = obj` after `a = obj` wrote the object into itself,
and merging, cloning, comparing, tracing or serialising the result then
overflowed the stack. The hosted expression node now checks, before each
write, whether the value reaches the object it is written into and fails the
row with "cyclic value at <key>". Compiled nodes that write a possibly
container value under a key an earlier entry set are routed through the same
row evaluation, so every path (first call, repeated, compiled, batch,
columnar, traced) reports the error for that row only.

* test(engine): cover a script returning a cyclic object on version 2

Ignored until the version 2 JS runtime rejects cyclic results; it hangs today.

* fix(engine): match version 1 in script globals and dates, stop idle or cyclic scripts, and load date support lazily

* fix(engine): leave version 1 table indexes as released and give version 2 its own

* fix(engine): show the tested value under its key when a table reads the whole root

* fix(engine): copy values read through $ and leave written-back keys alone, as version 1 merges them

* perf(engine): keep tables whose outputs read the tested value on the compiled plan

* test(engine): record pinned Date results across zones, DST gaps and far years

* perf(engine): pin Date in Rust instead of a JavaScript shim on version 2

Function nodes on version 2 replaced Date with a JavaScript module whose
local getters, setters and string methods rebuilt every field through
native calls and allocations, and whose lazy half cost about 45 us to
load on the first Date use of each evaluation.

The pinned constructor, Date.now, Date.parse, Math.random and the zone
dependent prototype methods are now callable Rust classes built with the
safe rquickjs API. They read the time value through the native getTime,
compute fields and offsets with chrono-tz in Rust (fixed offset zones
skip the lookup, the last instant's fields are cached per evaluation)
and keep QuickJS's Date for storage and everything zone independent.
The constructor is a bound function so calls and constructions are
told apart exactly. The prototype methods are still installed on the
first construction or parse, now in about 6 us.

Results are unchanged: recorded per-zone results, version parity and
the isolation spec pass as before.

* fix(engine): keep the machine time zone out of parsed script dates
2026-11-23 17:49:17 +01:00
..
2026-11-23 17:49:17 +01:00
2026-11-03 17:25:56 +01:00
2026-11-03 17:25:56 +01:00

ZEN engine conformance suite

Executable specification of decision graphs and policies, the engine-level sibling of core/expression/tests/spec. Each case states what a decision is meant to produce, not only what the current engine does. Known deviations are recorded in place.

Layout

  • graph/NN-chapter.json5: decision graphs (JDM), evaluated by the graph walker.
  • policy/NN-chapter.json5: policies, evaluated by the policy driver.

A chapter is a sequence of suites. A suite is one decision plus the cases run against it. Files use a JSON5-like syntax: // and /* */ comments, unquoted keys, single or double quoted strings, trailing commas, and """raw""" strings for multi-line source (function nodes). Numbers are read as exact decimals. date('...') is a date input that keeps its source text, as the engine produces for schema date fields. Graph requests are normalized at the input node, so in graph suites a date() input arrives as text; build date values with an upstream d(...) expression or an input schema field with format: date.

Cases

cases: [
  [input, output],
  [input, output, "bug: why the engine differs"],
  {input: {...}, output: {...}, goals: ["customer.tier"], note: "question: ..."},
]
  • output: the expected result, compared by value. Numbers compare by exact decimal value (1.10 == 1.1); objects compare unordered. "!error" expects any error; "!error: text" expects an error whose serialized form contains text (use it only for stable, user-facing error kinds).
  • note (optional):
    • bug: <why>: the output holds the intended result and the engine differs. A bug case that starts passing fails the run, so the note gets removed.
    • question: <why>: the output holds current behaviour whose intent is unclear.
  • goals (policy only): the request goals.
  • engines (object form only): a documented difference between the reference (walker or driver) and some compiled modes: engines: {modes: ["batch", "columnar"], intended: true, why: "..."}. Modes are single, batch, columnar, engine (DecisionEngine) and traced. Modes not listed are still compared with the reference. With intended: true the listed modes give the intended result and are checked against the spec output. With intended: false the listed modes are a known open difference; once one of them matches the reference again the run fails, so the mode gets removed from the note. List only the modes that differ.

Evaluation time is fixed at 2025-03-20T10:15:30Z, time zone UTC (SPEC_TZ overrides).

Graph suites

{
  name: "first hit returns the first matching rule",
  graph: {
    nodes: [
      {table: "rules", hit: "first", inputs: ["age"], outputs: ["tier"], rules: [
        ["> 18", "'adult'"],
        ["", "'minor'"],
      ]},
    ],
  },
  cases: [
    [{age: 20}, {tier: "adult"}],
  ],
}

graph is either {raw: <full JDM content>} or the shorthand below. Shorthand nodes name their kind with one key whose value is the node name (also its id unless id is given):

node fields
{input: "request", schema?} schema is a JSON schema object or string
{output: "response", schema?}
{expression: "calc", fields} fields is {key: "expr"} in order, or [["key", "expr"], ...] for duplicate keys
{table: "t", hit?, inputs, outputs, rules} hit is first (default) or collect; inputs are field strings (null/"" = no field) or {field, name}; outputs are field paths (a [] suffix collects per column) or {field, type}; rules are rows of cell strings, inputs then outputs ("" = any)
{switch: "s", hit?, when: ["cond", ...]} "" is the default branch; edges leave branch i as "s:i"
{function: "f", source} v2 function node (export const handler = async (input) => ...)
{functionV1: "f", source} v1 function node
{decision: "d", key} sub-decision loaded from the suite's decisions
{custom: "c", kind, config} spec adapter kinds: echo (returns input), config (returns config), render (each config key rendered as a template field), fail (errors with config.message)

Expression, table and decision nodes also take passThrough, inputField, outputPath and executionMode ("single" or "loop").

When the graph has no input or output node, nodes named input and output are added. edges is a list of chains: "input -> a -> b -> output", "route:0 -> adult". Without edges, the nodes are chained in order from input to output.

decisions: {key: <graph shorthand> | {raw: ...} | {policy: <policy shorthand>}} registers sub-decisions for decision nodes.

Policy suites

{
  name: "an expression block writes a computed property",
  policy: {
    models: {customer: {age: "number", companies: "company[]"}, company: {revenue: "number"}},
    blocks: [
      {expression: "customer.adult", value: "customer.age >= 18"},
    ],
  },
  cases: [
    [{customer: {age: 20, companies: []}}, {customer: {age: 20, companies: [], adult: true}}],
  ],
}

policy is either {raw: <PolicyDocument>} or:

  • models: {entity: {property: "type"}} and globals: {name: {...}} (global scope). Types: string, number, boolean, date, string(a|b|c) (enum), entity (relationship), &entity (reference); suffix [] for arrays and ? for optional ("company[]?").
  • dictionaries: {name: ["value", ["value", "label"], ...]}
  • imports: ["path", ...] naming documents in the suite's policies.
  • blocks, in document order:
    • {expression: "path", value: "expr"}
    • {match: "path", arms: [["condition", "value"], ["", "default"]]}
    • {assertion: "path", conditions: ["expr", ["or", "expr", depth], ...]}
    • {table: "id", hit?, inputs: ["field", ...], outputs: ["path", ...], rules: [[...]]}
    • any block takes an explicit id.

policies: {path: <policy shorthand> | {graph: <graph shorthand>}} registers other workspace documents. The suite's own policy is evaluated at path main.

Policies with error diagnostics are refused by DecisionEngine, so the runners gate them the same way: every case of such a suite yields CompilationErrors [codes]. A suite that sets diagnostics: ["TYPE_MISMATCH", ...] pins the exact set of error codes and evaluates its cases through the workspace API, which runs policies despite errors; use it to specify runtime behaviour of policies that only the workspace (editor) path can execute.

Runners

All runners live in core/engine/tests/spec.rs. Run with --all-features (exact decimals need arbitrary_precision):

  • graph_spec_matches_walker: the graph walker against the spec.
  • graph_engines_match_walker: the compiled engine (single, batch, columnar with plain, list and cycled column layouts, and DecisionEngine with a loader) against the walker's actual result, bugs included.
  • policy_spec_matches_driver: the policy driver against the spec.
  • policy_engines_match_driver: the compiled policy engine (single, batch, and DecisionEngine for cases without goals) against the driver's actual result.

A panic in any engine is reported as a failure of its suite and does not stop the run.

cargo test -p zen-engine --all-features --release --test spec

Environment knobs: SPEC_FILE=<substring> (files), SPEC_SUITE=<substring> (suite names), SPEC_SHOW=<n> (failures printed), SPEC_BUGS=1 (list known bugs).