Repository navigation
engine: implement indexed dimension broadcasting support - #142
Conversation
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.
|
@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.
PR Review: Indexed Dimension Broadcasting SupportThis 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: Strengths1. Excellent Semantic Safety
2. Comprehensive Test Coverage
3. Well-Structured Algorithm
4. Future-Proofing
Issues and Concerns1. Potential Duplicate Matching Bug 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 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 Recommendation: Add a 2. Incomplete 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 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 Recommendation: When dimensions match by name but have different sizes in UNION broadcasting, return 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 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 Performance Considerations1. HashMap Construction
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
Suggestion: Could be combined into a single pass with early returns. Code QualityPositive:
Minor Issues:
Security ConcernsNone identified. The dimension matching logic is purely computational and doesn't involve external input or unsafe operations. Recommendations SummaryMust Fix:
Should Fix: Nice to Have: ConclusionThis 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. |
There was a problem hiding this comment.
💡 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".
| for (i, target) in target_dims.iter().enumerate() { | ||
| if !used[i] | ||
| && let Dimension::Indexed(_, target_size) = target | ||
| && source_size == target_size | ||
| { |
There was a problem hiding this comment.
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 👍 / 👎.
|
❌ Visual regression tests failed. View artifacts to see the differences. |
Codecov Report❌ Patch coverage is
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. 🚀 New features to boost your workflow:
|
|
❌ 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.
Code Review SummaryThis 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. Strengths1. Exceptional Test Coverage
2. Well-Documented Implementation
3. Sound Algorithm Design
4. Semantic Safety
5. Code Quality
Issues and RecommendationsMinor Issues1. Comment Syntax InconsistencySeveral comments use // 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 failureThese should use 2. Test Mock Returns Wrong ValueIn 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 3. UNION Broadcasting Size ValidationWhen dimensions match by name in the UNION case ( Some((matched_name, matched_size)) => {
// Already present in a, don't add again
}If 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 Opportunities4. broadcast_view Sparse Array HandlingThe Some(ArrayView {
dims: new_dims,
strides: new_strides,
offset: source_view.offset,
sparse: Vec::new(), // Always empty
dim_names: new_dim_names,
})If 5. Performance: Unused Result AllocationsIn Security & CorrectnessNo security concerns identified. The implementation:
PerformanceThe 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. ConclusionThis is high-quality work that demonstrates:
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) |
|
@codex review |
|
❌ 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.
There was a problem hiding this comment.
💡 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".
| fn is_indexed_dimension(&self, _name: &str) -> bool { | ||
| // For tests, assume all dimensions are indexed | ||
| false |
There was a problem hiding this comment.
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 👍 / 👎.
PR Review: Indexed Dimension Broadcasting SupportI've reviewed this PR implementing indexed dimension broadcasting support. This is a substantial and well-executed feature addition that enables operations like Overall AssessmentVerdict: Approve with minor recommendations This is high-quality work that demonstrates:
Code QualityStrengths
Potential Issues & RecommendationsP2: Consider Edge Case in
|
|
❌ Visual regression tests failed. View artifacts to see the differences. |
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.
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:
Extended unify_dims_with_names in ast/expr2.rs to support:
neither is a subset of the other (e.g., a[X] + b[Y] → result[X,Y])
Added is_indexed_dimension method to Expr2Context trait to distinguish
indexed dimensions from named dimensions during type checking.
Added dimension matching infrastructure in compiler.rs:
Added comprehensive tests:
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.