Skip to content

engine: XMILE conveyor and queue stock types - #869

Merged
bpowers merged 74 commits into
mainfrom
conveyor-engine
Jul 12, 2026
Merged

bpowers merged 74 commits into
mainfrom
conveyor-engine

Conversation

@bpowers

@bpowers bpowers commented Jul 8, 2026 •

Copy link
Copy Markdown
Owner

What this does

Implements the full XMILE conveyor and queue stock types in simlin-engine, ending the round-trip corruption where importing a Stella model with either construct silently dropped it and re-exported a plain INTEG stock. Both are now first-class: they parse, round-trip, simulate, participate in arrays and container access, unit-check, degrade LTM loudly, and — the whole point of queues — a queue can feed a discrete conveyor with the XMILE batch-taking semantics. Both constructs now simulate on both backends: the bytecode VM and the wasm code generator, held to parity by the fixture corpus.

Two specifications drive the work and live with it:

  • docs/design/conveyors.md (the conveyor spec + a verified reference prototype)
  • docs/design/queues.md (the companion queue spec authored on this branch — conveyors.md §11 referenced it before it existed)

Design decisions (I owned these; flagged the ones to probe against Stella)

  • Conveyor and queue data live in datamodel::Compat, alongside non_negative, rather than as first-class Stock/Flow fields — adding them does not churn hundreds of construction sites. Proto fields append only (a DB holds serialized instances).
  • Runtime as a side table + native pass. Each stock is expanded (pre-pass) into an ordinary INTEG stock with placeholder-0 driven flows, and a native pass runs between the VM's Flows and Stocks phases; the stock integrates through the ordinary Stocks phase from the pass-written rates (the conservation identity Δstock = admitted − out − leak / Δqueue = inflow − outflow). The belt/batch side table tracks the same total at slat/batch granularity. This keeps the compiler and bytecode VM unaware of either construct.
  • Loud, never silently wrong. A conveyor/queue marker that reaches the ordinary compile path un-expanded is rejected loudly (ConveyorNotExpanded/QueueNotExpanded); reading a driven flow in an equation (which would see the pre-pass 0) is rejected (ConveyorDrivenFlowRead/QueueDrivenFlowRead); both are Euler-only; LTM over either degrades to a Warning (ConveyorLtmDegraded/QueueLtmDegraded) because the flow-to-stock link score assumes plain INTEG.
  • Container access without a dynamic-length array. conv[j]/queue[k], SUM/MEAN/SIZE/MIN/MAX/STDDEV, published by the pass into a synthesized hidden stock at step-start (a stock is read-but-not-recomputed by the Flows phase), which gives the spec's start-of-step visibility for free and sidesteps the belt/queue length being runtime-dynamic. The conveyor and queue paths share this machinery (parameterized by the source vector).
  • Queue = FIFO of scalar-volume batches, outflows engine-driven; an unconstrained outflow (to a cloud/regular stock) empties the queue, a conveyor-bound one is throttled by the conveyor's capacity/inflow-limit. Append-then-serve ordering, and an overflow drains exactly the desire − taken volume a capacity/inflow-limit/arrest block rejected. The append-then-serve ordering and a few §4/§5/§6 corners are flagged in the specs as Stella-probe points to confirm against a Stella run.
  • Queue→conveyor coupling shares one flow; the conveyor's admission_budget (mirroring its phase_b capacity/inflow-limit math) sizes the demand-pull, and take_for_conveyor implements the four one_at_a_time/batch_integrity rules. The conveyor run_pass was split into run_phase_a + conveyor_phase_b_one so a coupled pair interleaves (belt Phase A → budget → queue supply → belt Phase B); the uncoupled path stays byte-identical (all Phase A before any Phase B, preserving conveyor→conveyor chains and held exits).

The wasm lowering (this closes GH #884's gap)

The wasm backend now lowers the complete conveyor pass, in the same plan-specialized, unrolled style as the queue pass: nothing walks a plan structure in linear memory at runtime, and the only runtime loops are over a belt's dynamic slat count. Judgement calls made along the way:

  • A runtime error channel for the blob (GH wasm: the blob has no runtime error channel (needed for ConveyorTransitTooLong) #921). A wasm export cannot return a Result, so the blob carries two error globals and one new export, get_error() -> i64, packing (belt << 32) | code. Raising is a capability: only the driver that opened an unwind block can mint an ErrorScope, and a pass emitted at a site with no block panics at emit time — the alternative failure mode was a validated br into run_to's loop, i.e. a silent infinite spin (caught by adversarial review, empirically). The channel is sticky until reset: a host that forgets to poll fails closed instead of computing over a half-built side table. This deliberately diverges from the VM, whose own resume-after-error double-advances belts (GH engine: a conveyor step error leaves the VM half-advanced #938). The TS direct backend polls after every run_to and throws, with a mutation-verified wiring test.
  • Belt grow/shrink landed in step 1, not step 3 as the issue sketched: <sample> defaults to 1, so every belt re-latches <len> each DT, and nothing in ConveyorPlan distinguishes a constant <len> expression from a time-varying one — a fixed-size ring would silently mis-simulate.
  • Exact parity, not epsilon parity. Every accumulation is emitted in the VM's own fold order, so the backends are bit-identical except where wasm's f64 semantics genuinely differ from Rust's (f64.max/f64.min NaN propagation, the -0.0 tie) — those sites use selects on strict comparisons and are documented individually. slat_count is floor(t/dt + 0.5) half-away-from-zero, deliberately not f64.nearest (half-to-even).
  • <sample> needs no new state (the latched transit is only ever consumed as a slat count, which the descriptor already holds); the mid-run slat-bound check sits inside the sample gate's if because a select would evaluate both arms and trap narrowing a huge non-latched transit.
  • Coupling is lowered from the VM's own CouplingTable rather than re-derived, so the two backends' admission priorities cannot drift; the queue side's Coupled rejection is gone.
  • VM bugs found while mirroring were mirrored, not fixed unilaterally — the VM is the oracle, and a one-backend fix would break parity. Each is tracked: GH engine: integer leakage is ignored on an exponential-leak conveyor #942 (exponential belts silently ignore <leak_integers/>), engine: integer leak into an arrested conveyor inflates its stock #947 (an integer leak into an arrested belt diverges the flat stock from the ring), engine: queue-fed discrete conveyor holds fractional amounts #950 (the spec's claim that coupled inflow is integral contradicts the runtime's fractional batch-splitting).
  • Verification was mutation-first, per the issues' own acceptance criteria. Roughly 60 mutants across rounding, admission, capacity, zones, carries, coupling order, preview restore, and hook placement each die under a named test; the handful of survivors are documented equivalent mutants. Four originally-green tests were found vacuous (steady-state or symmetric fixtures) and strengthened; the slab comparator itself had a false positive on infinite values. The corpus gate was verified in both failure directions: re-adding the conveyor reject reddens exactly the six conveyor fixtures on the hard-failure arm, and perturbing the admitted volume reddens them in the slab comparison.

Test-infrastructure and diagnostics fixes bundled here

  • GH test: simlin-engine's simulation corpus is gated behind feature file_io (294 vs 650 tests) #925: a bare cargo test -p simlin-engine --test integration ran 294 tests instead of 652 because the corpus was gated behind the production file_io feature. Fixed with a self dev-dependency (default-features = false, features = ["file_io"]) so test targets get the feature unconditionally while production and wasm builds keep it off. default-features = false is load-bearing — without it the edge silently re-enables the default set and makes --no-default-features a no-op for dev targets.
  • GH cli: Warning-severity diagnostics are printed with an "error" prefix #919: Warning-severity diagnostics printed with an "error" prefix. FormattedError now carries the diagnostic's severity and the formatters render the word from it, so --ltm on a conveyor model prints warning in model 'main': ...conveyor_ltm_degraded... instead of masquerading as a failure. The CLI's has_model_errors/has_variable_errors count Error severity only — previously a warning could suppress the explanation of a genuine build failure. Note the blast radius: this changes the message text of every Warning-severity diagnostic everywhere FormattedError.message is shown (CLI, diagram UI, MCP warnings arrays) — e.g. unit-consistency mismatches now read units warning in model ....
  • Four new conveyor fixtures (leaky_conveyor, conveyor_containers, discrete_conveyor, queue_coupled_conveyor) join the corpus. They are additions — no existing file under test/ changed. The corpus README states honestly what the special-stock corpus does and does not pin (round-trip + backend parity; numeric truth is anchored by hand-derived unit tests, with GH test: nothing checks conveyor results against the spec's prototype #951 tracking an independent oracle).

How it was built

Each chunk was implemented by a fresh agent, then adversarially reviewed by another fresh agent, iterated until no material findings. The final tree got a holistic adversarial review across the integration seams (preview save/restore composition, error-channel contract, doc consistency), whose findings were fixed and re-verified. Mutation testing was the standing acceptance bar throughout — reviews repeatedly caught tests that were green but vacuous, which is exactly what the queue-fixture incident (#924's motivation) predicted.

A machine-environment note: this workstation's fseventsd daemon degraded mid-session (~1s fsevents latency; GH #945 tracks the resulting test-runtime fragility in simlin-serve's watcher suite), which pushed cargo test's wall-clock past the pre-commit hook's 180s cap late in the session. The final four work items therefore landed as one commit rather than four; the per-piece boundaries were preserved as review-time snapshots and each piece was reviewed in isolation before the next began.

Branch review burndown

A full adversarial review of the branch produced 28 confirmed findings. Working them one at a time — each fix reviewed by a fresh adversarial reviewer, iterated until no material findings, committed only on a green pre-commit — surfaced a further cluster of pre-existing engine bugs that the conveyor work happened to expose.

The most consequential is unrelated to conveyors. The equation printer and parser disagreed, and builtins_visitor round-trips a module-backed builtin argument through print_eqn and re-parses it. So x = SMTH1((IF (1 > 0) THEN 10 ELSE 20) / 2, 1) simulated to 10 instead of 5: the printed if (1 > 0) then (10) else (20) / 2 re-parsed with the if swallowing the division. No error, no warning, wrong number. The same corruption ran through LTM, where a link-score partial is built by re-parsing printed text — 448 of C-LEARN's link scores were computed from a mis-grouped equation. Fixing it required also correcting ^ associativity (right-to-left per XMILE §3.3.1, Vensim, and our own mdl::parser; the checked-in arithmetics/output.tab records cons4^cons3^cons2 as 262144 where the engine computed 4096), the parenthesization rule in all four printers, &&/|| precedence, and the !a / a != b spellings the lexer has no rule for. The two Vensim operator-precedence reference fixtures that would have caught all of this were in no run set; they are now.

Other user-visible fixes along the way: a host-aborting panic on duplicate canonical flow idents, a silently-ignored set_value, a mid-run get_value returning placeholder zeros, silent conveyor/queue marker loss on every pysimlin and web-editor edit, silently-dropped duplicate-ident variables, display names eroded by every patch upsert, a one-line canonicalization bug corrupting piecewise-subrange stocks, 34 use-after-free sites plus 8 silent test-skip guards in the libsimlin test suite, and a wrapping queue[k] index in the landed queue wasm lowering (queue[2^32+1] returned the front batch where the VM returns NaN).

No checked-in expected-data file under test/ changed.

Fixes #863
Fixes #870
Fixes #871
Fixes #872
Fixes #873
Fixes #874
Fixes #875
Fixes #876
Fixes #877
Fixes #878
Fixes #879
Fixes #880
Fixes #881
Fixes #882
Fixes #883
Fixes #884
Fixes #885
Fixes #887
Fixes #888
Fixes #889
Fixes #890
Fixes #891
Fixes #897
Fixes #898
Fixes #902
Fixes #903
Fixes #905
Fixes #906
Fixes #907
Fixes #908
Fixes #909
Fixes #910
Fixes #912
Fixes #913
Fixes #919
Fixes #921
Fixes #922
Fixes #923
Fixes #924
Fixes #925

On Fixes #922: its body's enumerated scope (phase_a, phase_b, leaks, zones, discrete, coupling, the Coupled reject) is complete. The §8 spread-input placements (even/dest/dist/source) are not lowered — they were never in #922's enumeration, and GH #946 tracks them as the memory-layout feature they are, with a loud Unsupported reject and tests pinning all four in the meantime.

Deferred, tracked follow-ups (not closed by this PR)

The diagram-editor authoring surface for conveyors/queues is a separate future enhancement noted in the specs.

🤖 Generated with Claude Code

@codecov

codecov Bot commented Jul 8, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 96.08303% with 117 lines in your changes missing coverage. Please review.
✅ Project coverage is 91.52%. Comparing base (aebf890) to head (764322b).
⚠️ Report is 1 commits behind head on main.

Files with missing lines Patch % Lines
src/simlin-engine/src/db/ltm/link_scores.rs 79.03% 26 Missing ⚠️
src/libsimlin/src/lib.rs 24.00% 19 Missing ⚠️
src/simlin-engine/src/common.rs 82.07% 19 Missing ⚠️
src/simlin-engine/src/conveyor.rs 98.35% 10 Missing ⚠️
src/simlin-engine/src/db/units.rs 97.53% 10 Missing ⚠️
src/simlin-engine/src/ast/mod.rs 96.67% 9 Missing ⚠️
src/simlin-engine/src/ltm_augment.rs 94.23% 9 Missing ⚠️
src/simlin-cli/src/main.rs 94.62% 5 Missing ⚠️
src/simlin-engine/src/db/diagnostic.rs 98.03% 5 Missing ⚠️
src/libsimlin/src/simulation.rs 98.30% 1 Missing ⚠️
... and 4 more
Additional details and impacted files
@@            Coverage Diff             @@
##             main     #869      +/-   ##
==========================================
+ Coverage   91.00%   91.52%   +0.52%     
==========================================
  Files         226      234       +8     
  Lines      145803   156283   +10480     
==========================================
+ Hits       132684   143035   +10351     
- Misses      13119    13248     +129     

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@claude

claude Bot commented Jul 8, 2026

Copy link
Copy Markdown

Review

Focused review across the conveyor/queue runtime + compile passes plus the integration/serde/xmile files. Three actionable findings; queue.rs, queue_compile.rs, and the vm/proto/serde integration paths look correct.

[P1] ConveyorDrivenFlowRead scan misses synthesized <len>/<capacity>/<in_limit>/<sample>/<arrest>/leak-fraction auxes

File: src/simlin-engine/src/conveyor_compile.rs Lines: 768–795

The scan iterates model.variables before new_auxes (the synthesized parameter/leak-fraction auxes built at lines 691, 705–708, 660) are appended (line 923). A <capacity>graduating*10</capacity> — where graduating is a conveyor-driven outflow — is materialized into $conv$…$cap from the raw expression string but is never scanned, so the reader-of-a-driven-flow check §4.3 mandates is bypassed. Compile succeeds; at runtime graduating's slot holds the pre-pass placeholder 0 when Flows evaluates the cap aux, so capacity stays at 0 (no admission → driven flow written 0 → cap stays 0), silently freezing the belt instead of erroring loudly. Repeating the same-body scan across new_auxes (and the leak-fraction aux built at line 660) closes the gap.

[P2] Discrete conveyor with explicit per-slat init collapses length-N list into per-block lumps

File: src/simlin-engine/src/conveyor.rs Lines: 611–613

fill_slats unconditionally calls merge_time_unit_blocks() for any discrete conveyor, but §7.2 length-N says entry j "fills slat j-1 directly … the only interpretation available for non-integer transit times." When values.len() == n_slats (the caller at line 530 already routed around spread_per_time_unit), the per-slat placement is silently re-collapsed onto block-deepest slats, contradicting the spec for the non-integer-transit case (where the block partition doesn't cleanly align with slats). Guarding the merge on values.len() != n_slats — i.e. moving it to the else-branch of init_explicit — preserves the existing per-time-unit block semantics while honoring the length-N rule. No existing test covers init_explicit on a discrete conveyor.

[P3] Writer never emits <uses_conveyor/> even when the project contains a conveyor

File: src/simlin-engine/src/xmile/mod.rs Lines: 246–250

Feature::UsesQueue is emitted from a has_queue scan, but there is no parallel has_conveyor scan / Feature::UsesConveyor push, so a conveyor-only project written by simlin drops the <uses_conveyor/> header option (round-trip fidelity gap — mirrors what the queue path already does, and the UsesConveyor variant already exists at lines 862–865).

Overall verdict

The patch is largely correct — 12k lines, but the runtime cores (belt Phase A/B, leakage schedules, queue batch rules, coupling admission budget) match the specs and are extensively test-oracled. The three findings above are localized and do not block correctness of the happy path.

Reviewed by Claude Opus 4.7.

@claude

claude Bot commented Jul 8, 2026

Copy link
Copy Markdown

Code review — 2 findings (medium/low)

[P2] ConveyorDrivenFlowRead guard misses module input references — src/simlin-engine/src/conveyor_compile.rs:853-871

equation_scalar_strings(v) returns an empty Vec for Variable::Module(_), so the driven-flow-read guard only inspects Stock/Flow/Aux equations. A sub-model input wired to a conveyor-driven flow (ModuleReference { src: "<driven flow>", dst: "<port>" }) never trips the check; because the pass runs after the Flows phase, the sub-model receives the pre-pass placeholder 0 instead of the belt-driven rate on every step. This is the silent-wrong-value the guard was written to prevent (design spec §4.3 / “loud, never silently wrong”). Repro: any main-model module whose references includes a conveyor primary or leak flow. Suggest scanning Module.references (the src side) against driven_set in the same loop.

[P3] Arrayed conveyor runtime error names the bare stock, not the element — src/simlin-engine/src/conveyor_compile.rs:1794-1795

ConveyorPlan.name is set to meta.stock.clone() for every element of an arrayed conveyor, so ConveyorTransitNotPositive at init_belts (line 2008) and ConveyorTransitTooLong at check_slat_bound (line 1983) report conveyor 'belt' for a per-element failure (e.g. belt[b] with <len>=-1, others fine), giving the modeler no way to distinguish which element tripped. meta.element_subscripts[e] is already available at this call site — mirroring the subscripted-key convention eoff uses on line 1727 for the offset lookup would attach [elem] to the plan name.

Overall correctness

The patch looks correct. The changes are well-tested (hand-computed oracles + conservation asserts + arrayed independence + loud-rejection coverage), the compat-based side-table design keeps the compiler/VM unaware of both constructs, and the loud-error guards are consistent with the spec. The two items above are quality-of-diagnostic gaps rather than blockers.

@bpowers

bpowers commented Jul 10, 2026

Copy link
Copy Markdown
Owner Author

@codex review

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: e478160232

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread src/simlin-cli/src/main.rs Outdated

set_project_ltm_enabled(&mut db, source_project, true);
match run_simulation(&db, source_project, "main") {
match run_simulation(&db, source_project, project, "main") {

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Warn before returning special-stock LTM runs

When simlin simulate --ltm is used on a conveyor or queue model, this call now goes through build_sim, whose special-stock path intentionally builds a non-LTM VM and succeeds. Because diagnostics are collected just above while ltm_enabled is still false, the conveyor/queue LTM-degraded warnings are never emitted, and the Ok branch returns regular results with no LTM series or explanation even though the user explicitly requested LTM.

Useful? React with 👍 / 👎.

Comment on lines +1466 to +1467
if crate::conveyor_compile::project_has_conveyor(datamodel, main_model)
|| project_has_queue(datamodel, main_model)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Route overflow-only models through queue validation

This dispatch only enters build_vm when the main model has a queue/conveyor stock, so a model with a flow marked <overflow/> but no queue stock takes the ordinary compile path and never runs validate_overflow_markers. In that case the documented QueueOverflowNotOnQueue error is bypassed and the overflow flow is simulated as an ordinary flow, despite <overflow/> being valid only on non-primary queue outflows.

Useful? React with 👍 / 👎.

@claude

claude Bot commented Jul 11, 2026

Copy link
Copy Markdown

Code review for PR #869

Reviewed the new conveyor/queue subsystem, the AST print/parse fix, the VM integration, and the compat round-trip. Two actionable findings; the rest of the audit came back clean.


[P1] fill_slats §7.2 explicit-list init — leak_basis missing per-slat scale
File: src/simlin-engine/src/conveyor.rs:632-636

The §7.2 spec (line 780-782 of docs/design/conveyors.md) says each filled slat gets the linear-leak schedule of a §7.1 cohort that traveled to its position. In §7.1 (init_steady, line 466-475), for cohort entry volume E, basis[k] = E · r_k / M_k(N) and content = E · c[i]. Solving for E given a §7.2 slat content x, the entry volume is E = x / c[i], so basis[k] = (x / c[i]) · r_k / M_k(N). The current code writes basis[k] = x · r_k / M_k(N) — the 1/c[i] divisor is dropped. The inline comment at lines 616-620 acknowledges cohort entry volume is x / c[i] but then justifies the shortcut as a per-content basis of r0/M — this only matches §7.1 for the entry slat (c[N-1] = 1); every non-entry slat with a linear leak fraction gets an under-computed schedule. The prototype at test/conveyors/reference_prototype.py:14 explicitly notes explicit-list init not exercised here, so no oracle catches it.

Failure scenario: §7.2 explicit-list init with any non-zero linear leak fraction and a full/entry-start zone; non-entry slats leak too slowly across their traversal.


[P2] rename_model_equations skips XMILE expression strings in Compat.conveyor / Compat.leakage
File: src/simlin-engine/src/patch.rs:621-663

The Stock arm rewrites the main equation but nothing walks Compat.conveyor.{transit_time, capacity, inflow_limit, sample, arrest}; the Flow arm rewrites active_initial but nothing walks Compat.leakage.{fraction, zone_start, zone_end} or Compat.spreadflow. Those fields are XMILE expression strings compiled by conveyor_compile, and a RenameVariable patch on a variable those expressions reference silently leaves stale idents. After a rename the conveyor compiled transit_time/capacity/inflow_limit/etc. reference a name that no longer exists, and the model fails to compile (or worse, resolves to the wrong entity if the old name gets reused).

Failure scenario: a model with a conveyor whose capacity equation references aux foo; a RenameVariable(foo -> bar) patch leaves Compat.conveyor.capacity = "foo", so the belt next expansion produces an UnknownIdent on foo.


Overall correctness verdict: Correct with caveats. The queue runtime, the printer/parser rework, the wasm queue pass lowering, and the compat round-trip through JSON/proto/patch/MDL/XMILE all held up under scrutiny. The two findings above are bounded — the first affects only §7.2 explicit-list init with linear leaks (an uncommon shape not covered by the reference prototype); the second surfaces only on rename patches that touch a conveyor expression parameters. Both are fixable in one small commit each without disturbing the surrounding design.

bpowers added 13 commits July 11, 2026 18:26
First of five build-sequence steps for XMILE conveyor support
(docs/design/conveyors.md §12). This step adds the datamodel/proto/XMILE
representation and fixes the import-then-export corruption where the
<conveyor> block, leak flows, and isee:spreadflow inputs were silently
dropped. Runtime simulation lands in later steps.

datamodel: add Conveyor, Leakage, and SpreadFlow types. These ride on
Compat rather than as first-class Stock/Flow fields: non_negative -- the
other mutually-exclusive XMILE stock option -- already lives there, and
it avoids churning ~314 struct-literal construction sites.

proto: new Conveyor/Leakage/SpreadFlow messages and fresh Compat fields
6/7/8 (backward compatible -- absent fields decode to None).

xmile: read/write the <conveyor> block, both leak encodings, leak_integers,
leak zones, and isee:spreadflow + <isee:distrib_eq>. Round-trip verified
idempotent on all three vendored fixtures.

Known follow-ups: conveyor data is not yet plumbed through the JSON/SDAI
format, and ignore_earlier_zone_losses is not yet persisted to XMILE.
Second build-sequence step (docs/design/conveyors.md §12): the pure
functional-core runtime engine, a faithful Rust port of the executable
reference test/conveyors/reference_prototype.py. Not yet wired into the
VM -- that is the next step -- so this lands as a self-contained,
directly-testable module.

conveyor.rs implements the §4.3 two-phase per-DT pass (arrest, latch,
leak, exit / admit, shift, insert), linear and exponential leakage with
zones and the staggered-zone retained-profile r_k (§5), integer leakage
(§5.4), capacity and per-time-unit inflow limits (§6.3), variable transit
with cohort merging (§6.2), discrete quantized admission with per-inflow
attribution (§6.4), steady-state and explicit-list initialization (§7),
and time-unit-block lumping for discrete conveyors. It holds only belt
state and does no expression evaluation: every dynamic quantity is passed
in per step, so chains and cycles need no topological ordering.

conveyor_tests.rs reproduces scenarios S1-S15 from the spec's §15 as
oracle tests (asserting the conservation identity every step) plus
integer-leak, arrested-destination, and explicit/discrete-init property
tests. An adversarial review confirmed the engine is bit-identical to the
reference prototype on full per-step trajectories (S2/S9/S13).
Wire the standalone conveyor engine (docs/design/conveyors.md) into the
simulator so real XMILE conveyor models simulate. A conveyor is VM-native,
not bytecode (spec 9.3): conveyor_compile::expand_conveyors rewrites each
belt into hidden parameter auxes ($conv$stock$len/$cap/$inlim/$sample/
$arrest and per-leak $conv$leak$flow$frac) plus placeholder-0 driven flows,
so the parameters flow through normal layout/compilation into ordinary data
slots; resolve_plans maps the synthesized names to offsets; and a native
two-phase pass (run_pass) runs between the Flows and Stocks phases each Euler
step. Because the pass writes the driven-flow rates before stock integration,
the conveyor stock integrates to the sum of belt contents through the
ordinary Stocks phase -- no special-casing (the spec 4.3 conservation
identity guarantees dstock = admitted - out - leak). The belts are
initialized in run_initials after one extra flows evaluation, since the
synthesized parameter auxes are not in the initials runlist.

Make the production path safe and reachable. The ordinary compile path
integrated a conveyor stock as a plain INTEG, which silently mis-simulates
real Stella files (their primary outflow carries a placeholder 0, so no
empty-equation error fires). expand_conveyors now clears the conveyor/leakage
markers so the expanded model is plain, and compile_project_incremental
rejects any surviving conveyor marker with ConveyorNotExpanded -- so every
ordinary path (including wasmgen) fails loudly instead of producing a
valid-but-wrong result. libsimlin's simlin_sim_new routes conveyor models
through the conveyor build path (build_compiled) and caches the compiled sim
plus the resolved plans so reset can recreate the VM and re-attach the pass.
An equation that reads a conveyor-driven flow by name would see the pre-pass
placeholder 0, so expansion rejects it with ConveyorDrivenFlowRead rather
than mis-compute. Conveyors are Euler-only (spec 9.4), enforced at build time
and guarded in run_to.
Implement the isee:spreadflow inflow placement methods (conveyors spec 8) in
the conveyor runtime. At insert time each admitted component -- the lumped
conveyor-driven volume and every equation inflow -- is distributed across belt
slats per its placement into per-slat shares, which are then inserted once per
slat. Because a cohort's linear-leak schedule is linear in its volume, shares
that land on the same slat (same insertion depth d_c = i+1) merge exactly into
one cohort_schedule call, so mid-belt shares get their leak budget prorated to
the zone slats they will traverse (spec 8 / 5.1). The default beginning
placement reduces to the prior single-entry insert, so non-spread models are
byte-identical.

Placement threads from the flow's isee:spreadflow through InflowMeta/InflowPlan
to the phase-B pass. beginning/even/dest are supported; dist (needs the
distribution graphical function evaluated per slat) and source (needs
upstream-leak coupling) are recognized and rejected loudly with
ConveyorSpreadflowUnsupported rather than silently placed at the entry.
Complete the isee:spreadflow methods (conveyors spec 8). dist distributes an
inflow as A_i = A * w_i / sum(w) over the entry-path slats, with the weights
w_i = max(0, g(x_i)) evaluated per step (the entry depth d, and thus the slat
positions x_i = 1 - (i+0.5)/d, vary with a time-varying transit). The
<isee:distrib_eq> is stored as an opaque string; resolve_dist_profile accepts
two representable forms -- a graphical-function variable name (evaluated with
the engine's own continuous LOOKUP interpolation, reusing crate::vm::lookup so
dist matches how a LOOKUP call site would read the same profile) or a
comma-separated numeric array (indexed floor(x_i * m)) -- and rejects an empty
distribution, an inline expression, or a name without a graphical function
loudly rather than silently placing at the entry. The GF is sampled at the raw
x_i in [0,1] against the table's own x-values, which is correct for the
conventional [0,1]-scaled density profile.

source mirrors an upstream leak: for a conveyor-driven inflow that is itself an
upstream leak flow, each upstream slat's leaked volume is placed on the nearest
downstream slat by fractional position (ties toward the exit), reproduced
exactly as a Dist weight vector. This needs Phase A to expose a per-leak,
per-slat volume breakdown (PhaseAResult.leak_slat_vols); integer leakage keeps
it in sync with the requantized totals so it still sums to leak_vols. The lumped
conveyor-driven inflow input (conv_vol) becomes a per-inflow (volume, placement)
list so a source-coupled leak carries its own placement.
An arrayed conveyor stock (conveyors spec 10) is N independent conveyors, one
per array element, each with its own transit time, leak flows, capacity, and
inflow limit. Detection: the conveyor stock's equation carries array
dimensions. expand_conveyors then synthesizes the hidden parameter auxes
($conv$stock$len/$cap/$inlim/$sample/$arrest and per-leak fractions) as
apply-to-all over the stock's dimensions instead of scalar, and the
driven-flow placeholders as apply-to-all "0", so every element gets its own
len/cap/fraction/flow slots. A shared per-attribute expression is the only
arrayed form the datamodel can represent (Conveyor holds one string per
attribute); per-element values come from array references in that expression.

resolve_plans flattens each arrayed meta into one scalar ConveyorPlan per
element, so run_pass, init_belts, and ConveyorState are unchanged and a scalar
conveyor stays the 1-element degenerate case (byte-identical). Per-element
offsets are resolved by reconstructing the compiler's canonical
name[elem1,elem2] keys via the same SubscriptIterator the flattened-offset
builder uses (row-major, honoring declared element order). A held-exit
destination links element e to element e of the downstream conveyor. An
arrayed conveyor over an undefined dimension errors with
ConveyorArrayedDimensionUnresolved. Container access (conv[j], SUM/SIZE over
belt contents) and cross-shape conveyor chaining remain follow-ups.
Reading a conveyor's belt slats in an equation -- conv[j], or a single-argument
reducer/SIZE over a conveyor (conveyors spec 10 container access) -- cannot be
compiled today: expand_conveyors rewrites a conveyor into an ordinary INTEG
stock and clears the marker before compilation, so the compiler and bytecode VM
never see a conveyor and the stock slot holds only the sum of slat contents.
The physical belt length is also runtime-dynamic and unbounded (a variable
<len> can grow, and a transit shrink leaves a stale tail), so there is no
compile-time-fixed array to reduce over. Left as-is these forms silently return
the belt total (SIZE -> 1, MEAN -> total, etc.), exactly the silent-wrong class
the spec forbids.

Detect container-position use during expansion and reject it loudly with
ConveyorContainerAccessUnsupported. The boundary rejects: any subscript of a
scalar conveyor; over-subscripting an arrayed conveyor past its array dims; any
reducer/SIZE whose argument subtree references a scalar conveyor (bare or
wrapped, e.g. MEAN(belt/x)) or selects a single belt of an arrayed conveyor
(SUM(conv[a])); and a bare arrayed conveyor under any reducer except SUM. It
allows the operations that resolve correctly over per-element belt totals: a
bare read, a single-element read conv[a], SUM over an arrayed conveyor or an
array expression of it, and two-argument MIN/MAX. Full native container-access
reads are the next step.
Support container access into a conveyor's belt from equations: the reducers
SUM/MEAN/SIZE/MIN/MAX/STDDEV over a single belt (a bare scalar conveyor, or a
single-belt subscript of an arrayed one), and conv[j] / conv[elem, j] for a
compile-time-constant j (1-based from the exit; out-of-range or a stale post-
shrink tail yields NaN). This replaces the interim loud rejection for exactly
these forms.

The compiler never sees a conveyor -- it is expanded into an ordinary stock
whose slot holds only the sum of slat contents -- and the physical belt length
is runtime-dynamic and unbounded, so there is no fixed array for the bytecode
to reduce over. Instead the conveyor pass computes each container result
natively from the ConveyorState and publishes it into a synthesized hidden
stock's slot at step-start: at the top of the Euler loop before the flows eval,
and in run_initials after the belts are initialized. A stock is the one slot
kind the flows phase reads but never recomputes, and a no-inflow stock is
carried unchanged by the stocks phase, so the published start-of-step value
survives the flows eval and is visible to any equation that reads it -- an
ordinary aux would be recomputed to a placeholder and clobber it. The
reader-to-container dependency is a stock read, which is treated as
start-of-step, so the spec's visibility rule (the belt as it was before this
step's leak/exit/insert) holds for free.

Each supported container subexpression is rewritten in place (AST substitution
plus reprint) to reference its synthesized stock, arrayed over the conveyor's
dimensions for an arrayed conveyor. The same rewrite is applied to the conveyor
parameter and leak-fraction expressions, so container access there is likewise
supported (as a lagged start-of-step dependency) or loudly rejected, never
silently mis-bound to the scalar stock. Residual forms that genuinely need the
per-slat vector -- a reducer over an expression of the belt, a dynamic index,
or ranges/wildcards over slats -- keep the loud ConveyorContainerAccessUnsupported
rejection.
A conveyor is a stock with non-INTEG dynamics, but the LTM flow-to-stock
link-score formula assumes plain INTEG under Euler, so a conveyor's internal
slat dynamics are not scored correctly. Rather than emit a silently-wrong
score, LTM analysis over a model containing a conveyor now degrades loudly:
one Warning per conveyor stock, carrying ErrorCode::ConveyorLtmDegraded and
naming the conveyor, on the same diagnostic path as the auto-flip advisories.
Full LTM-through-conveyor attribution is a separate enhancement.

The warning is emitted from model_all_diagnostics, inside its existing
ltm_enabled branch, iterating that model's own conveyor stocks. That query is
drained exactly once per model by collect_all_diagnostics and -- unlike
model_ltm_variables -- is never invoked transitively across a module edge, so
the warning fires exactly once per conveyor even when the conveyor lives in a
sub-model referenced as a module (the transitively-reachable path would
otherwise double-report; the same latent duplication for the other
model_ltm_variables warnings is tracked as #866). It is a Warning carrying the
real error code (DiagnosticError::Model, not Assembly, which would surface as
NotSimulatable), so the model still reports simulatable and still runs through
the conveyor build path.
Check each conveyor-block expression against its expected units: <len> against
the model time unit t, <capacity> against the conveyor stock's units S,
<in_limit> against S/t, a linear leak fraction against dimensionless, and an
exponential leak rate against 1/t. <sample> and <arrest> are deliberately not
checked -- they are nonzero conditions (a predicate like TIME > 10 type-checks
dimensionless), so requiring t would reject valid expressions. A mismatch is a
best-effort Warning, never a hard error; the model still simulates.

The conveyor parameters live as datamodel expression strings on Compat, not as
ModelStage1 variables, so the ordinary per-variable unit check never sees them.
The check runs in check_model_units, which has datamodel access: for each
conveyor stock it synthesizes one hidden aux per parameter (the parameter
string as its equation) into a clone of the stage-0 model, lowers that clone,
and evaluates each expression through the existing UnitEvaluator. The clone is
used only for these checks -- inference and the ordinary unit check run on the
un-augmented model, so nothing about existing unit checking changes. A conveyor
stock with no declared units, or a parameter referencing a variable with
unknown units, is skipped, consistent with the rest of the unit subsystem.
Author the queue design doc that conveyors.md 11 references as the "companion
queue document." It specifies the XMILE queue stock type (FIFO batch tracking,
driven outflows, priority/overflow outflows, container access, arrayed queues)
and the queue side of the queue-conveyor coupling, mirroring the conveyor spec's
structure and its Stella-wins precedence rule.

Key design decisions documented (with Stella-probe flags where OASIS prose is
silent): a batch is a scalar volume (no age, unlike a conveyor slat); queue
outflows are engine-driven, not user equations; an unconstrained outflow (to a
cloud or regular stock) empties the queue while a conveyor-bound outflow is
throttled by the conveyor's capacity/inflow-limit; append-then-serve ordering;
overflow drains exactly what a capacity/inflow-limit/arrest block rejected;
container access reuses the conveyor mechanism verbatim; and the runtime mirrors
conveyor_compile (pre-pass expansion, QueueNotExpanded guard, Euler-only,
per-instance side table).
…phase 1)

Add the datamodel and format-surface representation for XMILE queue stocks,
mirroring how conveyors are represented one feature over. A queue is a bare
marker (no options, XMILE 4.2): Compat gains queue: Option<Queue> on a stock
and overflow: bool on a flow (the <overflow/> outflow property), with proto
fields appended (Queue message; Compat queue = 9, overflow = 10 -- nothing
renumbered, since a DB holds serialized instances). The XMILE reader recognizes
<queue/>, <overflow/>, and the <uses_queue> header; the writer re-emits them
(<uses_queue overflow="true"/> when any queue outflow is an overflow), which
fixes the import-then-export corruption of a Stella queue model. serde carries
both fields datamodel<->proto symmetrically.

This is representation and round-trip only; no runtime or simulation yet (the
<queue/> marker will be rejected loudly by the ordinary compile path until the
runtime lands, the same staging conveyors used). See docs/design/queues.md 11.
Add queue.rs: QueueState, a FIFO of batch volumes (front = oldest) that is the
pure functional core of queue simulation, mirroring conveyor.rs. It exposes
init_empty/init_from_value (a positive initial value seeds one front batch),
admit (append one back batch of max(inflow,0)*dt, skipping a non-positive
volume so the count never accrues empty batches), take_from_front (the serving
primitive: pop whole front batches that fit and split the boundary batch on a
partial take, leaving a strictly-positive remainder), serve_unconstrained (the
cloud/regular-stock drain that empties the queue), and the container-access
accessors batch_contents/batch_count/batch/total.

take_from_front is the one primitive every outflow shape composes from:
unconstrained drain is the whole queue, the future conveyor coupling is a take
of the conveyor's admission budget with the batch rules layered on top, and an
overflow is a take of the redirectable front volume. serve_unconstrained sums
then clears rather than requesting total() or INFINITY through take_from_front:
the former drifts when a tiny batch sits behind a huge one, the latter strands
batches behind a non-finite one (INFINITY - INFINITY = NaN), while sum-then-
clear empties unconditionally and returns exactly the batch sum. No VM or
datamodel coupling yet; the constrained, overflow, and coupling cases build on
take_from_front in later phases. See docs/design/queues.md 4, 7, 8.
bpowers added 23 commits July 11, 2026 18:26
Silent fixture-skip guards (if missing, eprintln and return) turned
tests into no-op passes -- test_set_value_phases no-op-passed for
months on a wrong fixture path, hiding a stale assertion. All eight
remaining guards now fail loudly naming the fixture; every referenced
fixture was verified present, so no test was actually skipping today
(the change defuses the landmine rather than resurrecting dead tests).

The integration tests' error reporting also carried a use-after-free
class: 34 sites borrowed an error's message, freed the error, then
panicked with the dangling reference. The owned-String
expect_no_error/expect_error_code helpers move to the shared
common module and every site (plus ~20 message-less free-then-panic
boilerplate blocks) migrates to them; sites that already copied the
message before freeing are untouched. A scripted scan finds zero
remaining borrow-free-use shapes. Test-only change.
Vensim has no conveyor or queue primitive, so the MDL writer exported a
conveyor/queue stock as a plain INTEG stock and a leak/spreadflow/
overflow flow as an ordinary flow with no diagnostic -- silent,
irreversible fidelity loss on a surface that already has the #856
lossiness warnings channel for exactly this class of drop.

Emit one ExportWarning per dropped marker from both emission paths
(stock and aux/flow), mirroring warn_dropped_non_negative's placement
so warnings ride the side channel in variable order and never change
the emitted text. Both leak encodings (explicit fraction and bare
marker plus eqn) warn; the CLI already prints the channel to stderr.
Any unknown options child element hard-rejected the entire XMILE file
with an unknown-variant error: the OASIS spec's OWN sample block spells
uses_conveyors (plural) and lists uses_submodels, and neither opened --
though conveyors.md 3.1 promises both spellings are accepted. Header
options are declarative capability hints; the per-stock blocks are
authoritative, so rejecting a whole file over one is wrong.

Replace the Feature Deserialize derive with a manual impl dispatching
on the element name: all ten spec option elements get explicit variants
(UsesSubmodels added), the spec's alternate spellings alias
(uses_conveyors/uses_queues/uses_array/uses_annotations), and genuinely
unknown elements are fully consumed into a tolerated Unknown variant
the writer never emits. Known-feature parse results are identical to
the old derive (pinned by a gen1==gen2 round-trip test), and four
variants' spec attributes that the old derive silently dropped for
lack of @ renames (uses_arrays maximum_dimensions among them) now
parse. The options element's namespace ATTRIBUTE gains its missing @
rename too (GH #902).
The GH #885 gate covered every production route, but the legacy
ModelStage0 construction and Project::from_salsa (the test-only
monolithic path TestProject::compile and the engine unit suites
exercise) still collapsed duplicate canonical idents last-wins --
letting a test-written model silently drop a twin. Both now seed a
model-level DuplicateVariable error from the shared #885 helpers, so
every surface reports byte-identical messages. Fixing this exposed a
latent clobber: ModelStage1::set_dependencies overwrote self.errors,
discarding any Stage0-seeded model error; it now extends instead.

Also documents the deliberate element-compat subset on
json::ElementEquation (the datamodel's Arrayed element tuple carries
only active_initial; every other Compat field is a variable-level
concept), which regenerates the JSON schema description.
The per-element explicit init list rejection (a leftover from the 7.2
wiring) misapplied the conveyor-block one-expression-per-attribute rule
to the element EQUATION: XMILE 4.5.2 explicitly lets each non-A2A
element define its own equation (with the conveyor marker shared at
block level), and a conveyor stock's equation is its initial value, so
a per-element comma list is that element's belt initialization.

Expansion now resolves Arrayed equations per element (matched by
canonical subscript, never Vec position -- pinned by a scrambled-order
2-D test), each list element's placeholder carries its own normalized
total (so chained conveyors/queues seeded from belt[elem] see the
normalized value, closing the arrayed twin of the scalar divergence
fixed earlier), an EXCEPT default list applies to unlisted elements,
and mixing list and steady-init elements is supported (belts are
independent). Loud rejection remains only for genuinely unusable
lists: non-literal entries or a non-literal shared transit.

Also resolves the header-encoding doc contract: Stella's
uses_conveyor="" attribute on the root/smile element is deliberately
not mapped -- verified ignored-but-harmless (the per-stock block is
authoritative and export re-canonicalizes), with regression tests
pinning both placements, and conveyors.md 3.1 now states exactly what
each encoding does. Per-element transit remains unrepresented (GH
#904); silent typo'd element subscripts are engine-wide pre-existing
behavior (GH #905).
The engine's established invariant stores display names verbatim (the
XMILE reader keeps the name attribute as written) and canonicalizes at
every lookup; patch.rs was the lone violator, canonicalizing the
STORED ident on all four upserts and on rename -- so a routine
pysimlin/MCP edit demoted "Students" to "students" and
"testing\nassymptomatic" to "testing_assymptomatic" in the persisted
model.

Upserts now store the caller's raw spelling (reference lists stay
canonicalized on write, matching the reader); rename stores the raw
target while rewriting equation references in canonical printed form,
so spaced names never appear unquoted in equation text. A canonically
identical rename now restamps the display spelling (previously a
silent no-op), which also means a case-only rename of a missing
variable correctly errors with DoesNotExist. Upsert dedup still
matches by canonical ident, preserving UIDs so view elements stay
wired across a respelling. The web editor's own canonicalize-before-
send lossiness remains and is tracked as GH #906.
The engine preserves display spellings (patch.rs stores names verbatim
and matches canonically), but the TS layer undid it: core's datamodel
canonicalized the wire name into ident on read and sent it back as the
upsert name, and Editor.tsx canonicalized the rename target -- so any
web-editor edit of an imported Stella model downgraded the variables
block one variable at a time, and a case-only rename restamped a
preserved spelling.

ident stays canonical (a consumer census found ~20 keying/join sites
across three packages matching engine-canonical strings -- sim results,
error caches, incoming links -- so flipping ident to raw would be a
high-risk editor change). Instead variables carry an additive optional
rawName populated from the wire name; toJson emits rawName else ident,
so full upserts round-trip the spelling. Renames go through a new
functional-core rename-ops helper sending the typed name raw (newlines
encoded, from canonical), with the paired upsertView keeping the sketch
label in sync. Pinned by core round-trip tests, real-engine e2e
upsert-replace tests, and a browser A/B in the dev app (the stale
bundle reproduced the bug; the rebuilt one preserves the spelling
through save and reload).
An Arrayed equation entry whose subscript matches no declared element
combination was silently dropped by every consumer (compiler, GF table
layout, conveyor init lists) with the element left zero-filled -- a
502-model corpus scan found real casualties: a beer-game MDL import
loses 13 entries (importer bug, GH #908) and a known-broken xmutil
conversion loses 9, all silently.

Emit a Warning-severity UnknownElementSubscript from
model_all_diagnostics when an entry fails BOTH production matchers:
the per-part canonicalization the conveyor path uses AND the
whole-string canonical key the compiler and GF-table paths use -- an
entry either matcher resolves is never flagged, so "the equation is
ignored" is true by construction (pinned by comma-element-name and
quoted-subscript counterexample tests). Warning, not Error: imported
models rely on the silent drop today. The unlisted-element zero-fill
half of GH #905 stays tracked.

Also amends conveyors.md section 10: per-element conveyor attributes
(a per-element len) are not implemented -- the conveyor block is one
shared block per stock; the reader silently drops a per-element len
beside an eqn and hard-fails an eqn-less element (GH #907) -- while
shared expressions still vary per element and per-element initial
values (including init lists) remain supported. Tracked as GH #904.
An <element> block without an <eqn> (gf-only, spec-legal per XMILE
4.5.2) failed the ENTIRE file parse with an opaque missing-field
error; the vendored non-a2a-gf.stmx fixture was unopenable.

VarElement.eqn becomes Option<String>; an absent per-element eqn
converts to the empty element equation -- the same no-functional-input
encoding a whole lookup-only variable uses, so a fully eqn-less
arrayed gf holder becomes a static table reachable via
LOOKUP(g[elem], x), and the fixture's top-level-eqn-plus-gf-elements
shape takes the existing EXCEPT-default rule. The writer emits <eqn>
only when non-empty (previously an empty element equation wrote
<eqn></eqn>; both spellings re-read identically, pinned by gen1==gen2
byte comparison). The fixture joins the XMILE and JSON round-trip
corpora and a simulate test pins current behavior, including the
documented divergence from Stella's per-element WITH-LOOKUP wrap
(scalar-only in our compiler; tracked as GH #909).
The MDL importer already promoted a piecewise-over-subranges stock's
synthesized net_flow dims to the parent dimension, but the promotion
passed the FORMATTED dimension name (Lower_Levels) to
resolve_subrange_to_parent, whose tables are canonical-keyed (lower
levels, since to_lower_space treats underscores as whitespace) -- the
lookup missed and the promotion silently no-op'd for any subrange name
that isn't a single lowercase word. The net_flow kept the first arm's
subrange dims while its entries spanned every arm: on the beer-game
model 13 GameN,Factory entries were silently dropped and those
elements integrated a zero net flow.

Canonicalize before resolving, byte-identical to the stock path's own
promotion (which is why the stock's dims were always right). The
beer-game import now produces zero UnknownElementSubscript warnings,
pinned by an integration test alongside a minimal hand-computed
piecewise fixture whose subrange name deliberately contains a space.
A variable carrying both an equation and gf tables lowers as
LOOKUP(self, input) -- but the wrap lived only in the scalar branch, so
an arrayed variable with per-element graphical functions evaluated the
raw input equation with every gf silently ignored (Stella computes
gf_elem(input) per element).

Unify the wrap into apply_implicit_with_lookup, post-processing the
expansion output: each element's AssignCurr input is wrapped as a
lookup against the variable's own table at that element's row-major
index (t=0 shared for a variable-level gf), reusing the existing
Lookup lowering -- extract_table_info resolves per-element Var refs by
offset-range containment, so no codegen change was needed (the issue's
BadTable diagnosis was mistaken; the fix is far smaller than
anticipated). The scalar path is byte-identical through the unified
helper (verified down to a bit-identical wasm blob), wasm parity holds
with no wasmgen change, and the pinned non-a2a-gf divergence test now
asserts the Stella behavior. Deliberate corner rules pinned by tests:
a zero-point table is treated as absent (raw input, not NaN), a
gf-less element keeps its raw equation, and a gf-only element with no
default evaluates gf of the fabricated zero input (the silent-fill
diagnostic remains tracked in GH #905). LTM's blindness to the
implicit wrap is pre-existing and tracked as GH #910.
A `v = WITH LOOKUP(input, table)` variable is lowered by the compiler to
`LOOKUP(v, input)` for every equation shape, but LTM computed both link
polarities and link-score partial equations against the variable's raw
input equation. The gf was invisible to attribution.

The polarity half composes the input's polarity with the gf's monotonicity
(`compose_with_lookup_polarity`), mirroring `apply_implicit_with_lookup`'s
rules exactly: an empty-placeholder or zero-point table keeps the raw input,
and a shared table applies to every element.

The score half is the subtler one. A link score's guard form subtracts
`PREVIOUS(target)` from the partial, so a partial that re-evaluates the
target's equation is in gf-INPUT units while the anchor is in gf-OUTPUT
units. Left unwrapped alongside a now-correct polarity, such a score can
carry the opposite sign from the link it scores and a magnitude far outside
the [-1, 1] normalization -- strictly worse than being uniformly wrong.
Every partial therefore falls into one of two classes: a full re-evaluation
must be wrapped in the gf application, and a delta-ratio stand-in (the RANK
arm, the nested-arithmetic arm) is already in output units and must never be
wrapped, or a gf output would be fed back through the gf. The coverage table
on `is_implicit_with_lookup` enumerates every emitter against that rule.

The Linear (SUM/MEAN) reducer partial was incremental -- `PREVIOUS(target)`
plus a body delta -- which mixes an output-units anchor with an input-units
delta and cannot be wrapped as written. On the gf path it is rebuilt as an
enumerated full re-evaluation (scored row live, other rows frozen), the
shape the Nonlinear arm already used. That form is confined to the gf path
so gf-less emitted equation text stays byte-identical.

An arrayed target's table reference is pinned to `to[1,...]` rather than
left bare: a bare arrayed reference resolves each iterated element's own
table offset, which the VM reads as NaN past `table_count`.

Residuals are documented rather than papered over: an `Ast::Arrayed`
target's EXCEPT-default slot renders one shared text and so cannot name a
per-element table, and module composite scores are delta transfer formulas
with no target-equation partial to wrap.
The MDL writer emitted raw XMILE text whenever an equation would not parse,
so `INT(0)` leaked into the .mdl and re-imported as `LOOKUP(INT, 0)`. Chasing
that back found the printer and the parser disagreeing in several ways, and
the disagreement was not confined to export: `builtins_visitor` serializes a
module-backed builtin argument through `print_eqn` and re-parses it, so a
printer that emits text the parser reads differently silently changes what a
model computes.

  x = SMTH1((IF (1 > 0) THEN 10 ELSE 20) / 2, 1)

simulated to 10. The answer is 5. `Div(If(..), 2)` printed as
`if (1 > 0) then (10) else (20) / 2`, and the `if` swallowed the division on
the way back in. No error, no warning, wrong number. The same corruption ran
through LTM: a link-score partial is built by re-parsing printed text, so 448
of C-LEARN's link scores were computed from a mis-grouped equation.

The fixes are one cluster because each is wrong without the others.

Stacked unary prefixes now parse. `parse_unary` recursed into
`parse_exponentiation`, so `- -3` was a hard error -- while Vensim accepts it
and the MDL importer's `xmile_compat` renders a nested negative unparenthesized.
The importer manufactured stored equations this engine's own parser rejected.
All three prefix arms recurse, matching `mdl::parser`, which always has.

Exponentiation is right-associative. XMILE 3.3.1 says right to left,
`mdl::parser::parse_power` already agreed, and the checked-in Vensim reference
`test/test-models/tests/arithmetics/output.tab` records `cons4^cons3^cons2` as
262144 while spelling `(cons4^cons3)^cons2` separately as 4096. The engine
computed 4096. That fixture, and `arithmetics_exp`, were in no run set; they
are now, which is the regression guard this whole class lacked. Unary binds
looser than `^` as before: `-2^2` is still -4.

Flipping the associativity flips which operand needs grouping when printed, so
all four printers move together. Equal precedence now parenthesizes the left
child of `^` and the right child of every left-associative operator -- `+` and
`*` included, since floating-point addition is not associative and printing
`a + (b + c)` as `a + b + c` silently reassociated it. `print_eqn` also emitted
`!a` and `a != b`, which the lexer has no rule for, so `<>` or `not` inside any
SMTH/DELAY/TREND argument failed to compile. Transpose and a postfix-applied
call (`abs(a)'`) were unparenthesized too.

`&&` and `||` shared one precedence level, where XMILE 3.3.1 and Vensim put AND
above OR. `mdl::parser` had it right, so importing `x = 1 :OR: 0 :AND: 0` built
the correct tree, printed it flat, and re-read it wrong.

`xmile_compat` deliberately still emits binary operators without precedence
parentheses. `mdl::parser`'s table is inverted relative to Vensim -- `+`/`-`
loosest, `:AND:` above the comparisons -- so it builds a wrong AST that the flat
text launders back to the right one through the XMILE grammar on re-parse.
Parenthesizing faithfully preserves the wrong tree and costs 49,239 C-LEARN
tolerance violations. Only the `^` base is guarded, because that grouping cannot
be recovered from flat text. Tracked as #914.

The wasm backend's open-coded pow returned NaN for a negative base, which the
new arithmetics fixtures reach via `(-Time)^2`. It now decides odd/even off the
sign bit with the infinite and zero cases split out ahead of the integrality
test, and its special values match `powf` bit for bit.

`equation_to_mdl` records an ExportWarning when it must fall back to raw text,
so a degraded export is never silent again. The `is_data_equation` placeholders
are opaque by design and stay quiet.

C-LEARN's LTM variable count moves 6709 -> 6891. Of that, +182 is attribution it
was silently missing: 50 edges whose partials would not parse were skipped, and
a per-element edge warns once while dropping all 21 of its element scores. The
remaining 448 changed equations are the mis-grouped partials above, corrected.
Nothing in test/ pinned them. The count pin is the weak guard; the mechanism
assert that every C-LEARN partial parses is the real one.

No checked-in expected-data file changed.
The branch wired five new engine modules into lib.rs without touching the
module map that claims to say where functionality lives, so an agent grepping
`src/simlin-engine/CLAUDE.md` for "conveyor" was told the feature did not exist.
Adds a section covering the runtime/compile split for both special stock types,
the marker-scan dispatch, and the two build entry points -- `build_sim` as the
unified one every caller should use, `build_compiled` as the raw special-path
build that libsimlin calls directly because it also threads LTM loop-partition
snapshots.

The libsimlin description of `simlin_sim_new` was worse than absent: it asserted
that both LTM and non-LTM go through `compile_project_incremental`, which stopped
being true once the special-stock path landed. A conveyor or queue model builds
on a private db, skips incremental compilation, and does not participate in LTM.
Someone trusting that line would have looked for an LTM bug that cannot exist.

Also records the sibling test modules and `ltm_augment_with_lookup.rs` added
while burning down the branch review, and indexes the queue spec from
docs/README.md, which docs/CLAUDE.md requires.
The watcher integration tests slept 50ms after `spawn_watcher` and then wrote,
on the assumption that the OS-level watch was live by then. It often is not.
`Watcher::watch` returning only means the stream was handed to the OS; on macOS
`fseventsd` completes registration asynchronously, and the stream's "since now"
event id is resolved at registration rather than at `watch()`. Every change made
in that window is lost permanently -- not delayed, never delivered. The window
has no upper bound: it grows with load and with the number of streams the
process has already registered.

That last property is why the suite degraded rather than merely flaked. Each
test passed in isolation; 7 of 157 failed when run as a suite; and a serial run,
where every test has more prior streams alive than in a parallel one, failed
MORE often than parallel. A race between tests would behave the opposite way.

A longer sleep does not fix it, which is the interesting part. Measurements on a
host with a saturated `fseventsd` (recorded in `PROBE_FILE_PREFIX`'s rustdoc,
reproduced against a raw `notify::RecommendedWatcher` so the debouncer is not
implicated) show a second effect: a stream that is provably live still drops the
next event it should report after an idle gap. Sleeping two seconds after
readiness missed 6 of 6 triggers; probing until observed and then triggering
immediately missed 0 of 6. Readiness is not a one-shot property, so callers must
fire their trigger with nothing in between.

No OS offers a "the stream is live" callback, and `notify` exposes neither the
underlying `FSEventStreamRef` nor `FSEventStreamFlushSync`, the one Apple
primitive that would answer this directly. The only sound check is to cause a
filesystem event and wait for it to come back. `spawn_watcher` now returns a
`WatcherHandle` carrying a `probe_sightings()` watch channel; a caller creates
`{PROBE_FILE_PREFIX}{nonce}` and waits for the channel to reach its nonce.

The nonce is what makes a probe more than a liveness check. Sightings are
reported inside the per-event loop, in event order, so observing nonce N implies
every event published before it has already been dispatched. That turns the probe
into an ordering barrier, which is what the tests whose triggers cannot be
repeated -- a git commit, a rename -- need in order to establish readiness before
triggering, and what the test asserting the ABSENCE of an event needs in order to
not pass vacuously.

The probe scan reports and then falls through to classification; it never
consumes the event. A `RenameMode::Both` event carries two paths, so short-
circuiting on "any path is a probe" would silently drop the creation of a model
renamed from a probe-shaped name. Falling through costs nothing, because a probe
carries no model extension and `classify` independently maps it to `Ignored`.

Production changes are confined to that handle: `main.rs` awaits
`into_join_handle()`. The server itself never waits for readiness, so it retains
the same startup window -- a file created between `spawn_watcher` and stream
registration is invisible until something else touches it. That is pre-existing
and is left alone here.

`handle_batch_keeps_the_highest_probe_nonce` is named for what it asserts. The
barrier's ordering invariant is deliberately called out as uncovered: the
function runs to completion before a test can observe the interleaving, so
someone hoisting the probe scan out of the classification loop would break it
with this suite still green.
A conveyor/queue model rebuilt its entire expanded project from a cold salsa
database on every editor keystroke. `queue_compile::build_compiled` created a
throwaway `SimlinDb` and synced the expanded datamodel with no prior handles, so
every fragment recompiled from scratch; `build_sim` received the caller's db and
`SourceProject` and discarded both. `apply_patch` calls `build_sim` on every
edit, including its dry run, so the cost was paid twice per keystroke. This was
an API-shape accident rather than a salsa incompatibility.

`SimlinDb` now carries a second input slot, `expanded_state`, holding the
expanded project's `PersistentSyncState`. `sync_expanded` re-syncs each build's
freshly expanded datamodel onto the PRIOR expanded handles, so an unrelated
single-variable edit invalidates one fragment instead of the whole project. The
expansion cannot itself be a salsa tracked function -- it creates variables,
hence salsa inputs -- so it stays on the `&mut db` build path, where it is a
linear datamodel walk, trivially cheap next to compilation.

Expansion deliberately runs at build time rather than inside `sync()`.
`datamodel::Project` has no main-model field, so `sync()` cannot know which
model to expand, and expanding the wrong one is a correctness bug: a sub-model
conveyor must survive un-expanded to trip `ConveyorInSubmodelUnsupported`. This
also removes the need for staged-patch rollback bookkeeping. `build_compiled`
re-syncs the caller's current datamodel immediately before reading the handle,
and the slot is otherwise unreachable (`expanded_source_project` is test-only),
so a rolled-back staged patch cannot leave stale expanded inputs behind --
structurally, not by convention. Rollback would buy no incrementality anyway:
salsa's `Setter::to` bumps `changed_at` unconditionally and backdates.

`compile_sim` is the new unified dispatch that every VM-backed production caller
funnels through, returning a `SimBuild` carrying the compiled simulation, both
plan sets, and a `special` flag. `simlin_sim_new` reads that flag to decide
whether to snapshot LTM loop-partition metadata; the special path has none,
since the expanded `SourceProject` always has `ltm_enabled == false`.
Conveyor/queue plus LTM remains a documented degradation.

Fold in a real bug this exposed. `<overflow/>` is a marker on a FLOW, but both
dispatch predicates scan for a marked STOCK, so a model with a stray overflow
and no queue took the ordinary path and `validate_overflow_markers` never ran:
the documented `QueueOverflowNotOnQueue` error was unreachable for such a model
and the flow simulated as an ordinary one. Validating inside the dispatch would
have been insufficient -- `wasmgen::compile_datamodel_to_artifact` is a
production path that calls `compile_project_incremental` directly and never
passes through `compile_sim`, so the VM would have rejected what wasm accepted.
The check therefore lives in `compile_project_incremental`, whose
`assemble_simulation` has exactly one production caller: nothing compiles
without passing it.

`expand_queues` keeps its own pre-expansion copy of the check, because expansion
CLEARS the overflow marker on every driven outflow. The "not a queue outflow"
violation survives expansion and is caught late; the "never a queue's FIRST
outflow" violation does not -- expansion erases exactly the evidence -- and must
be caught early. Both callers share one algorithm,
`validate_overflow_markers_over` over a `MarkerVar` projection, so the datamodel
and salsa-input views cannot drift. A stray `<overflow/>` in a sub-model is now
rejected too, rather than silently ignored on every path.

Precedence, stated precisely: placing the check after the duplicate-variable
gate keeps `DuplicateVariable` outranking `QueueOverflowNotOnQueue`, which a new
test pins. The one genuine change is that a model carrying both a stray overflow
and an assembly failure now reports `QueueOverflowNotOnQueue` where it
previously reported `NotSimulatable`. That is the fix, not a regression: the
overflow error was the unreachable one.

The expanded slot is never cleared. Salsa 0.26 has no input reclamation, so
dropping the handle map frees nothing -- the inputs, field values, and memos
live in the arena forever -- while forcing the next expanded sync down the
`prev == None` path, which mints a second input set. An earlier revision of this
change did clear it, and measurably caused the reallocation its comment claimed
to prevent: six conveyor/ordinary toggles on one db produced six distinct
`SourceProject` ids, `Id(801)` through `Id(806)`, reachable from `apply_patch`'s
per-keystroke dry run. Keeping the handles bounds a db at exactly one expanded
input set: the same six toggles now yield `Id(801)` six times. An ordinary model
never allocates the slot at all.

`simlin_sim_new` now holds the datamodel and db locks simultaneously where it
previously took them sequentially. This closes a TOCTOU -- a concurrent
`apply_patch` could commit between the marker scan and the compile, so the build
proceeded on a stale marker verdict -- at the cost of blocking datamodel readers
for the duration of a compile. Lock ordering is datamodel then db everywhere, so
no site can invert it and deadlock.

The models scanned by the `NotExpanded`/`InSubmodelUnsupported` guard, and their
variables, are now walked in sorted canonical order. Both were `HashMap`s, so a
project with marked stocks in two sub-models named a nondeterministic offender
in a user-facing message. Pre-existing; fixed while adjacent.

`check-docs.py` now skips backticked XML tags. Its CLAUDE.md path check fires on
any backticked token containing a slash, so documenting `<overflow/>` -- a
self-closing XMILE tag, not a path -- was impossible. Rephrasing to dodge the
checker would have degraded the prose.

Twelve new tests in `queue_compile_db_tests.rs` (+607). The incrementality
evidence follows the established `db/fragment_cache_tests.rs` pattern:
`unrelated_edit_reuses_expanded_inputs_and_fragments` asserts `as_id()`
stability of the expanded `SourceProject`/`SourceModel`/`SourceVariable` across
an unrelated edit, a pointer-equal `compile_var_fragment` memo for the untouched
variable, a changed fragment for the edited one, and a correct simulation.
`conveyor_ordinary_toggles_reuse_one_expanded_input_set` pins the id stability
above. Diagnostics still come from the unexpanded `SourceProject`, so synthetic
`$conv$`/`$queue$` idents never reach an error message
(`diagnostics_come_from_the_unexpanded_project`). No `ErrorCode` or message text
changed, and no checked-in expected-output file under `test/` moved.
`simulate --ltm` collected diagnostics and then enabled LTM. But
`model_all_diagnostics` emits the `ConveyorLtmDegraded`/`QueueLtmDegraded`
warnings only inside its `project.ltm_enabled(db)` gate (`db/diagnostic.rs:194`),
so the warnings were computed against a project on which LTM was still off and
never appeared. A conveyor or queue model therefore ran, printed results with no
loop scores, and said nothing about why -- the one diagnostic written to explain
that exact situation was structurally unreachable from this entry point.

Enabling LTM first is also the more defensible reading of the flag: when the user
asks for `--ltm`, the LTM-enabled project is the one whose diagnostics they want.
This surfaces the LTM-synthetic-variable assembly failures too, which were
previously invisible here for the same reason.

Verified against `test/conveyors/covid19_severity.stmx`: eight
`conveyor_ltm_degraded` warnings now print where none did before.
The wasm backend rejected every conveyor and queue model up front, so the
bytecode VM was the only backend that could simulate them. This lowers the queue
half: `wasmgen::compile_datamodel_to_artifact` now routes through
`queue_compile::compile_sim`, the same unified dispatch the VM takes, so it
compiles the identical expanded project and resolves the identical `QueuePlan`s
rather than reproducing the expansion. Conveyors remain `Unsupported` and are
rejected before the dispatch; the belt pass is a later change.

The pass is emitted as unrolled, plan-specialized wasm. A `QueuePlan` is flat
compile-time data -- slot offsets, small vectors, bools -- so every inflow,
outflow, and container access is open-coded at emit time. The only runtime loops
walk the dynamic batch count (sum, take-from-front, min/max, stddev, and the two
ring copies). Nothing interprets a plan structure in linear memory.

Batch rings live in a bump region past the static layout, addressed by a new
mutable global `G_HEAP`. A ring doubles on overflow: a larger ring is bump-
allocated, the live batches are copied into it in ring order, and the old region
is abandoned. Doubling bounds total waste under 2x the final size, and `reset`
rewinds `G_HEAP` to `heap_base` wholesale, so repeated resets cannot leak. A
failed `memory.grow` traps rather than continuing: the blob has no error channel
yet, and a trap is a loud, contained failure where continuing would write past
linear memory and trap anyway, further from the cause.

Both VM hook points are preserved, and they are distinct: container-access values
publish at step start, before the Flows phase, while admit-then-serve runs between
Flows and Stocks. Conveyors and queues are Euler-only (a compile-time gate), so
`emit_euler_step` is the only site the step pass hangs off.

Mid-run `get_value` is a side-effect-free preview, mirroring `vm.rs:1187-1216`.
The VM clones its side tables; the blob saves each descriptor, repoints
`base_ptr` at a bump-allocated verbatim copy of the ring, runs the pass, restores
the descriptors, and rewinds `G_HEAP`. Without this a host reading `curr` mid-run
would double-advance the FIFO. The rewind also reclaims anything a grow inside
the preview allocated, so repeated previews cannot leak either.

`test/queues/minimal_queue.xmile` and `test/queues/queue_drain.xmile` were
previously simulated by NEITHER backend: `compile_vm` calls
`compile_project_incremental` directly, whose `QueueNotExpanded` guard fires on a
live marker, so the corpus excluded them. They now run through
`simulate_special_path`, which builds the VM side via the unified dispatch and
gates the wasm side on parity. No reference series is checked in beside these
fixtures, so the VM is the oracle; what the harness adds is that the protobuf
round-trip, the XMILE round-trip, and the wasm lowering all reproduce it.

Both gates were verified by mutation rather than assumed. Re-adding the queue
rejection turns exactly those two fixtures red on the parity gate; perturbing the
wasm admit path by 0.125 turns them red on the slab comparison. The rustdoc above
`wasm_parity_hook` and section 10.4 of docs/design/queues.md both asserted the
wasm backend rejects queues, which is no longer true; both are corrected here.
Nothing under test/ changed.
A bare 'cargo test -p simlin-engine --test integration' ran 294 tests
instead of 652, silently omitting the model corpus and the VM-vs-wasm
parity hook. The modules were gated on file_io because the fixture
comparisons call load_dat/load_csv and the GET DIRECT tests use
FilesystemDataProvider, all of which the feature gates as production
API (keeping the csv crate out of the wasm bundle).

Fix via a self dev-dependency (default-features = false, features =
["file_io"]) so every test, bench, and example target gets the
feature unconditionally while cargo build, cargo check --lib, and the
wasm32 no-default-features build keep it off. default-features = false
is load-bearing: without it the edge silently re-enables the default
set for dev targets and makes --no-default-features a no-op there.
This relies on resolver = "2"; both properties are documented in
Cargo.toml along with the crate::-not-simlin_engine:: extern-prelude
hazard the self-dep introduces.

Scope notes: CI and pre-commit already ran the full corpus because
simlin-cli's dependency unified file_io into workspace-wide test runs;
the blindness was confined to -p simlin-engine invocations, exactly
the local-iteration workflow. The change also un-gates 41 lib unit
tests (compat:: load_dat/load_csv and db differential tests) that were
behind cfg(all(test, feature = "file_io")). Investigating the fix
surfaced that the unit tests have never compiled without debug-derive,
so feature-gating hygiene must be checked --lib-scoped; tech-debt item
60 is updated accordingly.
The blob had no way to report a per-step failure to the host: no error
global, no getter, no early-return path in run_to/run_initials. The
conveyor belt pass (GH #922) needs one -- init_belts and the <sample>
re-latch growth path raise ConveyorTransitTooLong (and init also
raises ConveyorTransitNotPositive) at runtime.

Two mutable i32 globals (G_ERR_CODE, G_ERR_BELT) and one new export,
get_error() -> i64, packing (belt << 32) | code with both halves
zero-extended. The code is the engine ErrorCode's declaration-order
discriminant, not libsimlin's wire numbering, which collapses conveyor
codes into Generic and cannot carry the belt identity.

Raising is a capability: errors::open_pass_block mints an ErrorScope
as it emits the enclosing block, hooks thread Option<ErrorScope> into
the pass bodies, and expect_scope panics at emit time if a raising
pass is emitted at a site with no unwind block -- without this the br
would validate, resolve to run_to's step loop, and spin forever. The
raise is a br, not a return, so one pass body serves both the real
step (abandons the run) and the mid-run preview (restores curr, clears
the channel, still runs its descriptor-restore epilogue).

Semantics match the VM at each hook: the failing step saves no row and
does not advance the clock; run_initials returns before publish,
reconciliation, and did_initials; the preview swallows. One deliberate
divergence: the channel is sticky until reset, so a host that forgets
to poll fails closed instead of computing over a half-built side
table. The VM's own resume-after-error double-advances belts (GH #938),
so there is nothing worth bug-compatibility with.

Message text is byte-identical to the VM's: the transit error
constructors moved out of conveyor_compile into shared functions, and
errors::reconstruct_error rebuilds the exact string from the plan.
Passes::needs_flows_before_init lets the driver emit the Flows call
that populates the synthesized belt-parameter auxes before the init
hook, mirroring vm.rs; without it the init-site transit reads 0.

Hosts: the integration harness polls after every run and segment; the
TS direct backend declares get_error and throws after both run_to
sites (always 0 today, but the guard predates GH #924 removing the
conveyor compile-time reject, so a raising run can never come back as
a silently truncated series). libsimlin compiles blobs but never runs
them, documented as such. The queue allocator's OOM stays a trap:
matching the VM's abort, and br cannot cross the call boundary out of
the FIFO helpers.
Step 1 of GH #922 (the queue half landed in d043434): continuous
belts with no leaks, no <sample>/<arrest>, no discrete mode, no
queue coupling, and no container access -- each of those fails loudly
in belt::reject_unsupported until the later steps remove the rejects.
The public entry still rejects every conveyor model up front; tests
reach the lowering through a cfg(test) seam that routes through the
same queue_compile::compile_sim dispatch the VM uses, so both
backends compile the same expanded project.

Plans are fully-resolved compile-time data, so the pass is emitted
unrolled and plan-specialized; the only runtime loops are over the
dynamic slat count. Each belt owns a static descriptor plus a
growable ring on the shared bump allocator, addressed modulo cap
(not a power-of-two mask -- only the queue ring is mask-addressable),
with the slat stride 1 + 2*n_leaks f64s derived from the plan so
steps 2 and 3 need no memory re-layout. Belt grow/shrink is included
in this step even though the issue lists it under step 3: <sample>
defaults to 1, so every belt re-latches <len> each DT, and nothing in
ConveyorPlan distinguishes a constant <len> expression from a
time-varying one -- a fixed-size ring would silently mis-simulate.

Parity with the VM is exact, no epsilon: accumulation orders are
matched term for term, and the two genuine wasm-vs-Rust divergences
(f64.max NaN propagation, the -0.0/+0.0 max ambiguity) are handled
with selects on strict comparisons and documented. slat_count is
floor(t / dt + 0.5), half-away-from-zero -- not f64.nearest, which is
round-half-to-even and diverges at every half.

Every load-bearing edit was verified by mutation: ten mutants across
rounding, admission, capacity room, init-list spread, ring grow copy
order, shrink, NaN poisoning, preview restore, and phase ordering
each go red under exactly one named test. Four originally-green tests
turned out to be vacuous (steady-state or symmetric fixtures made the
code path unobservable) and were strengthened; the slab comparator
had an active false positive on infinite values ((INF-INF).abs() is
NaN) and gained a v == w short-circuit. Deleting b_shrink wholesale
is a genuinely equivalent mutant -- the no-shrink state is
correct_state plus trailing zeros, invisible to every observable --
and the rustdoc records why so nobody re-litigates it; what the
function buys is bounded ring growth.

Real fixtures pinned now (corpus membership arrives with GH #924):
minimal_conveyor.xmile and arrayed_conveyor.xmile match the VM slab
exactly.
…rity

The remainder of GH #922 (steps 2 and 3), GH #923, GH #924, and
GH #919, landed together; each piece was implemented by a fresh agent,
adversarially reviewed by another, and iterated to zero material
findings before the next began, with a final holistic review across
the seams. Completes the conveyor half of the wasm backend: leaks and
zones, the hard flags, queue coupling, container access, the
public-entry gate, and the diagnostic-severity fix the work surfaced.

Leaks and zones: linear and exponential leaks, zone_start and zone_end
path-based schedules, leak_integers carry, ignore_earlier_zone_losses,
and both leaky init fills at exact VM parity -- every fold in the VM's
own accumulation order, bit-identical rather than within-epsilon. Zone
membership is positional and per-step, so plan-independent helpers
read per-plan static scratch while emission stays unrolled and
plan-specialized.

Hard flags and coupling: sample needs no new state (the latched
transit is only ever consumed as a slat count, already in the
descriptor; the mid-run bound check sits inside the sample gate's if,
since a select would evaluate both arms and trap). Arrest freezes the
latch, leak, and exit without freezing the time-unit clock; a held
exit merges the front two slats. Discrete belts carry quant_carry per
inflow, in_carry in the descriptor, and a pass-global time unit
computed on the ideal grid rather than the drifted clock.
Queue-conveyor coupling is lowered on both sides from the VM's own
CouplingTable; the queue lowering's Coupled rejection is gone.

Container access: conv[j], SUM, MEAN, MIN, MAX, SIZE, and STDDEV
publish at step start before the Flows phase, conveyor branch ahead of
the queue branch per the VM ordering. conv[j] is 1-based from the
exit; STDDEV is the population deviation; every reducer ranges over
the physical slat count, never the entry depth. Fixed en route: the
landed queue lowering narrowed queue[k] with a wrapping cast, so
queue[2^32+1] returned the front batch where the VM returns NaN.

The gate: the up-front conveyor rejection is deleted, so a conveyor
model routes through the same dispatch as a queue model on the public
entries, including libsimlin and the TS direct backend, whose
get_error guard is now live code with a mutation-verified wiring test.
Six fixtures run under the parity corpus -- the two existing conveyor
models plus four new ones covering leaks, containers, discrete
admission, and coupling -- with a directory-accounting test, and the
two blocked fixtures pinned on their exact ErrorCode so fixing GH #941
or #944 forces a promotion decision. Both failure directions are
mutation-verified. GH #884 is thereby resolved.

Severity (GH #919): FormattedError carries the diagnostic's severity
and the formatters render the word from it, so conveyor_ltm_degraded
and other advisories print as warnings instead of errors; the CLI's
has_model_errors/has_variable_errors count Error severity only, so a
warning can no longer swallow the reason for a real build failure.

belt::reject_unsupported retains two conditions: a non-default
isee:spreadflow placement (even, dest, dist, source -- GH #946) and
the slat-bound-fits-i32 soundness guard. Mutation-verified throughout;
survivors are documented equivalents. VM behaviors were mirrored, not
fixed unilaterally, and tracked: #942, #943, #944, #946, #947, #948,
#949, #950, #951, #952, #953, #954.
The Jest-to-Rstest migration (2d5c09a, PR #900) converted every test
file that existed on main to import describe/it/expect from
@rstest/core, but rename-ops.test.ts was added on this branch after
the migration's snapshot, so the rebase left it as the one file still
using jest-style globals -- it failed to load under rstest in CI and
tripped eslint's no-undef locally. Also drops the stale
jest-environment docblock; the tests are pure functions of view data
and run in the default node environment like their siblings.
@claude

claude Bot commented Jul 12, 2026

Copy link
Copy Markdown

Review

Reviewed the non-test source changes in the printer/parser rewrite, apply_patch display-name preservation, the wasm error channel, load_csv empty-cell handling, and the libsimlin/pysimlin/CLI/serve integration. The core work (AST printer parenthesization for If/^/transpose, parser precedence fix for and/or/^, display-name preservation on upsert and rename, unified build_sim dispatch, JSON conveyor/queue mirror) all look correct and well-tested. Three actionable findings that don't overlap the previously-reported ones.

[P3] `load_csv` empty-cell carry-forward applies to the Time column too

File: `src/simlin-engine/src/compat.rs` Lines: 235-252

The new "empty cell means unchanged, carry the previous row's value" rule fires for every column index, including `i = 0` (Time). Vensim never elides Time in its `.tab`/`.csv` exports, so this is a defensive corner rather than a Vensim-triggered path, but a hand-authored or mid-file-corrupted `.tab` with an empty Time cell now silently produces two rows with the same timestamp — reference-data comparisons that read this via `ensure_results` / `ensure_vdf_results` would compare against a non-monotonic time series without any diagnostic. The empty-first-row error path already handles `i = 0` correctly; the same guard on subsequent rows (or scoping the carry-forward to `i != 0`) matches the "constants get elided" intent stated in the code comment.

[P3] pysimlin `_structure_merged_compat` now round-trips `nonNegative` on Aux/Module

File: `src/pysimlin/simlin/json_converter.py` Lines: 679-699 (also called from `structure_auxiliary`/`structure_module`)

The prior per-type builders explicitly omitted `non_negative` from the compat merge for `Auxiliary` and `Module`; the unified helper OR-merges it for every variable type. Rust's `datamodel::Compat` accepts the field on any variable kind, so this is more permissive than a bug, but any legacy JSON that happens to carry `nonNegative: true` on an Aux/Module (buggy source, or a stale export) now round-trips as `compat.nonNegative = true` where it previously silently dropped. If the intent was strict Stock/Flow scoping (the same reasoning the Rust `From` uses to zero conveyor/queue fields exhaustively), the merge should keep the per-type gate.

[P3] CLI `--ltm` leaves `ltm_enabled` set on the salsa input after a successful run

File: `src/simlin-cli/src/main.rs` Lines: 534-544

`simulate()` calls `set_project_ltm_enabled(&mut db, source_project, true)` before the diagnostic pass, then only restores it in the LTM-fallback branch after a failed run (line 553). On the happy path `run_simulation` returns `Ok` and the function returns with `ltm_enabled` still `true` on the salsa input. Harmless in the CLI itself (the process exits after `simulate` returns), but the `LtmEnabledGuard` RAII scope guard exists everywhere else in the workspace precisely to make this restore-on-drop unconditional; using it here would prevent a future refactor that reuses the db from silently inheriting an enabled-LTM state.

Overall correctness

The patch is correct. The main runtime cores (conveyor belt Phase A/B, queue batch rules, coupling admission budget, wasm error channel packing), the printer/parser agreement rewrite (with proptest coverage over the full operator set), the display-name preservation on upsert/rename, and the JSON/protobuf/patch round-trips through `datamodel::Compat` all held up under scrutiny. The three findings above are localized quality-of-life concerns that do not block the happy path.

Reviewed by Claude Opus 4.7.

Three fixes for the CI failures the branch inherited from main.

The real one: main's Code Coverage job tripped the writer proptest
equation_write_reparse_is_fixpoint on -((-0) ^ SUM(arr[*])). The chain
on main: mdl_paren_if_necessary dropped the parens around a negated ^
base, the MDL parser re-read the sign flipped, and the third render
hit the pre-#912 stacked-unary parse failure whose raw-text fallback
leaked the XMILE-only [*] wildcard spelling into MDL. Both halves are
already fixed on this branch (the prefixed-base grouping rule and
parse_unary recursion, from the printer/parser cluster), so main's
CI is seed-flaky on this test until this PR merges. The counterexample
seed is deliberately NOT committed: cc lines are RNG seeds replayed
through the strategy, and this branch changed the strategy (deleted
the is_ok prop_filter that was masking the bug), so the seed would be
a permanently-green line pinning nothing.

What this adds instead: a deterministic conjunction-guard regression
test reproducing the full three-render chain (fails on origin/main,
passes here), and -- the review's real catch -- per-rule pins for
mdl_paren_if_necessary's ^ grouping, which had ZERO coverage: reverting
either the right-associative left-child rule or the prefixed-base rule
left the entire crate green including the proptest at 8192 cases,
because both corruptions are text fixpoints from the second render on.
Without the new test, (4^3)^2 = 4096 exported as a model computing
262144 and (-a)^b as the sign-flipped -a^b, silently.

Also: crossbeam-epoch 0.9.18 -> 0.9.20 (RUSTSEC-2026-0204), and
src/diagram/CLAUDE.md no longer references the gitignored lib/ build
output with a backticked slash-token, which check-docs.py resolves
against the filesystem and therefore failed only on clean checkouts
(the checker gap itself is GH #725).
@bpowers
bpowers merged commit 553dbeb into main Jul 12, 2026
15 checks passed
@bpowers
bpowers deleted the conveyor-engine branch July 12, 2026 05:12
bpowers added a commit that referenced this pull request Jul 13, 2026
A test binary's parallel wall clock is max(longest single test,
total/threads), and after #869 turned the model corpus on for bare
cargo test (the GH #925 self dev-dependency), the suite's cost was
dominated by a handful of serial mega-tests rather than test volume.
Split the VDF parity harness into one test per corpus root (the
python3 extraction is ~5.7s serial for the combined corpus; the three
roots now extract concurrently) and verify fixtures with rayon; feed
both MDL writer ratchets from one memoized, rayon-parallel corpus
pass (their walks were identical up through the second parse); split
the VDF truncation/mutation sweep per fixture and scale truncation
points with file size; and hoist the JSON Schema validator out of two
proptest closures that recompiled it once per generated case.

Also optimize three dependencies in dev/test builds
(profile.dev.package: serde_json, wasm-interpreter, checked).
Workspace crates stay at opt-level 0 so incremental rebuilds are
unaffected, but the DLR-FT interpreter executes every wasmgen parity
test and debug-build interpretation dominated those tests. Net:
cargo test wall 21.4s -> 12.7s at 32 threads, 28.5s -> 20.1s for the
two big engine binaries at CI-like 4 threads, with no coverage
change. Documents the per-test timing technique in docs/dev/rust.md;
the LTM circuit-enumeration string churn found while profiling is
tracked as #955.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment