Skip to content

engine: salsa roofline engine-side items and the LTM overlay key - #1057

Merged
bpowers merged 16 commits into
mainfrom
salsa-roofline-engine
Sep 6, 2026
Merged

bpowers merged 16 commits into
mainfrom
salsa-roofline-engine

Conversation

@bpowers

@bpowers bpowers commented Sep 5, 2026 •

Copy link
Copy Markdown
Owner

An editor built on this engine holds 117 MiB of dead memos after renaming one unreferenced constant in C-LEARN, and every LTM simulation it runs after a diagnostics pass re-executes a third of a cold LTM compile. Both costs come from how the engine uses salsa, not from salsa: salsa's own bookkeeping is 2.4 MiB of the 29 MiB a plain C-LEARN database holds and 6.3 MiB of the 222 MiB an LTM one holds; the rest is what our queries return and keep. This series removes both costs, shrinks the parse trees and compiled artifacts the database retains, cuts 7% off a cold plain compile, and writes the design plan for the cold LTM compile, which is ten times the plain one because every link score is generated as equation text and lowered through every compiler tier once per link (docs/design-plans/2026-09-04-link-scores-from-fragments.md). The measurements and the protocol behind them are in docs/design/engine-performance.md, section C7.

Salsa keeps a superseded memo until the next revision, and a revision is an input write, so an editor that syncs, answers its diagnostics and compile queries, and then waits for the next keystroke holds every value the last edit replaced until the edit after it. SimlinDb::release_replaced_memos runs salsa's deferred-delete sweep on demand, and libsimlin's DbLock guard runs it when the guard drops at the end of every entry point, so the garbage is freed inside the edit that made it. The database field is crate-private and the guard is its only accessor, so no entry point can skip the release. The sweep is an exclusive salsa access; salsa counts those in a byte and opens a synthetic revision on the 256th without an input write, and the next entry point then deep-verifies the memo cone it touches, once, at about 1,880 instructions per memo, re-executing nothing. Neither way of gating the release works. A flag set by the engine's writers misses memos, because a memo an edit superseded is replaced in whichever later entry point first re-executes it: patch, then a plain diagnostics pass that clears the flag, then an LTM simulation leaves the 117 MiB cone resident until the next edit. An exact gate on salsa's execution event needs an event callback, and with one registered salsa builds an event on every memo fetch. The rustdoc on the guard records both.

Whether a compile assembles the LTM overlay was a salsa input on the project. libsimlin set it before every LTM simulation, cleared it after, and set it again under a guard to harvest LTM diagnostics, and each flip was a revision: salsa discarded the other variant's memos and re-verified every memo in the database. On C-LEARN a warm LTM simulation after a plain diagnostics pass re-executed 1,035 query bodies (2.9 G instructions), and the diagnostics pass after it 1,676 (2.5 G). The overlay is now db::LtmOverlay, an argument of every query whose value depends on it: the layout, the shape a cross-module read resolves through, the fragments that make such a read, the assembly, and the diagnostics. Both variants stay memoized side by side, the input with its setter and guard is gone, and every caller names the overlay it wants. A fragment's value depends on the overlay only through the shapes of the module instances it reads, so only fragments that read one are keyed on it; every other fragment has one memo for both overlays, and a debug assertion in the fragment constructor fires if that predicate ever misses a module read, because a miss there would be a silent miscompile. ltm_discovery_mode is still an input of the same shape and flips the same way; moving it is #1056.

Expr0's argument and index lists are exact-size Box<[T]> instead of Vecs carrying Vec's minimum capacity, and Range boxes its bounds, which takes IndexExpr0 from 120 bytes to 48 and removes 45 MiB of empty capacity from C-LEARN's LTM parse trees. An LTM arm's diagnostic text is an Arc shared by the per-link memo and the whole-model list instead of a String in each (9 MiB). compile_project_incremental returns the assembly memo's own Arc, and the Vm and libsimlin hold that Arc instead of two deep copies per LTM edit (62 M instructions). model_implicit_var_by_name returns a reference into its memo instead of cloning the helper's metadata on every lookup. The dependency graph's transitive closure, a third of the graph's quarter of a cold compile, works over a dense node index with one bit per node, so absorbing a dependency's closure is a word-wise OR instead of a BTreeSet union with one interned-string compare per element per edge. The traversal order, the SCC and back-edge rules, and the sets the readers see are unchanged: examples/depgraph_dump.rs, added here, writes every corpus model's runlists, cycle verdict, resolved SCCs and dependency maps, and the file is byte-identical before and after, under the empty module-input wiring and under every wiring an instance binds. Cold plain compile of C-LEARN: 6.937 G to 6.449 G retired instructions, -7.0% over three interleaved base/new pairs with 0.05% spread.

A review of the branch found fifteen defects, and the last commits fix them. Three changed behavior. The set of slots a conveyor or queue pass writes, which no override may claim, was computed in three places and copied into a fourth, and the Vm's copy only grew, so re-attaching plans left stale retractions; one predicate over the plans answers the question everywhere now, the wasm backend included. simlin_analyze_get_loops_runtime read an arrayed loop's slot width from the current revision while the column base came from the sim's results, so a patch that widened a loop's dimension made it classify the next loop's column as one of its own scores; it reads the sim's own snapshot, as its sibling entry points already did. The overlay migration had given a shared test helper the plain overlay while every test calling it had run with LTM on, which left eight "every fragment must compile" assertions unable to fail; an audit of every plain-overlay site the migration introduced, keyed on which tests set the old flag, fixed those helpers and two other tests the same shape had hollowed out.

Every commit passed the pre-commit hook: rustfmt, clippy and the workspace tests, the TypeScript lint, build, type check and tests, the wasm build, and pysimlin's tests. The instruction counts are perf stat over the C-LEARN compile harness, three interleaved base/new pairs on a quiet machine. The overlay change is pinned by db::ltm_overlay_tests (interleaving the two overlays re-executes no tracked query, and a plain assembly never derives the overlay), the memo release by the refcount of a superseded compile's program, and the dependency-graph rewrite by the dump. Not measured: libsimlin's edit path end to end with all of these together, since each was measured or pinned alone; and the 2.9 G, 2.5 G and 117 MiB figures are the investigation's measurements of what the change removes, not a re-measurement afterward.

Fixes #643
Updates #1056

The parser built a call's arguments and a subscript's indices by push
into a Vec, and Vec's first growth allocates four slots, so every one- or
two-element list retained two or three empty slots for the life of the
parse tree. On C-LEARN under LTM that was 45 MiB of the 117 MiB of
generated equation trees the database holds, and IndexExpr0 was 120
bytes wide because Range carried both bounds inline, so every index of
every subscript paid that width (docs/design/engine-performance.md, C7).

Both lists are now Box<[T]>: the parser shrinks once when a list closes,
and the type cannot regrow. Range boxes its bounds. Expr0 and IndexExpr0
are both 48 bytes on 64-bit targets, pinned by a test so the next field
added is a decision rather than a drift. SmallVec was not the tool:
inlining even one 120-byte element would have widened every Expr0
variant.
Every emitted link score is cloned out of the per-link shaped_link_score
memo into model_ltm_variables' whole-model list, and while the parsed
tree already rode that clone as an Arc, the arm's diagnostic text was an
owned String and was deep-copied: 9 MiB of the per-link memos' own
footprint on C-LEARN, on top of the 9.8 MiB the whole-model vector holds
(docs/design/engine-performance.md, C7).

The text is now an Arc<str>, so the clone is a refcount bump and one
copy is retained. The text is still the generator's exact spelling,
retained only for diagnostics and never re-parsed; readers borrow it as
a str.
compile_project_incremental deep-copied the CompiledSimulation out of
the assemble_simulation memo to return it by value, and libsimlin then
cloned it again into Vm::new so it could keep a copy for reset: the
modules map, the name-to-slot map and the constant index, 62 M
instructions per LTM edit on C-LEARN (docs/design/engine-performance.md,
C7).

The entry point now returns the memo's own Arc, SimBuild and the FFI's
SimState carry that Arc, and Vm::new takes anything that converts into
one, holding it for the cold paths (name lookups, overrides) instead of
owning copies. The conveyor/queue path still has to retract the
pass-written slots from the constant index, so it takes a private copy
with Arc::make_mut; that clone is the special-stock path's cost alone.
The Vm keeps its own retraction as a small overlay set rather than
editing the shared index.
model_implicit_var_by_name is the per-name firewall the fragment path
resolves SMOOTH/DELAY/PREVIOUS helpers through, and it returned its
ImplicitVarMeta by clone: the helper's name, its model name and its
dimension list, allocated afresh on every hit for readers that only
inspect the metadata. It now returns a reference into the memo. The one
reader that stores the metadata (DeclaredName::Helper, which the
lowering memos retain) clones at that site alone.
model_dependency_graph is a quarter of a cold plain compile on C-LEARN,
and a profile with inlined frames put a third of that in the transitive
closure's BTreeSet<Ident> unions: one interned-string memcmp per element
per edge, over a thousand nodes closing into sets of hundreds of names,
walked up to twice per phase once the recurrence gate has resolved its
SCCs (docs/design/engine-performance.md, C7).

The closure now works over a dense node index with one bit per node, so
absorbing a dependency's closure is a word-wise OR. The traversal order
is unchanged (it decides which member of a genuine cycle is reported),
the SCC-collapsing and back-edge rules are carried over line for line,
and every set is materialized back into the BTreeSet<Ident> its readers
iterate: nodes are numbered in lexicographic order, so a set's ascending
bits are already that order. A module's direct dependencies stay
verbatim, since they can name variables the model does not declare. The
recurrence resolution reuses the graph's own var_info on the no-input
wiring rather than building it a second time, and each phase's successor
lists are computed once rather than once per walk.

Whole-process cold plain compile (CLEARN_COMPILE_ITERS=5): 6.937 G to
6.449 G retired instructions, -7.0% over three interleaved pairs with a
0.05% spread; under LTM -0.15%. The dependency graphs of every model
under test/ are byte-identical before and after, checked with the new
examples/depgraph_dump.rs, which is the runlist-and-relation sweep the
performance doc asks for on a change like this and did not have a tool
for.
Salsa does not drop a memo when a query re-executes: the superseded memo
goes on the ingredient's deferred-delete list and is freed at the start
of the NEXT revision, inside the next input write. For an editor that
syncs, answers its diagnostics and compile queries, and then waits for
the next submit, that is indefinitely: one rename of an unreferenced
constant leaves 117 MiB waiting under LTM and 5 MiB plain on C-LEARN
(docs/design/engine-performance.md, C7).

SimlinDb::release_replaced_memos runs the same reset on demand (salsa's
trigger_lru_eviction; nothing declares an LRU, the deferred-delete sweep
is the part that matters), and libsimlin calls it at the end of the
patch, get_errors, sim_new and is_simulatable entry points, after the
queries an edit provokes have run. It costs 10 ms under LTM when there
is something to free and a walk over empty lists otherwise, and the
drop is paid inside the edit that caused it rather than one edit late.
The engine test pins the mechanism on the refcount of the program a
superseded compile handed out.
Whether a compile assembles the Loops That Matter overlay was a salsa
input on the project (ltm_enabled). libsimlin set it before an LTM
simulation and cleared it after, and get_errors flipped it back on under
a guard to harvest the overlay's diagnostics, so every simulation after a
diagnostics pass and every diagnostics pass after a simulation was a new
revision that discarded the other variant's memos and re-verified every
memo in the database: on C-LEARN a warm LTM simulation re-executed
1,035 query bodies (2.9 G instructions, a third of a cold LTM compile),
the diagnostics pass after it 1,676 (2.5 G), and a plain simulation
after either 181 (docs/design/engine-performance.md, C7).

The overlay is now an argument, db::LtmOverlay, of every query whose
value depends on it: the layout, the shape a cross-module read resolves
through (a sub-model's layout carries its LTM section, so the fragments
that resolve such a read are keyed too), the assembly, and the
diagnostics, down through compile_project_incremental, compile_sim,
build_sim and collect_all_diagnostics. Both variants stay memoized side
by side, and the input, its setter and the guard are gone; the callers
that flipped them (libsimlin, the CLI, the MCP tools, wasmgen, the
analysis and loop-detection paths) name the overlay they want instead.
The LTM derivations themselves are overlay-independent and are derived
once whichever assembly first reads them; the dependency graph's SCC
probe and the unit pass read the plain shapes, since neither reads a
module's layout. The discovery-mode flag stays an input: it keys the
derivation itself, and moving it is a separate change.

The price is one fragment memo per overlay a variable has been compiled
under, about 5 MiB on C-LEARN when both have been used. Two probe tests
pin the point: interleaving the two overlays re-executes no tracked
query, and a plain assembly never derives the overlay.
The salsa and roofline investigation of 2026-09-04 found that the cold
LTM compile is ten times the plain one and the LTM database seven times
its size because every link score is built as equation text: printed,
parsed and lowered through every compiler tier once per link, and held
in one whole-model value that any edit invalidates. Nothing salsa-side
moves that; the generated program is the gap.

The plan derives each link score's program from the target's compiled
symbolic fragment instead: the ceteris-paribus freeze as a rewrite over
the opcode stream keyed per link on the target and its live slot range,
the remaining formula families as typed builders, one LinkScore opcode
over shared per-variable deltas, and a native post-pass over saved
states. Six phases, each gated on bit-identical series against the text
generators. The acceptance criteria are proposed and need review before
an implementation plan is written from them.

The performance doc's residency section gains the two findings this
branch did not act on: why the 24-byte SymbolicOpcode is not a field
change away from 16 (a nested 16-byte SymVarRef sets the width), and
the co-owned LTM trees the plan frees by never generating them.
The branch review's findings, in one commit.

libsimlin: the release of superseded salsa memos has one owner. Every
entry point locks the database through SimlinProject::lock_db, and the
DbLock guard releases the memos when it drops, so no entry point can
forget the call (two had). Salsa opens one synthetic revision per 256
exclusive accesses without an input write, which the doc now states.

dep_graph: the recurrence resolution is a tracked query keyed on
(model, project, phase). Its result is a function of those alone (the
no-input wiring is fixed inside it), while the dependency graph that
reads it is keyed per module-input set, so a sub-model instantiated
under several wirings resolved its recurrences once per wiring. One
DenseIndex now numbers the nodes for both consumers of the cycle
relation, the closure and Tarjan (IndexedGraph::from_dense), so the two
cannot drift; the closure walk drops the is_module guard, since a
module's set is Direct and only a Reached set is absorbed, and the dead
same-SCC branch on the cycle path is a plain error.

Constant retraction is an overlay, not a scrub: SimBuild reports the
retracted constant offsets, the Vm and the FFI's SimState consult that
set next to the program's constant set, and the wasm lowering retracts
unconditionally. Scrubbing the compiled program's constant set forced an
Arc::make_mut deep copy of the shared program on every special-stock
build, which was the copy the Arc was introduced to remove.

var_fragment: source_dimensions and helper_dimensions own the
dimension-list derivation the shape, units and layout queries all
repeated. analyze_model restores the caller's discovery mode instead of
leaving it on. The Expr0 width test pins the relation between the node
types rather than a platform constant. The overlay-keying probe tests
run over both fixture arms, a plain loop and a loop through a SMOOTH
instance, since only a module read resolves through the shape memo the
overlay keys; the module fixture is what shows that arm reached.

Docs describe the overlay as an argument everywhere it was still a flag:
the engine, libsimlin and MCP-core CLAUDE.md files, the LTM and
performance design docs, the rustdoc and test comments that named the
old input or its guard, and the ltm_full_bench stage list, which no
longer has a no-op stage for it. The rustdoc on the width and sharing
changes states each constraint rather than narrating the edit, and
simlin.h is regenerated, since cbindgen copies the FFI rustdoc into it.
The performance doc's C7 names the input that remains, ltm_discovery_mode
(GH #1056).
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Sep 5, 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-05T14:00:47.547311Z f1d5ae2 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.

@codecov

codecov Bot commented Sep 5, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 94.85407% with 67 lines in your changes missing coverage. Please review.
✅ Project coverage is 93.21%. Comparing base (c2048c1) to head (8144414).
⚠️ Report is 3 commits behind head on main.

Files with missing lines Patch % Lines
src/simlin-cli/src/main.rs 54.34% 21 Missing ⚠️
src/simlin-engine/src/conveyor_compile.rs 33.33% 14 Missing ⚠️
src/simlin-engine/src/ast/mod.rs 41.66% 7 Missing ⚠️
src/simlin-engine/src/db/analysis.rs 80.00% 4 Missing ⚠️
src/simlin-engine/src/db/dep_graph.rs 98.51% 4 Missing ⚠️
src/simlin-engine/src/ast/expr0.rs 94.33% 3 Missing ⚠️
src/simlin-engine/src/ltm_augment.rs 83.33% 3 Missing ⚠️
src/simlin-engine/src/patch.rs 66.66% 3 Missing ⚠️
src/simlin-engine/src/db/ltm/equation.rs 84.61% 2 Missing ⚠️
src/libsimlin/src/project.rs 96.29% 1 Missing ⚠️
... and 5 more
Additional details and impacted files
@@           Coverage Diff            @@
##             main    #1057    +/-   ##
========================================
  Coverage   93.21%   93.21%            
========================================
  Files         253      253            
  Lines      152944   153504   +560     
========================================
+ Hits       142563   143096   +533     
- Misses      10381    10408    +27     

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

The slots a conveyor or queue pass writes every step compile to the same
flows AssignConstCurr as a user's constant 0, so the shared program's
constant index cannot tell them apart and an override on one must be
refused by reading the plans. That subtraction was spelled in three
places -- Vm::set_conveyor_plans/set_queue_plans, wasmgen's local
pass_written set, SimBuild::retracted_constant_offsets -- and the FFI
carried a fourth copy on SimState, threaded through a six-tuple. The Vm's
copy only ever grew: a Vm whose plans were re-attached with a different
set kept the earlier plans' slots retracted, so its gate and the FFI's
disagreed on the same program.

queue_compile::is_pass_written(conveyor_plans, queue_plans, off) is now
the one statement of the union, and
CompiledSimulation::is_overridable_offset(conveyor_plans, queue_plans, off)
the one override gate over it. The Vm asks it under the plans it holds
(Vm::retracted_constants is gone, so replacing the plans is the
retraction), libsimlin asks it under the plan sets it already caches for
reset (SimState::retracted_constants and the tuple element are gone), and
the wasm backend subtracts through the same predicate once, after its
parity assertion. That assertion now compares wasmgen's constant walk
with the VM's collect_constant_info before any subtraction, so it checks
the two walks and nothing derived from the caller's own plan arguments;
compile_simulation's rustdoc says what is true instead of promising a
retraction check the shared program cannot support.

The re-attachment arm is pinned per setter with production-built plans
(two belts, two queues; resolve_plans over the expanded program, one
plan attached and then the other): the newly attached plan's outflow is
refused and the replaced plan's is an ordinary constant again. Both were
red on the extend-only code. The libsimlin queue test now also refuses
on the no-Vm path after run_to_end, which is the arm that pins the FFI
consulting its cached queue plans and not only the conveyor ones.
The dependency graph's cycle relation had two derivations of its
offending SCCs and two builds of its no-input var_info.
resolve_recurrence_sccs and the test accessor dt_cycle_sccs each ran
DenseIndex -> successors -> self-loop scan -> Tarjan -> len >= 2, and
only the production copy then subsumed a self-loop into the >= 2 SCC
that contains it, so the accessor's "the engine's relation by
construction" claim was false: on a member of a multi-variable SCC
that also carries a direct self-edge (the C-LEARN shape) the accessor
reported one SCC more than the engine resolves, and its cross-check
panicked on a model the engine compiles. phase_cycle_sccs is the one
derivation, the subsumption inside it, and
dt_cycle_sccs_subsumes_a_self_loop_inside_a_multi_scc pins that arm
through the production cross-check.

The no-input var_info is a tracked memo, no_input_var_info, read by
the no-input dependency graph, the recurrence resolution and the
root's invariance pass; a wired instance's graph builds its own
through model_var_info and retains nothing. The tracked resolution
cannot borrow the graph's map, so the map both read is a memo: a
per-model map of two small Ident sets per node (about 0.5 MiB on
C-LEARN against 29 MiB of plain residency), compared per element by
pointer, and backdated by an edit that leaves every node's ordering
edges in place.

The resolved SCCs are projected onto the dense index once per phase
(SccIndex: an id per node, the members per id) instead of a name-keyed
map re-projected on every closure walk with an O(n) member scan per
collapsed SCC. An id is the SCC's position in the list the index was
built from, and the init index is built over the dt SCCs and then the
init-only ones, so an init-only id never collides with a dt id (the
name-keyed map numbered init-only SCCs from resolved_sccs.len(), which
is 0 after a failed dt re-run while the dt map still held ids 0..;
only a model already refused with a cycle reaches that path, and no
corpus model does).

IndexedGraph::node_to_idx is gone: from_edges keeps the map as a local
for its edge translation, and from_dense builds nothing and asserts,
in debug, the one numbering contract it states (nodes sorted by
canonical name). The rustdoc of walk_successors and the dep_graph test
comments describe the dense closure -- no unknown-name arm, a module's
set is Closed::Direct and only a Reached set is absorbed, processing
is a bool vector -- and the accessor and resolution docs name
scc_components_of.

examples/depgraph_dump.rs dumps every model under the empty wiring and
then under every bound-port set an instance of it binds
(enumerate_module_instances from every model as a root, now pub with
ModuleInstanceMap), so the byte-identity sweep covers the wired arm,
where a with-inputs relation meets the no-input resolution. Over the
4906 models under test/ every pre-existing section is byte-identical
before and after; the extension adds 161 wired sections, none with a
recurrence SCC; the only other difference is which missing GET DIRECT
data file an importer refusal names first, which flips between two
runs of the same binary and is the importer's, not the graph's.
The C7 section of the engine-performance doc, the LtmOverlay rustdoc
and the ltm_full_bench stage comments narrated the edits that produced
them, and two of the sentences had stopped being true: the recurrence
resolution is a tracked query that reads the no-input var_info memo
the dependency graph reads, not a borrower of the graph's map, and the
bench's body comments numbered stages against a list one entry longer
than its header. The doc rule is that documentation describes the
current state and git history is the changelog.

Each paragraph now states what the code does and keeps the measurement
as a measurement of the design it was taken against. The memo-release
paragraph gains the cost class of the guard's synthetic revision --
one deep verification of the touched memo cone per 256 exclusive
accesses without an input write, because LOW durability's last-changed
revision is the current revision -- and the two gates that would remove
it and why each is wrong (a writer-set flag misses memos re-executed by
a later read-only entry point; salsa's execution event needs a callback
that runs on every query fetch). The overlay paragraph states the
one-time emission pass the per-overlay fragment key costs beside the
memory it costs, and the width bullet the per-pointer-width pins.
simlin_analyze_get_loops_runtime read the per-loop slot width for
reclassify_loops_from_results off the CURRENT revision's loop_partitions
while the column base came from the sim's compile-era results. The LTM
layout is name-ordered, so after an edit that widened an A2A loop's
dimension the primitive read the next loop's column as one of the widened
loop's scores: a balancing loop over a 2-element dimension, widened to 3
by a patch, classified Undetermined at confidence 0.33 instead of
Balancing at 1.0 on an unchanged sim. The width now comes from the sim's
own SimState::loop_partitions, the same source
simlin_analyze_get_relative_loop_score resolves against, so a sim's
classification is a function of its own results. The loop list is still
the current model's; that stale-snapshot caveat is documented on
simlin_project_apply_patch as it is on simlin_project_replace_contents.
Pinned by runtime_loops_read_slot_width_from_the_sims_own_snapshot, which
asserts the name-ordered adjacency and the 3-vs-2 widths as preconditions
so it cannot pass vacuously.

analysis::ltm_snapshots is the one derivation of the LTM snapshot
(loop_partitions, loop_element_index, mode): simlin_sim_new stores it on
the SimState and the from-wasm rel-loop-score twin derives it per call.
Its rustdoc says what each caller gets, in particular that the from-wasm
caller's snapshot matches the blob only for a blob compiled from the same
contents in exhaustive mode, since simlin_model_compile_to_wasm compiles
in a throwaway db under its own discovery flag.

SimlinProject::db is pub(crate) and lock_db is pub, so DbLock is the only
guard the db can be reached through, inside the crate and from the
integration-test crate alike; the four raw db.lock() test sites go through
it. The DbLock and SimlinDb::release_replaced_memos rustdocs state the
release contract against salsa 0.28.1 by file: the deferred-delete list
insert_memo pushes to and reset_for_new_revision clears; the AtomicU8
cancellation counter cancel_others bumps on every exclusive access and the
synthetic revision it opens on the 256th without an input write; that a
synthetic revision moves the slot current_revision and
last_changed_revision(LOW) share, so every LOW memo fails
shallow_verify_memo_cold and the next entry point deep-verifies the cone
it touches once (~1,880 instructions per memo, ~27 M on C-LEARN plain, no
re-execution but the untracked-read model_all_diagnostics). The release
stays unconditional as a standing constraint: a writer-set dirty flag is
unsound because a superseded memo is replaced in whichever later entry
point first re-executes it (patch -> get_errors(Off) clears the flag ->
sim_new(On) replaces the 117 MiB LTM cone unreleased), and an exact
WillExecute gate needs an event callback that makes every fetch construct
a WillCheckCancellation event with thread::current().id().

The libsimlin CLAUDE.md states the locking contract on SimlinProject,
names SimState::is_overridable_offset as the set_value_by_offset gate, and
describes ltm_mode capture and the runtime loop surface without the
deleted ltm_enabled input.
@claude

claude Bot commented Sep 5, 2026

Copy link
Copy Markdown

Review

No correctness bugs identified in this PR.

Coverage of the review:

  • db/dep_graph.rs (+728/-552, the largest change): the dense-index rewrite preserves the previous semantics arm-by-arm. DenseIndex::new numbers var_info.keys() in lexicographic order (matching the old BTreeSet iteration order the closed sets materialized in). NodeSet::iter yields ascending indices; the collected BTreeSet<Ident> has the same members as the old accumulation. SccIndex::new's filter-map fallback would only fire if var_info differed from no_input_var_info, but build_var_info iterates source_vars plus synthesized helpers with a wiring-independent node set (only edges differ). The closure_of SCC block matches the old compute_inner block: intra-SCC skip, external absorb only for Reached (module Direct sets are never absorbed), collapse-set assigned to every member. Byte-identical dep-graph dumps over all 4906 corpus models via the new examples/depgraph_dump.rs back this up.

  • ast/expr0.rs and LTM Arc<str>: every Vec → Box<[T]> site keeps the vec local and .into()s once; no in-place mutation remains. LtmArm::text: Arc<str> preserves PartialEq/Hash (Arc<T> forwards to T), so salsa backdating equality is unchanged; no caller mutates the string.

  • libsimlin/{lib,project,simulation,analysis,patch,serialization,model}.rs: every production callsite routes through SimlinProject::lock_db(). DbLock::drop calls release_replaced_memos() while still holding the mutex, before MutexGuard::drop releases it — correct order. Arc<CompiledSimulation> is refcounted; salsa evicting its Arc does not free the value while SimState.compiled / Vm.compiled hold clones. Datamodel-then-db lock order is preserved everywhere.

  • LtmOverlay migration: all production LtmOverlay::{On,Off,from} sites thread the correct overlay. simlin_project_get_errors uses Off for the plain build_sim VM error (so an LTM-only rejection never masquerades as a project error) and LtmOverlay::from(ltm_requested) for collect_all_diagnostics; apply_project_patch_internal uses Off throughout; MCP read_model/edit_model use On symmetrically; wasmgen uses LtmOverlay::from(ltm_enabled). Every query in the chain (compute_layout, flattened_offsets, model_shape, module_dep_shape, source_dep_shape, implicit_dep_shape, compile_var_fragment, compile_implicit_var_fragment, explicit_fragment_input, implicit_fragment_input, var_phase_symbolic_fragment_memo, assemble_module, assemble_simulation, combine_resolved_sccs, model_flows_invariant, model_all_diagnostics, collect_model_diagnostics) takes and forwards overlay. The single hardcoded LtmOverlay::Off inside dep_graph::resolve_recurrence_sccs' element-graph builder is justified by construction. The new db/ltm_overlay_tests.rs pins both variants stay memoized side by side.

Overall correctness verdict

Correct. The patch is free of blocking issues. Non-blocking observations were not flagged per the review guidelines.

The layout path took &mut SimlinDb from try_detect_ltm_loops up through
generate_best_layout and the two libsimlin entry points that call it,
for a write that does not exist: the overlay is a compile argument, and
every read the layout makes is a shared query. The chain now borrows the
db (db_state: Option<(&SimlinDb, SourceProject)>), ensure_db_state syncs
an owned db through sync_from_datamodel(&db, ..) when the caller has
none, and simlin_project_diagram_sync and the render path hold the db
lock non-mutably through the layout.

Two rules had a second spelling: model_shape's LTM arm re-derived
dimensions_named inline, and five sites in ltm_augment hand-built the
PREVIOUS(expr) wrapper freeze_at_previous owns. Both go through the
owner (the value-position form, since neither walker descends into a
subscript index).

Tests that pinned one arm of a decision now pin the decision. The
discovery-mode restore in analyze_model is checked from both prior
values, since an unconditional false passed the false-start arm alone.
The CLI conveyor test drives the On overlay simulate() requests for
--ltm instead of the plain one. node_widths_are_pinned bounds Expr0 per
pointer width -- 48 bytes with 8-byte pointers, 32 on wasm32, both
measured -- because the 6 * size_of::<usize>() bound fails on wasm32
while the doc claimed every target. And a fixture whose recurrence SCC
member reads a module output whose slot moves under the overlay pins the
argument symbolic_phase_element_order makes for taking its verdict over
the plain fragments: the On fragments differ only in that non-member
read, wire the same element graph, and the On assembly consumes the
plain-derived order without refusal. x_arrayed moves to testutils so
that fixture and assemble_tests build arrayed arms through one helper.
The overlay migration replaced the per-project ltm_enabled input with
an LtmOverlay argument on every query, one site at a time. Two of the
sites it introduced sit in helpers rather than in the tests that had set
the flag: fragment_failures in ltm_array_freeze_tests and
ltm_rank_decline_tests collected collect_all_diagnostics(.., Off), but
the "failed to compile" warnings they filter for are facts of the
overlay's derivation that model_all_diagnostics emits only under On
(db/diagnostic.rs), so every "no failing fragments" assertion behind
them was vacuous. Two more helpers hard-coded Off where the flag-on
caller's db had run under the flag: assert_module_decls_sit_at_layout_slots
compared an On assembly against the Off layout (a module's slot is its
sub-model's n_slots under the overlay, so the two can differ), and
render_resolved_scc rendered the SCC golden under Off whatever overlay
the fixture assembled under. And test_ltm_disabled_identical_bytecode
compiled three times on one db with no write between, so its "never
LTM" and "after LTM" programs were one assemble_simulation(.., Off)
memo compared with itself.

The audit is exhaustive rather than sampled: a script (in the review
report) takes every function that on main set the flag true, directly
or through a test-scope helper -- 353 of the 354 setter call lines are
attributed, the 354th being the deleted guard's own restore -- walks
every test-scope helper reachable from its body at HEAD, and lists every
LtmOverlay::Off and LtmOverlay::from(..) it reaches: 34 sites. Each is
either the plain arm the test wants (a fresh plain db used as the
numeric or compilability oracle, the Off baseline of an On > Off
comparison, a parameterised from(bool)) and now says so at the site, or
is switched. The reverse walk (tests reaching On that never set the
flag) finds only the two new tests in ltm_overlay_tests.

Both fragment_failures helpers collect under On; the layout-slot and
SCC-golden helpers take the overlay their caller assembled under; the
bytecode test derives its "never" arm in a fresh db and compares the
whole CompiledSimulation, with a non-vacuity check that the On program
did add offsets. Switching the rank-decline helper exposed two stale
things in that file: the ELM MAP test's comment claimed a sibling A2A
score still failed (it compiles, through a freeze helper), and the
ALLOCATE fixture declared pp[D,2] -- 2 names no dimension -- so pp and
result never compiled and the test asserted a decline on a model that
could not compile. The fixture declares the priority-profile axis, every
fixture in the file is asserted to compile as a plain model, and the
failure assertions are unfiltered.
db::LtmOverlay is an argument of four tracked queries, and a fragment's
value depends on it through exactly one path: module_dep_shape, the
sub-model layout a module instance's shape carries, which holds that
model's LTM section under On. Every other dependency shape is a
dimension list, identical under either overlay. Keying every fragment on
the overlay therefore paid for the module-reading minority with a second
memo and a second emission pass for every variable in the project: on the
overlay tests' three-variable fixture, the first pass under the second
overlay re-emitted 61 fragments, nearly all of them spliced stdlib
template variables that instantiate nothing.

var_fragment::fragment_reads_module is that question -- the variable is
an instance, a head it resolves through is one, or its parse minted one --
and fragment_overlay turns it into the key, with a helper twin for the
implicit fragments. Every production caller of compile_var_fragment,
compile_implicit_var_fragment, var_phase_symbolic_fragment_memo and
model_flows_invariant resolves its key through it, so a plain-keyed
fragment now serves both overlays. The predicate is salsa-tracked so a
caller gains a backdating bool rather than the lowering memo it is
derived from, and it is asserted rather than trusted: both constructors
debug_assert it against the shapes they actually built, because an
under-approximation is a silent miscompile -- an On assembly reading
module offsets resolved against the sub-model's Off layout, with no bad
id and no bad reference to notice. model_flows_invariant keeps its
overlay argument: a variable whose parse minted an instance can still be
classified invariant, so the walk genuinely reads overlay-keyed memos.

a_second_overlay_re_emits_only_the_module_reading_fragments measures the
narrowing from salsa's own execution events and the fragment compilers'
body log: the plain-loop fixture re-emits nothing (was 61 explicit
fragments) and the loop-through-a-module fixture re-emits smoothed and
its SMOOTH instance alone (was 67 explicit and 2 implicit), with the
expected set cross-derived by running the predicate over every model the
passes walk. a_fragment_reads_a_module_through_each_arm_of_the_rule rows
every arm for variables and helpers alike, and the constructors'
assertions ran over the whole engine suite -- 5,722 unit and 793
integration tests -- without firing.
@bpowers
bpowers merged commit d7cabaf into main Sep 6, 2026
18 checks passed
@bpowers
bpowers deleted the salsa-roofline-engine branch September 6, 2026 03:06
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

engine: compile_project_incremental deep-clones CompiledSimulation out of the Arc on every call

1 participant