Skip to content

engine: one owner per compiler decision, LTM as a first-class consumer - #1040

Merged
bpowers merged 19 commits into
mainfrom
compiler-unification-v2
Sep 4, 2026
Merged

bpowers merged 19 commits into
mainfrom
compiler-unification-v2

Conversation

@bpowers

@bpowers bpowers commented Sep 3, 2026 •

Copy link
Copy Markdown
Owner

Why

The engine compiler stated the same facts in several places and did the same work in several near-copies: four fragment compilers over stub Variables, per-builtin facts in exhaustive matches, array temps materialized at three IR levels, several dimension matchers, dependencies classified three ways on strings, whole-model lowered stages, and a parse that was not a function of the equation because PREVIOUS/INIT/SMOOTH helpers were synthesized as text under the model's module set. This branch gives each of those decisions one owner and makes Loops That Matter a consumer of every unification rather than a special case left behind. The plan, every pinned behaviour change and the per-commit measurements are in docs/design-plans/2026-08-25-compiler-unification.md; src/simlin-engine/CLAUDE.md is the map of the result.

Fixes #372
Fixes #554
Fixes #866
Fixes #1028
Fixes #1029
Fixes #1033
Fixes #1035

What landed

Nineteen commits over 5c406dd5 (Phase 7.2 on main): seventeen engine commits, each reviewed adversarially before it was committed through the hook, and two documentation commits that rewrite the engine map and the plan's ledger:

Net engine change, counted as the branch rules count it (non-test = src/** minus *test*.rs, testutils and test_common, so a #[cfg(test)] module inside a production file counts as non-test): src/simlin-engine non-test Rust falls on every chunk except the two 7.5 chunks (+253 each: rustdoc and the element-scope machinery), the NodeBounds box (+17) and Phase 9 (+115 under that split; -3 with its rewritten in-file test modules excluded); the per-chunk numbers are in each chunk's report.

Non-obvious decisions

  • Restart from 5c406dd5 rather than fix forward on compiler-unification: three adversarial reviews of that branch found a silent-wrong-number defect, a loud refusal regression and a dead production path; its commits were mined for fixtures and pinned divergences, not copied.
  • The compile path does not resolve m·x dimensions at the Expr2 tier. A module output is never a LoweringScope key and lowers without bounds; compiler::Context resolves it through the instance's shape. Byte-identical artifacts were the tie-breaker.
  • INIT-only capture slots are hidden from the results map. Nothing writes them per step, so the VM's zeroed step chunks and wasm's retained memory would expose different scratch values under one key; hiding them keeps the VM as wasmgen's oracle on every exposed slot.
  • engine: a stock (or stdlib instance) initialized from a stockless sub-model's output reads 0 at t=0 (initials runlist is closed per model) #1028 is closed by a flat-model rule, not a per-instance fixed point: every value-bearing variable of a model that is instantiated as a module is an initials member, because XMILE's model is one flat graph and a parent's initials may read any port.
  • A helper reads what the plain spelling reads. A hoisted argument, a capture and a per-element helper lower under the parent's element context and dependency shapes; where the base's helpers disagreed with the plain equation (whole-array sums under an apply-to-all body, ordinal reads under an element map) the plain spelling's answer won, and each such change is an enumerated divergence (Phase 7.5 items 7-13, Phase 8.1's 48-row value table and 5-row refusal table).
  • Rename is syntactic, over the equation text as written: the parse memo's tree is the expanded one and the lowered tree is absent for an equation the compiler refuses, which must still be renamed.

Evidence, matched to the claim

  • Numbers are unchanged where no divergence is named. C-LEARN's bytecode_profile blocks, plain and under CLEARN_LTM=1, are byte-identical across every commit that claims identity (ledger, artifact column); the four commits that move the artifact (6b, 7.4, 7.5ab, 7.5cd) name every count that moved. Every commit ran both CLIs over all 509 models under test/, plain and --ltm: no model refused on one side only, every mover either a named divergence or a GH mdl: one file imports differently from run to run #859 importer flipper (resampled per binary to tell the two apart). The test/ diagnostics corpus (rows per (model, variable, code)) is identical across the diagnostics-touching commits except the rows each names.
  • Every behaviour change is pinned. 61 numbered semantic-divergence entries across this branch's commits (one per numbered item in the design doc's per-phase lists, 8.1's one mechanism counted once; the 7.3 diagnostic-only change and the engine: a stock (or stdlib instance) initialized from a stockless sub-model's output reads 0 at t=0 (initials runlist is closed per model) #1028 fix are recorded beside them unnumbered, and the ledger's divergences column counts the same way), each with a test that fails on the base's answer; the LTM entries (V9a-1..4, V9b-1..7) are pinned against the VM's executed read, and several correct base numbers that were silently wrong (a DELAY3 link score reading an unwritten lag, a nested sub-model stock read closing an invisible ordering cycle, a whole-array reducer scored against a per-element read).
  • Incrementality. AC3.1 is measured by execution counts over every tracked query (db::exec_probe::ProbedDb): a module-instantiating add recompiles the added variable, the template's first instance and the input source whose initials membership changed, and nothing else.
  • Compile cost. Cold C-LEARN compile falls from 8.696 G retired instructions at 5c406dd5 to 6.9521 G at the head (-20%); the LTM compile channel is recorded per row against its own base (6b -4.42%, 7.5cd -6.56%, 8.2+8.3 -3.12%, 8.3b -1.07%, 8.5 -1.63%, V9b -1.16%, with 9 +1.22% and V9a +0.96% attributed and accepted), and the run channel moved on 7.5ab (-3.16%) and 7.5cd (-1.82%). Compile-only residency on C-LEARN is +6.0 MiB over the pre-memo base (last measured at 8.5: 28.97 MiB against 22.94) for a caller that never runs the unit pass the memos serve (pysimlin Model.simulate() alone, an FFI embedder without get_errors); every path that collects diagnostics retains less than before. Accepted as a cost.
  • Gates. Every commit is green through the pre-commit hook: engine lib and integration suites, the 12-repeat determinism modules, libsimlin, CLI and mcp-core suites, clippy -D warnings, cargo fmt --check, the wasm and pysimlin builds, and simlin.h under cbindgen. The #[ignore]d C-LEARN release gates (clearn_with_ltm_simulates_model_vars_identically, clearn_ltm_var_count_guardrail, clearn_ltm_slot_maxima_digest) were re-run and re-pinned on the chunks that moved the LTM surface.

What the evidence does not establish

  • There is no reference interpreter for compiler::Expr; correctness rests on the genuine-output corpus, the divergence pins and VM/wasm parity, not on an independent evaluator (out of scope by decision, its own PR later).
  • What Stella computes for a bare arrayed name as a reducer argument inside an apply-to-all body (x[region] = SUM(pop)) is unverified; the engine's answer rests on the helper == plain-spelling invariant and XMILE 3.7.1's apply-to-all rule, which does not address that position. Likewise the reading of a repeated active dimension (o[D,D] = square[D,D]; Vensim DSS rejects the declaration itself, "DimA appears more than once on LHS", measured 2026-08-04 on vensim-probes/repeated_dimension.mdl and recorded under Phase 6b item 3) and the cross-product operand of RANK/VECTOR SORT ORDER are Simlin's definitions, pinned so a future ground truth moves a test rather than a number.
  • arrays_cname, arrays_varname and subscript_transposition alternate between two outputs on both binaries (GH mdl: one file imports differently from run to run #859, the MDL importer's hash-seed nondeterminism); the sweeps establish nothing about them beyond that the set of outputs is unchanged. --ltm warning ORDER is process-random on both binaries (GH ltm: some --ltm output prints in a different order each run #1036); the sweeps compare stderr as sorted lines.
  • Loop-form lowering of apply-to-all equations (GH engine: compile apply-to-all equations to loops, not one op per element #1025) is sequenced after this branch; the per-element unrolling's runtime cost is recorded in the ledger, not reduced.

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Sep 3, 2026 •

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-09-03T16:38:21.412176Z 5bcc401 PR opened
ℹ️ 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" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

An array value codegen cannot express in place -- an array-producing builtin,
a per-element arrayed-GF apply, a computed array operand -- was moved into a
temp by two passes that could not see each other: `Expr3`'s Pass 1, on an
unresolved tree, and `compiler::array_operand`, on the lowered one. Whichever
pass saw a shape first decided it, so two spellings of one operand compiled
differently (`RANK(a[*] + b[*], 1)` unioned its axes while
`RANK(a[X] + b[Y], 1)` was refused), a `VECTOR SELECT` operand read the whole
array only when the equation also held an array-producing builtin, and the
apply-to-all hoisters lowered every element a second time just to decide
whether the builtin varied with the element.

`compiler/array_operand.rs` is now the only pass that materializes and the
only caller of `TempAllocator::alloc`. It runs once over the fully lowered,
constant-folded fragment, reads its positions off `BuiltinFn::signature()`,
and decides once-per-equation against once-per-element by structural identity
of the lowered body: a body two elements share takes one id hoisted ahead of
the element code, a body one element reads takes an id the elements reissue.
That spends strictly fewer temps than the rule it replaces (C-LEARN's LTM
artifact goes from 441 temp slots to 28; the plain artifact loses 12 opcodes
and 2 views, one element-invariant GF apply evaluated once instead of three
times) and takes GH #583's `u8` namespace out of reach of every write in the
corpus. `Expr3` keeps no temp variant, `Context::lower` returns one
expression, `DimensionRefs` and the `mark`/`discard_since` allocator scoping
are gone, and `Var::new`'s apply-to-all and arrayed arms are one per-element
walk. The LTM lowering scope is empty: the scoped re-lower fed only `Expr2`
bounds that nothing downstream reads (every dependency's shape comes from
`FragmentInput.deps`), C-LEARN's LTM artifact is byte-identical without it,
and the LTM compile channel falls 4.4% of retired instructions.

Deleting the fork settles nine questions that had two answers, each pinned
and recorded under "Phase 6b semantic divergences". Every subscript naming a
dimension resolves through the one mapped read, so `subrange_merge` matches
its checked-in Vensim output; each occurrence of a repeated active dimension
reads its own axis; `VECTOR SELECT`'s operands are reduced, the classification
the Vensim corpus requires; a temp axis the target does not name is read
through the declared correspondence and refused without one, where the old
projection read cell 0. Sharing one temp across elements changes what a
resolved recurrence SCC may reorder, so `segment_member_by_element` -- the one
statement of where a member's code splits, read by the element graph and the
combiner alike -- splits off the member's PROLOGUE (the leading temp blocks
two or more elements read) together with the elements that read it: the
prologue is emitted once, immediately before its first reader in
`element_order`, and its reads are edges into exactly those readers. An
EXCEPT default hoisted once beside an override it reads therefore evaluates
the override first on every step (it read zero-initialised temp storage on
the first step before), and a recurrence whose shared temp reads a non-reader
element, or whose first element materializes a private temp beside a shared
one, still compiles.

Cold C-LEARN compile is unchanged inside the instruction channel's floor
(+0.15%): every subscript naming a dimension goes through the subscript
lowering and `resolve_mapped_read` where Pass 1 folded an active one to an
ordinal in one step, and an exact-name fast path in `active_dim_ref` keeps
that route as cheap as the fold was. The run channel is unchanged inside its
floor. The differential sweep over `test/` moves `subrange_merge` onto its
Vensim ground truth and collapses `arrays_cname` and `arrays_varname` from two
importer-order-dependent outputs to one; nothing the base compiles is refused,
and the one new refusal (a temp axis with no correspondence to the target)
replaces a silent wrong number.
A stdlib or macro module-function call no longer synthesizes its instance
and its computed arguments as datamodel::Variable text that every compile
stage lexes and parses again. The parse leaves a capture::ImplicitModule
(target model plus input-port wiring) and one capture::HoistedArg per
argument that is not a bare identifier (the argument's Expr0 subtree, spans
intact) on the same ordered ImplicitVar list a capture rides, and
ImplicitVar::parsed_variable is the one exhaustive conversion at every
consumer, so no helper is printed and parsed back on the compile path. A
helper's equation errors carry spans into the parent's equation and are
reported on the parent; identical diagnostic rows collapse to one.
capture::insert_implicit_var owns "two helpers claim one name" inside a
walk, across per-element walks and across the dt/initial passes; the map's
silent last-wins let a macro named ARG1 invoked as ARG1(k, k * 2) wire its
own instance into its second port and simulate 3 for 9, now a
DuplicateVariable. A call with more arguments than ports is refused before
any is hoisted, where the base indexed the port list out of bounds.

MacroRegistry::resolve_call is the one routing decision for a parsed call
-- Expand, Passthrough, RenamedBuiltinSelfCall, Unresolved -- read by the
expansion visitor and by macro-recursion analysis, so the false init ->
init edge and the infinite re-resolution of GH #554 are absent for one
reason; a passthrough at an external call site keeps the macro's declared
arity. A hoisted argument's foreign dimension name resolves through
DimensionsContext::resolve_mapped_read, the rule the compiler applies to the
same spelling. Artifacts are byte-identical on C-LEARN plain and LTM; the
hoisted-argument column of mapped_reference_semantics_tests pins where a
hoisted argument and the plain equation still differ (GH #1035) rather than
adding a resolution rule.
A source variable's parse is keyed on the variable and the project alone.
It reads the variable's own fields, the dimensions its equation names and
the project-global contexts (units, the macro registry, macro_body_owner),
and nothing of the owning model: the interned ModuleIdentContext -- the
model's module-instance, module-call-aux and bound-port names, widened per
instance and per stdlib template -- is gone from the parse key, together
with the collect_module_idents/equation_is_module_call pre-scan that
re-parsed every equation of the model to build it, the stdlib-extended
and per-instance context constructors, LTM's parallel module-ident set,
and the empty-context twin parse the analysis, LTM, layout, libsimlin and
CLI paths ran beside the compile path's. One memo per variable serves
every consumer, so the causal graph sees the dependency sets the compiler
schedules, and adding a module instance parses and compiles the added
variable (plus a template's first instance and the input source whose
initials membership changed) and nothing else -- AC3.1, pinned over every
tracked query by db::exec_probe.

What a PREVIOUS/INIT argument's name denotes is therefore lowering's
question, answered by Context::snapshot_storage from the dependency's
shape: a bare module instance has no storage of its own and is refused
(the base captured it into a helper that read flattened slot zero of the
instance); a bound input port reads its own slot, which its fragment
assigns the parent's value every phase, so the lag and the freeze are
what a capture held; a scalar module-call aux and a qualified module
output port are the fixed slots codegen's static_slot already addressed.
The parse keeps the one module-backed decision it can make without the
model, a module instance synthesized earlier in the same walk. Reading a
bound port's own slot also corrects a silent wrong number: the two-step lag
in a DELAY3 instance's input -> stock link score is an LTM capture helper
whose body is the bound port, which the base could not lower and whose
absence the by-presence LTM tail hid, so that score read an unwritten 0 for
the lag (4, 10, 24 on a unit ramp where the formula gives 1, 2, 4). Dropping
a capture also renumbers the later helpers of the same walk; helper names
are external keys, so that is a pinned artifact-naming change.

Every value-bearing variable of a model that is instantiated as a module
-- an explicit module's target, a stdlib template, a macro -- is a member
of that model's initials runlist. XMILE's model is one flat graph in
which a module is a namespace, so a parent's initials may read any port
of an instance and the value has to exist when the read happens; the
rule is one flat bit per model rather than a per-instance propagation of
the ports each parent reads, the existing initials closure orders the
members, and the cost is one initial evaluation per sub-model aux. A
stock initialized from a stockless sub-model's output, and a stdlib
instance fed from one, now start at the output's t0 value (GH #1028).
SymbolicOpcode and Opcode are each declared by a table macro holding one
row per opcode -- the variant exactly as before plus one column: the
concrete twin it resolves to on the symbolic side, the arithmetic-stack
effect on the concrete side. An operand's type is its kind (SymVarRef,
LiteralId, ModuleId, ViewId, DimListId, TempId, GraphicalFunctionId with
its TableCount, PcOffset, anything else data), and resolve_opcode,
renumber_opcode, gf_run, var_ref and jump_offset on the symbolic side
and stack_effect, name and jump_offset on the concrete side are
generated from the rows by per-kind rules, so adding an opcode is one
row plus its vm.rs and wasmgen arms rather than five matches that had
to agree by hand. The table is a callback, so the every-row tests and
the merge proptest's blanking oracle derive from the same rows with
their own per-kind expectations; a GraphicalFunctionId operand declared
without a TableCount beside it is a compile error, the shape whose
silent omission would have collapsed a GF run into an unreferenced gap.

Opcode keeps its variants, fields, order and 8-byte size, the bytecode
is byte-identical on C-LEARN plain and under LTM, every checked add and
the temp-base narrowing keep their error text, and the dead-code lint
still denies a row nothing constructs. The accessors bind only the
operand their kind reads (bind_kind! in pattern position); the two
functions that bind every operand, resolve_opcode and stack_effect, are
the only ones that allow unused_variables and say why. The execution
arms, the fusion patterns and the db/ read/write scans stay
hand-written: they name variants by what they mean, not by what their
operands are.
`Results::print_tsv` printed one column per SLOT of the results buffer,
naming a slot the offsets map has no key for `UNKNOWN`. Unnamed slots are
legitimate: a standalone lookup table keeps its layout slot and produces no
series (GH #606), and a helper the map hides holds only a backend's scratch
value after initials, so such a column showed one backend's scratch beside
the real series. The TSV is now the offsets map's keys in slot order and
nothing else, which is the contract every other reader of a series shares.

GH #1033 stays open: it is the same `UNKNOWN` surfacing, but its root cause
is an arrayed capture helper keyed once, so its later slots are unnamed
values a reader would want -- the remedy there is more keys, and this change
only stops printing the slots the map cannot name.
A PREVIOUS/INIT argument whose subscripts pin one declared element (a bare
`vals[e1]`, a qualified `vals[Dim.e1]`) reads that slot directly in a user
equation, as it already did in a generated LTM equation. The decision stays
in the parse because a capture cannot be un-minted at lowering, and the
parse asks the owning model exactly two per-name facts through
`SnapshotIndexFacts::Axes`: the referenced variable's declared axis, through
`model_variable_by_name` and `variable_dimensions` reached via the variable's
owning model, and whether the project declares a qualified element, through
the per-name `project_has_qualified_element` projection. The owner is the
`owner_model` name the sync sets on every `SourceVariable` and
`variable_owner_model` resolves; a name rather than a handle because a
model's variable map is a constructor argument of the model, so the
variables exist before it does and a salsa input field can only be set
afterwards through `&mut`, which the fresh sync path does not hold. The same
projection says which macro a body variable belongs to, so the project-wide
map of macro bodies goes. Precedence is XMILE 1.0 footnote 9 -- an element
of the referenced axis wins over a same-named variable -- which is also the
compiler's own `resolve_axis_index_name`. The generated LTM parse keeps its
whole-surface rule because its targets may be synthetic variables with no
declared axis to ask; the one observable consequence is a consumer that
reads its operand's extent, `VECTOR ELM MAP` over a bare element snapshot,
which now ranges over the variable exactly as the numeric spelling does.

A capture's kind is its phase demand: PREVIOUS storage is refreshed in flows
and never seeded into initials, INIT storage is populated in initials and
enters flows only when a per-step definition's current-value closure reads
it, and the same storage minted by the dt and active-initial parses for
different consumers is one capture with the union of the two. LTM helpers
compile exactly those phases. An INIT-only capture keeps its layout slot but
has no results key and is no LTM causal node: nothing writes it per step, so
the VM's zeroed step chunks and wasm's retained memory disagree on the slot,
and a link score into it would publish that disagreement under an exposed
name (the VM computed `2 dk / (0 - v0)` where wasm computed 0). An INIT read
is a snapshot, not a per-step link, so `model_causal_edges` takes no edge
into or out of such a capture; the two backends agree on every key of the
results map, LTM on or off, and the VM stays wasmgen's oracle. On C-LEARN
this removes 26 capture slots and 207 per-step capture evaluations (-2177
flow opcodes plain, -1.6% compile instructions), and under LTM 921 scalar
scores whose edges no longer exist (207 capture->parent, identically 0, and
714 source->capture, 21 of which the base held at 1 because it re-evaluated
the capture per step) plus the 14 array-freeze helpers of those scores: the
all-slot digest moves from 20,892 to 20,221 LTM slots and from 3,141 to
3,106 ever non-zero slots, the 21 scores and the 14 freeze slots.
A helper synthesized for an apply-to-all body used to be rewritten before
the hoist, because a scalar helper had no axis for lowering to resolve a
dimension name against: an active dimension name became its element by
ordinal and a foreign one was replayed through a parse-time copy of the
compiler's mapping rule. Two resolvers of one spelling drifted exactly where
the rule is non-trivial (GH #1035): under a permuted, many-to-one or
shared-name element map a hoisted argument read a different element than
the plain equation, a bare arrayed argument was refused, and a helper body
the compiler could not shape was refused with a different code on a
different variable. The helper now carries the element it is one element
of (variable::ElementScope on VarKind::Aux) and the compiler lowers it under
that element, the same Context the parent's own element gets, so the hoisted
and the plain spelling read the same slot and refuse with the same code at
the argument's span. A snapshot-only apply-to-all body needs no per-element
walk at all: per_element_requirements classifies the body once, and such a
body is captured structurally, as one apply-to-all capture over the parent's
dimensions, keyed per element in the results map (GH #1033); a snapshot
subscript naming a dimension the parent's axes relate to reads its slot
directly, decided by the compiler's own axis matcher. DELAYN/SMTHN wire only
the ports the call names, since the stdlib model's isModuleInput(initial_value)
guard already falls back to the input as XMILE 1.0 section 3.5.3 states.

For LTM, db::ltm::endpoint_dimensions is the projection of model_dep_shape
onto plain variables, read by the causal edges, the element graph, the score
emitters, the loop builders and the pins; one shape answer is not one
emitter, so the scalar-source emitters admit only explicit scalar sources
and an element-bound helper's edge is scored by the implicit emitter alone.
The describers see a scoped helper with its pinned reads spelled as the
static index the compiler resolves them to, so the element graph and the
scores name the slot the helper's fragment reads. An edge read from a strict subset of an
Ast::Arrayed target's slots is target-restricted and keeps its cycles on the
element-level path, so a loop that exists at one slot is not reported over
the whole dimension. C-LEARN's plain artifact is byte-identical on every
results key with 126 fewer initial programs, and the compile channel is
7.7% cheaper.
Every fragment constructor already built a DepShape map -- the dimensions
and kind of every name the variable can reference -- for the compiler, and
then built a second, whole-model-shaped scope for the Expr0 -> Expr2
lowering: a ModelStage0 literal holding its bare dependencies' cloned parse
memos, read only by ArrayContext::get_dimensions. ast::LoweringScope is that
shape map plus the dimension context and the model's name, so the Expr2
tier and the compiler read one answer for a dependency's dimensions and a
parse-synthesized helper lowers under the shapes its parent's equation
lowers under. A module output (m.x) is never a key and lowers without
bounds: compiler::Context resolves it through the instance's shape, a
cross-module read keeps one resolver, and C-LEARN's artifacts are
byte-identical plain and under LTM while the compile channel drops 4.3%
(the cloned mini-stage was the cost). The whole-model ModelStage1 lowers
each model under its own variables' shapes and so reads no other model's
stage; a module target's edit re-executes its instantiators' unit checks
and not their lowered stages.

lower_variable's module arm is db::build_module_inputs, the wiring every
production constructor built by hand around it; ScopeStage0 and its
resolve_module_input/resolve_relative validation twin -- whose verdict no
production path read, the user-facing BadModuleInputSrc being
model_module_wiring_diagnostics' -- go, with the model_scope_models ident
edge that existed for it, the reconstruct module bypasses, and the 8.0 dead
surface (Variable::scalar_equation, previous_referenced_idents, the
ModelStage1 export). One mechanism-level divergence follows and is pinned
by its enumeration: a helper lowers under its parent's shapes, so it reads
and is refused exactly as the plain spelling of its body is. The base
lowered helpers bounds-free, so the compiler's bare-reference rewrite never
ran on them: a reducer over a bare arrayed name in an apply-to-all body read
the whole array where the plain spelling reads the element (every reducer,
helper kind and target rank, a 48-row table), and a helper whose body the
plain spelling refuses ran (pairing an unrelated axis by ordinal, or summing
a scaled whole array) where it is now refused as the plain spelling is, on
the parent at the argument's span for an Expr2 refusal and on the helper for
a codegen one.
Every variable's Expr2 form has one owner: the per-variable salsa memos
lowered_source_variable and lowered_implicit_variable, each lowered once
under the dimensions of the names its equation references. The fragment
compiler borrows the memo (FragmentInput::target is a Cow), and the unit
pass and the LTM describers hold its Arc through model_lowered_variables,
a map of handles that is the one builder both consume. The whole-model
stages (ModelStage0/ModelStage1, db/stages.rs), their database-free test
oracle, and the LTM describers' third lowering (reconstruct_model_variables
and its implicit-variable and module-instance twins) go with it: there is
no whole-model lowered copy and no second implementation of the lowering
for tests to compare against. Each memo carries the resolved heads of the
names it looked up, so the fragment constructor projects the compiler's
shapes and tables from them rather than resolving the names a second time.

The memo lowers under dimensions only, never a module instance's sub-model
layout: the Expr2 tier reads nothing of an instance, and the layout is a
recursive query that a module cycle -- which the unit pass reaches -- turns
into a salsa panic. For the same reason the map's one non-memo entry, an
element-scoped helper's element-pinned projection (which resolves a module
head through that layout), is taken only where the project's module graph
reaches no cycle from the model; under a cycle the map holds the memo's
handle, which the unit pass reads identically. The unit inference scope is
an iterative name-only worklist over the explicit module variables and the
parse-synthesized instances, and a module's wiring resolves under the
model's canonical name, so a root model spelled Main wires as main does. A
dependency's tables reach a fragment through the tracked variable_tables,
so an equation-only edit recompiles the edited variable alone.

The rename patch reads neither compiler tier: it parses each equation
string as written, renames, and reprints only what changed. The parse
memo's tree is the expanded one (a SMTH1 call is already an instance read,
so printing it back destroyed the call), and the lowered tree is absent for
an equation the compiler refuses, which left the old name in place and
turned the refusal into an unknown dependency.

C-LEARN artifacts are byte-identical plain and under LTM; the LTM compile
channel is -3.1% of retired instructions; a compile-only caller (pysimlin's
Model.simulate() alone, an embedder that never asks for errors) retains the
lowered trees it used to drop (+9.2 MiB on C-LEARN), while every path that
collects diagnostics retains less than before (-3.0 MiB plain, -15.3 MiB
LTM). The standing mitigation, boxing Expr2's inline Option<ArrayBounds>
(72 of a node's 128 bytes), is its own change.
model_detected_loops is an analysis entry point, so it carries the
module-cycle gate itself, the rule analyze_model already applies: a model
the project's module graph reaches a cycle from has no detected loops (the
empty result), because the cycle is the model error the diagnostics pass
reports for it, and enumerating its loops recurses into an instance's
sub-model layout, which under a module cycle is salsa's dependency-graph
panic. The gate lives in the engine rather than in each caller because the
entry point is what every caller reaches; the CLI's --ltm loop listing,
which listed loops before it collected diagnostics, printed nothing on
such a project and aborted the process with the panic where it now prints
the circular_dependency error and exits non-zero.
open_model unwrapped the model file read, so a missing or unreadable path
was a panic with a backtrace rather than a refusal. The file is read once
(read_model_file), refused with the path and the OS's reason, and each
format parses the bytes it holds; a text format that is not UTF-8 is
refused the same way.
A lowered node's bounds slot is ast::NodeBounds, an Option<Box<ArrayBounds>>
stated once and carried by Expr2 and its structural rewrite Expr3 alike. The
trees that carry it are retained -- the per-variable lowering memos and the
LTM handle maps -- and a bound is None on every scalar subexpression, so the
inline enum (72 of a node's 128 bytes) was paid by every node for the few
that carry one; boxed, a node is 64 bytes and a None one pointer. Readers go
through get_array_bounds, a copy of a node clones the slot as it stands, and
the box is spelled only where a bound is produced (Expr2::from and the
compiler's bare-reference rewrite), so no consumer knows the representation.
Expr3 takes the same slot because from_expr2 copies it verbatim: an inline
slot there would spell an unbox at each of its six arms and add a free per
arrayed node for a tree that lives only inside one fragment's lowering.

C-LEARN artifacts are byte-identical plain and under LTM, the test/ sweeps
and diagnostics corpus are identical, and the compile channel is -1.0% of
retired instructions plain and -1.1% under LTM (a node moves half the
bytes), for one box per bound produced (+0.1% allocations plain). The
database retains 2.7 MiB less on every census row (plain compile-only 32.2
-> 29.5 MiB, LTM 226.0 -> 223.1 MiB), which is the trees at half a node; the
Variable beside each tree, the resolved heads and the handle map are the
larger share of what a compile-only caller retains over the pre-memo base
and are the next slimming.
A variable's reads were classified into six string sets that every consumer
re-split on the interpunct: the dependency graph normalized and filtered them,
the causal-edge builder and both LTM output-port scans collapsed module reads
by string surgery, the pinned-loop and statelessness gates compared spellings,
and the query lowered every variable to Expr2 a second time under an empty
scope just to walk it. classify_dependencies now runs once per variable on the
typed Expr1 (ast::typed_ast, the first half of lower_ast) through a DepExpr
projection LTM's per-slot readers share for Expr2, and records each read with
its lag. The salsa query attaches the phase and resolves each name into a
DepRef whose DepTarget proves every hop against metadata through the per-name
projections (an explicit Module, an implicit instance, then project_model_by_name
and model_variable_by_name per segment), reading the terminal's kind in the
same walk; an unproven spelling is one local name. VariableDeps and
ImplicitVarDeps carry one DepRefs with one set of projections, and every
consumer reads them: no interpunct is split downstream, the causal edges record
the sub-model outputs each node reads once and both LTM modes select a loop's
exit port from that record, run invariance is the compiler-local verdict joined
with the Dt/Current reads, and Expr2 issues no temp id.

Seven pinned divergences. A qualified read of a sub-model stock is a prior-step
read at any depth, where the base resolved one hop and, with the instance's
input fed from the nested reader, emitted the instance before its input (the
#591-c1 stale-input class at depth two: m.feed read 0 every step after the
first). The previous-only relation is Previous minus Current (an INIT read is
a snapshot and does not cancel a lag, so a stockless PREVIOUS(y, INIT(y)) cycle
with its init phase broken is instrumented rather than bypassed). A sub-model
output whose only reader is a bare-argument stdlib instance is an output port,
so that sub-model gains its LTM series. A literal-folded IF keeps both arms'
reads (under-hoist only); an unproven qualified spelling is UnknownDependency
at its reference site; a module input wired from a lookup-only table is
refused at the instance under the parent-scope spelling as under the bare one;
and the libsimlin incoming-links surface lists a module instance's input
sources under either spelling (a module-output read still lists nothing, while
the layout keeps drawing that link to the module box). C-LEARN artifacts are
byte-identical plain and under LTM; the compile channel is -1.8% plain and
-1.6% under LTM.
A diagnostic was three things between its raising site and
`collect_all_diagnostics`: a `Variable`'s two error lists, a `Diagnostic`
wrapped in the `CompilationDiagnostic` accumulator, and a second
classification in `errors.rs` that re-derived a unit kind from a `Model`
error's code (`UnitErrorKind`) because the unit-inference umbrella was
filed as a model error. Every seam was a place to attach context twice, to
drop a field, or to disagree about what a row was; and the LTM derivations,
being recursive, accumulated their warnings inside memos that a parent's
accumulator DFS reached as well as the child's, so a sub-model's warning
was reported once per parent (GH #866) and a cycle recorded inside the
module-input-keyed dependency graph was dormant under every other key.

`diagnostic::Diagnostic` is now the payload and the accumulator, with the
typed `DiagnosticError` its raising site produced and `code`, `category`,
`location`, `reason` and `is` as the projections every consumer reads.
Context is a type: `Variable::diagnostics` holds context-free errors, and a
`Diagnostic` is built only where the model and variable are known, so a
double attach cannot compile and nothing is asserted at run time. A
recursive or multiply-keyed query never accumulates -- `model_ltm_variables`
returns its warnings and declined edges through one `LtmWarnings` sink,
`model_ltm_fragment_diagnostics` returns its rows, an unscoreable link
score carries its warning as the variant's payload, the dependency graph
records its cycle variables -- and the non-recursive `model_all_diagnostics`
emits each model's facts once, the cycle facts and the LTM facts as tracked
children read after the variables' fragments (salsa's accumulator walk yields
a memo's own rows before its inputs'), so a cycle member's own failure stays
the first row libsimlin reports. The umbrella is a
`Unit(InferenceError)` filed under no variable, so `FormattedError` carries
the category instead of a second unit-kind spelling; a helper's row carries
its `owner`, the variable a consumer presents it under. Two carried items
ride along: codegen's array-operand refusal names the expression kind
instead of a Rust discriminant, and the arm reported for an arrayed
equation with several failing arms is the first in declared element order
rather than whichever a `HashMap` yielded.
A generated LTM equation is parsed exactly once, at its emitter, and
nothing before that point prints engine text to parse it back: a helper
carries no `Variable::eqn` (the generators read a target's axes and body
off its lowered `ast()`, keeping the `eqn` arm for user-authored source
text), a target whose Expr2 lowering failed is declined loudly
(`MissingTypedTarget`) instead of scored around its user text or a `0`
body -- the edge into it stands because dependencies are classified on
the typed tier, and the project does not compile -- an aggregate node's
own equation and its feeder link scores are built from the classified
reducer (`AggNode::reducer_expr0`, `LtmArm::from_typed`), and the
per-element emitters pin element subscripts on the wrapped tree and read
their completeness guard off the one arm they emit. `AggNode::reducer_key`
survives as the reducer's printed identity (the dedup, the IR's routing,
the wrap's matching), never as text to parse; `shaped_link_score` is the
per-shape query's name, since it returns a typed value.

The LTM constructors lower under shapes like every other constructor:
`lower_ltm_variable` types a generated equation once, classifies its reads
on that tree, resolves them to the shapes the compiler reads, and lowers
the same tree under that map (`lower_variable_from_typed`). That is a
named divergence: a frozen-whole reducer over a bare arrayed argument in
an apply-to-all body now lowers per element, as execution lowers the
target, where the bounds-free lowering summed the whole array into the
score (design doc, "Phase LTM semantic divergences", V9a-1). A generated
equation mints captures only, so `LtmImplicitVarMeta` says so and LTM adds
no module instance; `enumerate_module_instances` walks a model's explicit
and parse-synthesized instances as one candidate shape and records each
under (target model, bound-port set), where a reference's port is one
reading (`port_of`) and the bound-port set and the lowered wiring are
projections of one rule over it (`bound_port`), so an instance is
compiled under exactly the ports its inputs write: a reference to one of
an instance's own ports from inside the instance binds nothing and is
warned (a cross-instance connect recorded on the source instance, the
corpus's only instance-qualified sources, stays the dst check's report),
where two owners of the rule left the VM looking up a child under an
identity it was never compiled for (V9a-2). C-LEARN's plain and LTM
artifacts are identical and both corpus sweeps move only GH #859
flippers; the compile channel is -0.4% plain and +1.0% under LTM (the
Expr2 tier's array bounds on 7k generated equations, against the parses
the text boundary no longer pays).
The LTM describers held three derivations of what a dimension-named read
means -- a positional correspondence for the iterated spelling, a
name-keyed pairing of declared dimension lists for a bare one, and a
class of loud declines for reducers over a bare arrayed argument -- and
each disagreed with the compiler somewhere: a permuting element map was
described as the ordinal diagonal, an undeclared pair sharing element
names or a subrange over a superset dimension as a cross-product, and a
bare reducer argument as unscoreable on the premise (GH #789) that
execution scales it by the dimension's size, which the VM refutes. Every
dimension-named subscript is now described by the one rule the compiler
resolves it with, DimensionsContext::executed_read_correspondence (the
element's name first, then the declared map), and every bare read by one
pairing of the declared lists (db::bare_axis_pairing, the compiler's own
matcher) under the relations the spelling's own lowering consults: pass
0's for a read in an equation body, the full context's for a stock's
flows. The IR is Bare exactly when the lists reproduce the subscript's
pairing, PerElement otherwise, and a reducer's bare argument that pairs
with no axis is Wildcard, the whole array.

A bare reducer argument reads what pass 0 spells for it and is stored
spelled on the aggregate node; that spelled reducer is the synthetic
node's identity, so two owners of one text under different iterations are
two nodes and a text is resolved to a node only among its owner's own.
The consumers follow the site rather than re-deriving it: a frozen
PerElement occurrence keeps its subscript, dependency pins resolve each
axis per spelled dimension name by position, a source element no target
element reads is no row, and an un-hoisted reducer's wildcard argument is
held live in its own edge's partial with the co-sources frozen around it.
A per-element slot's bare reducer argument reads the row its element
pins while the node minted for it is the whole array, so the slot's edge
through that node is declined loudly rather than scored against the
wrong read; a flow feeding its stock through a parent mapping is admitted
under the wiring's pairing and spelled bare in the flow-to-stock score,
which then equals the ratio the recorded series give. The one executed
read left undescribed is the ordinal fallback of an undeclared pair with
disjoint names at equal cardinality (GH #527), which stays a loud
decline. C-LEARN's plain and LTM artifacts are unchanged; the natural
movers are named as divergences in the design plan and pinned against
the compiler's executed read.
The engine CLAUDE.md is rewritten as a map a reader scans: one bullet per
pipeline stage and per db/ file, the "one owner" names beside the stage
that owns them, the salsa rules and the standing invariants each with the
test that pins it, and the LTM section as the describer rules the code
keeps. Every invariant the previous text stated survives; what changes is
the shape (item 3 was a 900-word paragraph) and the stale names the branch
deleted. docs/architecture.md's engine section, engine-performance.md's
compile-side sections and docs/README.md say the same thing in fewer
words; 2026-02-21-incremental-compilation.md is marked the historical
design record it is.

The compiler-unification plan's Definition of Done and Acceptance Criteria
state what is true at the branch head with the command or test that shows
it (AC3.2 holds only to the one-percent band the plan records), Phases 8
and 9 read as design, the Phase 7 investigation narratives are cut to the
decisions that survive and their pins, and the ledger is one compact table
with a fixed shape and every commit on the branch, the 7.3 row included,
with commit hashes rather than subjects now that every commit exists. The
LTM design doc's describer section agrees with the engine CLAUDE.md (one
correspondence, one pairing, the spelled reducer as a node's identity) and
its carve-outs name the declines the code makes. Comments and rustdoc in
fourteen engine files that narrated an edit ("used to", "no longer", "had
lost") state the standing rule or constraint the code keeps instead; no
non-comment line changes.
@bpowers
bpowers force-pushed the compiler-unification-v2 branch from cbb5f77 to 78d0195 Compare September 4, 2026 02:28
A row of the compiler-unification ledger names the commit it measures.
For commits already on main a hash is a stable name; for the rows of a
branch that is rebased before it merges, every hash is rewritten by the
rebase and again by the merge, so a hash in the ledger is orphaned before
anyone reads it. The branch rows therefore carry the commit subject, which
survives both, and a reader finds the commit with git log --grep. The one
hash the performance doc cited for a branch commit is replaced the same way.
@codecov

codecov Bot commented Sep 4, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 94.61264% with 121 lines in your changes missing coverage. Please review.
✅ Project coverage is 93.21%. Comparing base (d04593e) to head (1cfac81).

Files with missing lines Patch % Lines
src/simlin-engine/src/db/assemble.rs 91.83% 25 Missing ⚠️
src/simlin-engine/src/compiler/array_operand.rs 92.16% 21 Missing ⚠️
src/simlin-cli/src/main.rs 78.26% 20 Missing ⚠️
src/simlin-engine/src/compiler/context.rs 93.85% 11 Missing ⚠️
src/simlin-engine/src/compiler/codegen.rs 16.66% 10 Missing ⚠️
src/simlin-engine/src/db/analysis.rs 97.23% 9 Missing ⚠️
src/simlin-engine/src/compiler/subscript.rs 86.04% 6 Missing ⚠️
src/simlin-engine/src/compiler/mod.rs 97.94% 5 Missing ⚠️
src/simlin-engine/src/capture.rs 97.93% 4 Missing ⚠️
src/simlin-engine/src/ast/expr2.rs 92.10% 3 Missing ⚠️
... and 4 more
Additional details and impacted files
@@            Coverage Diff             @@
##             main    #1040      +/-   ##
==========================================
+ Coverage   93.02%   93.21%   +0.18%     
==========================================
  Files         253      253              
  Lines      155948   152944    -3004     
==========================================
- Hits       145074   142563    -2511     
+ Misses      10874    10381     -493     

☔ 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.

A subscript that names an iterated dimension of the target, over a source
axis that declares no correspondence to it and shares no element name, is
read at the active element's ordinal, and that last resort lives in one
place, `DimensionsContext::resolve_dimension_subscript`, which both
subscript paths call: `build_view_from_ops`'s `ActiveDimRef` arm when every
sibling index is static and `lower_index_expr3`'s `Dimension` arm when a
sibling needs runtime evaluation. Phase 6b had left the ordinal on the
static arm alone, so `target[state] = m[state, idx]` was refused where
`m[state, 1]` compiled and where origin/main compiled both -- a sibling
index decided which rule fired. The step takes the ordinal only for a
subscript that NAMES its active dimension (`IndexOp::ActiveDimRef` carries
the spelled dimension beside the active position), the rule origin/main's
pass-1 fold applied, so a pairing made through a declared mapping is refused
on both paths as it is there. Within the source's extent the undeclared pair
therefore compiles exactly where origin/main compiles it; past the extent
the dynamic spelling is refused where origin/main ran with NaN in the cell,
a divergence Phase 6b already carried and this names. Whether the engine
should keep the ordinal or refuse the pair as Vensim does is GH #1044's
decision, made once for every spelling rather than per path. LTM's GH #527
carve-out (the describers decline the undeclared pair) is unchanged.

Two further divergences the branch already carried are named and pinned:
the Phase 6b refusal of a reducer over a 0-d operand in an apply-to-all body
(`SUM(pop * 2)`, main's GH #789 wrong number, GH #1051 owns compiling it)
and the Phase 7.5 code move for a bare snapshot of a variable named like a
dimension (`PREVIOUS(other)`, `NotSimulatable` to `DoesNotExist`, GH #1050
owns the definition-time refusal). GH #1029's subrange read is pinned on
the issue's own model as reading by element name in every spelling, the
reading Phase 6b established; the `is_subdimension` rung stays opt-in for
the superset direction alone.
@bpowers
bpowers merged commit c2048c1 into main Sep 4, 2026
16 of 17 checks passed
@bpowers
bpowers deleted the compiler-unification-v2 branch September 4, 2026 13:25
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment