You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
engine: init-time feedback through SMTH1 gives wrong t=0 value, no error #595
When a variable's initial value feeds back into itself through a SMTH1/SMOOTH-style module, the engine can compute initial values in the wrong order and give a wrong t=0 value with no error.
A real initial-value cycle through such a module also compiles and simulates instead of being reported.
The cycle check treats every module instance as having no dependencies, so it never sees a cycle through one.
The initial-value ordering still has the edges, finds the cycle, and breaks it at whichever variable sorts first.
The order is now deterministic (it used to vary run to run), but it can still be wrong.
Expected y[r1] = 13 from t=0.
Actual y[r1] = 0, 13, 13, 13: the smoothing stock initializes from its input before the input is computed.
A correct order exists (y[r2], the input, the module, y[r1]), so this should simulate correctly, not error.
Second case: a = SMTH1(b, 1) with b = a + 1 has no well-defined initial value but simulates a = 1, 2, 3, 4.
It should be a circular-dependency error.
Because initialization reads a slot before writing it, re-running the same compiled simulation after reset gives different numbers.
Why it matters
Silent wrong initial values.
Both examples are constructed; no corpus model is known to hit it now (C-LEARN hit the old nondeterministic version).
Fix
Cheapest: make a cycle that the initial-value ordering finds but the cycle check missed a compile error.
That turns wrong numbers into an error, including for the first example; check that C-LEARN and the corpus still compile.
Better: in the initial-value phase, let the cycle check see through a module to the inputs its outputs' initial values actually read, so the element-level recurrence logic can order the first example and reject the second.
Pointers
src/simlin-engine/src/db/dep_graph.rs: walk_successors (modules have no successors), topo_sort_str in model_dependency_graph_impl
Correction: the "no known in-repo model triggers it" claim is FALSIFIED -- C-LEARN is a concrete reproducer
The issue body currently states (Scope / trigger, and Severity):
No known in-repo model triggers it today, so there is currently no failing test -- it is a latent soundness gap, not an observed regression.
That is no longer true. The C-LEARN model (test/xmutil_test_models/C-LEARN v77 for Vensim.mdl) deterministically triggers this init-phase ordering nondeterminism. It was found while profiling C-LEARN's run phase, not during the original dt-phase work.
The triggering shape in C-LEARN
C-LEARN has a cross-element cumulative init recurrence:
Depth at Bottom[lower] = INITIAL(Depth at Bottom[upper] + Layer Depth[lower])
Each layer's init value depends on the layer above it, and the recurrence is realized through synthetic init helpers. This is precisely the "init-time algebraic cycle through a synthetic-module stock output" shape this issue describes -- and unlike emissions_with_stopped_growth (whose feedback is init-broken by ACTIVE INITIAL, which is why the C-LEARN residual work never surfaced this), this recurrence is not init-broken, so its init ordering is genuinely subject to the HashMap-iteration-order tie-break.
Symptom
The depth_at_bottom slots receive a per-process permutation of their layer->value assignment: the values 300 / 700 / 1300 / 1600 / 2000 permute among the depth_at_bottom slots, and which value lands in which slot varies on every process invocation. The wrong init values then propagate through all 251 saved timesteps.
This is HashMap-iteration order from the per-process RandomState seed, not a threading race: it reproduces with RAYON_NUM_THREADS=1. The NaN count is stable (12299 NaNs), so it is not NaN-payload noise either -- only the depth_at_bottom-derived slots differ between runs.
Why the test suite never caught it
depth_at_bottom is in tests/simulate.rs's EXPECTED_VDF_RESIDUAL carve-out (src/simlin-engine/tests/simulate.rs:1597, the carve-out tracked under #591), so simulates_clearn never compares those slots against Ref.vdf. The nondeterminism is therefore invisible to the integration test today -- it sits entirely inside the carved-out residual.
Reproducer (first-hand verified)
cargo build --release -p simlin-engine --example clearn_profile
RAYON_NUM_THREADS=1 ./target/release/examples/clearn_profile # run several times
Each run prints a result_fingerprint line. The fingerprint (an FNV-1a-style fold over all saved result bits, computed outside the timing loop) changes across runs -- the low 4 bytes are stable, the high 4 bytes vary -- and only the depth_at_bottom-derived slots differ. Six consecutive runs here (single-threaded), all with identical slot/step geometry (5726 slots/step x 251 steps):
run 1: result_fingerprint: afa6a1ba7346a804
run 2: result_fingerprint: ba6461ba7346a804
run 3: result_fingerprint: afa6a1ba7346a804
run 4: result_fingerprint: afa6a1ba7346a804
run 5: result_fingerprint: ba6461ba7346a804
run 6: result_fingerprint: ba6461ba7346a804
(The clearn_profile.rs example already documents this caveat inline at the result_fingerprint computation and attributes it to this issue; see src/simlin-engine/examples/clearn_profile.rs ~lines 268-278.)
Consequences for this issue
The "latent / no observed trigger" framing should be updated: this is now an observed, deterministically reproducible nondeterminism in a real in-repo model, not just a theoretical soundness gap.
C-LEARN can serve as (or seed) the regression fixture this issue calls for, alongside the minimal inline SMOOTH/SAMPLE IF TRUE fixture. Note that C-LEARN alone is unsuitable as the only regression guard: it is #[ignore]d for runtime and its depth_at_bottom slots are carved out of the comparator, so a guard built on it would need to assert init-ordering determinism directly (e.g. fingerprint stability across compilations) rather than rely on the VDF comparison.
The nondeterminism half is FIXED by e24b0080; the deeper soundness gap remains
Updating disposition as part of C-LEARN-residual Phase 4.
Fixed: the observable nondeterminism
Commit e24b0080 ("engine: make simulation runlist ordering deterministic") closes the nondeterminism half of this issue. The init runlist ordering is now a deterministic function of the model, not the per-process RandomState/HashMap-iteration seed. Concretely:
C-LEARN's depth_at_bottom cross-element cumulative init recurrence (Depth at Bottom[lower] = INITIAL(Depth at Bottom[upper] + Layer Depth[lower])) -- the concrete reproducer from the earlier comment -- no longer permutes its per-layer values across runs.
clearn_residual_exactness now passes deterministically (re-run twice in Phase 4, byte-identical: 3482 idents matched; 21 live residual bases vs 21 excluded both times). Before, depth_at_bottom was in the carve-out and its slots permuted per process.
With the deterministic ordering, depth_at_bottom now matches Ref.vdf and was pruned from EXPECTED_VDF_RESIDUAL in Phase 4.
Remaining: the deeper soundness gap
The structural gap this issue describes is not fully closed. The init-phase cycle relation (init_walk_successors) still treats a synthetic module as a sink, so a genuine init-time algebraic cycle through a synthetic-module stock output can be invisible to cycle detection while the ordering data still carries the closing edge. e24b0080 made the tie-break deterministic, but the invariant this issue calls for -- "the set of edges topo_sort_str orders on must be exactly the set the cycle detector walked, so a real init cycle is reported (CircularDependency) and a non-cycle is deterministically ordered" -- is the part that still needs a general structural fix.
In other words: a deterministic-but-still-arbitrary ordering of an undetected init cycle could, on a different model shape, deterministically pick a wrong order rather than a nondeterministic one. The determinism fix removes the run-to-run variation; it does not yet make every such init cycle a detected error.
Recommendation
Keep this issue open for the soundness gap, but downgrade the severity note from "nondeterministic/incorrect init values" to "init-phase ordering may silently order an undetected init cycle". The regression fixture this issue asks for (a non-init-broken SMOOTH/SAMPLE IF TRUE feedback whose init cycle should be a detected CircularDependency) is still the right next step.
Two minimal reproducers for the remaining soundness gap, plus a Vm::reset consequence
The previous comment predicted that the deterministic-but-arbitrary tie-break "could, on a different model shape, deterministically pick a wrong order". Here are two 3-variable shapes where it does, both verified on the compiler-unification-v2 branch (PR #1040) and, by that PR's Phase 7.5c+d adversarial review, on the branch base as well -- the mechanism is exactly the one this issue describes and predates the branch.
Sim 0..3, dt 1. Every equation is element-acyclic: y[r1] reads y[r2], a constant. The correct t=0 value of y[r1] is 13 (SMTH1's stock initializes to its input, 3 + 10).
Observed (simlin simulate, and the same slot for slot from the wasm engine):
variable
t=0
t=1
t=2
t=3
$⁚y⁚0⁚arg0⁚r1 (hoisted y[r2] + vals[r1])
13
13
13
13
$⁚y⁚0⁚smth1⁚r1·input
13
13
13
13
$⁚y⁚0⁚smth1⁚r1·output
0
13
13
13
$⁚y⁚0⁚smth1⁚r1·flow
13
0
0
0
y[r1]
0
13
13
13
y[r2] = 3 and y[r3] = 30 are correct throughout. The instance's stock initialized from an unwritten input (0 in a clean buffer); the flows phase then computed the real input and a spurious first-step flow of 13.
The dep graph for main (model_dependency_graph) shows why:
The ordering data carries the cycle smth1 -> arg0 -> y -> smth1 (the variable-level self-edge of y through the instance), but walk_successors returns no successors for a module ("A module is a sink in both phases", db/dep_graph.rs), so cycle detection sees nothing (cycle_variables empty), resolve_recurrence_sccs is never handed the SCC (resolved_sccs empty -- there is no combined fragment involved), and topo_sort_str's add breaks the cycle at whichever node the sorted init_list enters first. add marks a node used before recursing into its deps, so the entry node is pushed last, after everything that depends on it. $⁚y⁚0⁚arg0⁚r1 sorts first (helpers start with $), so the module runs before its own input helper. Deterministic since e24b0080; deterministically wrong.
Two contrasting shapes are correct, which pins the trigger to the self-edge through the instance: the scalar twin (y1 = SMTH1(y2 + v1, 1), y2 = 3) and the arrayed twin whose input reads a different variable (y[r1] = SMTH1(z[r2] + vals[r1], 1)) both give 13 from t=0 and a bit-identical rerun.
Note that the correct fix for this shape is not a CircularDependency: the correct order exists (y[r2], arg0, smth1, y[r1]), but it is an element order. The init cycle relation has to see the cycle for the element-cycle refinement (resolve_recurrence_sccs, SccPhase::Initial) to get a chance to resolve it; today the module-as-sink rule hides the SCC from the refinement and from the detector alike.
Shape 2: a genuine init cycle compiles and simulates
a = SMTH1(b, 1)
b = a + 1
The stock's initial value is its input b, which is the stock's own output plus one: there is no well-defined t=0 value. The engine reports no error (cycle_variables: []), emits runlist_initials: [$⁚a⁚0⁚arg1, a, b, $⁚a⁚0⁚smth1] -- again the instance last, after the reader of its output -- and simulates a = 1, 2, 3, 4, b = 2, 3, 4, 5. This is the shape the previous comment asked the regression fixture to cover ("should be a detected CircularDependency"); it is a 2-line inline fixture now.
Vm::reset consequence: a rerun of the same CompiledSimulation is not bit-identical
Vm::reset deliberately does not zero the data buffer: "The data buffer is NOT zeroed here because run_initials() fully reinitializes all variable slots" (vm.rs). That premise is exactly what this defect violates -- a slot is read during initials before it is written -- so the first run reads a clean 0 and the rerun reads the previous run's final value:
run 1
run 2 (after reset())
Shape 1 y[r1]
[0, 13, 13, 13]
[13, 13, 13, 13]
Shape 1 $⁚y⁚0⁚smth1⁚r1·flow
[13, 0, 0, 0]
[0, 0, 0, 0]
Shape 2 a
[1, 2, 3, 4]
[2, 3, 4, 5]
Shape 2 b
[2, 3, 4, 5]
[3, 4, 5, 6]
(vm.run_to_end(); vm.reset(); vm.run_to_end(); on one Vm, every slot compared by to_bits.) The rerun is the "correct" one in Shape 1 only by accident. Whether reset should also zero the buffer as a defensive measure is a separate question; the invariant the comment states is the right one, and this issue is what breaks it.
Orthogonal, and NOT covered by PR #1040's fix for #1028. That fix is about initials-runlist membership (every value-bearing variable of an instantiated model becomes an initials member so a parent's read of a port has a value). In both shapes above membership is already complete -- arg0, the instance and y/a are all in runlist_initials; what is wrong is their order, decided by topo_sort_str over an ordering graph whose cycle the detector never walked.
Suggested disposition
The title's "nondeterministic" is stale since e24b0080; the live defect is "init runlist orders an undetected init cycle through a module instance arbitrarily -- module before its own input (silent wrong t=0 value), and a genuine init cycle is never reported". Worth retitling so the next person searching for "reads unwritten input" / "reset not bit-identical" lands here.
Shape 1 and Shape 2 are the two arms the fix's tests need: an element-acyclic self-edge through an instance that must order correctly, and a genuine cycle that must be refused.
Discovered during the PR #1040 Phase 7.5c+d adversarial review (the review's default_reads_overridden_module_explicit probe); reproduced independently with a standalone Vm harness while triaging for a duplicate. Pre-existing on the branch base.
changed the title [-]engine: init runlist ordering is nondeterministic for an init-time algebraic cycle through a synthetic-module stock output[/-][+]engine: init-time feedback through SMTH1 gives wrong t=0 value, no error[/+]on Oct 12, 2026
Activity
bpowers commentedon May 20, 2026
Correction: the "no known in-repo model triggers it" claim is FALSIFIED -- C-LEARN is a concrete reproducer
The issue body currently states (Scope / trigger, and Severity):
That is no longer true. The C-LEARN model (
test/xmutil_test_models/C-LEARN v77 for Vensim.mdl) deterministically triggers this init-phase ordering nondeterminism. It was found while profiling C-LEARN's run phase, not during the original dt-phase work.The triggering shape in C-LEARN
C-LEARN has a cross-element cumulative init recurrence:
Each layer's init value depends on the layer above it, and the recurrence is realized through synthetic init helpers. This is precisely the "init-time algebraic cycle through a synthetic-module stock output" shape this issue describes -- and unlike
emissions_with_stopped_growth(whose feedback is init-broken byACTIVE INITIAL, which is why the C-LEARN residual work never surfaced this), this recurrence is not init-broken, so its init ordering is genuinely subject to the HashMap-iteration-order tie-break.Symptom
The
depth_at_bottomslots receive a per-process permutation of their layer->value assignment: the values 300 / 700 / 1300 / 1600 / 2000 permute among thedepth_at_bottomslots, and which value lands in which slot varies on every process invocation. The wrong init values then propagate through all 251 saved timesteps.This is HashMap-iteration order from the per-process
RandomStateseed, not a threading race: it reproduces withRAYON_NUM_THREADS=1. The NaN count is stable (12299 NaNs), so it is not NaN-payload noise either -- only thedepth_at_bottom-derived slots differ between runs.Why the test suite never caught it
depth_at_bottomis intests/simulate.rs'sEXPECTED_VDF_RESIDUALcarve-out (src/simlin-engine/tests/simulate.rs:1597, the carve-out tracked under #591), sosimulates_clearnnever compares those slots againstRef.vdf. The nondeterminism is therefore invisible to the integration test today -- it sits entirely inside the carved-out residual.Reproducer (first-hand verified)
Each run prints a
result_fingerprintline. The fingerprint (an FNV-1a-style fold over all saved result bits, computed outside the timing loop) changes across runs -- the low 4 bytes are stable, the high 4 bytes vary -- and only thedepth_at_bottom-derived slots differ. Six consecutive runs here (single-threaded), all with identical slot/step geometry (5726 slots/step x 251 steps):(The
clearn_profile.rsexample already documents this caveat inline at theresult_fingerprintcomputation and attributes it to this issue; seesrc/simlin-engine/examples/clearn_profile.rs~lines 268-278.)Consequences for this issue
SMOOTH/SAMPLE IF TRUEfixture. Note that C-LEARN alone is unsuitable as the only regression guard: it is#[ignore]d for runtime and itsdepth_at_bottomslots are carved out of the comparator, so a guard built on it would need to assert init-ordering determinism directly (e.g. fingerprint stability across compilations) rather than rely on the VDF comparison.EXPECTED_VDF_RESIDUALcarve-out fordepth_at_bottom(engine: four C-LEARN variables still differ from the Vensim reference run #591) is currently masking this; once the init ordering is made deterministic, thedepth_at_bottomresidual should be re-evaluated to see whether it can leave the carve-out.Discovered during C-LEARN run-phase profiling (the
clearn_profileexample), 2026-05-20.bpowers commentedon May 20, 2026
The nondeterminism half is FIXED by
e24b0080; the deeper soundness gap remainsUpdating disposition as part of C-LEARN-residual Phase 4.
Fixed: the observable nondeterminism
Commit
e24b0080("engine: make simulation runlist ordering deterministic") closes the nondeterminism half of this issue. The init runlist ordering is now a deterministic function of the model, not the per-processRandomState/HashMap-iteration seed. Concretely:depth_at_bottomcross-element cumulative init recurrence (Depth at Bottom[lower] = INITIAL(Depth at Bottom[upper] + Layer Depth[lower])) -- the concrete reproducer from the earlier comment -- no longer permutes its per-layer values across runs.clearn_residual_exactnessnow passes deterministically (re-run twice in Phase 4, byte-identical:3482 idents matched; 21 live residual bases vs 21 excludedboth times). Before,depth_at_bottomwas in the carve-out and its slots permuted per process.depth_at_bottomnow matchesRef.vdfand was pruned fromEXPECTED_VDF_RESIDUALin Phase 4.Remaining: the deeper soundness gap
The structural gap this issue describes is not fully closed. The init-phase cycle relation (
init_walk_successors) still treats a synthetic module as a sink, so a genuine init-time algebraic cycle through a synthetic-module stock output can be invisible to cycle detection while the ordering data still carries the closing edge.e24b0080made the tie-break deterministic, but the invariant this issue calls for -- "the set of edgestopo_sort_strorders on must be exactly the set the cycle detector walked, so a real init cycle is reported (CircularDependency) and a non-cycle is deterministically ordered" -- is the part that still needs a general structural fix.In other words: a deterministic-but-still-arbitrary ordering of an undetected init cycle could, on a different model shape, deterministically pick a wrong order rather than a nondeterministic one. The determinism fix removes the run-to-run variation; it does not yet make every such init cycle a detected error.
Recommendation
Keep this issue open for the soundness gap, but downgrade the severity note from "nondeterministic/incorrect init values" to "init-phase ordering may silently order an undetected init cycle". The regression fixture this issue asks for (a non-init-broken
SMOOTH/SAMPLE IF TRUEfeedback whose init cycle should be a detectedCircularDependency) is still the right next step.engine: make simulation runlist ordering deterministic
engine: tighten C-LEARN VDF residual carve-out to the proven remainder
docs: update engine/cli context for C-LEARN residual closure
engine: compiler optimization pass (C-LEARN -33%, LTM on world3 9.8x,…
engine: make implicit-helper identity a name, not a hash-ordered posi…
mdl: import a single apply-to-all equation as ApplyToAll, not explode…
bpowers commentedon Sep 4, 2026
Two minimal reproducers for the remaining soundness gap, plus a
Vm::resetconsequenceThe previous comment predicted that the deterministic-but-arbitrary tie-break "could, on a different model shape, deterministically pick a wrong order". Here are two 3-variable shapes where it does, both verified on the
compiler-unification-v2branch (PR #1040) and, by that PR's Phase 7.5c+d adversarial review, on the branch base as well -- the mechanism is exactly the one this issue describes and predates the branch.Shape 1: element-acyclic, ordered wrong (silent wrong number)
Dimension
R = {r1, r2, r3},vals[R] = 10, 20, 30, and an explicit-elementy:Sim 0..3, dt 1. Every equation is element-acyclic:
y[r1]readsy[r2], a constant. The correct t=0 value ofy[r1]is 13 (SMTH1's stock initializes to its input, 3 + 10).Observed (
simlin simulate, and the same slot for slot from the wasm engine):$⁚y⁚0⁚arg0⁚r1(hoistedy[r2] + vals[r1])$⁚y⁚0⁚smth1⁚r1·input$⁚y⁚0⁚smth1⁚r1·output$⁚y⁚0⁚smth1⁚r1·flowy[r1]y[r2] = 3andy[r3] = 30are correct throughout. The instance's stock initialized from an unwritteninput(0 in a clean buffer); the flows phase then computed the real input and a spurious first-step flow of 13.The dep graph for
main(model_dependency_graph) shows why:The ordering data carries the cycle
smth1 -> arg0 -> y -> smth1(the variable-level self-edge ofythrough the instance), butwalk_successorsreturns no successors for a module ("A module is a sink in both phases",db/dep_graph.rs), so cycle detection sees nothing (cycle_variablesempty),resolve_recurrence_sccsis never handed the SCC (resolved_sccsempty -- there is no combined fragment involved), andtopo_sort_str'saddbreaks the cycle at whichever node the sortedinit_listenters first.addmarks a node used before recursing into its deps, so the entry node is pushed last, after everything that depends on it.$⁚y⁚0⁚arg0⁚r1sorts first (helpers start with$), so the module runs before its own input helper. Deterministic sincee24b0080; deterministically wrong.Two contrasting shapes are correct, which pins the trigger to the self-edge through the instance: the scalar twin (
y1 = SMTH1(y2 + v1, 1),y2 = 3) and the arrayed twin whose input reads a different variable (y[r1] = SMTH1(z[r2] + vals[r1], 1)) both give 13 from t=0 and a bit-identical rerun.Note that the correct fix for this shape is not a
CircularDependency: the correct order exists (y[r2],arg0,smth1,y[r1]), but it is an element order. The init cycle relation has to see the cycle for the element-cycle refinement (resolve_recurrence_sccs,SccPhase::Initial) to get a chance to resolve it; today the module-as-sink rule hides the SCC from the refinement and from the detector alike.Shape 2: a genuine init cycle compiles and simulates
The stock's initial value is its input
b, which is the stock's own output plus one: there is no well-defined t=0 value. The engine reports no error (cycle_variables: []), emitsrunlist_initials: [$⁚a⁚0⁚arg1, a, b, $⁚a⁚0⁚smth1]-- again the instance last, after the reader of its output -- and simulatesa = 1, 2, 3, 4,b = 2, 3, 4, 5. This is the shape the previous comment asked the regression fixture to cover ("should be a detectedCircularDependency"); it is a 2-line inline fixture now.Vm::resetconsequence: a rerun of the sameCompiledSimulationis not bit-identicalVm::resetdeliberately does not zero the data buffer: "The data buffer is NOT zeroed here becauserun_initials()fully reinitializes all variable slots" (vm.rs). That premise is exactly what this defect violates -- a slot is read during initials before it is written -- so the first run reads a clean 0 and the rerun reads the previous run's final value:reset())y[r1][0, 13, 13, 13][13, 13, 13, 13]$⁚y⁚0⁚smth1⁚r1·flow[13, 0, 0, 0][0, 0, 0, 0]a[1, 2, 3, 4][2, 3, 4, 5]b[2, 3, 4, 5][3, 4, 5, 6](
vm.run_to_end(); vm.reset(); vm.run_to_end();on oneVm, every slot compared byto_bits.) The rerun is the "correct" one in Shape 1 only by accident. Whetherresetshould also zero the buffer as a defensive measure is a separate question; the invariant the comment states is the right one, and this issue is what breaks it.Relationship to #1028
Orthogonal, and NOT covered by PR #1040's fix for #1028. That fix is about initials-runlist membership (every value-bearing variable of an instantiated model becomes an initials member so a parent's read of a port has a value). In both shapes above membership is already complete --
arg0, the instance andy/aare all inrunlist_initials; what is wrong is their order, decided bytopo_sort_strover an ordering graph whose cycle the detector never walked.Suggested disposition
e24b0080; the live defect is "init runlist orders an undetected init cycle through a module instance arbitrarily -- module before its own input (silent wrong t=0 value), and a genuine init cycle is never reported". Worth retitling so the next person searching for "reads unwritten input" / "reset not bit-identical" lands here.Discovered during the PR #1040 Phase 7.5c+d adversarial review (the review's
default_reads_overridden_module_explicitprobe); reproduced independently with a standaloneVmharness while triaging for a duplicate. Pre-existing on the branch base.[-]engine: init runlist ordering is nondeterministic for an init-time algebraic cycle through a synthetic-module stock output[/-][+]engine: init-time feedback through SMTH1 gives wrong t=0 value, no error[/+]