Skip to content

engine: unify compiler lowering and dependencies - #1032

Closed
bpowers wants to merge 14 commits into
mainfrom
compiler-unification
Closed

bpowers wants to merge 14 commits into
mainfrom
compiler-unification

Conversation

@bpowers

@bpowers bpowers commented Aug 27, 2026 •

Copy link
Copy Markdown
Owner

Why

The compiler carried several parallel answers for the same questions: how an
implicit helper is represented, whether a macro call is expandable, which
model names affect parsing, and where an array-valued operand becomes scratch
storage. Besides making incremental invalidation broad, those copies could
disagree on mappings, repeated axes, snapshot reads, or temp lifetime.

This branch gives those decisions one owner each. It is intentionally compiler
cleanup rather than the later loop-form optimization: array-producing equations
still execute per element, and the measured runtime cost of that choice is
recorded rather than hidden.

Scope

Phase 6b: one post-resolution array materializer

  • compiler::array_operand is the sole owner of array operand and
    array-producing-builtin materialization, after subscript resolution and
    constant folding. Expr3's Pass 1 temp ownership and the A2A/Arrayed
    hoist/probe/replay paths are gone; TempAllocator is the one allocator.
  • A final-expression cache reuses only a recursively pure definition with the
    exact same output ArrayView in the allocator's same physical slot. It does
    not cross a phase, assignment position, active coordinate, nested temp,
    module evaluation, snapshot, lagged/stateful operation, or target read.
  • Computed mapped operands use match_axes_partial and
    executed_read_correspondence, including both mapping declaration
    directions, explicit element maps, repeated occurrences, deterministic
    same-rung ties, and loud refusal of an incomplete relation.
  • Repeated target dimensions allocate occurrences positionally. For example,
    out[D,D] = square[D,D] reads (d_i,d_j), not (d_i,d_i).
  • Resolved SCC assembly refuses a temp whose definition/use would span
    reorderable element segments. A direct combine_scc_fragment backstop also
    protects callers with a stale or hand-built resolved verdict.
  • Phase 6b changes 50 files with 3,024 insertions and 4,687 deletions, net
    -1,663 lines.

Phase 7.3a: typed implicit modules

  • Carry computed call arguments as exact Expr0 subtrees and implicit
    instances as typed model/wiring values.
  • Build parse-stage variables through one exhaustive
    ImplicitVar::parsed_variable conversion across analysis, fragment
    compilation, per-variable lowering, and LTM consumers.
  • Derive helper names and port destinations from typed callsite inputs, and
    refuse conflicting helper identities before map insertion.

Phase 7.3b: one macro call router

MacroRegistry::resolve_call is the exhaustive decision shared by expansion
and recursion analysis: ordinary expansion, external passthrough,
importer-renamed builtin self-call, or unresolved call. Registered macro
routes retain their descriptor through exact-arity validation. Renamed
self-calls deliberately use builtin arity, preventing #554's false
INIT = INITIAL(x) recursion.

Phase 7.4: model-context-free source parsing

  • parse_source_variable(var, project) is the sole source parse query.
    Model-local identifier contexts, contextual/empty twin parses, pre-parse
    module-call probes, and LTM's parallel module-ident set are absent from parse
    keys.
  • Snapshot storage classification uses compiler instance facts. Qualified
    scalar and array module outputs remain direct snapshot reads; bound module
    inputs and bare module instances refuse PREVIOUS and INIT loudly.
  • Adding an unrelated stdlib call parses only that source and its helpers.
    Existing sources and helpers stay cached; only the source newly admitted to
    the instance's initial closure gains an initial fragment.
  • Generated-LTM bare-element shadowing remains guarded by
    ltm_model_var_names; source element classification is completed separately
    below without widening source parse keys to that whole generated surface.

Phase 7.5a: static source element snapshots

  • Source PREVIOUS and INIT calls read bare and qualified element
    subscripts directly when they select one slot of the referenced axis. The
    shared resolve_snapshot_axis_index primitive uses the canonical name and
    position resolvers; XMILE footnote 9 makes an owning-axis element win over a
    same-named source variable.
  • Qualified names use a tracked per-name position projection. Moving or
    removing that element invalidates the parse, while an unrelated dimension
    edit backdates before the parse executes. A qualifier may legally obtain its
    position from a different axis; that position is applied to the referenced
    variable's own axis.
  • Generated LTM equations deliberately retain their conservative whole-surface
    helper and same-named-variable shadowing rule. A production topology fixture
    proves static bare/qualified reads avoid captures and coalesce dimensioned
    scores, while a dynamic control retains scalar capture scores and loud
    refusal behavior remains unchanged.

Phase 7.5b: capture phase demand

  • CaptureKind is the exhaustive phase contract: PREVIOUS refreshes its
    storage in flows, INIT populates it in initials, and identical positional
    storage shared by dt and active-initial parsing unions both demands in either
    intrinsic order. A body or helper-form mismatch still refuses loudly.
  • INIT-only helpers leave flows unless a production current-value dependency
    makes the slot live. PREVIOUS helpers do not seed themselves into initials;
    an independent initial consumer still pulls one through the ordinary
    closure. Raw dt INIT referents from explicit and implicit definitions remain
    first-class initialization roots, including sparse nested module outputs.
  • LTM helpers select required phases directly because they bypass the ordinary
    model runlists, and the LTM diagnostic gate checks every demanded phase.
    Generated scores currently synthesize PREVIOUS captures; typed LTM coverage
    pins both source capture kinds.

Phase 7.5c: structural capture and LTM endpoint shape

The remaining shape loss had two owners. The builtin visitor scalarized a
snapshot helper as soon as an apply-to-all equation needed capture storage,
and LTM consumers then reconstructed hidden endpoint shapes from explicit
source variables or a scalar fallback. That made one logical helper become N
per-element helpers, let arrayed defaults leak into overridden slots, and let
INIT-only syntax create scores even when no flow could observe it.

  • PerElementRequirements uses the authoritative MacroRegistry::resolve_call
    route, including opcode passthrough, renamed-builtin self calls, stdlib
    fallthrough, and project-macro expansion. Snapshot-only equations retain one
    structural Ast::ApplyToAll; module-bearing expressions materialize only
    where execution is genuinely per element. Both IndexExpr0::Range endpoints
    participate in classification, substitution, and walking.
  • Explicit array defaults preserve element coverage. Snapshot defaults create
    one shaped capture and place its rewritten read only in missing bodies;
    module-call defaults materialize only missing bodies. Inactive and fully
    overridden defaults mint no helper.
  • endpoint_dimensions is the single explicit-or-per-name-implicit shape
    projection used by causal edges, element graphs, link scores, loops, and
    pins. Whole-model builders cache it locally; per-edge salsa queries retain
    per-name and per-module invalidation firewalls.
  • model_flow_member_names and dt_causal_dependencies are the shared LTM
    phase projection. INIT-only sources, parents, aggregates, reference sites,
    module ports, and width checks stay outside scoring unless an ordinary
    current read promotes the capture. PREVIOUS-only state remains causal and
    participates in stateless and pinned-cycle lag classification.
  • target_restricted_edges forces the element graph for a bare edge observed
    at only a strict subset of target slots. A materialized missing-only snapshot
    or module-call default therefore cannot manufacture loops or pins for an
    overridden slot. Incompatible axes decline loudly and deterministically;
    there is no scalar score fallback.

Phase 7.5d: sparse delay initial ports

  • Omitted-initial DELAYN and SMTHN calls normalize to
    [input, delay_time]. The canonical stdlib module's
    isModuleInput(initial_value) guard is the single implementation of
    XMILE 1.0 section 3.5.3: an
    unwired initial-value port uses the input's initial value. The computed input
    is therefore evaluated and stored once, and LTM sees no two-port alias to
    reconcile.
  • An explicit fourth argument still supplies an independent third port, even
    when its source text or location-free AST equals the input. Different
    callsites retain distinct instance and helper identities.
  • A per-element HoistedArg retains canonical (axis, element) coordinates
    only. parsed_variable resolves the full Dimension transiently from
    DimensionsContext, so salsa-retained metadata is O(rank) instead of
    cloning every named dimension's elements and mappings into every helper.
    Source expansion and parsed-variable replay share one idempotent substitution walker;
    the parse key remains model-context-free.

Qualified child initialization

  • A project-level fixed point derives same-step qualified initial-output
    requirements from production dependency facts, filters PREVIOUS-only
    paths, preserves nested module suffixes, and unions requirements by model
    and exact bound-port set.
  • Each child graph seeds only demanded outputs and their child-local initial
    dependency closure, including explicit/generated modules, arrays, stocks,
    active-initial equations, input-set variants, and resolved SCCs.
  • VM and wasm EvalModule execution stays phase-symmetric: parent
    initialization never runs a child's flows program.
  • Base graph/SCC facts are accumulator-free. One per-model trigger emits at
    most one attributed cycle diagnostic, and canonical DFS roots/successors
    make first-cycle attribution deterministic.

Phase 8a: structured source dependencies

  • The production Expr2 walk emits canonical DependencyOccurrence { ident, lag }
    rows once. variable_direct_dependencies attaches DepPhase and resolves
    each target to DepTarget { module_path, variable }; the full canonical
    instance path and terminal source identity remain separate.
  • A separator only tokenizes a candidate. Every module hop is proven against
    explicit model metadata, same-parse implicit modules, or the per-name source
    implicit registry used by generated LTM equations. This distinguishes
    module·output from the identical dimension·element source spelling and
    preserves distinct same-leaf targets below different nested instance paths.
  • Scheduling, build_var_info, sparse nested initialization, causal/LTM
    edges and pins, module-output ports, layout metadata, all fragment-input
    constructors, and libsimlin incoming-link projection consume the structured
    relation. Their parallel split/normalize/re-intern paths are absent.
  • Lag-only state is Previous - Current: an Initial fallback or sibling
    snapshot never cancels a PREVIOUS edge. Input-free modules are not
    misclassified as constants.
  • Tracked per-name model and variable projections keep qualified dependency
    readers cached across unrelated owner, intermediate-model, and project
    structural edits. Physical instance offsets cannot own this relation because
    assembly resolution has already erased nested instance names and terminal
    source identity.

Phase 8b: one dependency-consumer boundary

  • An explicit fragment carries one compiler-local
    flow_locally_invariant verdict. The exhaustive compiler::invariance walk
    owns lowered facts such as constant folding, temps, module evaluation/input
    loads, and BuiltinSig::invariance, while treating every resolved value
    reference as invariant. It carries no dependency identity.
  • model_flows_invariant combines that verdict with the authoritative source
    relation as local compiler invariant && every local Dt/Current DepRef target invariant. INIT reads frozen storage and PREVIOUS is locally lagged.
    The source relation retains both arms of a constant-selected conditional for
    validation, runlists, and cycles, so a folded dynamic arm conservatively
    under-hoists instead of weakening source semantics for an optimization.
  • collect_expr_refs, fragment dep_names, identifier_set, and
    DepClassification::all_names are absent. LTM ceteris-paribus rewriting
    receives ExpressionTransformNames { value_candidates, table_holders }, a
    crate-private syntax membership that cannot represent phase, lag, a resolved
    module path, or a scheduling target. Every scheduling consumer uses
    DepRef; lookup holders remain an explicit layout side channel.
  • CausalGraph carries complete dt DepTarget paths for explicit and
    parse-synthesized readers. Exhaustive and discovery module exits share that
    projection, preserving nested instance paths, equal leaf ports under
    distinct roots, repeated ports, and explicit ambiguity for multi-output
    readers. Exit selection does not split or strip reconstructed names.
  • Per-name execution probes keep unrelated edits behind the dependency and
    graph projection firewalls. The one remaining generated-equation
    classify_dependencies use resolves immediately to DepTarget and uses
    local targets plus lookup layout only for expression-shape construction.

Phase 8c: per-variable lowered ownership

  • lowered_source_variable and lowered_implicit_variable each retain one
    shared Arc<Variable<Expr2>> payload. Explicit and ordinary implicit
    FragmentInputs borrow those handles through Cow; transient LTM equations
    and their helpers own their handles. Unit analysis, causal/polarity graphs,
    and LTM maps clone only Arcs, never equation trees.
  • model_stage0, model_stage1, their stage types, the whole-model
    reconstruction query and its per-name projections, the legacy stage oracle,
    and Project::from_salsa are absent. Removing that legacy path also removes
    both dangling-module panic sites tracked by engine: unguarded panics on dangling module model_name in legacy from_salsa path (module_deps, topo_sort) #806.
  • Unit inference builds a stack-local UnitModel over a lightweight transitive
    module-target closure derived from the same explicit and parse-synthesized
    module facts compilation uses. It never returns or caches a second lowered
    model. Production execution probes pin one shared lowering result per
    variable and show unrelated equation or topology edits stay behind the
    per-variable and names-only query boundaries.
  • Module lowering always starts from the production parse result and replaces
    only resolved VarKind::Module wiring, preserving declared units, equation
    metadata, parse errors, and malformed-unit diagnostics. Production tests pin
    all variable kinds, both helper classes, nested/renamed macros, topology
    removal, strict stdlib classification, and the unknown-stdlib-prefix unit
    checking boundary.

Phase 9: one lossless compiler diagnostic

  • Diagnostic is the authoritative parse/lower, salsa-accumulator, and
    collection payload. It retains category, code, severity, raw and display
    details, source span, physical helper identity, user-facing owner, element,
    proven module-instance path, and ordered related sources. The DB boundary
    attaches that context exactly once.
  • Recursive LTM queries return pure, ordered, model-local warning facts. One
    non-recursive per-model emitter owned by model_all_diagnostics emits only
    the current model's facts, so a parent query cannot duplicate a child's
    warnings through salsa's transitive accumulator tree. There is no global
    equality deduplication; every edge-warning family carries ordered source and
    target identity through one constructor. This closes engine: model_ltm_variables warnings duplicated across a module boundary in project error report #866.
  • Explicit and implicit fragment compilers coalesce an identical lowering or
    codegen failure reached through multiple required runlist phases only after
    full attribution and by complete Diagnostic equality. Independent source
    fields, phases, elements, helpers, and module instances remain separate and
    retain first-producer order.
  • Stock/flow declared-unit mismatches are UnitConsistency /
    UnitMismatch; malformed unit syntax remains UnitDefinition. Generated
    LTM equations retain all parser failures, and transient conveyor checks keep
    the original typed unit error, span, and raw detail while degradation prose
    lives only in display detail.
  • Queue, conveyor, LTM, unit, macro, fragment, assembly, and libsimlin
    boundaries carry the typed payload without string-only downgrades.
    CompilationDiagnostic, DiagnosticError, fatal/unit fragment wrappers,
    formatter twins, and the parallel Variable.errors / unit_errors fields
    are absent.

Section G closure: one module-instance traversal

  • Explicit source modules and ordinary parse-synthesized modules remain separate discovery namespaces, then feed typed candidates to one record_module_instance owner for target validation, canonical (model, bound-port set) identity, insertion, deduplication, cycle termination, and nested descent. Each candidate retains its exact missing-target diagnostic.
  • Both namespaces sort their guaranteed canonical map keys before traversal, with explicit precedence. Production multi-missing fixtures pin the exact first error across reversed declaration order, fresh map seeds, and repeated processes. The initial-dependency wrapper delegates to the same top-level traversal.
  • bound_module_port is the one filtering policy behind emitted ModuleInputs and enumerated compilation identity: own-instance sources are internal and foreign destinations bind nothing. A synced internal-reference fixture derives the empty instance key and emitted EvalModule declaration from production, resolves the same child key in the VM, and pins the output series.
  • Every production LtmEquation producer consumes the post-module-expansion source AST or combines qualified generated references. The unreachable LTM module-candidate path is absent; LTM parsing adds PREVIOUS/INIT captures only. Generic visitor module arms and typed metadata remain as the defensive type-system boundary, not a third production module namespace.

Evidence

  • The normal pre-commit hook passed dependency policy, documentation links,
    project lint, Rust fmt/cbindgen/clippy/tests, TypeScript
    lint/build/typecheck/tests, and pysimlin tests. Workspace all-target,
    all-feature clippy also passes with warnings denied.

  • Final engine counts: library 5,760 passed / 2 ignored; integration
    787 passed / 16 ignored; libsimlin unit/integration 21 / 244 passed;
    VM allocation 4 passed; doctests 2 passed / 1 ignored.

  • Section G is byte-identical to exact base 8bc52697 after removing timing and embedded source-path lines: 5,189 / 28,490 slots, 54,825 / 856,568 opcodes, complete histograms, 17,017 / 384,463 post-fusion flow+stock opcodes, and 4,900 / 13,800 result offsets. Release LTM user-series parity, variable-count guardrail, every generated partial, the exact 23-warning surface, and the all-slot digest are green. Fragment, diagnostic, module-enumeration, exact multi-missing, and internal-reference determinism pass 12 consecutive process invocations. Five pinned-core alternating PMU pairs establish no compile-cost movement: plain is +0.0799% by per-side medians / +0.0678% paired median, and LTM is -0.0038% / -0.0106%.

  • Phase 9's production-derived matrix covers every live producer family,
    diagnostic category/code and both severities; explicit, implicit, module,
    nested-LTM, conveyor and queue paths; malformed equations and units;
    element/module/source identity; warning-only results; independent duplicate
    source occurrences; identical and distinct multi-phase failures; stable
    order across revisions; and per-variable invalidation. Both diagnostics and
    fragment determinism modules pass 12 consecutive invocations.

  • Phase 9's plain and LTM C-LEARN artifacts are byte-identical to the Phase 8c
    base: 5,189 / 28,490 slots, 54,825 / 856,568 opcodes, 17,017 / 384,463
    post-fusion flow+stock opcodes, 4,900 / 13,800 result offsets, complete
    histograms, and all-slot digest
    (19264, 0, 3106, 19264, 790401758590, 2212, 7484877280482623718).
    VM/WASM, VDF, user-series, generated-partial, pinned-loop, and exact
    23-warning gates are green. Pinned-core PMU puts plain compilation at
    +0.8509% paired median and LTM at +0.0742%, both below the one-percent
    investigation threshold.

  • Phase 6b's production-derived matrices cover scalar/A2A/Arrayed and EXCEPT,
    wildcard/range/element/mapped/subrange/repeated-axis operands, reducers and
    array results, snapshots, tables/dimension names, per-element graphical
    functions, active-coordinate variation, mapped same-rung ties and incomplete
    relations, SCC refusal plus an acyclic local-temp control, and absolute VM
    and wasm values plus parity. The determinism gates pass 12 consecutive
    invocations.

  • The Phase 7 production gates cover the complete PREVIOUS/INIT
    addressability/refusal table, scalar/array/nested qualified values,
    generated LTM, active-initial and stock outputs, distinct and shared module
    keys, implicit modules, SCC placement, reset/repeated initials, VM/wasm
    absolute values and parity, macro routing, fragment-cache execution,
    diagnostics, and declaration-order determinism.

  • Phase 7.5a's production-derived exhaustive matrix crosses both intrinsics
    with same-name collision, unrelated qualification, missing qualified/bare
    names, globally ambiguous bare names, mapped axes, and a proper
    subdimension. qualified_snapshot_position_has_per_name_invalidation pins
    the salsa firewall; ltm_snapshot_element_reads_preserve_score_topology_and_values
    pins user values, score values, captures, slots, and score extents.

  • Phase 7.5b derives every source capture kind and storage shape through
    production parsing and dependency extraction, including explicit, dynamic,
    array, module, macro, and typed/generated-LTM routes. It pins exact
    initials/flows/stocks fragment membership, both union orders, VM reset/rerun,
    user-variable VM/wasm parity, and sparse qualified INIT propagation. The
    semantic regressions are pinned directly: local and nested qualified
    PREVIOUS(INIT(k)+1,-7) produce [-7, 4, 4, 4]; mixed
    driver + INIT(child.needed) produces [13, 14, 15, 16] while an
    unrelated child output stays outside initials.

  • Phase 7.5c's production-derived matrix crosses PREVIOUS and INIT; scalar,
    dynamic, fixed, array-valued, mapped, repeated, and proper-subdimension
    operands; explicit/default/implicit/module equations; stock, initial, flow,
    SCC, LTM score, loop, and pin routes; reset/repeated initialization; exact VM
    and wasm values; every MacroCallResolution and IndexExpr0 arm; and loud
    incompatible topology. The focused contract tests include
    shaped_snapshot_captures_preserve_arrayed_dynamic_indices_in_both_backends,
    shaped_snapshot_captures_preserve_mapped_subdimension_and_repeated_axes,
    xmile_arrayed_snapshot_defaults_keep_each_missing_elements_storage,
    xmile_arrayed_module_defaults_materialize_only_missing_elements,
    explicit_element_range_endpoints_substitute_and_capture_once,
    ltm_causal_edges_follow_the_production_flow_phase_boundary,
    shaped_snapshot_default_scores_only_missing_elements,
    shaped_previous_capture_pin_is_one_dimensioned_loop, and
    test_stockless_captured_previous_cycle_is_state_for_scores_and_pins.

  • Phase 7.5d derives both aliases and all four MacroCallResolution routes
    through production registry build and salsa parsing. It covers omitted and
    explicit initial forms, DELAYN's valid 3/4 and invalid 2/5 arities,
    engine-supported literal orders 1/3 plus loud literal/dynamic refusals,
    scalar/array/dynamic/mapped/proper-subdimension/repeated-axis sources,
    nested INIT/PREVIOUS, qualified modules, sparse child initials, exact phase
    demand, SCCs, reset/rerun, and VM/WASM values. Direct DELAY1/3 and SMTH1/3
    omitted-port controls match the aliases in VM, WASM, reset, and exact LTM
    names/equations/partitions/offsets/all-slot series. A 64-element production
    expansion pins every helper's active context to one vector and each
    coordinate to two interned canonical-name handles.

  • Phase 8a's production-derived classifier matrix covers every lag, phase,
    expression-context, and IndexExpr2 arm. Resolver rows cover explicit,
    same-parse implicit, source-registered implicit, leading-parent, missing
    target/intermediate/non-module/leaf, depth-three, same-leaf/different-path,
    and module-vs-dimension namespaces. The full missing-leaf identity survives
    into diagnostics. Explicit, implicit, module, LTM, macro, array/mapping/
    subdimension, SCC, sparse-initial, and no-input dynamic-module routes are
    pinned. The libsimlin regression uses a real public child·output source
    collision, so metadata resolution must produce a nonempty module path rather
    than passing through textual filtering.

  • Phase 8b derives the invariance equation through production source parsing,
    dependency resolution, fragment lowering, assembly, VM, wasm, and reset.
    The exhaustive compiler table covers every Expr and builtin invariance
    arm; mixed Current/Previous/Initial rows prove that only local dt-current
    targets propagate. Constant-selected dynamic branches pin deliberate
    under-hoisting. Array, lookup, reducer, stock, module, macro, implicit/LTM,
    SCC, nested-path, same-port/different-root, multi-output ambiguity, and
    per-name execution-count rows all use production extraction rather than
    hand-built dependency sets.

  • The exact C-LEARN invariant identity diff against 4d5302d6 has no removals
    and fifteen additions. Offsets 902--908 are the seven COP elements of
    forestry_emissions_at_start_year: an immutable graphical-function holder
    indexed only by constant forestry_start_year and one_year. Offsets
    2371--2377 are projected_population_in_target_year: three immutable UN
    lookup holders with invariant scale/scenario/weights/one-year inputs and an
    INIT-frozen target year. Offset 2370 is the pure SUM
    projected_global_population_in_target_year. A production-derived
    per-element lookup/reducer matrix pins both classes, TIME-indexed negative
    twins, source rows, table holders, local verdicts, final offsets, and exact
    VM series. All 883 current and all 868 base invariant slots are bit-constant
    in the release oracle; neither side has a violation.

  • Final Phase 8a validation: engine library 5,731 passed / 2 ignored;
    integration 786 passed / 16 ignored; VM allocation 4 passed;
    doctests 2 passed / 1 ignored; libsimlin integration 244 passed.
    Fragment and diagnostic determinism each pass 12 consecutive process
    invocations. Release C-LEARN plain/LTM parity, all generated partials,
    complete warnings, VM/wasm discovery parity, and the all-slot digest pass.

  • Unrelated CI repair: crates.io yanked transitive chacha20 0.10.1
    after the lockfile was produced. Separate commit 4d5302d6 updates only that
    package and checksum to semver-compatible 0.10.2 through
    rmcp 1.8.0 -> rand 0.10.2. The sparse index marks 0.10.2 non-yanked,
    the fetched crate and registry/lock checksums agree, enabled features and the
    dependency graph are unchanged, and cargo-deny reports advisories, bans,
    licenses, and sources green. This is CI maintenance, not Phase 8a behavior.

  • The incrementality firewalls are executed, not inferred:
    unrelated_snapshot_helper_does_not_regenerate_implicit_endpoint_score and
    unrelated_module_port_and_helper_do_not_regenerate_module_edge_score count
    salsa executions around production sync edits. Diagnostic and fragment
    determinism suites each pass 12 consecutive invocations.

  • The Phase 7 corpus sweep covered 509 models: 396 byte-identical results,
    110 identical refusals, and the same two-output sets across 12 resamples for
    the three known importer-nondeterministic models.

  • The genuine Vensim vector.xmile and MDL twin are full, un-narrowed gates,
    including engine: VECTOR ELM MAP(x[three], DimA - 1) fails to compile #578's scalar-source/expression-offset VECTOR ELM MAP. C-LEARN
    compiles and runs through synthetic capture helpers and per-element arrayed
    graphical functions (engine: C-LEARN fails with "failed to compile fragments" #580), and its recycled temp pool is 28 rather than
    overflowing TempId (engine: an equation needing over 256 temp arrays silently aliases them #583). Sparse star-range transpose/reorder has direct
    view tests, absolute simulation values, an elementwise consumer, and VM/wasm
    parity (engine: transposed star-range (sparse subdimension) view reads all-NaN -- ArrayView::transpose keeps stale SparseInfo.dim_index #1027).

C-LEARN artifacts and cost

Against exact base c666c4a6, plain C-LEARN has 57,206 opcodes:
30,814 flow / 1,477 stock / 24,915 initial, or +120 flow and +120 initial.
Each phase adds exactly 24 VectorElmMap, 48 PushStaticView, and 48
PopView; static views rise 643 -> 739. Slots, literals, graphical functions,
dimensions, names, modules, initials, stock opcodes, and every user-model
series are unchanged.

With LTM, the total is 938,465 opcodes: 908,217 flow / 1,477 stock /
28,771 initial. Flow independently removes 32 maps and 64 of each view opcode,
while initial adds the same 24/48/48 as plain, for net -160 flow, +120 initial,
and -16 static views. LTM temp slots fall 441 -> 28.

  • Isolated compile work: 1.1475 G retired instructions versus 1.1487 G,
    -0.103%. Compile allocations fall 1,996,628 -> 1,989,055 and allocated
    bytes fall 245.0 -> 223.0 MiB.
  • Plain RUN_ITERS=20: +6.865%, or +105.39 M retired instructions per
    VM construction/run.
  • LTM, five alternating base/current rounds with a matching zero control for
    every binary and round: 19.4937 G versus 19.6967 G per added run,
    +1.0413% or +203.0 M/run; paired range +1.0095%..+1.0715%.

The runtime regressions are accepted temporarily because loop-form/batched
lowering was explicitly sequenced after compiler cleanup, not because the
numbers are small. The four residual definitions are
sorted_target_active, sorted_target_type, sorted_target_value, and
sorted_target_year; each has seven coordinate-specific final source slices.
Recovering their batched form is the next work in #1025.

Phase 7.5a C-LEARN artifacts and cost

Against the exact saved Phase 6b binary, plain C-LEARN falls from 57,206 to
57,076 opcodes
: 30,762 flow / 1,477 stock / 24,837 initial. Removing 26
captures removes 26 slots, 52 flow opcodes, 78 initial opcodes, and 26 initial
programs. Literals (1,740), graphical functions (162), temps (28), and views
(739) are unchanged; post-fusion flow falls 17,063 -> 17,037.

With LTM, the total falls from 938,465 to 936,585 opcodes: 906,415 flow /
1,477 stock / 28,693 initial. The 26 source captures disappear while 35
scalar/per-element score names coalesce into dimensioned variables whose
declared extents add 278 slots, for a net 30,123 -> 30,375 slots and 16,749 ->
17,027 literals. Post-fusion flow falls 419,166 -> 418,560. The integration
guard pins 7,128 LTM variables and 30,375 slots, and release C-LEARN preserves
every user series with LTM off and on.

  • Five paired control-subtracted compile rounds measure plain at 1.14007 G
    retired instructions versus 1.14676 G, -0.583% (range
    -0.838%..-0.492%), and LTM at 13.4423 G versus 13.5152 G, -0.539%
    (-0.962%..-0.296%).
  • Control-subtracted execution is 1.45260 G versus 1.49290 G per plain run,
    -2.699% (five-pair range -2.735%..-2.684%), and 31.9781 G versus
    32.6132 G per LTM run, -1.947% (all five pairs improve; range
    -2.093%..-1.403%).

Phase 7.5b C-LEARN artifacts and cost

Against the exact saved Phase 7.5a binary, plain C-LEARN falls from 57,076 to
54,951 opcodes
: 28,637 flow / 1,477 stock / 24,837 initial, with 1,164
initial programs. Slots remain 5,189 and result offsets 5,032. The change
removes 2,125 flow opcodes, 217 literals, and 14 static views; post-fusion flow
falls 17,037 -> 15,942.

With LTM, the total falls from 936,585 to 930,604 opcodes: 904,290 flow /
1,477 stock / 24,837 initial, with 1,164 initial programs. Slots remain 30,375
and result offsets 16,012. The same 2,125 flow opcodes disappear, plus 3,856
initial opcodes and 770 redundant generated-PREVIOUS initial programs; literals
fall 17,027 -> 16,443, views 2,850 -> 2,446, and post-fusion flow 418,560 ->
417,465. Names, modules, graphical functions, temps, and dimensions are
unchanged. Release C-LEARN preserves every user-model series with LTM off and
on.

  • Five paired, alternating, per-binary control-subtracted compile rounds
    measure plain at 1.13212 G retired instructions versus 1.14225 G,
    -0.888% (paired range -0.975%..-0.807%), and LTM at 13.4573 G versus
    13.4923 G, -0.259% (-0.420%..-0.137%).
  • Control-subtracted execution is 1.40792 G versus 1.45267 G per plain run,
    -3.080% (paired range -3.103%..-3.068%), and 19.1659 G versus 19.2109 G
    per LTM run, -0.234% (-0.260%..-0.215%). Every pair improves.

Phase 7.5c C-LEARN artifacts, values, and cost

The exact 7.5b binary, the shaped pre-phase-filter review artifact, and the
committed final artifact were profiled separately:

surface exact 7.5b shaped, before phase filtering final
plain root slots 5,189 5,189 5,189
plain flow / stock / initial opcodes 28,637 / 1,477 / 24,837 28,637 / 1,477 / 24,711 28,637 / 1,477 / 24,711
plain literals / GFs / temps / views 1,523 / 162 / 28 / 725 1,358 / 162 / 28 / 725 1,358 / 162 / 28 / 725
plain result offsets / post-fusion flow+stock 5,032 / 17,017 4,900 / 17,017 4,900 / 17,017
LTM emitted variables / root slots 7,128 / 30,375 6,862 / 30,480 5,561 / 28,490
LTM flow / stock / initial opcodes 904,290 / 1,477 / 24,837 903,758 / 1,477 / 24,711 830,380 / 1,477 / 24,711
LTM literals / GFs / temps / views 16,443 / 162 / 28 / 2,446 15,609 / 162 / 28 / 2,362 13,113 / 162 / 28 / 2,334
LTM result offsets / post-fusion flow+stock 16,012 / 418,540 15,115 / 418,155 13,800 / 384,463

The generated implicit-helper census moves from 738 scalar variables / 738
slots at 7.5b to 225 shaped variables / 759 slots. This removes the residual
slot-ceiling risk tracked by #654 while keeping all 371 names, seven modules,
162 graphical functions, 28 temp slots, and 126 dimensions fixed.

The ignored all-slot digest pins
(slots, unknown_extent, nonzero, finite, mantissa, exponent, identity):

  • exact 7.5b: (20892, 0, 3141, 20892, 798101758590, 2254, 11438420344658315382);
  • shaped pre-phase-filter: (21156, 0, 3120, 21156, 796001758590, 2254, 3469289498152604485);
  • final: (19264, 0, 3106, 19264, 790401758590, 2212, 7484877280482623718).

Structural extents add 278 slots to the 7.5b digest and fixed-slice refusal
removes 14, yielding 21,156 before phase filtering. The shaped artifact's 21
fewer nonzero identities are the named coalescing of redundant scalar helpers,
not lost user values. Phase-aware discovery then removes 1,864 zero link-score
slots and 28 INIT-only freezer slots. Fourteen freezer slots are zero; the
other 14 are exactly two effective_target_year elements in each of seven COP
regions, each with maximum magnitude 4,000. Every one of the 19,264 final
identities shared with the shaped pre-filter artifact has the same maximum.
Release C-LEARN preserves every user-model series with LTM both off and on
against the exact 7.5b binary.

The complete warning pin is the exact 7.5b surface: one discovery-mode switch,
17 incompatible-dimension declines, and five rank-like partial declines. The
discovery warning is:

LTM analysis auto-switched from exhaustive to discovery mode: the
variable-level causal graph's largest SCC has 149 nodes, exceeding
MAX_LTM_SCC_NODES = 50. Variable-level Johnson at this scale would enumerate
millions of circuits (see
docs/design-plans/2026-04-18-ltm-cap-lift-diagnosis.md and
docs/design-plans/2026-05-06-ltm-482-variable-level-loop-enumeration.md).
Per-loop scores are found and ranked post-simulation from the recorded link
scores; see docs/design/ltm--loops-that-matter.md for the two-tier strategy.

The 17 incompatible edges are:

co2_equivalent_emissions -> aggregated_co2eq_emissions,
co2_equivalent_emissions -> semi_agg_co2eq_emissions,
co2_ff_emissions -> aggregated_co2_ff_emissions,
co2_ff_emissions -> semi_agg_co2_ff_emissions,
co2_ff_emissions -> top_of_stacked_co2_ff,
co2_forestry_net_emissions -> aggregated_forestry_emissions,
co2_forestry_net_emissions -> semi_agg_forestry_emissions,
cumulative_co2 -> aggregated_cumulative_co2,
cumulative_co2 -> semi_agg_cumulative_co2,
fraction_of_cumulative_emissions -> aggregated_fraction_of_cumulative_emissions,
fraction_of_cumulative_emissions -> semi_agg_fraction_of_cumulative_emissions,
fraction_of_cumulative_emissions -> top_of_stacked_cum_fraction,
gdp -> aggregated_gdp, gdp -> semi_agg_gdp,
gwp_of_hfc -> rs_co2eq_nonforest_emissions,
population -> aggregated_population, and
population -> semi_agg_population. Each complete message is
LTM link score for edge {edge} could not be computed: both variables are arrayed but their dimensions do not correspond -- an unmapped pair, or a mapped one whose two reference spellings read different source elements, which cannot share one per-target-element score slot -- so the conservative score has no compilable shape; this edge will have no link-score variable and feedback loops through it will not be scored.

The five exact rank-like variable/equation pairs are:

  • $⁚ltm⁚link_score⁚ascending→target_order[oecd_us,t1]:
    vector_sort_order(effective_target_year[cop, target], ascending);
  • $⁚ltm⁚link_score⁚effective_target_year[oecd_us,t1]→sorted_target_year[oecd_us,t1]:
    vector_elm_map(effective_target_year[cop, t1], target_order[cop, target]);
  • $⁚ltm⁚link_score⁚target_is_active[oecd_us,t1]→sorted_target_active[oecd_us,t1]:
    vector_elm_map(target_is_active[cop, t1], target_order[cop, target]);
  • $⁚ltm⁚link_score⁚target_type[oecd_us,t1]→sorted_target_type[oecd_us,t1]:
    vector_elm_map(target_type[cop, t1], target_order[cop, target]);
  • $⁚ltm⁚link_score⁚target_value[oecd_us,t1]→sorted_target_value[oecd_us,t1]:
    vector_elm_map(target_value[cop, t1], target_order[cop, target]).

Each message follows that attribution with applies an array-producing builtin (VECTOR SORT ORDER, RANK, ALLOCATE, or VECTOR ELM MAP), whose array result a per-element scalar partial cannot hold -- and for the order-statistic builtins the scalarization would also pin the ranked array down to a single element, whose order statistic is meaningless (a 1-element rank is always 0). The edge is declined -- and dependent loop scores dropped -- rather than scored with a plausible-looking constant; where the same target has a compiling whole-array (A2A-shaped) score, that score carries the edge's attribution instead (GH #995). No last_set_target_year warning survives.
The test compares every warning's model, optional variable attribution, and
complete message, so a new warning of any category cannot hide outside these
lists.

Five alternating rounds subtract a matching zero-iteration control for every
binary, mode, and round. Against exact 7.5b, one plain compile is
1.02096621756 G retired instructions versus 1.13250087780 G, -9.8485%
(paired range -9.9812%..-9.7160%); LTM is 11.30831967700 G versus
13.46594365524 G, -16.0228% (-16.1638%..-15.8714%). Plain compile
cycles / branches / branch misses move -9.7455% / -9.6711% / -10.8682%; LTM
moves -15.3566% / -16.0980% / -16.4733%.

One plain run is 1.38435796576 G versus 1.40779940405 G retired instructions,
-1.6651% (paired range -1.6791%..-1.6549%); one LTM run is
17.75973315108 G versus 19.16757675252 G, -7.3449%
(-7.3729%..-7.3175%). Plain run cycles / branches / branch misses move
-0.7613% / +0.0393% / -1.8155%; LTM moves -6.8262% / -6.8936% /
-6.5532%. The small plain branch increase is noise-sized while instructions,
cycles, and misses all improve. RuntimeView::dense_linear_start stays
explicitly inlined because it is reachable from the per-element generic
addressing path and an out-of-line call there is avoidable VM cost.

Phase 7.5d C-LEARN artifacts, values, and cost

Against the exact saved 7.5c binary, C-LEARN's complete plain and LTM profile
blocks are byte-identical: 5,189 / 28,490 root slots; 54,825 / 856,568 total
opcodes; 28,637 / 830,380 flow, 1,477 stock, and 24,711 initial opcodes; 1,358 /
13,113 literals; 162 graphical functions; 28 temps; 725 / 2,334 views; 4,900 /
13,800 result offsets; 371 names; and seven modules. Post-fusion flow+stock
remains 17,017 / 384,463. The release user series match plain versus LTM, the
WASM/VDF gate matches 2,924 variables across 251 steps, every emitted LTM
partial parses, the complete warning surface is unchanged, and the all-slot
digest remains (19264, 0, 3106, 19264, 790401758590, 2212, 7484877280482623718).

Five paired rounds alternate binary order and control/treatment order and
subtract each binary's matching zero-iteration control. One plain compile is
1.01913 G retired instructions current versus 1.02065 G base, -0.1486%
(paired range -0.2390%..-0.0969%). One LTM compile is 11.12913 G versus
11.30982 G, -1.5974% (-1.7719%..-1.3896%); cycles / branches / branch
misses move -1.3810% / -1.5258% / -0.8632%. C-LEARN contains no DELAY N,
SMOOTH N, DELAYN, or SMTHN call, and this slice also changes active-coordinate
residency and replay for per-element module arguments. The LTM compile signal
is therefore confounded; without an isolated A/B, this PR assigns it no causal
mechanism.

Execution is flat: one plain run is 1.38437 G current versus 1.38440 G base,
-0.0024% (paired range -0.0412%..+0.0244%), and one LTM run is 17.75099 G
versus 17.76045 G, -0.0533% (-0.0838%..-0.0304%). C-LEARN cannot
demonstrate affected storage-count reduction because it has no N-order alias;
the production 64-element scale fixture is the residency boundary.

Phase 8a C-LEARN artifacts and cost

Against exact base af201c7f, plain and LTM compiled artifacts are identical.
Plain has 5,189 slots, 54,825 opcodes (28,637 flow / 1,477 stock / 24,711
initial), 17,017 post-fusion flow+stock opcodes, 4,900 result offsets, 1,358
literals, 162 graphical functions / 37,065 points, 28 temps, 126 dimensions,
725 views, 371 names, and seven modules. LTM has 28,490 slots, 856,568 opcodes
(830,380 / 1,477 / 24,711), 384,463 post-fusion flow+stock opcodes, 13,800
result offsets, 13,113 literals, 162 graphical functions, 28 temps, 126
dimensions, 2,334 views, 371 names, and seven modules. Every opcode histogram
and fused histogram agrees. The digest remains
(19264, 0, 3106, 19264, 790401758590, 2212, 7484877280482623718).

Five alternating paired PMU rounds pin one performance core and subtract each
binary's matching zero-extra-compile control. Plain's per-side median is
1.023250102 G retired instructions at base versus 0.991202796 G current
(-3.1319%); paired median -3.1766%, range
-3.4966%..-2.0100%. LTM is 11.147363920 G versus 10.953716686 G
(-1.7372%); paired median -1.9886%, range
-2.2128%..-0.3720%.

Phase 8b C-LEARN artifacts and cost

Against exact base 4d5302d6, complete plain and LTM compiled artifacts are
identical: 5,189 / 28,490 slots; 54,825 / 856,568 total opcodes; 28,637 /
830,380 flow, 1,477 stock, and 24,711 initial opcodes; 17,017 / 384,463
post-fusion flow+stock opcodes; 4,900 / 13,800 result offsets; 1,358 / 13,113
literals; 162 graphical functions; 28 temps; 126 dimensions; 725 / 2,334
views; 371 names; and seven modules. Every opcode/fused histogram and the
all-slot digest (19264, 0, 3106, 19264, 790401758590, 2212, 7484877280482623718) agree. Release C-LEARN plain/LTM user-series and VDF
parity, complete warnings, every generated partial, plain wasm, and discovery
VM/wasm parity are green.

Five alternating pinned-core rounds subtract each binary's matching
zero-extra-work control. Plain compile is 0.98292 G retired instructions
current versus 0.98821 G base (-0.5359% by per-side medians); median paired
delta -0.4926%, range -0.6062%..-0.1671%. LTM compile is 10.94342 G versus
10.93254 G (+0.0996%); median paired +0.0366%, range
-0.0592%..+0.2726%, inside the channel's noise floor.

The same five-round protocol on complete runs measures +0.3833% plain by
per-side medians / +0.3784% paired (range +0.3748%..+0.4122%), and
+0.3194% LTM / +0.3220% paired (+0.2944%..+0.3461%). Both are below
the one-percent redesign threshold set for the conservative conditional rule.

Phase 8c C-LEARN artifacts, cost, and residency

Against exact base d80b8833, complete plain and LTM artifacts are
byte-identical: 5,189 / 28,490 slots; 54,825 / 856,568 total opcodes; 28,637 /
830,380 flow, 1,477 stock, and 24,711 initial opcodes; 17,017 / 384,463
post-fusion flow+stock opcodes; 4,900 / 13,800 result offsets; 1,358 / 13,113
literals; 162 graphical functions; 28 temps; 126 dimensions; 725 / 2,334
views; 371 names; and seven modules. Every opcode and fused histogram agrees.
Release plain/LTM user-series parity, the 2,924-variable by 251-step VDF gate,
all generated partials, plain wasm and discovery VM/wasm parity are green. The
warning surface remains exactly one discovery switch, 17
incompatible-dimension declines, and five rank-like declines; the all-slot
digest remains (19264, 0, 3106, 19264, 790401758590, 2212, 7484877280482623718).

Five alternating pinned-core rounds subtract each binary's matching
zero-extra-work control. Plain compile is 0.93708 G retired instructions
current versus 0.98425 G base (-4.7926% by per-side medians; median paired
-4.7394%, range -4.8739%..-4.5569%). LTM compile is 10.56555 G versus
10.94546 G (-3.4709%; paired -3.2972%, range -3.8574%..-3.1686%). Runtime is
-0.8090% plain by per-side medians / -0.8119% paired
(-0.8246%..-0.7967%) and -0.7085% LTM / -0.7147% paired
(-0.8702%..-0.6572%), below the one-percent redesign threshold.

Allocation calls and bytes fall from 1,753,314 / 199.5 MiB to 1,538,885 /
178.2 MiB plain and from 26,624,414 / 2,802.0 MiB to 25,331,791 / 2,566.3
MiB LTM. Peak live moves 32.3 -> 40.5 MiB plain and 260.8 -> 256.8 MiB LTM.
A matched owner-lifecycle census, with the parsed datamodel alive, reports base
-> current retained deltas for db+sync+artifact, after dropping the artifact,
after dropping the db, and after dropping sync: plain 25.39 -> 33.59, 25.16 ->
33.36, 0.29 -> 0.29, and 0.20 -> 0.20 MiB; LTM 224.83 -> 220.78, 224.05 ->
219.99, 0.75 -> 0.75, and 0.66 -> 0.66 MiB. Per-variable memo granularity
costs about 8.2 MiB in both modes. Plain never demanded the legacy
reconstruction owner; deleting that owner saves about 12.3 MiB under LTM, for
a measured 4.1 MiB net LTM reduction. This is an ownership tradeoff, not a
blanket residency-improvement claim.

Limits

Fixes #372
Fixes #554
Fixes #584
Fixes #866
Fixes #1028
Closes #654
Closes #806

Represent stdlib and macro module instances plus computed arguments as typed ImplicitModule and HoistedArg values. Compiler consumers build VariableStage0 directly, preserving source spans and removing the generated helper equation print/reparse boundary.

Derive module names and port wiring from typed callsite inputs, and reject conflicting implicit-helper insertions before name-keyed maps can overwrite them. Production tests pin exact AST identity, macro and stdlib wiring, phase collisions, and deterministic artifacts.
@codecov

codecov Bot commented Aug 27, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 92.92196% with 195 lines in your changes missing coverage. Please review.
✅ Project coverage is 93.05%. Comparing base (5c406dd) to head (8eedddd).

Files with missing lines Patch % Lines
src/simlin-engine/src/compiler/mod.rs 80.36% 54 Missing ⚠️
src/simlin-engine/src/compiler/array_operand.rs 92.66% 38 Missing ⚠️
src/simlin-engine/src/compiler/context.rs 84.23% 29 Missing ⚠️
src/simlin-engine/src/db/dep_graph.rs 94.35% 27 Missing ⚠️
src/simlin-engine/src/db/fragment_compile.rs 89.63% 20 Missing ⚠️
src/simlin-engine/src/compiler/subscript.rs 88.73% 8 Missing ⚠️
src/simlin-engine/src/db/implicit_deps.rs 93.58% 5 Missing ⚠️
src/simlin-engine/src/capture.rs 98.38% 4 Missing ⚠️
src/libsimlin/src/patch.rs 80.00% 2 Missing ⚠️
src/simlin-engine/src/db.rs 96.72% 2 Missing ⚠️
... and 4 more
Additional details and impacted files
@@            Coverage Diff             @@
##             main    #1032      +/-   ##
==========================================
+ Coverage   93.02%   93.05%   +0.02%     
==========================================
  Files         253      254       +1     
  Lines      155948   157018    +1070     
==========================================
+ Hits       145076   146115    +1039     
- Misses      10872    10903      +31     

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

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

@claude

claude Bot commented Aug 27, 2026

Copy link
Copy Markdown

Code Review

No blocking issues found. Notes below are non-blocking observations.

Strengths

  • insert_implicit_var is the single map-insertion chokepoint, and its exhaustive-match tests (dedup_vars_covers_the_complete_variant_pair_matrix, checked_insertion_keeps_first_and_refuses_conflicting_definition) derive rows from the enum itself, so a fourth arm becomes a compile error rather than a silent gap.
  • Cross-kind collision reachability is pinned by both a production-parse regression (active_initial_capture_cannot_replace_dt_hoisted_argument, macro_name_cannot_overwrite_its_same_named_hoisted_argument) and a diagnostic assertion, so a regression here surfaces with attribution.
  • The subtree_variable_stage0 re-walk through instantiate_implicit_modules is safe: printed hoisted-arg bodies contain only bare Var references to storage (SnapshotAccess::Slot), so no nested capture is synthesized; the debug_assert!(nested.is_empty()) invariant holds.
  • Wiring correctness is doubly pinned: every_module_call_shape_carries_its_idents_model_and_wiring asserts exact spellings, while every_synthesized_module_targets_a_real_stdlib_model_and_port cross-checks against the stdlib registry so a rename cannot leave the rows agreeing with a dangling reference.

Minor observations (non-blocking)

  • insert_implicit_var reports collisions with an eqn_err!(DuplicateVariable, 0, 0, ...) span. Details carry the collision name so automation works, but user-facing diagnostics point to position 0 of the equation rather than the offending call site. Matches the pre-existing dedup_vars_by_ident convention, so consistent, but worth revisiting if diagnostic quality becomes a goal for Phase 7.3b.
  • every_helper_stage0_matches_parsing_its_equivalent_datamodel_variable compares ASTs by their printed form (via the print_ast closure), which cannot distinguish two ASTs whose print_eqn outputs happen to coincide. This is the exact GH engine: three more print_eqn/parser asymmetries (unary !, !=, and right-nested ^ re-parsing to a different AST) #913 shape (Div(If, 2) vs If(_, _, Div)); module_backed_builtin_if_argument_is_not_regrouped covers that class directly, so the weaker equivalence here is not load-bearing.

Overall correctness

Correct.

Make expansion and recursion analysis consume one exhaustive routing decision, and give every compile-stage helper consumer the same typed stage conversion.

Passthrough macros retain their descriptor long enough to enforce exact declared arity, while importer-renamed self-calls deliberately use builtin arity so their bodies do not become false recursion.
@claude

claude Bot commented Aug 27, 2026

Copy link
Copy Markdown

Automated review

No blocking findings.

Scope of review: the correctness of the refactor from printed-and-reparsed helper text to typed HoistedArg/ImplicitModule carrying Expr0 subtrees, the new insert_implicit_var collision refusal, the MacroCallResolution consolidation, and the exhaustive variable_stage0 dispatch on compile-stage consumers.

Notes on things that looked worth checking and turned out to be intentional:

  • collect_called_macros no longer records edges for Passthrough results. This is a real behavior change from the old macros.contains_key(canonical) check, but it is correct: a passthrough macro is classified only when the body is exactly out = BUILTIN(param) with BUILTIN a renamed-builtin collision, so the body never expands and can never re-enter itself or another macro. Removing the false edge cannot mask a real cycle.
  • insert_implicit_var emits DuplicateVariable with a (0, 0) span. The macro ARG1(k, k*2) test asserts against details.contains(collision_name) rather than a span, matching the reachable diagnostic shape.
  • subtree_variable_stage0 re-walks the arg through instantiate_implicit_modules with empty context, guarded by debug_assert!(nested.is_empty()). The ?-propagation invariant ensures the walked arg only contains Var/Const/Op*/If (module calls already turned into a module-output Var), so the re-walk generates no new helpers; empty registry + snapshot_arg classifying a bare synthetic Var as whole() keeps the assertion satisfied in practice.
  • equation_dims() on HoistedArg is always empty. Consistent with expand_module_function always producing a per-element scalar aux (dimension refs substituted before the hoist).

The corpus evidence (396/509 byte-identical, 110 identical refusals, C-LEARN opcode/histogram parity under both LTM modes) is the load-bearing check for behavior preservation; the new implicit_module_tests.rs fixture pins the 3x3 variant matrix and the ARG1-vs-arg1 collision in the same direction as the invariants described.

Remove model-local variable sets and instance wiring from source parse keys so unrelated edits preserve cached parses. Keep LTM bare-element shadowing explicit until the lowering classifier lands in Phase 7.5.

Propagate qualified INIT requirements into sparse child initial programs by exact module compilation key. Derive project requirements from accumulator-free graph facts and emit each model's cycle diagnostic through one dedicated trigger.
@claude

claude Bot commented Aug 27, 2026

Copy link
Copy Markdown

Review

Reviewed the two-phase change: typed implicit-module transport (HoistedArg/ImplicitModule + ImplicitVar::variable_stage0) and the unified MacroRegistry::resolve_call router.

No qualifying findings.

Spot-checks confirmed:

  • The router's four arms have correct precedence: RenamedBuiltinSelfCall is decided before the macro-descriptor lookup, so a same-named self-call cannot be misclassified as Passthrough and cannot produce a false recursion edge (the engine: macro whose body wraps a same-canonical-name intrinsic (INIT = INITIAL(x)) causes false recursion cycle, blocking C-LEARN macro expansion #554 class).
  • Arity placement is intentional and correct: strict declared-macro arity gates both Expand and Passthrough; RenamedBuiltinSelfCall deliberately falls through to builtin arity. This matches the PR's DELAY1/PREVIOUS passthrough-arity behavior claim.
  • Both consumers (macro expansion and recursion analysis) read the same resolve_call return, so they cannot disagree on a callsite.
  • Typed helper idents flow through capture::synthetic_ident at a single site; helper-name collisions refuse before IndexMap overwrite.
  • Initial-output fixed point in dep_graph.rs routes qualified paths per boundary and gates additions on known_keys, preserving nested suffixes.
  • The cycle diagnostic move off the shared graph query onto a per-model trigger looks correct.

Overall correctness

Correct. The patch is free of blocking issues in the reviewed surface. Tests, corpus sweep, and C-LEARN artifact/perf evidence documented in the PR body support the parity claim within its stated boundary (measured corpus, C-LEARN instruction channel).

Make compiler::array_operand the sole owner of computed array operands and array-valued builtin results, after canonical subscript and mapping resolution. Preserve one TempAllocator and reject recurrence SCCs whose segment reordering cannot preserve temp dominance.

This cleanup intentionally leaves batched whole-array execution to the sequenced loop-form work in GH #1025; the plan records the measured plain and LTM runtime cost and its acceptance boundary.
Resolve source PREVIOUS and INIT element subscripts from their referenced axis, following XMILE footnote 9 for bare element precedence. A per-qualified-name salsa projection preserves narrow parse invalidation while the shared resolver keeps source and datamodel classification aligned.

Generated LTM equations retain their conservative whole-surface shadowing boundary. Production-derived topology tests pin capture removal, dimensioned score coalescing, direct VM values, and loud dynamic refusals.
Capture storage now carries the phase demand of its snapshot consumers, so INIT-only helpers avoid redundant flow work while shared INIT/PREVIOUS storage unions both requirements.

Preserve raw INIT dependency facts as initialization roots, including sparse qualified module outputs, so removing helper phases cannot leave frozen referents uninitialized.
Keep apply-to-all storage shape as the single source of truth for snapshot captures, LTM endpoints, loops, scores, and pins. Phase-aware dependency projections exclude INIT-only syntax while retaining live and PREVIOUS-only state.

Materialize element-dependent defaults only where they are consumed, and preserve loud deterministic refusal for incompatible shapes. Production-derived VM, wasm, LTM, incrementality, artifact, warning, and performance coverage pins the resulting behavior.
Let the canonical stdlib modules own omitted DELAYN and SMTHN initial-value semantics, so computed inputs are evaluated and stored once without ambiguous LTM wiring. Explicit initial arguments remain independent.

Keep per-element hoist context O(rank) by retaining canonical coordinates and resolving full dimension metadata during stage0 replay.
Carry phase, lag, full module-instance path, and terminal identity in one dependency relation so scheduling consumers no longer parse canonical text. Resolve every module hop through tracked per-name metadata projections.

This keeps source scheduling identity available through sparse initialization and diagnostics while leaving lookup-table layout names and compiler-expression facts to their explicit later boundaries.
@bpowers bpowers changed the title engine: carry implicit module arguments as ASTs engine: unify compiler lowering and dependencies Aug 28, 2026
Move the rmcp dependency chain from yanked chacha20 0.10.1 to its semver-compatible 0.10.2 patch release. This restores cargo-deny without changing the dependency graph or enabled features.
Make structured source dependencies the sole scheduling identity while compiler lowering owns only local invariance facts. LTM transformations now receive a syntax-only membership type, and module exit selection preserves complete instance paths instead of reconstructing names.

The conservative invariance fixpoint keeps all source current dependencies, so folded dynamic branches under-hoist safely. Production matrices, exact C-LEARN slot accounting, artifact parity, and paired performance gates pin the boundary.
Lower each explicit and parse-synthesized variable once behind a shared memo handle, then let fragments, units, causal graphs, and LTM borrow or clone that handle. This removes the duplicate whole-model Expr0/Expr2 owners while keeping model topology lightweight and incremental.

Preserve module parse diagnostics and units while resolving wiring, and pin the ownership, invalidation, artifact, and lifecycle-residency boundaries through production-derived tests and profiling.
Use one lossless Diagnostic payload from parsing through public collection, with source context attached once at the database boundary. Recursive LTM queries return pure warning facts, and fragment phase deduplication uses complete attributed identity while preserving independent source occurrences.
Route explicit and ordinary implicit candidates through one deterministic validation, identity, and recursion owner. Share bound-port filtering with emitted module inputs, and keep generated LTM helpers capture-only by construction.
@bpowers

bpowers commented Sep 3, 2026

Copy link
Copy Markdown
Owner Author

Superseded by the restart branch compiler-unification-v2, opened as its own PR (#1040). Three adversarial reviews of this branch found a silent-wrong-number defect (a base-scored LTM link over a whole-array read), a loud refusal regression and a dead production path (the Expr0 fallback classifier); the plan's remaining phases were re-implemented from 5c406dd5 with those commits mined for fixtures and pinned divergences rather than rebased. The design doc on the new branch records every divergence and the per-commit measurements.

@bpowers bpowers closed this Sep 3, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment