Repository navigation
Description
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:
- the access shape --
Bare/FixedIndex(elems)/Wildcard/DynamicIndex; - whether the reference sits inside a hoistable inline reducer (
ReferenceSite::in_reducer); - 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 inmodel_element_causal_edges(route_through_agg = !routed_aggs.is_empty() && site.in_reducer, whererouted_aggs = enumerate_agg_nodes(...).aggs_in_var(to).filter(is_synthetic && readsfrom)), which fans a routed site out to all synthetic aggs intothat readfrom.ltm_agg.rs:enumerate_agg_nodesindependently 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_extentdecide 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 iteratesaggs_in_var(to)and emitssource[d] -> agg(+agg -> to[e]).db_analysis.rs:builtin_is_array_reducer-- a recognition-set predicate that must stay in sync withenumerate_agg_nodes's hoist set (currentlySUM/MEAN/MIN/MAX/STDDEV/RANK, excludingSIZEand 2-argMIN/MAX).
Why this is worth fixing
- 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 inbuiltin_is_array_reducerand inskip_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 aloop_scoreequation referencing a missing variable -> the fragment compiler's zero-contribution stub-dep fallback -> a silently wrong score (no diagnostic). - 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.
- 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 }-> emitfrom[d] -> agg.name+agg.name -> to[e](honoringagg.result_dimsfor arrayed aggs).model_ltm_variables:Direct-> emit the per-shapelink score (the existingemit_per_shape_link_scoresbody, but driven by the IR rather than re-walking);ThroughAgg { agg }-> ensure the agg'ssource[d] -> aggandagg -> to[e]link scores are emitted, deduped across sites that share an agg.builtin_is_array_reducerdisappears -- 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 reconstructedExpr2ASTs the current walkers use -- visit variables in canonical-sorted order, ASTs left-to-right DFS (same disciplineenumerate_agg_nodesalready 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_*indb_analysis.rs, theagg_*/ element-graph tests) -- they become regression guards for the IR.
Out of scope (separately tracked)
- ltm: sliced reducer sub-expressions are not hoisted into aggregate nodes (stay on the wildcard-link-score path) #514 -- hoisting sliced-reducer subexpressions. The IR makes this easier (
AggIdcould grow aread_slicefield), but the carve-out's current behavior is independent of this refactor. - ltm: MAX_AGG_PETALS=8 caps (and drops) cross-element-through-aggregate loop recovery; per-subset (not per-ordering) enumeration #515 --
MAX_AGG_PETALScap shape (drop vs truncate; per-subset vs per-ordering enumeration). - ltm: cross-element loops through aggregate nodes always classify as Undetermined (agg-hop link polarity is always Unknown) #516 -- agg-hop link polarity always
Unknown(arecover_cross_agg_loopsissue, not a walker issue). - engine: SUM(PREVIOUS(arr[*])) silently evaluates to 0.0 under an active A2A dimension (no LoadPrev-of-array-view path) #517 --
SUM(PREVIOUS(arr[*]))evaluates to 0 under A2A (a codegen /wrap_non_matching_in_previousissue).
Acceptance
- A single
ClassifiedSite-style IR is the only place reference-site shape + agg routing is decided. - Both
model_element_causal_edgesandmodel_ltm_variablesconsume it; neither re-walks the AST for shape/routing. builtin_is_array_reduceris removed (or reduced to a thin re-export ofenumerate_agg_nodes's recognition predicate).- All existing LTM tests pass; reducer-bearing golden data unchanged.
Tracked under the LTM epic #488.
Activity
engine: LTM cross-element aggregate scoring (aggregate nodes) (#519)
doc: add LTM arrays hardening design plan
bpowers commentedon May 13, 2026
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, andmodel_ltm_variablesare pure readers. The consolidatedreducer_kind/ReducerKindtable lives inltm_agg.rs(builtin_is_array_reducerdropped).