Skip to content

ltm: unify the element-graph and link-score reference-site walkers behind a single classification IR #520

Closed

Description

@bpowers

Summary

LTM's element-level causal graph (model_element_causal_edges, src/simlin-engine/src/db_analysis.rs) and its link-score generation (model_ltm_variables, src/simlin-engine/src/db_ltm.rs -- via emit_per_shape_link_scores plus the aggregate-node link-score emitter) each independently walk a target variable's Expr2 AST to decide, for every reference to a source variable:

  1. the access shape -- Bare / FixedIndex(elems) / Wildcard / DynamicIndex;
  2. whether the reference sits inside a hoistable inline reducer (ReferenceSite::in_reducer);
  3. which synthetic $⁚ltm⁚agg⁚{n} aggregate node -- if any -- the reference should be routed through.

These two walkers reach the same conclusions only by convention plus cross-checking tests. There is no single source of truth. The convention is even spelled out in a comment in builtin_is_array_reducer (db_analysis.rs): "the reference-site walker's in_reducer flag agrees exactly with which reducers enumerate_agg_nodes hoists".

The parallel/duplicated logic, concretely:

  • db_analysis.rs: collect_reference_sites -> Vec<ReferenceSite { shape, target_element, in_reducer }>, then an inline reroute decision in model_element_causal_edges (route_through_agg = !routed_aggs.is_empty() && site.in_reducer, where routed_aggs = enumerate_agg_nodes(...).aggs_in_var(to).filter(is_synthetic && reads from)), which fans a routed site out to all synthetic aggs in to that read from.
  • ltm_agg.rs: enumerate_agg_nodes independently walks every variable's AST to find maximal reducer subexpressions and classify each as synthetic vs variable-backed; reducer_is_full_reduce / expr_is_full_extent decide whether a subexpr is hoistable (the GH ltm: sliced reducer sub-expressions are not hoisted into aggregate nodes (stay on the wildcard-link-score path) #514 carve-out).
  • db_ltm.rs: emit_per_shape_link_scores(skip_reducer_shapes) walks again to emit Bare/FixedIndex link scores while skipping the Wildcard shape (the hoisted reducer is scored by its agg's two halves instead); the agg link-score emitter iterates aggs_in_var(to) and emits source[d] -> agg (+ agg -> to[e]).
  • db_analysis.rs: builtin_is_array_reducer -- a recognition-set predicate that must stay in sync with enumerate_agg_nodes's hoist set (currently SUM/MEAN/MIN/MAX/STDDEV/RANK, excluding SIZE and 2-arg MIN/MAX).

Why this is worth fixing

  1. Brittle invariant. "These walkers agree" is enforced by comments + tests, not by sharing code. A future change to enumerate_agg_nodes's recognition set or to the slice carve-out (GH ltm: sliced reducer sub-expressions are not hoisted into aggregate nodes (stay on the wildcard-link-score path) #514) has to be mirrored by hand in builtin_is_array_reducer and in skip_reducer_shapes, or the element graph and the link scores silently disagree -- producing either an element edge with no corresponding link score or a link score for an edge that doesn't exist, which surfaces as a loop_score equation referencing a missing variable -> the fragment compiler's zero-contribution stub-dep fallback -> a silently wrong score (no diagnostic).
  2. Imprecise routing. The element-graph reroute fans a routed reference site out to every synthetic agg in the target that reads the source, rather than to the specific agg whose subexpression syntactically contains that site. Today this is harmless -- each such agg's equation genuinely reads the source, so every emitted edge / link score is real -- but it's a latent footgun and it makes the code harder to reason about.
  3. Three walks instead of one. collect_reference_sites (element graph) + enumerate_agg_nodes (aggs) + emit_per_shape_link_scores (link scores) + the agg emitter each re-derive overlapping facts about the same AST.

Proposed shape

A single salsa-tracked classification -- e.g. fold a richer result into enumerate_agg_nodes, or add model_ltm_reference_sites(db, model, project) -- that, per (from, to) causal edge, produces:

struct ClassifiedSite {
    shape: RefShape,                  // Bare / FixedIndex(elems) / Wildcard / DynamicIndex
    target_element: Option<Ident>,    // e.g. FixedIndex into an arrayed target
    routing: SiteRouting,
}
enum SiteRouting {
    Direct,                           // emit element edges per `shape`; emit a per-`shape` link score
    ThroughAgg { agg: AggId },         // emit `from[d] -> agg` + `agg -> to[e]`; link score = the agg's two halves; no per-`shape` link score for this site
}

AggId already carries kind (Synthetic vs VariableBacked) + owner_var + result_dims (post-#503 work; see commits e607beb, 84c6a62). enumerate_agg_nodes stays the place that decides "is this subexpr a hoistable maximal reducer". Both consumers then only read the IR:

  • model_element_causal_edges: Direct -> emit_edges_for_reference(shape, target_element); ThroughAgg { agg } -> emit from[d] -> agg.name + agg.name -> to[e] (honoring agg.result_dims for arrayed aggs).
  • model_ltm_variables: Direct -> emit the per-shape link score (the existing emit_per_shape_link_scores body, but driven by the IR rather than re-walking); ThroughAgg { agg } -> ensure the agg's source[d] -> agg and agg -> to[e] link scores are emitted, deduped across sites that share an agg.
  • builtin_is_array_reducer disappears -- the recognition set lives in exactly one place.

Net effect: the "element graph and link scores agree" property becomes structural (same IR), the duplicated recognition predicate is gone, routing is per-agg-precise, and three AST walks become one.

Constraints / notes

  • Salsa-friendly: pure function of (db, model, project), deterministic, consuming the same reconstructed Expr2 ASTs the current walkers use -- visit variables in canonical-sorted order, ASTs left-to-right DFS (same discipline enumerate_agg_nodes already follows).
  • No protobuf / on-disk format involved; pure internal refactor. Golden LTM data must be byte-unchanged: scalar / pure-A2A models have no reducers -> no site routes ThroughAgg -> identical output; reducer-bearing fixtures must also be byte-unchanged if the IR faithfully reproduces today's decisions.
  • Discovery mode (parse_link_offsets, ltm_finding.rs) is downstream of the emitted link-score names, not the walkers, so it's unaffected as long as the emitted names don't change.
  • Keep / strengthen the existing cross-checking tests (ref_site_* in db_analysis.rs, the agg_* / element-graph tests) -- they become regression guards for the IR.

Out of scope (separately tracked)

Acceptance

  • A single ClassifiedSite-style IR is the only place reference-site shape + agg routing is decided.
  • Both model_element_causal_edges and model_ltm_variables consume it; neither re-walks the AST for shape/routing.
  • builtin_is_array_reducer is removed (or reduced to a thin re-export of enumerate_agg_nodes's recognition predicate).
  • All existing LTM tests pass; reducer-bearing golden data unchanged.

Tracked under the LTM epic #488.

Activity

  1. added
    ltm
    on May 10, 2026
  2. bpowers commented on May 13, 2026

    @bpowers
    OwnerAuthor

    Resolved by b856480, 9d008f6, 0522f2f, 049455c, 48f80b5, 614c332 — Phase 1 of the LTM arrays hardening plan (docs/design-plans/2026-05-11-ltm-arrays-hardening.md). model_ltm_reference_sites (db_ltm_ir.rs) is now the single salsa-tracked place a causal edge's access shape and aggregate-node routing are decided; model_element_causal_edges, model_edge_shapes, and model_ltm_variables are pure readers. The consolidated reducer_kind/ReducerKind table lives in ltm_agg.rs (builtin_is_array_reducer dropped).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    ltm

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions