Skip to content

engine: implement indexed dimension broadcasting support - #142

Merged
bpowers merged 4 commits into
mainfrom
claude/array-indexed-broadcasting-J9rLW
Jan 2, 2026
Merged

bpowers merged 4 commits into
mainfrom
claude/array-indexed-broadcasting-J9rLW

Conversation

@bpowers

@bpowers bpowers commented Jan 2, 2026

Copy link
Copy Markdown
Owner

This implements support for broadcasting arrays with different indexed
dimensions that have the same size. For example, sales[Products] +
costs[Regions] now works when Products and Regions are both indexed
dimensions with matching sizes.

Key changes:

  1. Extended unify_dims_with_names in ast/expr2.rs to support:

    • Indexed dimension matching by size (when names don't match)
    • UNION broadcasting: combining dimensions from both arrays when
      neither is a subset of the other (e.g., a[X] + b[Y] → result[X,Y])
    • Named dimensions still require exact name matching (semantic safety)
  2. Added is_indexed_dimension method to Expr2Context trait to distinguish
    indexed dimensions from named dimensions during type checking.

  3. Added dimension matching infrastructure in compiler.rs:

    • find_target_for_source: name-first then size-based matching for indexed dims
    • DimensionMapping, match_dimensions, broadcast_view: scaffolding for future optimizations
  4. Added comprehensive tests:

    • Enabled 6 previously ignored broadcasting tests
    • Added 6 new N-dimensional tests (3D/4D broadcasting)

The implementation correctly distinguishes between indexed dimensions
(which can match by size) and named dimensions (which must match by name).
This prevents semantic errors like adding sales[Cities] + prices[Products]
just because both dimensions happen to have the same size.

This implements support for broadcasting arrays with different indexed
dimensions that have the same size. For example, sales[Products] +
costs[Regions] now works when Products and Regions are both indexed
dimensions with matching sizes.

Key changes:

1. Extended unify_dims_with_names in ast/expr2.rs to support:
   - Indexed dimension matching by size (when names don't match)
   - UNION broadcasting: combining dimensions from both arrays when
     neither is a subset of the other (e.g., a[X] + b[Y] → result[X,Y])
   - Named dimensions still require exact name matching (semantic safety)

2. Added is_indexed_dimension method to Expr2Context trait to distinguish
   indexed dimensions from named dimensions during type checking.

3. Added dimension matching infrastructure in compiler.rs:
   - find_target_for_source: name-first then size-based matching for indexed dims
   - DimensionMapping, match_dimensions, broadcast_view: scaffolding for future optimizations

4. Added comprehensive tests:
   - Enabled 6 previously ignored broadcasting tests
   - Added 6 new N-dimensional tests (3D/4D broadcasting)

The implementation correctly distinguishes between indexed dimensions
(which can match by size) and named dimensions (which must match by name).
This prevents semantic errors like adding sales[Cities] + prices[Products]
just because both dimensions happen to have the same size.
@bpowers

bpowers commented Jan 2, 2026

Copy link
Copy Markdown
Owner Author

@codex review

The plan has been fully implemented in commit 3621911. All features
described in the plan are now working:
- Indexed dimension matching by size
- UNION broadcasting for different dimension arrays
- Named dimension safety (name-only matching)
- N-dimensional support (3D, 4D tested)

All 476 tests pass.
@claude

claude Bot commented Jan 2, 2026

Copy link
Copy Markdown

PR Review: Indexed Dimension Broadcasting Support

This PR implements a sophisticated feature for broadcasting arrays with different indexed dimensions that have matching sizes. The implementation is well-designed with strong semantic safety guarantees. Here's my detailed review:

Strengths

1. Excellent Semantic Safety

  • The distinction between indexed dimensions (can match by size) and named dimensions (must match by name) prevents dangerous semantic errors
  • The example in the PR description is spot-on: preventing sales[Cities] + prices[Products] when both happen to have the same size is critical for correctness
  • This design choice demonstrates deep understanding of the domain

2. Comprehensive Test Coverage

  • 6 previously ignored tests now enabled
  • 6 new N-dimensional tests (3D/4D broadcasting)
  • Good edge case coverage: name-before-size matching, UNION broadcasting, partial dimension matching
  • Tests are well-documented with explicit expected values

3. Well-Structured Algorithm

  • Two-phase matching (name first, then size for indexed dims) is clean and predictable
  • UNION broadcasting logic (lines 353-402 in expr2.rs) correctly handles disjoint dimensions
  • The find_matching_dimension helper promotes code reuse

4. Future-Proofing

  • DimensionMapping, match_dimensions, and broadcast_view scaffolding in compiler.rs shows good planning for future optimizations
  • Dimension-agnostic design works for arbitrary N-dimensional arrays

Issues and Concerns

1. Potential Duplicate Matching Bug
In compiler.rs:1013-1035, the wildcard generation uses a greedy matching approach:

let mut used_targets = vec![false; active_dims.len()];
source_dims
    .iter()
    .map(|source_dim| {
        let target_idx = find_target_for_source(source_dim, active_dims, &used_targets);
        if let Some(idx) = target_idx {
            used_targets[idx] = true;  // Mark as used
            ...

However, in expr2.rs:313-339, the can_match_dimension helper does NOT check if dimensions are already matched:

fn can_match_dimension<C: Expr2Context>(
    ctx: &C,
    name: &str,
    size: usize,
    other_map: &std::collections::HashMap<&str, usize>,
    other_names: &[String],
) -> bool {
    if other_map.contains_key(name) {
        return true;  // No uniqueness check!
    }
    // size-based matching also doesn't track usage
    ...

Scenario: Consider a[X(3), Y(3)] unified with b[Z(3)] where X, Y, Z are all indexed dimensions of size 3. The can_match_dimension might allow Z to match both X and Y since it only checks if a match exists, not if it's unique.

Recommendation: Add a used parameter to can_match_dimension or refactor to use find_matching_dimension which already handles this correctly.

2. Incomplete broadcast_view Function
The broadcast_view function at line 4636 appears truncated:

Some(ArrayView {
    dims: new_dims,
    // Missing fields? strides, dim_names, offset, data?

Recommendation: Either complete this function or add a TODO/unimplemented!() to make it clear this is scaffolding.

3. Missing Size Validation in UNION Case
In the UNION broadcasting path (expr2.rs:378-402), when combining dimensions from both arrays, there's no explicit size validation between matched indexed dimensions:

for (b_name, &b_size) in b_names.iter().zip(b_dims.iter()) {
    let already_matched = Self::find_matching_dimension(ctx, b_name, b_size, a_names, a_dims).is_some();
    if !already_matched {
        unified_dims.push(b_size);  // Added without size check
        unified_names.push(b_name.clone());
    }
}

If a[X(3)] and b[X(5)] are unified (UNION case with different sizes for same name), this would silently create incorrect results.

Recommendation: When dimensions match by name but have different sizes in UNION broadcasting, return MismatchedDimensions error. Add explicit size validation:

if let Some((matched_name, matched_size)) = already_matched {
    if b_size != matched_size {
        return eqn_err!(MismatchedDimensions, loc.start, loc.end);
    }
}

4. Test Coverage Gap: Named Dimension Safety
While the implementation correctly prevents named dimension UNION broadcasting, there's no explicit test for this critical safety feature.

Recommendation: Add a test that verifies named dimensions with the same size do NOT broadcast:

#[test]
#[should_panic] // or assert compilation error
fn named_dims_same_size_no_broadcast() {
    let project = TestProject::new("named_no_broadcast")
        .named_dimension("Cities", vec!["NYC", "LA", "Chicago"])
        .named_dimension("Products", vec!["A", "B", "C"])
        .array_aux("sales[Cities]", "...")
        .array_aux("prices[Products]", "...")
        .array_aux("invalid[Cities, Products]", "sales + prices"); // Should fail
}

5. Minor: Inconsistent Error Handling
The test at line 2333 (out_of_bounds_iteration_returns_nan) is still marked #[ignore] with a TODO comment, but this PR doesn't address it. While not critical, consider either removing the test or filing a separate issue to track this work.

Performance Considerations

1. HashMap Construction
Lines 296-306 in expr2.rs build HashMaps for every dimension unification. For small arrays (2-3 dimensions), this is fine, but consider:

  • Most unifications will be simple name matches
  • HashMap overhead might exceed benefit for small dimension counts

Suggestion: Add a fast path for exact name sequence matching before building HashMaps:

// Fast path: exact match
if a_names == b_names {
    // Just verify sizes match
    if a_dims.iter().zip(b_dims).all(|(a, b)| a == b) {
        return Ok((a_dims.to_vec(), Some(a_names.to_vec())));
    }
}

2. Multiple Scans in UNION Case
The UNION broadcasting logic scans dimensions multiple times:

  • Lines 361-368: Check a's dimensions for matches
  • Lines 369-376: Check b's dimensions for matches
  • Lines 390-399: Build unified dimensions

Suggestion: Could be combined into a single pass with early returns.

Code Quality

Positive:

  • Clear comments explaining the algorithm
  • Good function decomposition
  • Consistent naming conventions
  • Proper use of Rust idioms (let-chains, Option/Result)

Minor Issues:

  • Line 4554: #[allow(dead_code)] on DimensionMapping - while noted as scaffolding, consider adding a timeline or issue reference for when this will be used
  • The nested function can_match_dimension (lines 313-339) could be moved to a module-level helper for testability

Security Concerns

None identified. The dimension matching logic is purely computational and doesn't involve external input or unsafe operations.

Recommendations Summary

Must Fix:

  1. Add size validation in UNION broadcasting when dimension names match
  2. Complete or stub out the broadcast_view function
  3. Verify can_match_dimension doesn't allow duplicate matching

Should Fix:
4. Add test coverage for named dimension safety
5. Add fast path for exact dimension matching (performance)

Nice to Have:
6. Add issue references for #[allow(dead_code)] scaffolding
7. Consolidate UNION broadcasting scans into single pass

Conclusion

This is a high-quality PR that adds significant functionality with strong semantic guarantees. The core algorithm is sound, the test coverage is excellent, and the code is well-documented. The main concerns are around edge case handling in the UNION broadcasting path and ensuring the duplicate matching scenario is properly handled. With the recommended fixes, this would be ready to merge.

Estimated review score: 8.5/10 - Excellent work overall, with a few edge cases to address.

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

ℹ️ 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 +4615 to +4619
for (i, target) in target_dims.iter().enumerate() {
if !used[i]
&& let Dimension::Indexed(_, target_size) = target
&& source_size == target_size
{

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 Reserve exact name matches before size-based matching

The size-based fallback here can consume a target dimension that should be reserved for a later exact name match, because matching is done sequentially per source dimension. If target dims are [Second(3), First(3)] and source dims are [Other(3), Second(3)], the first source (Other) size-matches Second, so the later Second name match is forced to size-match First, effectively swapping dimensions and broadcasting against the wrong axis. This produces incorrect results whenever same-sized indexed dims exist and source/target orders differ. A safer approach is to pre-assign all exact name matches first (or exclude targets that have pending exact-name matches) before applying size-based matching.

Useful? React with 👍 / 👎.

@github-actions

github-actions Bot commented Jan 2, 2026

Copy link
Copy Markdown

❌ Visual regression tests failed. View artifacts to see the differences.

@codecov

codecov Bot commented Jan 2, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 89.93711% with 16 lines in your changes missing coverage. Please review.
✅ Project coverage is 72.21%. Comparing base (9db385d) to head (3bfe53b).
⚠️ Report is 1 commits behind head on main.

Files with missing lines Patch % Lines
src/simlin-engine/src/ast/expr2.rs 80.00% 15 Missing ⚠️
src/simlin-engine/src/ast/mod.rs 83.33% 1 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main     #142      +/-   ##
==========================================
+ Coverage   71.99%   72.21%   +0.22%     
==========================================
  Files          43       43              
  Lines       13142    13270     +128     
==========================================
+ Hits         9461     9583     +122     
- Misses       3681     3687       +6     

☔ View full report in Codecov by Sentry.
📢 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.

@github-actions

github-actions Bot commented Jan 2, 2026

Copy link
Copy Markdown

❌ Visual regression tests failed. View artifacts to see the differences.

This addresses several issues identified in code review:

1. P1 FIX: Reserve exact name matches before size-based matching
   - Refactored dimension matching to use two-pass approach
   - Pass 1: Assign all exact name matches (reserve them)
   - Pass 2: For remaining sources, do size-based matching
   - Prevents greedy size-matching from stealing targets meant for name matches
   - Added match_dimensions_two_pass and match_dimensions_two_pass_partial

2. Fixed duplicate matching bug in can_match_dimension (expr2.rs)
   - Replaced per-dimension checking with can_all_match function
   - Properly tracks used targets to prevent same target matching multiple sources
   - Example: a[X(3), Y(3)] vs b[Z(3)] now correctly fails (X and Y can't both use Z)

3. Added size validation in UNION case
   - When dimensions match by name in UNION broadcasting, now validates sizes
   - Prevents silent size mismatches like a[X(3)] + b[X(5)]

4. Verified broadcast_view function is complete (no truncation)

Added new tests:
- name_match_reserved_before_size_match: verifies P1 fix
- duplicate_dimension_usage_tracking: verifies usage tracking
- named_dims_union_broadcasting_error: verifies named dim safety
- broadcast_1d_to_2d_correct_axis: verifies broadcast axis selection

All 480 tests pass.
@claude

claude Bot commented Jan 2, 2026

Copy link
Copy Markdown

Code Review Summary

This is an excellent implementation of indexed dimension broadcasting support. The PR demonstrates strong software engineering practices and a systematic approach to solving a complex problem.

Strengths

1. Exceptional Test Coverage

  • Enabled 6 previously ignored tests that define expected behavior
  • Added 6 comprehensive N-dimensional tests (3D, 4D) demonstrating the general-purpose nature of the solution
  • Added 4 edge case tests targeting specific bugs identified during implementation
  • Test-first approach ensures the implementation is driven by clear requirements
  • Tests include detailed comments explaining expected behavior with concrete examples

2. Well-Documented Implementation

  • Clear documentation of the two-pass matching algorithm (name matches reserved before size matches)
  • Inline comments explain key semantic distinctions (indexed vs named dimensions)
  • Function-level documentation describes purpose, algorithm, and edge cases
  • Commit messages follow the project style and provide excellent "why" context

3. Sound Algorithm Design

  • Two-pass matching correctly prioritizes name matches over size matches, preventing the P1 bug where greedy matching could "steal" targets
  • Usage tracking prevents multiple source dimensions from incorrectly matching the same target
  • UNION broadcasting properly validates that only indexed dimensions participate in cross-dimension broadcasting
  • Dimension-agnostic: Works for any N dimensions without special-casing

4. Semantic Safety

  • Correctly distinguishes between indexed dimensions (can match by size) and named dimensions (must match by name)
  • Prevents semantic errors like combining Cities and Products just because they have the same size
  • UNION case validation ensures named dimensions cannot be combined incorrectly

5. Code Quality

  • Functions are well-factored with clear single responsibilities
  • match_dimensions_two_pass and match_dimensions_two_pass_partial handle full and partial matching separately
  • Helper functions like can_all_match and find_matching_dimension are appropriately scoped
  • Dead code is marked with #[allow(dead_code)] and comments explain it's scaffolding for future optimizations

Issues and Recommendations

Minor Issues

1. Comment Syntax Inconsistency

Several comments use / instead of //:

// In expr2.rs:275-276
/ - SPECIAL: Indexed dimensions with same size are considered compatible even with different names
/ - Output dimension order: larger array's dimensions (or first if equal)

// In expr2.rs:299-301
/ For example, a[X(3), Y(3)] vs b[Z(3)]:
/ - Without usage tracking: X matches Z, Y matches Z → incorrectly reports a can match b
/ - With usage tracking: X matches Z, Y has no remaining match → correctly reports failure

These should use // for consistency with Rust standards.

2. Test Mock Returns Wrong Value

In expr2.rs:952-955, the test mock for is_indexed_dimension returns false with a comment saying "assume all dimensions are indexed":

fn is_indexed_dimension(&self, _name: &str) -> bool {
    // For tests, assume all dimensions are indexed
    false  // This is backwards!
}

The comment and implementation don't match. If tests assume all dimensions are indexed, it should return true. However, this may be intentional if the unit tests in that module don't exercise dimension matching. Consider clarifying or fixing.

3. UNION Broadcasting Size Validation

When dimensions match by name in the UNION case (expr2.rs:407-423), the code finds a match but doesn't validate that sizes are equal:

Some((matched_name, matched_size)) => {
    // Already present in a, don't add again
}

If a[X(3)] and b[X(5)] are being combined, this would silently skip the size mismatch. Consider adding size validation:

Some((matched_name, matched_size)) => {
    if matched_size != b_size {
        return eqn_err!(MismatchedDimensions, loc.start, loc.end);
    }
    // Already present in a, don't add again
}

UPDATE: Reviewing the third commit message, it appears this was supposed to be addressed. Please verify this is working correctly.

Enhancement Opportunities

4. broadcast_view Sparse Array Handling

The broadcast_view function at compiler.rs:4707-4741 always creates an empty sparse vector:

Some(ArrayView {
    dims: new_dims,
    strides: new_strides,
    offset: source_view.offset,
    sparse: Vec::new(),  // Always empty
    dim_names: new_dim_names,
})

If source_view.sparse is non-empty, this information is lost. Consider whether sparse information needs to be preserved or transformed. The comment indicates this is "scaffolding for future optimization", so this may be acceptable for now, but should be documented.

5. Performance: Unused Result Allocations

In can_all_match (expr2.rs:305-360), there's a source_matched vector that tracks whether each source found a match. This is allocated and populated but the function only returns a boolean. Consider whether the matching information could be reused to avoid redundant work in the subsequent dimension building phase.

Security & Correctness

No security concerns identified. The implementation:

  • Properly validates all inputs
  • Uses appropriate error handling
  • Doesn't introduce unbounded allocations (dimension counts are always small)
  • Has comprehensive test coverage including edge cases

Performance

The algorithm is O(n²) in the number of dimensions, which is acceptable since models rarely have more than 5-10 dimensions. The two-pass approach adds a constant factor but ensures correctness.

Conclusion

This is high-quality work that demonstrates:

  • Strong test-driven development practices
  • Clear understanding of the problem domain
  • Attention to semantic correctness and edge cases
  • Good software engineering discipline

The minor issues noted above don't detract from the overall quality. The implementation is ready to merge with only minor comment syntax fixes needed (the single-slash comments).

Recommendation: Approve with minor revisions (fix comment syntax, verify UNION size validation)

@bpowers

bpowers commented Jan 2, 2026

Copy link
Copy Markdown
Owner Author

@codex review

@github-actions

github-actions Bot commented Jan 2, 2026

Copy link
Copy Markdown

❌ Visual regression tests failed. View artifacts to see the differences.

Addresses code review feedback:

1. Fixed misleading comment in TestContext.is_indexed_dimension
   - Comment said "assume all dimensions are indexed" but returned false
   - Clarified that tests treat dimensions as named (not indexed) for
     conservative behavior - dimensions must match by name only
   - Tests needing indexed dimension behavior should use TestProject

2. Documented sparse array handling in broadcast_view
   - Added doc comment explaining that sparse info is not preserved
   - Added inline comment at the Vec::new() call
   - Noted that future sparse preservation would require transforming
     indices to account for dimension reordering and broadcasting

3. Verified UNION size validation is working correctly
   - Confirmed lines 411-416 in expr2.rs validate matched dimension sizes
   - Size mismatches between same-named dimensions return MismatchedDimensions

4. Checked for / comment syntax issues - none found in current code
   (may have been fixed in earlier commits)

All 480 tests pass.

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

ℹ️ 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 +952 to +954
fn is_indexed_dimension(&self, _name: &str) -> bool {
// For tests, assume all dimensions are indexed
false

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P3 Badge Make TestContext treat dims as indexed

The test-only Expr2Context implementation says it should assume all dimensions are indexed, but it currently returns false unconditionally. That means unit tests that rely on unify_dims_with_names will never exercise the size-based indexed-dimension matching path and can mask regressions in the new broadcasting logic. Returning true (or consulting self.dimensions) would align behavior with the comment and keep tests meaningful.

Useful? React with 👍 / 👎.

@claude

claude Bot commented Jan 2, 2026

Copy link
Copy Markdown

PR Review: Indexed Dimension Broadcasting Support

I've reviewed this PR implementing indexed dimension broadcasting support. This is a substantial and well-executed feature addition that enables operations like sales[Products] + costs[Regions] when Products and Regions have the same size.

Overall Assessment

Verdict: Approve with minor recommendations

This is high-quality work that demonstrates:

  • Careful design with semantic safety (indexed vs named dimensions)
  • Comprehensive test coverage including N-dimensional cases
  • Thoughtful two-pass matching algorithm to avoid greedy matching bugs
  • Good documentation and clear commit history showing iterative refinement

Code Quality

Strengths

  1. Semantic Safety: The distinction between indexed dimensions (can match by size) and named dimensions (must match by name) is well-implemented and prevents subtle bugs like accidentally adding Cities[NYC,LA] to Products[Widget,Gadget] just because both have size 2.

  2. Two-Pass Matching Algorithm (compiler.rs:4600-4661): The match_dimensions_two_pass function correctly reserves name matches before attempting size-based matching. This prevents the greedy matching bug tested in name_match_reserved_before_size_match.

  3. Comprehensive Test Coverage: The PR adds 307 lines of tests covering:

    • Previously ignored broadcasting tests (6 enabled)
    • N-dimensional broadcasting (3D, 4D)
    • Edge cases (duplicate dimension usage, name precedence, UNION broadcasting)
    • Broadcasting on different axes
  4. UNION Broadcasting: The implementation correctly handles cases like a[X] + b[Y] → result[X,Y] which creates a higher-dimensional result.

Potential Issues & Recommendations

P2: Consider Edge Case in find_matching_dimension

In expr2.rs:465-489, the function checks ctx.is_indexed_dimension(name) to enable size-based matching, but doesn't verify that both dimensions are indexed before returning a match by size. Currently line 482 checks both, which is correct, but the logic could be clearer:

// Current (line 480-485)
if ctx.is_indexed_dimension(name) {
    for (sec_name, &sec_size) in secondary_names.iter().zip(secondary_dims.iter()) {
        if ctx.is_indexed_dimension(sec_name) && size == sec_size {
            return Some((sec_name.as_str(), sec_size));
        }
    }
}

This is actually correct, but consider adding a comment explaining why we check both dimensions are indexed.

P3: Dead Code Annotations

Good use of #[allow(dead_code)] on broadcast_view (line 4711) and find_target_for_source (line 4669) marking them as scaffolding for future optimization. Consider adding GitHub issue numbers to these comments to track when they'll be utilized.

P3: Documentation Improvement

The doc comment on broadcast_view (lines 4698-4710) excellently explains that sparse array information is not preserved. Consider adding a similar note to match_dimensions explaining its O(n²) complexity is acceptable because dimension count is always small (<10).

Testing

The test coverage is excellent:

  • Enabled tests: 6 previously ignored tests now pass
  • New N-dimensional tests: 6 tests covering 3D/4D broadcasting
  • Edge case tests: 4 tests for matching bugs and UNION broadcasting

One minor suggestion:

P4: Consider Adding Performance Test

While the algorithm is O(n²) on dimension count (which is fine), consider adding a test with the maximum expected dimensions (e.g., 8-10 dimensions) to ensure performance remains acceptable.

Security Concerns

No security issues identified. The implementation correctly validates:

  • Dimension sizes must match when broadcasting
  • Named dimensions cannot be arbitrarily combined
  • All source dimensions must match or fail gracefully

Performance Considerations

  • The two-pass matching algorithm is O(n×m) where n=source dims, m=target dims
  • In practice, n and m are typically ≤ 5, so this is negligible
  • No unnecessary allocations in hot paths
  • Broadcasting uses stride 0 views (no data copying)

Best Practices Adherence

✅ Follows repository commit message style
✅ Proper error handling with meaningful error codes
✅ Comprehensive tests for new functionality
✅ Good use of Rust idioms (pattern matching, iterators)
✅ Clear documentation on complex algorithms
✅ Preserves backward compatibility (all existing tests pass per commit messages)

Minor Suggestions

  1. Line 953 (expr2.rs): The TestContext comment was clarified in commit 3bfe53b, but consider renaming the test context to ConservativeTestContext to make the conservative behavior more explicit.

  2. Commit message: The final commit message mentions "/ comment syntax issues" but I don't see these in the current code. If they were already fixed, great! If not, worth double-checking.

  3. Consider adding a high-level architecture comment at the top of match_dimensions_two_pass explaining the why behind the two-pass approach (prevents greedy matching bugs).

Summary

This is excellent work that adds a valuable feature with proper semantic safety guarantees. The implementation is clean, well-tested, and thoughtfully handles edge cases. The iterative refinement shown in the commit history (initial implementation → bug fixes → documentation improvements) demonstrates careful engineering.

Recommendation: Merge after considering the minor suggestions above.

Great job! 🎉

@github-actions

github-actions Bot commented Jan 2, 2026

Copy link
Copy Markdown

❌ Visual regression tests failed. View artifacts to see the differences.

@bpowers
bpowers merged commit d89e515 into main Jan 2, 2026
@bpowers
bpowers deleted the claude/array-indexed-broadcasting-J9rLW branch January 2, 2026 02:07
bpowers pushed a commit that referenced this pull request Jan 2, 2026
The array support implementation is substantially complete. This change:

- Removes plan.md which was a roadmap written before commits #135-#142
  implemented the planned bytecode compiler support
- Completely rewrites array-design.md to accurately reflect what is
  implemented vs what remains

The remaining work items are edge cases:
1. Cross-dimension broadcasting in array builtins (SUM(a[*]+h[*]) where
   a and h have different dimensions should produce cross-product)
2. Slice assignment size mismatch behavior (should NaN-extend not
   repeat last element)
3. Out-of-bounds iteration in A2A context
4. Complex combined operations (transpose+slice)
5. EXCEPT builtin (Vensim compatibility issue)

The document now serves as comprehensive background for future agents
working on the remaining items.
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.

2 participants