Skip to content

engine: make implicit-helper identity a name, not a hash-ordered position - #1006

Merged
bpowers merged 7 commits into
mainfrom
ltm-1002-implicit-var-identity
Aug 2, 2026
Merged

bpowers merged 7 commits into
mainfrom
ltm-1002-implicit-var-identity

Conversation

@bpowers

@bpowers bpowers commented Aug 1, 2026

Copy link
Copy Markdown
Owner

Fixes #1002

A sub-model that instantiates a stdlib module over a bound input compiled or
failed depending on the process's HashMap seed. On a 30-line fixture, roughly
one run in five returned the unattributed failed to compile fragments for variables: $⁚sm⁚0⁚arg1, $⁚sm⁚0⁚smth1.

Root cause

Not the one the issue proposed. BuiltinVisitor accumulated its synthesized
SMOOTH/DELAY/TREND/PREVIOUS helpers in a HashMap and every producer of
ParsedVariableResult::implicit_vars emitted it with .values(). Rust draws a
fresh RandomState key per map, so two parses of one variable -- in the same
process, differing only in their ModuleIdentContext -- reported the helpers in
two different ORDERS. ImplicitVarMeta identified a helper by its POSITION in
that vector, and a position is meaningful only against the exact vector it was
taken from: model_implicit_var_info records it under the no-extra-idents
context while assembly resolves it under the context widened by the instance's
module-input names. When the two orders disagreed the position named an aux
where a module was expected, or the reverse; both fail to lower, so the
sub-model lost every helper fragment.

The fix

Two changes, in three production edits, kept together because they close
different properties.

Identity. ImplicitVarMeta::name replaces index_in_parent. A helper
resolves to itself or to nothing, never to another helper. find_in carries an
index_hint checked against the name before it is accepted, so the common case
stays O(1) (see Performance).

Order. BuiltinVisitor::vars is an IndexMap, and a new
elements_in_stable_order walks Ast::Arrayed's per-element slot map -- itself
a HashMap -- at both expansion sites. Without this the two salsa-cached
vectors carrying that order (ParsedVariableResult::implicit_vars,
VariableDeps::implicit_vars) still differ run to run, salsa stops backdating,
and the compiled artifact stops being reproducible -- the #595 class, invisible
in numeric results and in the compile outcome alike.

Also deletes LtmImplicitVarMeta::index_in_parent, which nothing read.

What gates what

Measured, not predicted: each edit was reverted alone, faithfully, and the suite
re-run three times. The matrix is in the test module header.

reverted reds
IndexMap all three order tests
elements_in_stable_order, per-element site per_element_… alone
elements_in_stable_order, shared-visitor site undimensioned_arrayed_… alone
identity an_implicit_helper_declines_… alone
the hint's name check an_implicit_helper_declines_…

The identity fix having one gating test is a property of the problem, not thin
coverage: with a stable order a positional index resolves correctly whenever
the two contexts synthesize the same helper set, so only a diverging-set fixture
can tell the two schemes apart.

Performance

find_in replaces an index lookup with a name match, which is O(k^2) per parent
variable, and k is not small on ordinary models -- an apply-to-all SMTH1 over
an N-element dimension mints ~2N helpers on ONE variable. Measured with two
release binaries (worktree at the parent commit vs. the branch), interleaved, on
x[Dim] = SMTH1(y[Dim], 3):

N main scan only with hint
200 0.08s 0.14s 0.08s
400 0.29s 0.53s 0.31s
600 0.64s 1.20s 0.65s
800 1.12s 2.13s 1.16s

C-LEARN is unmoved throughout (0.39s), which is why a C-LEARN-only check missed
the regression and why the synthetic is in the record.

Verification

Full pre-commit gate green on each commit. 5553 lib + 647 integration. The
#[ignore]d tier has exactly its seven pre-existing failures, name for name
against #915. The original reproduction is 0/12.

Three adversarial review rounds; the first found a live coverage gap this
originally shipped with (the shared-visitor call site had no test, and a
name-only probe was structurally blind to it because that arm keeps names
stable and moves only the binding), a tautological anti-vacuity guard, and two
wrong cells in the mutation matrix. All fixed, each with the demonstration in
the commit message.

Not closed by this PR

  • engine: sub-model implicit-var identity is nondeterministic under module-input parse contexts (HashMap-order index misalignment) #1002's second reported observable (a phantom module-input binding
    randomising implicit-helper diagnostics) does not reproduce, and the reason is
    structural: collect_all_diagnostics probes helpers with the empty input set
    AND derives them from model_implicit_var_info, which uses the same context,
    so no second context exists on that path. Kept as a guard test with that
    reasoning recorded, so it starts working if the probe is ever changed to use
    real instantiation input sets.
  • The cross-context helper-SET divergence. When the widened context
    synthesizes genuinely different helpers (PREVIOUS over a bound input whose
    port lacks access="input"), a model's layout and its runlists disagree about
    which helpers exist and the project fails to compile. Deterministic,
    pre-existing (verified byte-identical at the parent commit), and engine: decouple module-aware parse context from per-variable parse cache #372's
    territory. This PR only makes the mis-resolution loud instead of silent.
  • Repeated helper names with different bodies. An Arrayed element with its
    own init equation, or a variable with compat.active_initial, makes the
    initial parse read a different equation while the helper-naming counter
    restarts at zero -- so two bodies can claim one name, which
    model_implicit_var_info collapses and compute_layout gives one slot. Found
    while writing the tripwire, pre-existing, and disclosed on
    repeated_implicit_helper_names_carry_identical_helpers rather than fixed:
    the fix is a phase discriminator in the synthesized name.

🤖 Generated with Claude Code

https://claude.ai/code/session_01S3vQ72pUeYXdMgCv7sSjaB

bpowers added 3 commits August 1, 2026 14:10
…tion

A sub-model that instantiates a stdlib module over a bound input compiled
or failed depending on the process's HashMap seed: across identical runs of
one fixture, roughly one in five returned the unattributed "failed to
compile fragments for variables: $/sm/0/arg1, $/sm/0/smth1".

BuiltinVisitor accumulated its synthesized SMOOTH/DELAY/TREND/PREVIOUS
helpers in a HashMap and every producer of implicit_vars emitted it with
.values(). Rust draws a fresh RandomState key per map, so two parses of the
SAME variable -- in one process, differing only in their ModuleIdentContext
-- reported the helpers in two different orders. ImplicitVarMeta identified
a helper by its POSITION in that vector, and a position is meaningful only
against the exact vector it was taken from: model_implicit_var_info records
it under the no-extra-idents context while assembly resolves it under the
context widened by the instance's module-input names. When the two orders
disagreed, the position named an aux where a module was expected or the
reverse; both fail to lower, so the sub-model lost every helper fragment.

Two fixes, kept together because they close different properties. IDENTITY:
ImplicitVarMeta carries the helper's canonical name and resolves by it, so a
helper resolves to itself or to nothing and a compile outcome no longer
depends on any ordering. ORDER: BuiltinVisitor::vars is an IndexMap and
elements_in_stable_order walks an Ast::Arrayed slot map -- itself a HashMap
-- in a stable order, so the two salsa-cached vectors carrying that order
(ParsedVariableResult::implicit_vars, VariableDeps::implicit_vars) equal
their own recomputation. Without the second, salsa stops backdating and the
compiled artifact is irreproducible, which no numeric result and no compile
outcome would have shown.

Which test gates which fix is measured rather than predicted: each was
reverted alone and the suite re-run, and the results are recorded in the
test module's header. Also deletes LtmImplicitVarMeta::index_in_parent,
which nothing read -- the same footgun sitting next to the fixed one.

One shape stays broken and is disclosed rather than implied: when the
widened context synthesizes a genuinely DIFFERENT helper set (PREVIOUS over
a bound input whose port carries no access="input"), the model's layout and
its runlists disagree about which helpers exist and the project fails to
compile. That is deterministic and pre-existing -- verified byte-identical
at the parent commit -- and its fix is GH #372's explicit model-level parse
context. What changes here is only that the mis-resolution is loud.

C-LEARN compile+run is unmoved at 0.44s; the ignored tier still has exactly
its seven pre-existing failures (#915), name for name.
Four corrections from an adversarial review of the parent commit, three of
which were wrong claims rather than wrong code.

The load-bearing one is a real coverage gap. `elements_in_stable_order`'s
rustdoc said its second call site -- the arm where one visitor spans every
slot -- was inert and reachable only when a declared dimension failed to
resolve. Both halves were false. A failed dimension lookup yields no AST at
all; the live route is an EMPTY dimension list, which `xmile::variables`
mints for any `<aux>` carrying `<element subscript=...>` children with no
`<dimensions>` sibling. Such a model compiles, and reverting that call site
re-binds which slot's equation each helper name carries. Nothing caught it:
the mutation left the whole 5551-test suite green.

It went uncaught because the probe compared helper NAMES, and names are the
one thing that arm keeps stable -- its counter is monotonic, so it emits
0, 1, 2 however the slots are walked, and only the BINDING moves. The probe
now renders each helper's equation too, and the mutation is caught 3 of 3.
The new fixture is read through the real XMILE reader rather than
hand-built, since the shape is only interesting because production mints it.

Two claims in the test module's mutation matrix were wrong, both because
the original mutation was over-strong (it made `find_in` return the first
helper unconditionally, where a faithful revert restores `index_in_parent`
and indexes with it). Re-measured, three runs each: reverting the IndexMap
reds all three order tests, not one; reverting identity reds ONE test, not
three. The corrected matrix now records why that is a property of the
problem rather than thin coverage -- with a stable order, a positional
index resolves correctly whenever the two parse contexts synthesize the
same helper set, so only a diverging-set fixture can tell the two identity
schemes apart.

The anti-vacuity guard on both sub-model tests was a tautology: it
round-tripped a literal `["port"]` through `ModuleInputSet` and compared it
to itself, reading nothing from the fixture. Both now take the input set
from production's own `enumerate_module_instances`, via a `#[cfg(test)]`
accessor mirroring `db::dep_graph`'s idiom. Verified by degrading the
fixture's wiring to `x_module("sub", &[], None)`: the old guard stayed
silent and every test passed, the new one reds both tests.

Also: `an_implicit_helper_resolves_to_its_own_name_...` was a single-sample
probabilistic detector in a file built on repetition, and missed the
pre-fix defect 45% of the time; it now runs REPEATS times. `find_in` grew
an index HINT, checked against the name before it is accepted, because the
scan alone is O(k^2) per parent and k is not small on ordinary models -- an
apply-to-all SMTH1 over N elements mints ~2N helpers on one variable, and
at N=800 the scan cost 2.13s against the parent's 1.12s. With the hint,
1.16s. Dropping the hint's name check restores positional identity and reds
the identity test, so the optimization is gated. Corrects a dangling
reference to a `walk_module_call` that does not exist, and drops a
`dedup_vars_by_ident` parenthetical that was still wrong after the parent
commit edited it -- layout iterates a name-keyed map, so duplicate names
collapse to one slot rather than colliding into several.
Writing a tripwire for the index hint's soundness argument disproved the
argument. The hint is still correct; the reason stated for it was not.

The claim was that at most one helper in a parse can carry a given name, so
accepting a name-checked hint must return what a scan would. That is false:
`parse_var_with_module_context` runs `parse_and_lower_eqn` twice over one
variable -- dt phase and initial phase -- and each appends to the same
vector. A `Scalar`/`ApplyToAll` initial pass returns nothing unless the
variable carries an ACTIVE INITIAL, so those do not repeat; the `Arrayed`
arm has no such early-out and re-parses every slot, so each helper of a
per-element variable appears exactly twice.

What that means here is narrow and now written down where it belongs.
`find_in` is sound regardless -- the name check makes it structurally unable
to return another helper. Where hint and scan can diverge is between
EQUALLY-named entries: the hint takes the last (which is what the
name-keyed, last-wins `model_implicit_var_info` recorded, and what
`index_in_parent` selected before this branch), the scan takes the first.
They are interchangeable exactly while repeated names carry identical
helpers, so that is what the test asserts, over five fixtures covering all
five routes into `implicit_vars`.

Worth stating because the branch briefly got this wrong in the other
direction: the parent commit's scan-only `find_in` selected the FIRST
occurrence, silently reversing a choice main had made. The hint restores
main's selection, so the shipped behaviour is unchanged either way -- but
that was luck rather than design until now.

Two pre-existing shapes can make a repeated name carry DIFFERENT helpers,
and both are disclosed on the test rather than fixed here: an `Arrayed`
element with its own init equation, and a variable with
`compat.active_initial`. Both make the initial pass parse a different
equation while the helper-naming counter restarts at zero, so two bodies can
claim one name -- which `model_implicit_var_info` collapses to one entry and
`compute_layout` gives one slot. The fix for that is a phase discriminator
in the synthesized name, not a change to `find_in`, and it is a defect of
its own rather than part of GH #1002.
@claude

claude Bot commented Aug 1, 2026

Copy link
Copy Markdown

[P3] Doc comment for enumerate_module_instances mislaid onto the new test-only accessor

File: src/simlin-engine/src/db/assemble.rs:2156-2170

Inserting module_input_sets_for before enumerate_module_instances left the original three-line doc comment (`/// Enumerate all module instances in a project, starting from the main model. …`) attached to the new function, so `module_input_sets_for` now has two stacked doc paragraphs (the first describing a different function) and `enumerate_module_instances` has no rustdoc at all. Small readability / maintainability regression per the `Preserve useful comments/docstrings when refactoring` rule in `CLAUDE.md`; the fix is to move the three original lines below the new function so they hang off `enumerate_module_instances` again.


Overall correctness verdict

Correct. The identity+order fix is well-scoped and each production edit is covered by a test whose gating is measured, not assumed. find_in is sound in both branches (hint accepted only when name matches; scan fallback preserves the name-only guarantee), and every remaining reader of parsed.implicit_vars either iterates the whole list or goes through find_in. IndexMap swap and elements_in_stable_order cover both call sites in instantiate_implicit_modules. The removed LtmImplicitVarMeta::index_in_parent had no readers. PartialEq still includes index_hint, so a future ordering regression is loud (wasteful recomputation) rather than silent — an acceptable canary given the stabilization already in place. No blocking bugs found.

@codecov

codecov Bot commented Aug 1, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 94.59459% with 4 lines in your changes missing coverage. Please review.
✅ Project coverage is 91.86%. Comparing base (d5db88a) to head (19acb6b).
⚠️ Report is 2 commits behind head on main.

Files with missing lines Patch % Lines
src/simlin-engine/src/db/query.rs 77.77% 4 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main    #1006      +/-   ##
==========================================
- Coverage   91.86%   91.86%   -0.01%     
==========================================
  Files         247      247              
  Lines      159174   159225      +51     
==========================================
+ Hits       146224   146267      +43     
- Misses      12950    12958       +8     

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

@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: 07e46f5402

ℹ️ 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".

&self,
parsed: &'a ParsedVariableResult,
) -> Option<&'a datamodel::Variable> {
let is_mine = |v: &datamodel::Variable| canonicalize(v.get_ident()) == self.name;

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 Make helper names independent of synthesis counters

When the instance context inserts a helper before an existing expression helper—for example, PREVIOUS(port, 0) + SMTH1(port + 1, 3) with port bound as a module input—the no-input SMTH argument and the widened PREVIOUS capture are both named $⁚sm⁚0⁚arg0. This predicate therefore accepts the newly inserted capture as the metadata's helper, returning the wrong fragment instead of the promised self-or-none result. Use a context-stable structural identity (or verify the stored helper content), and cover this name-collision arm in the determinism tests.

AGENTS.md reference: AGENTS.md:L97-L99

Useful? React with 👍 / 👎.

Comment on lines +423 to +427
/// Two shapes could break it, both PRE-EXISTING and neither in scope here: an
/// `Arrayed` element carrying its own `<init_eqn>`, and a `Scalar`/`ApplyToAll`
/// variable carrying `compat.active_initial`. Both make the initial pass parse
/// a DIFFERENT equation while `BuiltinVisitor`'s `n` counter restarts at zero,
/// so the two passes can mint the same helper NAME for different bodies --

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Give initial-phase helpers distinct names

For an Arrayed element with its own <init_eqn> or a variable using compat.active_initial, the flow and initial passes parse different equations while restarting the naming counter, so different helpers receive the same name; model_implicit_var_info then collapses them to one slot and one phase can silently execute the other phase's helper body. The new test deliberately excludes exactly these rows that falsify its universal invariant, so phase-qualify the synthesized names and add both cases rather than leaving this known result-corruption path green.

AGENTS.md reference: AGENTS.md:L97-L99

Useful? React with 👍 / 👎.

…e-stability claim

Three findings from automated review of the branch. Two are real defects in
what the branch CLAIMED; one is a pre-existing silent-corruption path the
claim led straight to.

**A variable's two parse phases could mint one helper name for two bodies.**
`parse_var_with_module_context` runs `parse_and_lower_eqn` twice -- dt phase
and initial phase -- and both name their helpers from a counter that restarts
at zero. When the initial pass reads a DIFFERENT equation (an `Arrayed`
element's own init equation, or `compat.active_initial`) the two passes mint
the same name for different bodies. `model_implicit_var_info` is name-keyed
and `compute_layout` allocates one slot per name, so one body was discarded
in silence and a phase ran the other phase's helper.

Verified silent, not theoretical: an aux with equation `SMTH1(driver * 2, 3)`
and ACTIVE INITIAL `SMTH1(driver * 100, 7)` COMPILED, keeping only the
initial pass's `$⁚v⁚0⁚arg0`, so the dt phase smoothed the wrong expression.
The append is now a MERGE with `dedup_vars_by_ident`'s rule applied across the
phases: a byte-identical repeat collapses (the `Arrayed` arm re-parses every
slot on the initial pass, so that is the common case and it also halves the
redundant entries), and a genuine collision is a loud `DuplicateVariable`.
Refusal rather than repair -- making the shape WORK needs a phase
discriminator in every synthesized helper name, which changes every helper's
identity and is its own change. Loud rejection is the choice
`dedup_vars_by_ident` already makes for the within-one-pass twin.

Blast radius measured, not assumed: the whole engine suite is green,
`simulates_clearn` included, and ACTIVE INITIAL appears in both C-LEARN and
WRLD3 -- so the shape the merge refuses does not occur in the corpus.

**A helper name is not the context-stable identity the branch claimed.**
"Resolves to itself or to nothing, never to another helper" is false. Names
embed the visitor's walk counter, so a context that inserts an EARLIER helper
renames every later one: for `PREVIOUS(port, 0) + SMTH1(port + 1, 3)` over a
bound `port`, the no-extra-idents parse calls `$⁚sm⁚0⁚arg0` the SMTH argument
and the widened parse calls it the PREVIOUS capture. The claim is corrected
wherever it was made, and the residual is bounded instead of hand-waved: such
a collision REQUIRES the two parses to synthesize different helper sequences,
which is the same condition that makes layout disagree with runlists, so the
project fails to compile before a mis-resolved fragment could run. Both halves
-- the collision and the failing compile -- are pinned in one test, so if the
compile ever starts succeeding the mis-resolution stops being harmless and
something says so. Context-stable naming is GH #372's.

The test whose premise this changes flipped with it: helper names within one
parse are unique again, now because the merge enforces it rather than because
it was assumed.

Also moves `enumerate_module_instances`' rustdoc back onto it -- inserting the
test-only accessor above it had left the doc on the accessor and the function
undocumented.
@bpowers

bpowers commented Aug 1, 2026

Copy link
Copy Markdown
Owner Author

All three findings were real. Verified each against a fixture before changing anything; two of them falsified claims this PR was making.

P1 — phase-collided helper names (confirmed, and it was silent). An aux with equation SMTH1(driver * 2, 3) and ACTIVE INITIAL SMTH1(driver * 100, 7) compiled, keeping only the initial pass's $⁚v⁚0⁚arg0, so the dt phase smoothed the wrong expression. Both passes name from a counter that restarts at zero, model_implicit_var_info is name-keyed, and compute_layout gives one slot per name.

Fixed by merging helpers across the two phases instead of appending, with dedup_vars_by_ident's rule: a byte-identical repeat collapses (the Arrayed arm re-parses every slot, so that is the common case — it also halves the redundant entries), a genuine collision is a loud DuplicateVariable.

Refusal rather than repair, deliberately. Phase-qualifying every synthesized helper name changes every helper's identity and its layout slot; that is its own change. Loud rejection is the choice dedup_vars_by_ident already makes for the within-one-pass twin of this collision. Blast radius measured rather than assumed: full engine suite green including simulates_clearn, heavy #[ignore]d tier unchanged at its 7 pre-existing failures — and ACTIVE INITIAL appears in both C-LEARN and WRLD3, so the refused shape genuinely does not occur in the corpus.

One note on the fixture, since it nearly fooled me: my first version used a different variable in each equation, and that failed to compile even before the fix — for an unrelated reason (the discarded helper's dependency was missing from the survivor's dep set). It would have passed against the defect it was meant to catch. The committed fixture has both equations reference the same variable.

P2 — names are not context-stable (confirmed; the PR's claim was wrong). Reproduced exactly as described: for PREVIOUS(port, 0) + SMTH1(port + 1, 3) over a bound port, $⁚sm⁚0⁚arg0 is the SMTH argument in the no-extra-idents parse and the PREVIOUS capture in the widened one. So "resolves to itself or to nothing, never to another helper" is false, and it is corrected everywhere it was stated.

I did not adopt the suggested structural identity, and here is the reasoning rather than a dismissal. The collision requires the two parses to synthesize different helper sequences — which is the same condition that makes the model's layout disagree with its runlists, so the project fails to compile before any mis-resolved fragment can run. I verified that: the fixture returns Err(failed to compile fragments…). Both halves are now pinned in one test, so if that compile ever starts succeeding, the mis-resolution stops being harmless and something reds. Making the names themselves context-stable is #372's explicit model-level parse context, not a local change here.

P3 (from the other reviewer) — enumerate_module_instances' rustdoc left on the new test-only accessor. Fixed; the doc is back on the function it describes.

Also worth recording against an earlier round: a reviewer reported a perf regression on find_in, then retracted it after an interleaved A/B. The retraction was wrong. Two release binaries in worktrees, interleaved, x[Dim] = SMTH1(y[Dim], 3): at N=800 the scan-only version took 2.13s against main's 1.12s. That is why find_in carries a name-checked index_hint (1.16s), and why dropping the hint's name check reds the identity test.

@codex review

@claude

claude Bot commented Aug 1, 2026

Copy link
Copy Markdown

Code review findings

[P2] Broken doc reference and stale premise in ImplicitVarMeta::index_hint doc

File: src/simlin-engine/src/db/query.rs:486-495

The rustdoc on index_hint describes a "One subtlety" where implicit_vars "can REPEAT a name, since an Arrayed equation is parsed once per phase and both passes append", and cites db::fragment_determinism_tests::repeated_implicit_helper_names_carry_identical_helpers as pinning that repeats carry identical content.

Two issues:

  1. The cited test does not exist. A repo-wide grep for repeated_implicit_helper_names_carry_identical_helpers matches only this docstring — the PR body also cites it ("disclosed on ... rather than fixed"), but nothing was added under that name. A reviewer following the citation to understand find_in's hint-vs-scan divergence guarantee will find nothing.

  2. The described "repeat" case cannot occur after the variable.rs merge in this PR. The merge in parse_var_with_module_context (src/simlin-engine/src/variable.rs:970-995) explicitly prevents both duplication and different-body collision across the dt and initial phases (byte-identical dupes collapse, different bodies push a DuplicateVariable error and skip the push). dedup_vars_by_ident handles within-one-pass dedup. So implicit_vars no longer contains duplicate names, and the "hint points at LAST occurrence, scan returns FIRST" divergence described in the doc has no reachable input.

Either the paragraph should be updated to reflect that the merge closes this case (and delete the dangling test reference), or the missing test should be added and the merge's contract explicitly stated.

@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: 7ba78dc9ec

ℹ️ 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".

/// and is its own change. A loud error is the same choice `dedup_vars_by_ident`
/// already makes for the within-one-pass twin of this collision.
#[test]
fn an_active_initial_that_collides_a_helper_name_is_refused() {

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Cover all cross-phase collision routes

Fresh evidence in this target is that this regression test constructs only a scalar aux using compat.active_initial, while parse_equation has distinct ApplyToAll active-initial and Arrayed per-element init_eqn routes, both explicitly identified as collision sources in the added documentation. implicit_helper_names_are_unique_within_one_parse exercises those variants only with identical phase bodies, so it cannot prove the new DuplicateVariable refusal for them; a regression limited to either route could restore silent phase-body substitution while the suite remains green. Add collision rows for both remaining equation variants or document where each is covered.

AGENTS.md reference: AGENTS.md:L97-L97

Useful? React with 👍 / 👎.

Comment thread src/simlin-engine/src/variable.rs Outdated
Comment on lines +976 to +978
match implicit_vars
.iter()
.find(|v| Ident::<Canonical>::new(v.get_ident()) == ident)

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 Keep cross-phase deduplication linear

When an arrayed equation synthesizes k distinct helpers—for example, SMTH1 over an N-element dimension yields roughly 2N—this lookup scans every previously inserted helper for every new helper. The first phase therefore already performs O(k²) identifier canonicalizations, and the initial phase repeats the scan for its duplicates, replacing the previous linear append path with quadratic parsing before the layout-size guard runs. This becomes prohibitive for dimensions in the thousands; maintain a name-to-index map or reuse a hash-based linear deduplication pass instead.

Useful? React with 👍 / 👎.

module_ident_context,
);
let implicit_dm_var = parsed.implicit_vars.get(meta.index_in_parent)?;
let implicit_dm_var = meta.find_in(parsed)?;

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Update the remaining positional-identity documentation

The name-based lookup introduced here leaves this function's production contract describing parent → parsed.implicit_vars[index] and saying that None means an implicit index is absent; the corresponding comments in assemble.rs still describe the same positional relation. Those statements are now false because find_in verifies the hint and may scan by canonical name, with None meaning that name is absent from the selected parse. Update these nearby contracts so future callers do not reintroduce positional assumptions while following the documented lowering path.

AGENTS.md reference: AGENTS.md:L118-L118

Useful? React with 👍 / 👎.

Round-2 review, on top of the cross-phase merge that the reviewer had not
seen. Two of its three items were already closed by that merge but left the
docs asserting the opposite; the third is a real blind spot in a test probe.

The `index_hint` rustdoc claimed a wrong hint "cannot change the answer",
then immediately qualified it with a paragraph saying a name is NOT unique
within a parse -- so the claim was false and the qualification was the
reason. The merge made the claim true, and both halves of the doc were
stale: it still described the duplicates it now prevents, and cited the
uniqueness test by a name that no longer exists. It now states the
PRECONDITION (no two entries of one parse share a name), says what
establishes it, and names the test that checks it -- and it separates that
WITHIN-parse property from the cross-parse residual on `name`, which is a
different thing and stays.

The same review re-ran the performance question with three genuinely
distinct binaries, having found that its earlier retraction came from
sharing one `CARGO_TARGET_DIR` across worktrees -- cargo never rebuilt, so
every "interleaved" number was one binary measured against itself. Its clean
run reproduces the regression and its instrumentation settles the
algorithmic claim without a clock: at N=800 the scan examines 17,289,600
entries against the hint's 14,400, a 1200x reduction, at a 100% hit rate on
C-LEARN, WRLD3, scirev7 and the synthetic. That is now the doc's evidence,
with the wall clock kept as the secondary number it is.

`implicit_helper_signatures` rendered `get_equation()`, which is `None` for a
`Variable::Module` -- so for exactly the helper kind carrying the WIRING the
signature degenerated to the bare name, and a mutation re-binding which
module reads which argument helper would have been invisible. Modules now
render their model name and references. The doc also records what the probe
is still weaker than (the compiled artifact, which differs on 21 of 23
repeats under the same mutation) so the next person can reach for the
stronger one deliberately.

`an_active_initial_that_collides_a_helper_name_is_refused` grew the
reviewer's spelling as a second arm. Only the same-dependency arm gates the
merge -- the disjoint-dependency one fails without it too, for an unrelated
dep-set reason -- and the doc now says which is which, so nobody later
deletes the arm that does the work. `ImplicitVarMeta`'s `Debug` renders
`index_hint`, since a wrong hint is precisely what someone reads that for.
@bpowers

bpowers commented Aug 2, 2026

Copy link
Copy Markdown
Owner Author

Follow-up review round landed as 60d14d25. Two of its findings were already closed by 7ba78dc9 (pushed after the reviewed commit) but had left the docs asserting the opposite; one was a genuine blind spot in a test probe.

The index_hint doc claimed something false and then explained why it was false. It said a wrong hint "cannot change the answer", then two paragraphs later noted that a name is not unique within a parse — which is exactly the missing precondition. 7ba78dc9's cross-phase merge makes names unique, so the claim is now true; the doc now states the precondition, what establishes it, and the test that checks it, and separates that within-parse property from the cross-parse residual, which is a different thing and stays. It also cited a test by a name I'd since renamed.

The dedup_vars_by_ident hole was the same defect, and is closed by the same merge — its guarantee ran inside one instantiate_implicit_modules call while the dt/init append happened above it, so a colliding pair was never seen by it. The reviewer's fixture is now a second arm of the regression test, with the doc recording that only the same-dependency arm gates the fix (theirs fails without it too, for an unrelated dep-set reason) so nobody later deletes the load-bearing one.

Adopted: implicit_helper_signatures had a named blind spot. Variable::Module has no equation, so {:?} degenerated to the bare name for exactly the helper kind carrying the wiring — a mutation re-binding which module reads which argument helper would have been invisible. Modules now render model name and references. The doc records that the compiled artifact is still strictly stronger (differs on 21 of 23 repeats under the same mutation), so the next person can reach for it deliberately rather than assuming this probe is the ceiling.

On the performance disagreement, now settled — and the resolution is worth recording for anyone doing A/B work in this repo. The earlier retraction came from sharing one CARGO_TARGET_DIR across git worktrees: cargo produced one artifact path and never rebuilt on switching, so every "interleaved main vs branch" measurement was one binary compared against itself. A clean run with three distinct binaries reproduces the regression (+53%/+60%/+63% at N=200/400/800, C-LEARN unmoved) and confirms the index_hint removes it.

Better still, it settles the algorithmic claim without a clock: instrumenting the scan, N=800 examines 17,289,600 entries without the hint and 14,400 with it — a 1200x reduction — at a 100% hit rate on C-LEARN, WRLD3, scirev7 and the synthetic. That is now the doc's primary evidence, with wall-clock kept as the secondary number it is.

Full pre-commit gate green on each commit; heavy #[ignore]d tier still at its 7 pre-existing failures, name for name.

@codex review

@claude

claude Bot commented Aug 2, 2026

Copy link
Copy Markdown

Review of PR #1006

I traced through the four production edits (BuiltinVisitor::vars → IndexMap, elements_in_stable_order at two call sites, ImplicitVarMeta::name/index_hint/find_in, and the cross-phase merge in variable::parse_var_with_module_context) plus the removal of LtmImplicitVarMeta::index_in_parent and the three call sites that now use meta.find_in(parsed).

Correctness checks I completed:

  • find_in verifies the hint's name before accepting it, so a stale hint can only ever return a helper with the correct name or None — the residual case (cross-context name collision) is bounded by the "project fails to compile before any mis-resolved fragment runs" argument, which the new a_cross_context_helper_name_collision_is_confined_to_a_failing_compile test enforces.
  • The cross-phase merge in variable.rs:974-996 correctly enforces uniqueness within parsed.implicit_vars, which is the precondition the hint-vs-scan tie-break relies on (implicit_helper_names_are_unique_within_one_parse).
  • The IndexMap insertion order is a function of the AST walk (four self.vars.insert(...) sites in builtins_visitor.rs), so it is stable across processes.
  • elements_in_stable_order sorts by CanonicalElementName, which is deterministic because the source HashMap's keys are unique.
  • DuplicateVariable with start: 0, end: 0 matches the existing usage pattern in db/diagnostic.rs.
  • The LtmImplicitVarMeta::index_in_parent deletion is safe — the LTM code stores the full variable: implicit_dm_var.clone() and doesn't need a position.

Overall correctness verdict: correct. The fix is well-scoped, the measured gating matrix in the test module header persuasively shows each edit is load-bearing, and the honest disclosure of the two residuals (a_cross_context_helper_name_collision_is_confined_to_a_failing_compile, repeated_implicit_helper_names_carry_identical_helpers) plus the phantom-input guard test are appropriately scoped for a follow-up rather than expanding this PR. No blocking issues found.

…utes

Three more findings from automated review, all real, and one of them a
regression the previous commit introduced.

**The cross-phase merge was O(k^2) -- the same shape it had just removed
elsewhere.** Scanning `implicit_vars` for each incoming helper costs a
canonicalize-and-intern per comparison, and `k` is ~2N for an apply-to-all
`SMTH1` over an N-element dimension. Worse, `model::ModelStage0` threads ONE
vector across every variable of a model, so each variable paid for every
helper minted before it. Measured against the previous commit with separate
target directories: N=800 went 1.18s -> 1.51s, about +30%. A name->index map,
seeded empty and grown as helpers are pushed, brings it back to 1.14s.

Seeded empty rather than from the caller's vector, and that is the point: only
helpers of the same PARENT can collide, since a synthesized name embeds its
parent's ident and two parents sharing a canonical name is already a
`DuplicateVariable` model error. Seeding from the shared vector would have
reproduced the model-wide quadratic the map exists to remove.

**The collision test covered one of three routes.** `parse_equation` has
exactly three arms that can make the initial pass read a different equation
than the dt pass -- `Scalar`+`active_initial`, `ApplyToAll`+`active_initial`,
and `Arrayed` with a per-element init equation -- and the test had only the
first. Enumerating the arms rather than sampling one was not academic: with
the merge reverted, THREE of the four rows now present compile and silently
drop a helper body. A regression confined to the `ApplyToAll` or `Arrayed`
route would have left the old test green. The doc records which row gates
what, since `scalar_disjoint_dep` fails without the merge too for an
unrelated dep-set reason and must not be mistaken for one that does the work.
The loop also reports every failing row at once instead of stopping at the
first, because the routes are independent and which one regressed is the
signal.

**Stale positional contracts.** `lower_implicit_var`'s rustdoc still described
the chain as `parent -> parsed.implicit_vars[index]` and said `None` meant an
absent index; `assemble.rs` carried the same prose in two more places. All
three now describe resolution by name, so nobody reintroduces a positional
assumption by following the documented path.

@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: 60d14d2538

ℹ️ 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 on lines +323 to +324
// Identity makes a helper resolve to itself or to nothing, so no compile
// outcome depends on any ordering. Order makes the two salsa-cached vectors

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 Correct the identity guarantee in the test header

This still says name-based identity can resolve only the intended helper or nothing, but a_cross_context_helper_name_collision_is_confined_to_a_failing_compile and the updated ImplicitVarMeta::name docs establish that, when a widened module context inserts an earlier capture, the same counter-derived name can resolve a different helper; the existing compile failure merely bounds the damage. Restate that residual here so future mutation work does not rely on the false invariant.

AGENTS.md reference: AGENTS.md:L115-L118

Useful? React with 👍 / 👎.

@bpowers

bpowers commented Aug 2, 2026

Copy link
Copy Markdown
Owner Author

All three findings were real, and one of them was a regression the previous commit introduced. Fixed in 28a26218.

P2 — the cross-phase merge was O(k²), the same shape it had just removed elsewhere. Confirmed by measurement. Scanning implicit_vars per incoming helper costs a canonicalize-and-intern per comparison, and k is ~2N for an apply-to-all SMTH1 over an N-element dimension. Worse than the local quadratic: model::ModelStage0 threads one vector across every variable of a model, so each variable was paying for every helper minted before it.

Measured against the previous commit, separate target dirs, interleaved:

N pre-merge with merge with index
400 0.30s 0.42s 0.30s
800 1.18s 1.51s 1.14s

A name→index map, seeded empty and grown as helpers are pushed, removes it. Seeded empty deliberately: only helpers of the same parent can collide (a synthesized name embeds its parent's ident, and two parents sharing a canonical name is already a DuplicateVariable error), so seeding from the shared vector would have reproduced the model-wide quadratic the map exists to remove.

P1 — the collision test covered one of three routes. This was the most valuable of the three findings. parse_equation has exactly three arms that can make the initial pass read a different equation than the dt pass, and I had tested one. Enumerating them was not academic: with the merge reverted, three of the four rows now present compile and silently drop a helper body — scalar_same_dep, apply_to_all, and arrayed_per_element_init. A regression confined to the ApplyToAll or Arrayed route would have left the old test green, and two live silent-corruption routes were uncovered.

The doc now records which row gates what, because scalar_disjoint_dep fails without the merge too (unrelated dep-set reason) and must not be mistaken for one that does the work. The loop reports every failing row at once rather than stopping at the first, since the routes are independent.

P1 — stale positional contracts. lower_implicit_var's rustdoc still described the chain as parent → parsed.implicit_vars[index] with None meaning an absent index, and assemble.rs carried the same prose twice more. All now describe resolution by name, so nobody reintroduces a positional assumption by following the documented path.

Full pre-commit gate green; heavy #[ignore]d tier still at its 7 pre-existing failures.

One note on methodology, since it bit an earlier round of this review badly enough to invert a conclusion: worktree A/B in this repo needs a separate CARGO_TARGET_DIR per worktree. A shared one makes cargo emit a single artifact path and skip the rebuild on switching, so the comparison silently measures one binary against itself. The numbers above were taken with distinct target dirs and md5-verified distinct binaries.

@codex review

@claude

claude Bot commented Aug 2, 2026

Copy link
Copy Markdown

Review

I reviewed the three production changes and the test coverage.

Findings: none. The change is correct on the axes I examined:

  • elements_in_stable_order sorts by CanonicalElementName (which has a proper Ord via CanonicalStorage) and is applied at both Ast::Arrayed call sites; the per-element path preserves determinism via SubscriptIterator iteration.
  • vars: IndexMap preserves the visitor's synthesis order, which the two salsa-cached vectors (ParsedVariableResult::implicit_vars, VariableDeps::implicit_vars) ride into cache-equality.
  • ImplicitVarMeta::find_in with index_hint is a pure optimization: the name check gates the fast path, and the fallback scan returns None when nothing matches — so a stale hint costs one comparison and cannot yield a wrong helper. The Cow<str> == String comparison in is_mine works via std's PartialEq<String> for Cow<'_, str>.
  • The cross-phase MERGE in parse_var_with_module_context correctly collapses byte-identical repeats and refuses genuine collisions with DuplicateVariable. implicit_index is a per-parent local map, and safety across the shared caller vector rests on the guarantee that helper names embed the parent ident ($⁚{parent}⁚{n}⁚…), which is enforced upstream by DuplicateVariable at the parent level.
  • LtmImplicitVarMeta::index_in_parent removal is a clean deletion — the LTM compile path reads the helper directly from meta.variable and never resolved by index.

The revert matrix in the test module header, cross-checked against each edit, is unusually thorough — including the enumeration of the three phase-collision routes (scalar_same_dep, apply_to_all, arrayed_per_element_init) with the discriminator row (scalar_disjoint_dep) called out as non-gating.

Overall verdict: correct.

@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: 28a262184f

ℹ️ 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".

/// names a different variable in the widened parse than it did in the parse
/// identity was derived from, deterministically. Positional identity therefore
/// produced a fragment whose `ident` was `$⁚sm⁚0⁚arg0` filed under the key
/// `$⁚sm⁚0⁚arg1`. A name resolves to its own helper or to nothing.

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 Remove the remaining self-or-none identity claim

Fresh evidence after the earlier header correction is the new a_cross_context_helper_name_collision_is_confined_to_a_failing_compile test: when two parse contexts assign the same counter-derived name to different bodies, find_in checks only that name and can return the unintended helper. Thus this sentence still states the false self-or-none contract; the order-test failure text at line 774 likewise still says identity is positional. Update both to describe the actual bounded guarantee so future work does not rely on an invariant this commit disproves.

AGENTS.md reference: AGENTS.md:L115-L118

Useful? React with 👍 / 👎.

@bpowers

bpowers commented Aug 2, 2026

Copy link
Copy Markdown
Owner Author

Two verifications worth recording, both reproduced independently after a reviewer raised them. No code changes; 28a26218 stands.

The branch carries no net regression against main. All the performance numbers in this thread so far have been commit-to-commit (1.18 → 1.51 → 1.14), which shows each step is sound but structurally cannot see cumulative drift — four commits each landing "back to about where we were" can still sit above main. Measured directly, fresh worktree at d5db88a3 with its own target dir, md5-verified distinct binaries, 3 interleaved rounds:

model main d5db88a3 head 28a26218
N=200 0.08s 0.08s
N=400 0.30s 0.30s
N=800 1.12s 1.12s
C-LEARN 0.39s 0.38s

The new refusal rejects nothing in the corpus — checked the strong way. "The engine suite is green" was the weaker evidence for this, because the suite only compiles a subset of test/, and a newly-added compile rejection is exactly the change where an un-compiled corpus model could break with nothing noticing. So: every model file under test/ — all 506 .stmx/.xmile/.itmx/.mdl — compiled with both binaries, outcomes diffed.

compile-outcome differences main -> 28a26218:   0 of 506
models emitting a duplicate_variable diagnostic: 0 on main, 0 on head

On landing that census as a test: deliberately not doing it, and the reason is #915. Nothing in pre-commit or CI runs the #[ignore]d tier — that is what #915 tracks — and it currently carries 7 unnoticed failures. A ratchet placed there would read as protection while never executing, which is precisely the failure mode this branch has spent four rounds correcting in its own tests. The honest version of that gate wants #915 fixed first, which is not this PR's scope. The evidence is recorded here instead.

One methodology note that inverted a conclusion earlier in this review and is worth the next person not rediscovering: worktree A/B in this repo needs a separate CARGO_TARGET_DIR per worktree. A shared one makes cargo emit a single artifact path and skip the rebuild on switching, so the comparison silently measures one binary against itself — and the tight agreement that produces looks exactly like evidence of no regression.

Correcting a false claim at the site it was argued is not the same as
correcting it. Three copies of "resolves to itself or to nothing, never to
another helper" outlived the commit that disproved it -- the test module's
header, one assertion message, and one comment -- and a fourth statement,
in the order test's failure text, still described identity as positional,
which it stopped being two commits earlier.

The header now says what name-based identity actually buys (no compile
outcome depends on the vector's ORDER) and, in its own paragraph, what it
does not: a name embeds the visitor's walk counter, so two parse contexts
can attach one name to two different helpers. It names the test that builds
that case and the failing compile that bounds it, and says outright not to
build mutation work on the stronger invariant.

The assertion message was the worst of the three, because it fires while
someone is debugging: it told them a helper "must resolve to itself or to
nothing" at exactly the moment that is the thing in question. It now states
the property the check actually verifies -- a fragment carries the name it
was resolved by -- and points at the test that owns the rest.

The order test's failure text described the mechanism as it was BEFORE the
identity fix. It now leads with the reason the order still matters (two
salsa-cached values with derived `PartialEq`, so an unstable order defeats
backdating) and keeps the positional history as history, which is where the
seed-dependence came from and is worth a reader knowing.

No behaviour change; every one of these is a string.
@bpowers

bpowers commented Aug 2, 2026

Copy link
Copy Markdown
Owner Author

Both real, both fixed in 19acb6bc. No behaviour change — every one of these is a string.

Correcting a false claim at the site where it was argued is not the same as correcting it, and that is the mistake here. When I corrected "resolves to itself or to nothing, never to another helper" on ImplicitVarMeta::name, three copies of it outlived the correction — the test module header, an assertion message, and a comment — plus a fourth statement in the order test's failure text still describing identity as positional, which it stopped being two commits earlier. Grepped for the phrasings this time rather than fixing the one I remembered writing.

The assertion message was the worst of the four, because it fires while someone is debugging: it told them a helper "must resolve to itself or to nothing" at precisely the moment that is the thing in question. It now states what the check actually verifies — a fragment carries the name it was resolved by — and points at the test that owns the rest.

The header now separates what name-based identity buys (no compile outcome depends on the vector's order) from what it does not, in its own paragraph, naming the test that builds the collision and the failing compile that bounds it, and saying outright not to build mutation work on the stronger invariant.

The order test's failure text described the pre-fix mechanism. It now leads with why the order still matters — two salsa-cached values with derived PartialEq, so an unstable one defeats backdating — and keeps the positional behaviour as history, since that is where the seed-dependence came from and a reader hitting this failure benefits from knowing it.

Verified no copies remain: grep for all four phrasings across src/simlin-engine/ returns nothing.

@claude

claude Bot commented Aug 2, 2026

Copy link
Copy Markdown

Review Summary

I reviewed the PR carefully, tracing the identity/order fixes and the cross-phase merge through their call sites. Key checks performed:

  • find_in semantics: The hint fast-path is safely gated by a name-check; a stale hint falls through to a linear scan that always yields the correctly-named helper. canonicalize(v.get_ident()) == self.name correctly compares Cow<str> against String.
  • parse_var_with_module_context merge: The per-call local implicit_index correctly handles the dt/initial phase collision. The precondition (parent canonical names are unique, per GH engine: no compile path rejects duplicate canonical variable idents -- one twin silently dropped #885) ensures the shared implicit_vars vector cannot contain cross-variable name collisions. The Ident::<Canonical>::new(...) path canonicalizes idempotently via the interner.
  • elements_in_stable_order: Correctly sorts by CanonicalElementName, handling sparse (EXCEPT default) maps by only ordering entries that are actually present.
  • LtmImplicitVarMeta: Removing index_in_parent is safe because compile_ltm_implicit_var_fragment reads the variable off meta.variable directly, so no positional lookup exists in the LTM path.
  • enumerate_module_instances_inner: The switch from parsed.implicit_vars.get(meta.index_in_parent) to meta.find_in(parsed) is safe: parsed is derived under the same no-extra-idents context as model_implicit_var_info, so find_in will always resolve by name.
  • Cross-context collision residual: The one honest gap (name embeds walk counter, so a widened context that inserts an earlier helper renames later ones) is bounded by a_cross_context_helper_name_collision_is_confined_to_a_failing_compile, which reliably ties the residual to a project that fails to compile.
  • Diagnostic determinism test: The phantom-input guard correctly documents the structural reason the second GH engine: sub-model implicit-var identity is nondeterministic under module-input parse contexts (HashMap-order index misalignment) #1002 observable doesn't reproduce (collect_all_diagnostics and model_implicit_var_info share the same empty-context parse memo).
  • Test enumeration: an_active_initial_that_collides_a_helper_name_is_refused correctly enumerates the three routes that can mint one name for two bodies (Scalar+active_initial, ApplyToAll+active_initial, Arrayed+per-element init), and the header explains why the scalar_disjoint_dep control row doesn't gate the fix.

Overall correctness verdict: correct. No blocking issues found. The two-part fix (order via IndexMap + elements_in_stable_order, identity via name-based find_in) closes the two properties the PR names, and the disclosed residual is properly pinned by a tripwire test.

@bpowers

bpowers commented Aug 2, 2026

Copy link
Copy Markdown
Owner Author

@codex review

@bpowers
bpowers merged commit 4fdb940 into main Aug 2, 2026
15 checks passed
@bpowers
bpowers deleted the ltm-1002-implicit-var-identity branch August 2, 2026 04:34
@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. More of your lovely PRs please.

Reviewed commit: 19acb6bc70

ℹ️ 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".

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: sub-model implicit-var identity is nondeterministic under module-input parse contexts (HashMap-order index misalignment)

1 participant