Repository navigation
engine: VM run-time wins + three data-verdicted optimization investigations - #717
Conversation
The per-timestep flow program re-evaluated every literal-only subtree on every step: C-LEARN's fused stream carried 792 BinConstConst sites (literal op literal), including one for every negative literal, since unary minus lowers to '0 - x'. Fold these once at compile time, in Var::new -- the single chokepoint both the monolithic and salsa per-variable lowering paths funnel through -- so the VM and the wasm backend both see the folded form. Folding is bit-exact by construction: it computes results with the VM's own eval_op2/is_truthy (so Eq keeps its ULP-based approx_eq and Mod its rem_euclid semantics), and only IEEE-exact operations fold. '^' (powf) and the transcendental builtins are platform libm, so folding them would bake platform-dependent literals into the compiled artifact and the emitted wasm blob; they stay runtime computations. No algebraic rewrites: '(x*2)*3' is left alone (f64 is non-associative), only constant-only subtrees collapse. On C-LEARN this removes all 792 BinConstConst dispatches per step (total bytecode -5.0%, fused per-step stream 23782 -> 23158) for a ~2% run improvement, and cascades into deeper 3-address fusion (BinVarConst 726 -> 1034). The simulates_clearn Ref.vdf exactness gate and the wasm parity twin both pass unchanged. A side effect worth noting: a variable whose entire RHS folds to a constant (e.g. 'x = 2*3' or 'x = -2') now compiles via the named- literal AssignConstCurr path and becomes set_value-overridable, consistent with how plain literal constants already behaved. The fused-binop operand-order test now pins BinConstConst via '7 ^ 3' -- the one operator folding leaves at runtime -- so the opcode's dispatch arm stays exercised.
The array machinery was the #2 cost center of a C-LEARN run (~13% across flat_offset, offset_for_iter_index, and the SmallVec shape compares in the iteration load arms). Three value-preserving fast paths, each keeping the general path as fallback: - RuntimeView::dense_linear_start(): "no sparse mappings and strides are exactly the row-major strides of the current dims" -- i.e. the k-th element in iteration order lives at flat offset start + k. This is is_contiguous minus the offset == 0 requirement, so offset slices like arr[2, *] and leading-dimension ranges arr[1:3, *] qualify too (is_contiguous is now expressed in terms of it). offset_for_iter_index, the BeginIter precompute decision, and reduce_view's new slice-fold fast path all key on it; reduce_view's linear fold visits elements in the same row-major order as the general path, so FP reductions stay bit-identical. - vector_elm_map: hoist the offset view's addressing out of the per-element loop (start + i when the view is one dense run, the common case), and skip maintaining the multi-dim indices entirely when the source is a full array (they are only needed for the strict-slice base). This was the single largest flat_offset caller (~4% of the run across C-LEARN's 168 VECTOR ELM MAP sites). - RuntimeView::same_shape(): hand-rolled dims/dim_ids equality for LoadIterViewTop/LoadIterViewAt. SmallVec's slice PartialEq lowers to an out-of-line memcmp call, ~2% of the run when executed per element per load site; a branchless accumulate over <= 4 u16s compiles to inline compares (and resists LLVM's loop-idiom conversion back into bcmp). flat_offset/offset_for_iter_index also gain #[inline] -- they are per-element calls whose call overhead and un-hoisted SmallVec spill checks were visible in the profile. C-LEARN run_to_end: 148 -> 138 ms (-7%); with the constant-folding commit, 151 -> 138 ms (-8.6%) cumulative. memcmp 2.1% -> 0.6%, flat_offset 8.2% -> ~4% of the (smaller) run. The simulates_clearn Ref.vdf exactness gate and the wasm parity twin pass unchanged.
Documents the constant-folding and linear-run fast-path work in docs/design/engine-performance.md: per-rung measurements on C-LEARN (151 -> ~137 ms, -9%), the R4 status update, the larger un-measured run-side swings identified during the round (lazy IF, time-invariant hoisting, lookup segment memo), and the vector_elm_map affine-base negative result -- a provably-equivalent rewrite that measured a consistent regression by perturbing eval_bytecode's codegen, reinforcing GH #604's measure-everything rule for the eval loop.
C-LEARN's 161 graphical functions (~229 points each) are evaluated ~780k times per run at a slowly-advancing TIME index, so consecutive LOOKUPs of the same table land in the same segment almost every time. `lookup` was ~2.2% of the run, dominated by a per-call binary search that almost always returns the same lower bound as the prior call. Add `lookup_with_hint`, a sibling of `lookup` that remembers the last binary-search lower bound per (module, graphical-function) and validates it in O(1) before falling back to the search. A hint `h` is valid iff `0 < h < len && table[h-1].0 < index <= table[h].0`, which for a sorted table uniquely identifies the search's lower bound `low`, so the shared `lookup_tail` runs on an identical `low` and returns the bit-identical f64. The hint is a pure optimization: it never changes a result, only whether the search runs. The early returns (empty / NaN / below-first / above-last) are unchanged and run before any hint logic. The memo (`Vec<Vec<u32>>` on `Vm`, indexed by (module_idx, gf_idx), threaded through `EvalState`) is only consulted by the scalar Interpolate-mode `Lookup` opcode; Forward/Backward modes and `LookupArray` stay unhinted. `reset()` does not clear it because a stale hint is only ever a miss or a still-valid hint, never a wrong result. `lookup` itself is untouched (it is the wasmgen lookup-helper oracle); both paths share the extracted `lookup_tail`. Verification: engine lib + integration suites pass, and the byte-exact C-LEARN gates (simulates_clearn vs Vensim Ref.vdf and the wasm parity twin simulates_clearn_wasm) both pass -- no simulated value changes. Measurement (CLEARN_RUN_ITERS=20, 3 runs): 136.53 / 136.68 / 137.04 ms/iter vs the ~137.4 ms baseline -- neutral-to-slightly-positive, within the eval-loop codegen noise band. The change is correctness-safe regardless of the timing; the manager decides keep/revert.
The hint uniqueness argument in lookup_with_hint (GH #602) requires the table's x-values to be non-decreasing: only then does a hint h satisfying table[h-1].0 < index <= table[h].0 uniquely identify the binary-search lower bound. No import path (XMILE, protobuf/DB, MDL, or variable.rs parse_table) validates or sorts x-values, so an unsorted table reaching lookup_with_hint could accept a stale hint, run lookup_tail on the wrong low, and return a completely wrong result -- diverging silently from lookup (the wasm oracle). Review found the reviewer's minimal reproducer: t = [(0,0), (10,1000), (5,50), (20,200)] first call at 0.25 seeds hint=1; second call at 7.0 accepts hint=1 (table[0].0=0 < 7 <= table[1].0=10), runs lookup_tail at low=1, and returns 700 instead of the correct 70. Fix: at Vm::new, classify each table with table_x_is_sorted (windows(2).all(|w| w[0].0 <= w[1].0)); unsorted tables (including any with NaN x-values, which compare false) are assigned LOOKUP_HINT_DISABLED (u32::MAX) in lookup_memo. lookup_with_hint checks the sentinel first: if disabled, it delegates to lookup verbatim and returns without touching the hint slot, making it structurally impossible for the miss path to overwrite the sentinel. Sorted tables continue to use 0 (never a valid hint, seeds on first interior lookup). No import-boundary validation or sorting is added (separate issue per manager decision: that changes behavior of DB-stored models). The lookup_hint_tests module is split to vm_lookup_hint_tests.rs to keep vm.rs under the 6000-line per-file limit. Tests added: the reviewer's exact reproducer (bit-exact with lookup, sentinel never overwritten across multiple calls), a proptest over unsorted tables with the forced sentinel (bit-exact + sentinel stable), table_x_is_sorted unit tests (sorted/unsorted/NaN/edge cases), and a Vm::new integration test (sorted GF round-trips correctly).
Reverts the per-GF last-segment memo (a411b5a) and its soundness fix (efd7425), banking the measurements as a negative result in docs/design/engine-performance.md. The memo's gross win was ~0.7 ms on the 137 ms C-LEARN run (the ~8-deep binary search over 229-point tables is already well-predicted when the index advances slowly). Review then demonstrated the hint diverges from lookup() on unsorted-x tables, which are reachable -- no import path validates x ordering (now tracked as GH #715) -- so correctness requires gating the hint per table. Both sound formulations (sentinel inside lookup_with_hint, and the check hoisted to the dispatch arm) measured a consistent +9..15 ms regression via interleaved worktree A/B: the extra branch + call edge in eval_bytecode's Lookup arm perturbs the giant function's codegen (instructions +1.5%, cycles +6.4%, IPC 4.34 -> 4.13, branches down). Gross 0.5% win, ~7% soundness cost: net negative on this microarchitecture, so the whole idea comes out rather than leaving hint state and an unsound-or-slow gate in the VM.
Records the run-invariance definition, the plumbing for stage B1
(classification + runlist partition + split metadata), and the B2
execution sketch.
The two load-bearing structural arguments this note pins down, by reading
the assembly and bytecode code:
* Fragment-length preservation: the salsa path concatenates per-variable
symbolic fragments 1:1 (renumber_fragment_code strips one trailing Ret
per fragment, the merger appends one terminal Ret) and resolve_module
is opcode-count-preserving (no fusion), so an invariant-prefix opcode
length is exactly the sum of the prefix fragments' Ret-stripped
lengths.
* Fusion-boundary safety: peephole runs per-fragment, and the whole-
program fuse_three_address only ever starts a window on a Load* and
ends it on an Op2/BinOpAssign combiner -- never an Assign*-family
opcode. Every fragment ends in an Assign* (the variable's final write),
so no fusion window crosses a fragment boundary, and the recorded
prefix length stays a clean opcode index.
The monolithic Module::new path is test-only (#[cfg(test)]); production is
the salsa assemble_module path. Both still funnel every variable through
Var::new, so the shared classifier over the lowered Vec<Expr> classifies
identically and an equivalence test guards against drift.
Stage B1 of time-invariant variable hoisting: classify which root-model flow variables are run-invariant (same value every timestep), partition the flow runlist so they form a contiguous prefix, and record the split boundary. Behavior-neutral -- the reordered single flow program is unchanged for the VM and wasmgen; stage B2 (a separate change) will run the invariant prefix once per run_to. The classifier (`compiler::invariance`) is a pure functional core: `exprs_are_invariant` walks a variable's lowered Vec<Expr>, exhaustive and default-variant over every Expr/BuiltinFn arm (a future new variant fails to compile here rather than being silently misclassified), parameterized by an offset-classification callback. Invariant sources: literals, Dt, the fixed time-globals, Init(_) of any var (the init buffer is frozen after initials), GF lookups with invariant indices, pure builtins / reducers / array-ops of invariant args, and other invariant vars by offset. Variant (default): Time/Pulse/Ramp/Step/Previous/ModuleInput/ EvalModule, stocks, and any slot owned by a module instance. The two prototype false-positive classes -- module-output reads via plain LoadVar offsets, and whole-array view reads of a variant array -- are both handled by the owner-resolving callback. The salsa path (`db::invariance::model_flows_invariant`) runs the shared classifier in a single topological pass over the flow runlist (deps precede readers, so one ordered pass is a fixpoint), feeding it a callback that inverts each variable's mini-layout to a dependency name and looks up the accumulated verdict. `assemble_module` stably partitions the flow fragments (invariant first) and records the invariant prefix's opcode length on CompiledModule; that length is exact because fragment concatenation and resolve are opcode-count-preserving and the boundary is fusion-proof (no fuse_three_address window crosses a fragment boundary -- every fragment ends in an Assign* and no window starts with / uses an Assign* as a combiner). The monolithic Module path is test-only (Module::new is #[cfg(test)]); it produces no production split. The equivalence is guarded by running the SAME shared classifier over both paths' lowered exprs and asserting the invariant var-name sets agree (`salsa_and_monolithic_paths_agree`). Soundness is pinned by an oracle that simulates and asserts every hoisted slot is bit-constant across all saved steps; its RED-GREEN was verified by temporarily classifying Time as invariant and watching the oracle trip. Ignored heavy oracles report C-LEARN: 868 invariant slots, 0 violations; WORLD3-03: 78 slots, 0 violations (the prototype measured 678/1368 and 71/242 root flow VARS -- the slot counts run higher because arrayed invariant vars occupy multiple slots, and the zero-violation result is strictly stronger than the prototype's).
Stage B1 of time-invariant hoisting (flow-runlist partition + split metadata) is behavior-neutral and should be perf-neutral, but the mandatory interleaved A/B (3 rounds, freshly-built clearn_profile, same model file) measured the reordered binary a consistent ~9.5 ms FASTER (145.0 -> 135.5 ms), not neutral: clustering the invariant constant-slot-writing fragments into one prefix improves the per-step memory-access locality of the throughput-bound run. Recorded alongside the classification counts (C-LEARN 868 invariant slots / 0 oracle violations, WORLD3 78) so the campaign's measurement trail stays complete.
Six minor fixes and one critical correctness fix. CORRECTNESS (critical): `compute_flow_invariance_support` collected `dep_names` from all mini-layout keys (both dt and init-phase deps). Variables that reference a dynamic dep only in their init expression (e.g. `INIT(dynamic_var)`) were incorrectly classified as variant because `dynamic_var` appeared in dep_names but not in the invariant set. The fix walks the actual flow expression (`per_phase_lowered.noninitial`) via `collect_expr_offsets` to collect only offsets actually referenced at dt time, then reverse-maps each offset through the mini-layout to the owning variable name. `Init(a)` arguments are NOT walked (mirroring `builtin_is_invariant` which returns `true` without walking `a` -- the initial-values buffer is frozen). This restores the oracle counts: C-LEARN 868 invariant-classified slots, 0 violations; WORLD3 78 slots, 0 violations (both previously showing 470/78 under the bug). Compile A/B (CLEARN_COMPILE_ITERS=20 CLEARN_PROFILE=compile, 3 rounds each, interleaved): base: ~572, ~589, ~575 ms (mean ~578 ms) current: ~580, ~575, ~578 ms (mean ~578 ms) Delta ~0 ms (<1%), within noise -- compile regression resolved. Minor fixes (all in the adversarial review): - `vm.rs`: add pre-fusion contract comment + `#[doc(hidden)]` on both test-support accessors (`invariant_flow_offsets`, `flows_invariant_ opcode_len`). - `invariance.rs`: `#[allow(dead_code)]` on `OffsetClass::Variant` with explanation comment. - `assemble.rs` + `invariance.rs`: drop external `is_root` double-guard; `model_flows_invariant` is now called unconditionally from `assemble_module`, with the authoritative guard inside. - Design plan added to `docs/README.md` index. - `engine-performance.md`: perf claim corrected to perf-neutral (~135.5 vs ~136.3 ms), methodology lesson added. - `design-plans/2026-06-04-time-invariant-hoisting.md`: "every fragment ends in Assign*" corrected to apply only to invariant-prefix fragments; false-positive class 1 description updated from "string-matching" to "kind-flag check via VarInfo.is_module". - `ltm/compile.rs`: `flow_invariance: None` with comment at both `VarFragmentResult` initializers (LTM synthetic vars are always dynamic).
Post-re-review housekeeping. The db/invariance.rs module doc and the CLAUDE.md entry still described the original mechanism (re-lowering each flow var and running the shared classifier with a mini-layout callback); the 0d0a151 rework moved the evidence onto the cached compile_var_fragment result (FlowInvarianceSupport: locally_pure + dep_names) with this query reduced to the topological fixpoint. Both docs now describe the shipped mechanism and where the soundness burden actually sits (dep_names + the bit-constancy oracle). Also adds the re-reviewer's recommended debug_assert in compute_flow_invariance_support: the offset->owner reverse-map's filter_map silently DROPS an unresolvable offset, which post-rework is the over-classification direction (a dependency invisible to the fixpoint -> stale values once B2 skips the invariant prefix). The drop is unreachable today (the mini-layout is contiguous and time globals never lower to Expr::Var), but a future lowering change should fail loudly in debug builds rather than weaken the classifier silently.
The B2 invariant-prefix execution stage is complete and gate-green but unmerged (preserved on experiment-712-b2-execution): removing ~45% of the root flow stream's static opcodes cut executed instructions only 1.3% -- per-step work is dominated by module evals and per-element loops, not the root scalar stream -- and the wall-clock delta sits inside the ~4% build-layout noise floor (two build pairs measured opposite signs; two builds of identical base source differed by 6 ms). B1 (classifier + partition) stays: behavior/perf-neutral and the foundation for a retry on a mispredict-bound core (branch-misses fell 8.4%), which GH #712 records as the retry condition. Also records the methodology consequence: effects under ~3% need layout-stable counters or multiple independent builds per side; a single worktree build pair only resolves effects above ~4%.
A dispatch census (temporary VM counters + stack-effect branch-span reconstruction over the fused stream) measured C-LEARN at exactly 30,524 executed dispatches/step, of which lazy-IF would skip 4,859 (15.9%) -- but 93% of the skipped opcodes are cheap scalar loads/binops, putting the instruction share at ~1.5%: below the ~4% build-layout measurement floor, at the highest complexity of the three round-3 candidates (forward jumps touch the stack validator, peephole/fusion jump maps, the symbolic layer, and wasmgen). WORLD3: 3.25% dispatch share. 69.8% of the skippable dispatches sit behind constant conditions (1,300 of 1,679 flow If sites take the same branch all run), pointing at the compile-time #712 family rather than runtime jumps. Revisit only on a mispredict-bound core or alongside a threaded-dispatch rewrite (#601). Also marks the #602 and #712-B2 swing entries with their round-3 outcomes (negative results #2 and #3).
Code ReviewI reviewed the constant folding pass, the run-invariance classifier, the linear-run fast paths, and the soundness oracle. The change is carefully built — VM-semantics-preserving folds, default-variant classifier, partition stability, fusion-proof boundary, and an end-to-end bit-constancy oracle on real corpus models. I didn't find a P0/P1 issue worth filing as an inline comment, but one design-vs-implementation observation is worth surfacing: [P2] Salsa path likely under-classifies LOOKUP-using flow varsThe design note ( In the salsa path however, This is a missed-optimization (under-classification) — it never produces a false positive, so the oracle stays clean and B1 stays behavior-neutral. But it materially undercounts hoistable slots for the (eventual) B2 stage on lookup-heavy models like C-LEARN. Either pre-seeding all Overall correctness verdict: correctThe patch is sound: existing tests/integrations pass, B1 is behavior-neutral by construction, the partition preserves topological order (invariant subgraph is closed under deps), the fusion-proof boundary argument holds, and the oracle catches any over-classification. No blocking issues. |
Summary
A measurement-driven hill-climb on bytecode-VM simulation runtime for large models (C-LEARN, WORLD3), continuing the docs/design/engine-performance.md campaign. Net result on the Apple M-series dev machine, warmed interleaved A/B vs main:
run_to_end(1000 Euler steps)Every commit passed the full pre-commit suite; the
simulates_clearnbyte-exactness gate (VM vs Vensim'sRef.vdf) and the wasm parity twin pass at every step, so no simulated value changed anywhere on this branch.Kept wins
compiler/fold.rs, 45fada4). The per-step flow program re-evaluated everyliteral op literalsubtree each step -- 792 sites on C-LEARN, including one per negative literal (unary minus lowers to0 - x). Folds are computed with the VM's owneval_op2/is_truthyso they are bit-identical by construction;^and transcendental builtins stay at runtime so compiled artifacts and the wasm blob remain platform-deterministic. Bytecode -5%, and the folds cascade into deeper 3-address fusion.RuntimeView::dense_linear_start()("strides are row-major for the current dims, no sparse" --is_contiguousminus theoffset == 0requirement) drives direct addressing inoffset_for_iter_index, theBeginIterprecompute decision, and a slice-fold fast path inreduce_view;vector_elm_map(the largestflat_offsetcaller, 168 sites on C-LEARN) hoists its per-element addressing; a branchlesssame_shapekills the per-element memcmp in the iteration load arms (2.1% -> 0.6% of the run).CompiledModule. Behavior-neutral and perf-neutral by design (verified twice); soundness is pinned by a bit-constancy oracle over real models (C-LEARN: 868 invariant slots, 0 violations; WORLD3: 78, 0). This is the foundation for any future hoisting attempt and useful model analysis in its own right. Adversarially reviewed in two rounds to APPROVE.Investigated to a data verdict (the negative results are documented in docs/design/engine-performance.md)
eval_bytecodecodegen perturbation. Net negative; reverted with the data recorded on engine: make graphical-function lookups faster in the VM #602.experiment-712-b2-execution(bcfcd6b3). Removing ~45% of the root flow stream's static opcodes from per-step execution removed only -1.3% of executed instructions: per-step work is dominated by module evaluations and per-element array loops, not the root scalar stream. The wall-clock delta sits inside the ~4% build-layout noise floor (two build pairs measured opposite signs). Branch-misses fell 8.4%, so the retry condition (recorded on engine: compute run-invariant variables once per run, not every step #712) is a mispredict-bound core.Methodology notes (recorded in the perf doc)
Three provably-equivalent changes regressed measurably through codegen perturbation of the giant inlined
eval_bytecode; build-to-build binary-layout variance reached ~6 ms for identical source. The doc now records the discipline that survived contact with all of this: warmed, interleaved, worktree-built A/Bs; layout-stable counters (instructions/branch-misses) for effects under ~3%; and static-opcode share is not a proxy for executed work.Test plan
cargo test -p simlin-engine --lib(4286+),--test integration --features file_io(482)simulates_clearn+simulates_clearn_wasm(release, byte-exact vsRef.vdf+ wasm parity)oracle_clearn/oracle_wrld3invariance soundness oracles (868/78 slots, 0 violations)vm_alloc(run stays zero-alloc)