Skip to content

engine: enumerate rank element loops - #796

Merged
bpowers merged 5 commits into
mainfrom
codex/ltm-rank-all-elements
Jun 18, 2026
Merged

bpowers merged 5 commits into
mainfrom
codex/ltm-rank-all-elements

Conversation

@bpowers

@bpowers bpowers commented Jun 18, 2026

Copy link
Copy Markdown
Owner

Summary

  • Represent array-valued RANK with synthetic arrayed aggregate helpers while keeping it out of scalar reducer hoisting.
  • Route bare and wildcard RANK arguments through the same helper so every ranked source row feeds every rank output slot in its iterated context.
  • Emit matching source-to-rank-helper link scores and update LTM tests to cover cross-element rank-mediated loops.

Tests

  • cargo test -p simlin-engine rank_
  • cargo test -p simlin-engine ltm_agg::tests
  • Pre-commit hook passed: dependency policy, docs links, project lint rules, Rust fmt/cbindgen/clippy/test, TypeScript lint/build/tsc/test, pysimlin tests.

Fixes #776

Represent array-valued RANK with synthetic arrayed aggregate helpers so bare and wildcard ranked arguments share the same element graph topology. Each ranked source row now feeds every rank output slot in its iterated context, which lets rank-mediated cross-element loops be enumerated and scored through the existing aggregate halves.

Keep RANK out of scalar-reducer hoisting while marking its reference sites as aggregate-routed. The link-score path still uses the existing conservative delta-ratio treatment for rank source halves, but now emits one score per source row and rank output slot so loop scoring has names for the new edges.
@codecov

codecov Bot commented Jun 18, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 87.52437% with 64 lines in your changes missing coverage. Please review.
✅ Project coverage is 90.83%. Comparing base (dba4081) to head (3212428).

Files with missing lines Patch % Lines
src/simlin-engine/src/db/ltm/link_scores.rs 79.31% 42 Missing ⚠️
src/simlin-engine/src/db/analysis.rs 71.05% 11 Missing ⚠️
src/simlin-engine/src/ltm_agg.rs 95.94% 11 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main     #796      +/-   ##
==========================================
- Coverage   90.88%   90.83%   -0.05%     
==========================================
  Files         224      224              
  Lines      142193   142627     +434     
==========================================
+ Hits       129225   129562     +337     
- Misses      12968    13065      +97     

☔ 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 Jun 18, 2026

Copy link
Copy Markdown

Review

[P2] Non-deterministic result_dims for multi-source RANK with positionally-mapped axes

File: src/simlin-engine/src/ltm_agg.rs:1137-1164

rank_result_dims_from_read_slice picks a source via slices.per_var.iter().find(...) and derives a Reduced axis result dim from that source declared dim name. per_var is a HashMap whose iteration order varies across processes, so when a RANK arg has two or more arrayed sources sharing the canonical slice but with positionally-mapped, differently-named axes (e.g. RANK(a[*] + b[*], 1) with a[Region] and b[State] and a State to Region positional mapping), the find can return either source. The resulting AggNode.result_dims (e.g. ["Region"] vs ["State"]) flows into agg-name subscripting, link-score equation generation, and the rank_dim_element_lists fallback in emit_source_to_agg_link_scores, so the LTM output for the same model can differ between processes/runs. Iterating per_var in canonical-sorted-by-key order (or switching to BTreeMap) would make the selection deterministic.

Overall correctness: correct

Edge case only; the main code paths (single arrayed source, scalar feeder, whole-extent or sliced RANK on one variable) appear to be exercised by the new element_graph_rank_arg_reads_all_elements_for_bare_and_wildcard_spellings test and the updated rank_frozen_subtree_link_score_scores_correctly integration test.

@bpowers
bpowers marked this pull request as ready for review June 18, 2026 04:50
@bpowers

bpowers commented Jun 18, 2026

Copy link
Copy Markdown
Owner Author

@codex review

Choose the RANK synthetic aggregate result dimension source from the sorted source list instead of iterating per_var, so mapped axes with equivalent canonical slices are deterministic.

Add a regression covering multi-source RANK inputs with positionally mapped axes.

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

ℹ️ 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 thread src/simlin-engine/src/ltm_agg.rs Outdated
match axis {
AxisRead::Pinned(_) => {}
AxisRead::Iterated { .. } => {
per_output_axis.push(vec![iterated_slots.next()?.clone()]);

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 Treat active RANK dimensions as ranked axes

For the normal active-dimension spelling out[D] = RANK(source[D], 1), classify_axis_access records the source axis as Iterated, but the compiler handles active dims inside vector builtins via with_vector_builtin_wildcards, so every source[D] row can change every rank output slot. Fixing Iterated axes to the current row here emits only source[a] -> agg[a] and misses cross-element source[a] -> agg[b] edges/scores, so rank-mediated loops remain under-enumerated for the syntax used by the existing RANK tests.

Useful? React with 👍 / 👎.

Comment thread src/simlin-engine/src/ltm_agg.rs Outdated
result_dims.push(canonical_dim_to_datamodel(dim, ctx.dm_dims));
}
AxisRead::Reduced { subset: _ } => {
result_dims.push(canonical_dim_to_datamodel(source_dim.name(), ctx.dm_dims));

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 Preserve subdimension rank result dimensions

When the ranked argument is a proper StarRange such as ranking[Core] = RANK(arr[*:Core], 1), the ranked array's result view is the subdimension Core, but this maps every Reduced axis back to the parent source dimension (for example Region). The synthetic helper is then emitted as agg[Region] = rank(arr[*:Core], 1), creating extra/mismatched slots and causing LTM helper compilation or scoring to drop valid subdimension-rank cases.

Useful? React with 👍 / 👎.

@claude

claude Bot commented Jun 18, 2026

Copy link
Copy Markdown

Code review

[P2] Multi-source array-valued RANK with mapped axes emits wrong slot names

File: src/simlin-engine/src/ltm_agg.rs lines 1922-1947 (and callers in src/simlin-engine/src/db/analysis.rs lines 987-996 and src/simlin-engine/src/db/ltm/link_scores.rs lines 2671-2675)

rank_output_slot_parts_for_row builds rank-output slot names from source_dim_element_lists (the per-source dim elements) for Reduced axes. But the agg slots are keyed off AggNode::result_dims, which rank_result_dims_from_read_slice derives from the canonical (first-by-sorted-name) source dimension. For the case the new rank_multi_source_result_dims_use_sorted_source_order test mints (a[Region], b[State] with a positional State to Region mapping, result_dims = Region), the b-source path emits edges/link-score names like b[s1] arrow agg[s1] while the agg actual element nodes are agg[r1]/agg[r2] -- leaving the source to agg edges and matching link scores dangling, so loops through any non-canonical mapped source go unscored. The metadata-only assertions in the new test do not exercise this path; this only manifests for multi-source RANK whose sources use differently-named (mapped or disjoint) dims. A fix would either pass result-dim elements for Reduced axes or remap each source reduced-axis elements through iterated_axis_slot_elements before building the slot tuples.

Overall correctness verdict

Not correct (narrow case). Single-source RANK (the dominant case and the only case covered by the end-to-end test rank_frozen_subtree_link_score_scores_correctly) appears to work as advertised. The multi-source RANK shape the PR explicitly adds support for (via rank_multi_source_result_dims_use_sorted_source_order) silently produces dangling source to agg edges/scores whenever the non-canonical source carries a different (mapped) dimension.

Treat every non-pinned RANK input axis as part of the ranked output view, including active-dimension spellings that scalar reducer slice logic records as Iterated.

RANK source-to-helper edges and scores now use the helper result dimensions for slot names, preserving subdimension views and remapping mapped sibling sources onto the canonical helper slots.
@bpowers

bpowers commented Jun 18, 2026

Copy link
Copy Markdown
Owner Author

@codex review

@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: 8aecae036e

ℹ️ 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 thread src/simlin-engine/src/ltm_agg.rs Outdated
Comment on lines +1966 to +1967
AxisRead::Iterated { .. } | AxisRead::Reduced { .. } => {
per_output_axis.push(result_axis_elements.next()?.clone());

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 Keep RANK iterated axes pinned per source row

When a RANK helper has both an iterated context axis and a ranked axis (for example r[Region,Product] = RANK(matrix[Region,*], 1)), this branch treats Iterated the same as Reduced and cartesian-products every Region output slot for every matrix row. A row like matrix[north,x] is then wired/scored as feeding $⁚ltm⁚agg⁚0[south,y], even though that helper slot evaluates RANK(matrix[south,*], 1) and cannot read the north row, so LTM enumerates phantom cross-region loops and emits link-score variables for non-existent reads; the iterated slot parts from read_slice_row_parts need to be preserved while only the ranked/reduced axes fan out.

Useful? React with 👍 / 👎.

@claude

claude Bot commented Jun 18, 2026

Copy link
Copy Markdown

Review summary

I traced the new array-valued RANK aggregate path end-to-end:

  • the new builtin_routes_through_agg predicate and the agg_candidate_for_builtin dispatch in walk_var_equation/walk_subexpr_for_aggs (whole-RHS RANK correctly mints synthetic, never variable-backed);
  • rank_source_vars / rank_combined_read_slice / rank_result_dims_from_read_slice (sorted-source determinism for multi-source RANK; subdimension recovery via rank_reduced_axis_result_dim);
  • rank_output_slot_parts_for_row and cartesian_element_parts (Pinned-aware slot enumeration, arity-checked fallback);
  • the array_valued_rank branches in emit_agg_routed_edges and emit_source_to_agg_link_scores (scalar-feeder/projection-feeder early returns still fire first, dim_ctx lookups go through from_raw which canonicalizes);
  • the IR change in db::ltm_ir (RANK's direction arg now in_reducer=true is benign: Bare shapes aren't reclassified, and there's no matching agg key so it stays Direct);
  • the LTM test that pins three rank-mediated loops (north/south self-rank + cross-element) and the element-graph tests covering bare/wildcard/active-dim/mapped/StarRange spellings.

Overall correctness: correct — no blocking findings. The mapped-source result-dim picker is order-dependent (first sorted source whose slice matches canonical wins), which is explicitly documented and tested, and the equation generators on the RANK source-half are the documented delta-ratio stand-in. The only nit I noticed is purely cosmetic: rank_output_slot_parts_for_row and qualified_coreduced are recomputed inside the per-row loops in emit_agg_routed_edges and emit_source_to_agg_link_scores despite being row-invariant — minor, not worth blocking.

Keep array-valued RANK helpers fanned out across ranked axes while preserving iterated context axes for slices like RANK(matrix[Region,*], 1).

The source-to-helper edge and link-score paths now both pass the row slot context into the shared RANK slot helper, and RANK comparison rows are grouped by that context when reduced axes are present.
@bpowers

bpowers commented Jun 18, 2026

Copy link
Copy Markdown
Owner Author

@codex review

@claude

claude Bot commented Jun 18, 2026

Copy link
Copy Markdown

Reviewed the array-valued RANK aggregation changes. Traced through rank_output_slot_parts_for_row, rank_result_dims_from_read_slice, the new array_valued_rank branches in emit_agg_routed_edges / emit_source_to_agg_link_scores, and the builtin_routes_through_agg reclassification side-effects.

The logic looks consistent across both surfaces (element edges and link scores) and the determinism story (sorted source_vars driving canonical source selection, slot grouping by iterated context) holds up. Test coverage is thorough: bare/wildcard/active-dim spellings, mapped sibling sources, StarRange subdimensions, mixed context/ranked axes, and an end-to-end LTM run that pins the cross-element rank-ordering loop.

No findings.

Overall correctness: 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: 8a88a4fabc

ℹ️ 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 +1181 to +1182
let Some(subset) = subset else {
return canonical_dim_to_datamodel(source_dim.name(), ctx.dm_dims);

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 Remap RANK helper dims before scoring mapped targets

When a RANK input is over a dimension that is only positionally mapped to the target, e.g. score[State] feeding ranked[Region] = RANK(score[*], 1) with State -> Region, returning the source dimension here makes the synthetic helper arrayed over State. The downstream agg→target score emitter only projects helper slots by exact target-dimension names, so it emits bare $⁚ltm⁚agg⁚0→ranked[r] score variables that fail to compile instead of mapped $⁚ltm⁚agg⁚0[s]→ranked[r] scores, and loops through the rank are dropped/stubbed. Please either choose the mapped target dimension for these RANK result axes or teach the agg→target scoring path to project mapped result dims.

Useful? React with 👍 / 👎.

Keep RANK helpers dimensioned over the ranked source view, then remap agg-to-target score projections through the project dimension mapping when the target uses a mapped dimension.

This preserves the helper semantics while making the link-score name, denominator, and body pin agree on the same mapped helper slot for target elements.
@bpowers

bpowers commented Jun 18, 2026

Copy link
Copy Markdown
Owner Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Nice work!

Reviewed commit: 32124288fc

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

@claude

claude Bot commented Jun 18, 2026

Copy link
Copy Markdown

Code review

Traced the array-valued RANK aggregation path end-to-end: agg_candidate_for_builtin dispatch, rank_source_vars/rank_combined_read_slice/rank_result_dims_from_read_slice, rank_output_slot_parts_for_row, the new array_valued_rank branches in emit_agg_routed_edges / emit_source_to_agg_link_scores, and the target_projection_for_result_dims positional-mapping projection in emit_agg_to_target_link_scores.

Spot-checked the active-dim spelling (RANK(pop[Region], 1) fans out across all output slots), mixed context/ranked (RANK(matrix[Region,*], 1) pins each row to its iterated context via rank_rows_by_iterated_slot), mapped-source result_dim selection (sorted-source determinism is now load-bearing and pinned by rank_multi_source_result_dims_use_sorted_source_order), and mapped helper→target projection (RANK(score[*], 1) with State→Region mapping correctly remaps r1→s1 slot via mapped_element_correspondence). Two prior P2 findings from earlier review rounds — non-deterministic per_var iteration and source-dim element names in slot tuples — are addressed by the sorted-source find and by switching the slot enumerator to consume the agg's result_dim_element_lists. Scalar-feeder and projection-feeder early returns still precede the new RANK code path, so existing feeder semantics are preserved. The rank_rows_by_iterated_slot[slot_parts] index is safe because both the populate and lookup loops gate on the same has_reduced_rank_axis and iterate the same rows.

The behavioral change in target_projection_for_result_dims (now consulting dim_ctx and positional mappings) is a no-op for scalar reducers because their result_dims are always target dim names by construction (result_dims_from_read_slice pushes the Iterated.dim target field). The new mapped branch only fires when a result_dim is the source dim — i.e., RANK's Reduced axis result_dim.

No blocking findings.

Overall correctness verdict

Correct.

@bpowers
bpowers merged commit 871022c into main Jun 18, 2026
14 of 15 checks passed
@bpowers
bpowers deleted the codex/ltm-rank-all-elements branch June 18, 2026 21:27
@bpowers bpowers mentioned this pull request Jul 29, 2026
1 of 29 tasks
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.

ltm: de-hoisted array-valued RANK gets diagonal-only element edges, so rank-mediated cross-element loops are not enumerated

1 participant