Repository navigation
release: version 2.2 - #580
Open
stefan-gorules wants to merge 11 commits into
Open
stefan-gorules wants to merge 11 commits into
stefan-gorules wants to merge 11 commits into
Conversation
… evaluation (#553) * feat(expression): lane VM and typed-mask engine for batch and columnar evaluation Adds a register-based lane VM (core/expression/src/lane) and a typed-mask engine (core/expression/src/typed) that evaluate ZEN expressions over batches and columns, matching the stack VM's results. zen-types gains shape-backed objects and dot-path helpers; existing public APIs only grow. The lane VM has no expression size limit: deep and wide expressions are compiled and run with the same stack growth the parser uses. ZEN_EXPRESSION_CONFIG.lane (off by default) switches Isolate::run_standard and run_unary to the lane VM at runtime. Lane internals and the typed module are doc(hidden); the documented entry points are LaneProgram, LaneRunner, Session, Columns and Output. Includes an executable specification of the expression language (core/expression/tests/spec, 28,852 cases) with differential tests that run every lane path against the stack VM. zen-expression and zen-types now declare rust-version 1.88. * refactor(types): remove the shape transition cap Shapes are freed when nothing uses them, so the 4,096-children cap per shape no longer bounds memory. Shape::with, Shape::of and Shape::without now always return a shape; objects only switch to a hash map past SPILL_AT keys, as on master. * fix(expression): debug-profile stack safety and Windows test build CI runs tests in the debug profile, where frames are larger and tail recursion is not optimised. Recursive lane, typed and parser helpers now grow the stack like the rest (Const::number, the kernel builder, typed lowering and lookup, lane compile helpers, Node::member_key). The parser's closure depth counter is u32 instead of u8, so 256 nested closures no longer wrap. median([]) and empty templates no longer overflow in debug builds; release results are unchanged. The deep/wide test runs on a 256 KiB stack so unprotected recursion fails quickly in any profile. The conformance helper compares with as_str(), which is unambiguous on Windows. * fix(expression): stack checks in the lane executor, LF test data on Windows In x86-64 debug builds Executor::cold has a ~93 KB frame, so nested closures (execute -> cold -> body) could use more stack between two checks than the stack-growth margin and overflow. execute and cold now check the stack themselves; both run per instruction batch, not per row. The expression test data is checked out with LF on every platform. Windows runners converted it to CRLF, which broke multi-line spec cases.
* feat(engine): compiled engine for columnar graphs and policies New engine for decisions and policies built on the lane VM: a compiled graph plan that evaluates batches column-wise (typed kernels where expressions allow, lane programs otherwise), a row runner for batch and single-row evaluation, and a compiled policy runtime with a columnar pass. - Decision::evaluate_columns / Workspace::evaluate_columns return one ColumnarOutput type; diagnostics live in zen_engine::diagnostics - rows the plan cannot finish are deferred to the row runner and never re-run nodes; sub-decisions run inside the parent plan; date input schemas stay on the plan - DecisionEngine keeps compiled graphs, sub-decisions and policies per key while the loader returns the same content - failed $dictionary imports are retried, not cached - the old engine stays available behind the driver feature for comparisons; there is no fallback to it - benchmark harness (tests/bench_matrix.rs) comparing old and new across the spec corpus, fixtures and policies * refactor(engine): isolate compiled engine from release node and graph code Release code outside core/engine/src/compiled is restored to release/2.2. The compiled engine keeps its own copy of the node, graph and JS function implementation under compiled/host and reaches release only through types and pure helpers. Release files gain only additive hooks: the ZEN_CONFIG.compiled runtime flag (off by default), per-instance interpreted()/compiled_engine() on Decision, DecisionEngine and PolicyWorkspace, and the batch and columnar entry points. - the driver feature and the modified old engine are removed; tests compare the compiled engine against the unmodified release engine - compiled-only behaviour (#7 empty collect columns, #16 collect order, BC1 thrown-object message) is allowlisted in the comparisons - #14 (policy whitespace cells) is dropped: release analysis rejects it - goldens re-recorded from the release engine - spec 42 nested-chain case lowered to depth 200: the release engine's JS conversion overflows a 2 MB debug thread at depth 500 * fix(engine): keep interpreted engines interpreted and tighten engine comparisons - DecisionEngine::interpreted() now holds while ZEN_CONFIG.compiled is on: decisions it creates (get_decision, create_decision, evaluation) carry its engine, and its release path runs in an interpreting scope so the Workspace built by the lazy policy path stays interpreted too - policy batches (DecisionEngine and PolicyWorkspace) deep-copy their inputs like graph batches, so callers' contexts are no longer written into - release test files run on the release engine again: the compiled-by-default ctor moved out of tests/support into tests/compiled_default, included only by the compiled test suites - spec `engines` notes are structured ({modes, intended, why}); unlisted modes are still compared with the reference, intended modes are checked against the spec, and open differences fail once they match the reference again. Stale notes found this way were removed; golden skips are per mode, and generated rows no longer inherit the first case's note * fix(engine): platform-independent spec suite ids and rustfmt - spec suite file paths are joined with '/', so suite ids and golden keys match on Windows (backslash paths missed every recorded golden) - engine spec json5 files are checked out with LF line endings - cargo fmt
* feat(engine): explicit evaluation context with now, timezone and seed
The compiled engine evaluates against an explicit EvaluationContext
instead of the host clock, host zone and an unseeded random source.
- zen_expression::context: EvaluationContext holds now (read once on
first use, shared by every row of a batch), the time zone (supplied
or the host zone cached per process), the locale, the seed (drawn on
the first draw) and per-row and per-item random streams created only
when a row or item draws. rows/picked/items/item/at narrow it with an
Rc clone; at and item allocate nothing. RowContext is the borrowed
per-row view builtins, kernels and function hosts read.
- the context is passed explicitly through the lane VM (LaneRunner,
Session, kernels, cells, builtins), typed Program::run, graph state,
rows, loops, sub-decisions, hosted rows, the columnar plan, policies
and their plans. There are no thread-locals for context data.
- rand draws once per lane, row and item from the row's stream, so
map(xs, rand(100)) draws per item. rand is never pure, folded,
memoised or compiled into kernels as a constant; Math.random is no
longer pure in the function purity analysis.
- function hosts (v1 and v2) install Date, Math.random and a minimal
Intl.DateTimeFormat once per runtime and read a per-call slot:
Date.now, new Date, local-time getters and setters, toString,
toLocale*String and getTimezoneOffset use the context's now, zone and
locale.
- EvaluationOptions and EvaluationSerializedOptions gain now, timezone,
seed and locale (en-US by default). Workspace gains evaluate_pinned,
evaluate_batch_pinned and evaluate_columns_pinned. In a batch, row i
draws with row_seed(seed, i) and replays alone with that seed.
- bindings: Node and Python accept and validate now, timezone, seed and
locale; C and uniffi pass them through and ignore invalid values.
- d('...') is folded at compile time only for texts with an explicit
zone; an invalid __ZEN_MOCK_UTC_TIME is ignored by the context.
- the interpreted engine and the stack VM are unchanged and ignore the
new options.
* refactor(engine): name evaluation context parameters ctx and context
* feat(engine): derive random draws from their location
A draw is now a pure function of (seed, stream, scope, field, site, n)
instead of a running counter per stream, so reordering, short-circuiting,
dead-code elimination or an extra rand elsewhere in a decision no longer
shifts other draws.
- site: occurrence index of rand( in source order, numbered at compile
time and carried on the lane call op
- field: stable label from node/rule/column/key/statement/block ids,
baked into multi-root programs at compile time or set on the context
by per-source (session) paths
- scope: chained per sub-decision call (caller node + key) and per
function node; JS Math.random uses a fixed site in that scope
- n: counter per (stream, address) for repeated evaluation only
Tables with draws run on the exact row path; fused cells and fused rules
refuse draws; object-literal expansion is skipped for drawing sources.
* refactor(expression): own the rand integer mapping
Map a draw to 0..=upper with Lemire multiply-shift and rejection, taking
further words from the same address on retry, so a dependency update can
never change rand(n) for a given seed. A negative upper bound now returns
"Invalid upper range" on both VMs instead of panicking, and the unseeded
root seed comes from a hashed counter, which drops fastrand.
* test(engine): keep evaluation context tests independent under cargo test
cargo test runs a crate's tests as threads of one process, so tests that
share process state raced:
- pinned.rs switched the global ZEN_CONFIG.compiled on and off; each
decision now picks its engine with compiled_engine() / interpreted().
- clock_reads() counted reads from every thread; it now counts the
current thread only.
- typed exact tests relied on __ZEN_MOCK_UTC_TIME, which is cached on the
first clock read by any test; they now pin now in the context.
* ci: pin Rust 1.99 for the Windows Node and UniFFI builds
Rust 1.100 makes Cargo's new build-dir layout permanent: every
dependency gets its own directory and its own -L dependency= flag.
For zen-engine with --target x86_64-pc-windows-msvc the rustc command
line passes Windows' 32,767-character limit, and sccache fails to spawn
rustc with os error 206. Cargo itself falls back to an argument file,
but sccache does not.
Other matrix entries stay on stable. Remove the pin once sccache
handles long command lines.
* refactor(engine): remove locale from the evaluation context
The locale option did not make evaluations more reproducible: QuickJS has
no ICU, so function nodes never picked up a host locale. It only added
approximate locale-aware date formatting from a hand-written table, as new
public API in every binding.
Function nodes keep the time zone of the context. toLocaleString,
toLocaleDateString and toLocaleTimeString return QuickJS's fixed format in
that zone and ignore a locale argument, as before. Intl is reduced to
DateTimeFormat().resolvedOptions(), which reports the time zone.
Drops the icu_locale_core dependency.
* test(engine): compare interpreted draws with the pinned ones
The interpreted engine's Math.random is QuickJS's own, seeded from the
clock in microseconds when a context is created. On Windows the clock is
coarser, so two evaluations in a row can get the same seed and the same
numbers. Assert instead that the interpreted engine does not return the
compiled engine's draws for the same seed.
* feat(trace): trace format v1 with TraceCollector on the compiled engine Adds trace format v1 to the compiled engine, recorded by explicit trace recorders and written natively. The interpreted engine keeps the legacy trace. - EvaluationOptions.trace is a TraceFormat (off, v1, legacy). Legacy traces are produced directly from the same recording. - zen_engine::trace exposes convert, restore and inspect for stored documents, with redaction and truncation markers. - The trace header takes evaluatedAt, timezone and seed from the evaluation context, so an evaluation replays from its own trace. - Batch and columnar evaluations record events as columns and write one document per row. - Bindings accept the trace format (true, 'v1', 'legacy'); the Node binding ships TypeScript types for the v1 document. - Golden, fixture and damaged-document tests cover byte identity with the legacy trace, restore, interop with the reference fixtures and malformed input. * perf(trace): build columnar request rows once with precomputed paths * perf(trace): write a node's edits from its written columns * perf(trace): capture node columns instead of row values in the columnar plan * perf(trace): reuse a node's rendered body for rows with the same rule and cell values * perf(trace): size the batch trace buffer up front, key node bodies on typed column words, share request rows as the input * perf(trace): read the request from input columns and build request rows only on demand * perf(trace): key node bodies on per-column codes and precompute node heads and result labels * perf(trace): keep first-hit table facts and their referenced fields as columns * perf(trace): write per-row expression results in the batch writer * perf(columnar): write result rows as JSON straight from output columns * perf(trace): keep collect-policy rule hits as columns and reuse hit text * perf(trace): pack loop results from columns and resolve result column accessors once per batch * perf(trace): share row-wise node outputs with the trace when nothing can alias them * perf(trace): pack lists without a string per distinct item * perf(trace): write new lists from columns and decide references by where a list came from * perf(trace): write wide list items from columns while the list has never been built * perf(trace): read list cells once while rendering * feat(trace): list table inputs once per node and key rule cells by column id * feat(trace): name matched policy table rows by rule id * feat(trace): store loop results as one column per key * build: optimise test builds
* feat(engine): select the engine with a version option * ci: run the two feature sets as parallel jobs * refactor(engine): drop the global compiled switch * feat(engine): pin the clock through options instead of the environment The __ZEN_MOCK_UTC_TIME variable and the ZEN_EXPRESSION_CONFIG lane flag are gone. Isolate takes with_now and with_lane, and the interpreted engine now honours the now option in expressions, so tests pass the instant explicitly. * test(engine): count trace paths per thread and drop the trace test lock * ci: run tests with nextest * test(engine): share golden trace outcomes between variants
* refactor(engine): carry the depth limit on the evaluation handle * refactor(engine): name the per-row evaluation handles * refactor(engine): pass one invocation through the compiled entry points * refactor(engine): track nesting depth on the evaluation handle * refactor(engine): drop argument-count allowances that no longer apply * refactor(engine): pass context and trace probe as one lane value * refactor(engine): hand the invocation to the policy entry * refactor(engine): read function timeout and nodes-in-context once per evaluation * refactor(expression): pass the evaluation context to comparison and table-cell helpers
* 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
chore: sync master
This branch has not been deployed
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
Adds engine version 2: a compiled engine for decision graphs and policies that runs next to the existing one. Version 1 stays the default and is left as it was. Version 2 is opt-in per engine instance, returns the same results as version 1, and adds batch and columnar evaluation for large data volumes.
Features
Batch and columnar evaluation for large data
Version 1 evaluates one input at a time: every row pays for walking the graph, building objects and merging them. That is fine for request/response use and too slow for scoring millions of rows. Version 2 adds two entry points for that case, both in the Rust API in this release:
evaluate_batchtakes many inputs and runs each node once over all of them. Results come back per row, in the same shape as single evaluations.evaluate_columnstakes typed columns (numbers, text, booleans, dates, lists and nested fields, each with a validity mask) and returns typed columns. No row objects are built on the way in or out, which is the shape data-frame engines such as Spark and file formats such as Parquet already use.For a pipeline this means about 25 million rows per second per core on the median sample graph (against about 96,000 for version 1), errors reported per row while the rest of the batch completes, and a stable output schema where a missing or null value is a null cell. A call runs on one thread; parallelism comes from the caller, for example one call per partition.
Faster single evaluations
A decision is compiled once into a plan and evaluated from it on later calls. Existing request/response workloads get about 1.7× the throughput without any change to the graphs. Graphs with function nodes run at the same speed as on version 1.
Reproducible evaluations
New options
now,timezoneandseedfix the clock, the time zone andrand()for an evaluation. They apply to expressions, decision tables and toDateandMath.randominside function nodes. In a batch every row draws from its own random stream, so a single row can be replayed alone and give the same result.Trace format v1
trace: trueon version 2 returns a compact trace document that records when and in which time zone the evaluation ran. It is produced per row for batches and columns and can be restored to the legacy trace shape.trace: 'legacy'returns the old format directly, and'string','reference'and'referenceString'keep working on both versions.Opt-in, side by side with version 1
The engine version is chosen per engine instance, so both versions can run in the same process and a migration can go decision by decision. Omitting the option keeps version 1.
Using it
new ZenEngine({ version: 2 })ZenEngine({"version": 2})ZenEngine.withVersion(2, loader, customNode)zen_engine_set_version(engine, 2)DecisionEngine::default().with_version(EngineVersion::V2)Standalone
evaluateExpressionstays on the old VM.Performance
86 sample graphs from
test-data/graphs(those without function or sub-decision nodes), 4,000 rows each, one core, release build:The "against version 1" column is the geometric mean over the graphs, with the range in brackets. With varied input rows the picture is the same: 1.7×, 7.3× and 160×.
Compatibility
Version 2 is checked against version 1 with a shared spec corpus (about 14,800 cases, each run on every evaluation path) and differential fuzzing over expressions, graphs, traces, policies and the Node binding.
Known, intended differences on version 2:
tags[]with no contributing rule) is written as[]; version 1 omits the key.{"code":7}) instead of a memory address.keys($nodes)has a stable order.Effect on version 1
Outside the new directories (
core/engine/src/compiled,core/expression/src/lane,core/expression/src/typed) the existing engine changes little: 10 of 62 files in the old expression crate, +96 / −22 lines. What a version 1 user can notice:nowoption is honoured in expressions, switch nodes and policies.rand()uses a different generator.median([]),joinon an empty list and very deeply nested expressions no longer crash.decision.evaluatereturns result keys in evaluation order instead of alphabetical order, and no longer aborts on integers beyond 64 bits.__ZEN_MOCK_UTC_TIMEenvironment variable is gone.EvaluationOptions.traceis aTraceFormatinstead of abool, and the policy request and result types are generic over the trace type.Testing
About 1,100 Rust tests for each feature set, the spec corpus above, and the Node, Python and UniFFI binding suites in CI.