Skip to content

engine: add bytecode infrastructure for array support - #135

Merged
bpowers merged 3 commits into
mainfrom
claude/array-bytecode-vm-design-EK8UY
Dec 29, 2025
Merged

bpowers merged 3 commits into
mainfrom
claude/array-bytecode-vm-design-EK8UY

Conversation

@bpowers

@bpowers bpowers commented Dec 29, 2025

Copy link
Copy Markdown
Owner

Add comprehensive bytecode and VM infrastructure for array operations:

Bytecode additions (bytecode.rs):

  • New type aliases: ViewId, DimId, TempId, PcOffset, NameId
  • DimensionInfo struct for dimension metadata (indexed vs named)
  • SubdimensionRelation for star range support
  • RuntimeView struct for dynamic array views with subscript/range/transpose ops
  • RuntimeSparseMapping for non-contiguous dimension access
  • StaticArrayView for compile-time array view descriptions
  • 30 new Opcode variants for view stack, iteration, reductions, broadcasting
  • Extended ByteCodeContext with dimensions, subdim_relations, names,
    static_views, temp_offsets, temp_total_size fields
  • Helper methods for interning names and managing dimensions/views

VM additions (vm.rs):

  • temp_storage Vec for array temporary values
  • IterState struct for iteration loop tracking
  • Converted eval() from for-loop to PC-based while-loop for jumps
  • Changed eval() and eval_module() to &mut self for iteration state
  • reduce_view() helper for SUM/MAX/MIN/MEAN/STDDEV/SIZE
  • Stub implementations for all new opcodes

This is infrastructure for array bytecode support. The compiler does not
yet emit these opcodes - that will come in subsequent changes.

Add comprehensive bytecode and VM infrastructure for array operations:

Bytecode additions (bytecode.rs):
- New type aliases: ViewId, DimId, TempId, PcOffset, NameId
- DimensionInfo struct for dimension metadata (indexed vs named)
- SubdimensionRelation for star range support
- RuntimeView struct for dynamic array views with subscript/range/transpose ops
- RuntimeSparseMapping for non-contiguous dimension access
- StaticArrayView for compile-time array view descriptions
- 30 new Opcode variants for view stack, iteration, reductions, broadcasting
- Extended ByteCodeContext with dimensions, subdim_relations, names,
  static_views, temp_offsets, temp_total_size fields
- Helper methods for interning names and managing dimensions/views

VM additions (vm.rs):
- temp_storage Vec<f64> for array temporary values
- IterState struct for iteration loop tracking
- Converted eval() from for-loop to PC-based while-loop for jumps
- Changed eval() and eval_module() to &mut self for iteration state
- reduce_view() helper for SUM/MAX/MIN/MEAN/STDDEV/SIZE
- Stub implementations for all new opcodes

This is infrastructure for array bytecode support. The compiler does not
yet emit these opcodes - that will come in subsequent changes.
Complete the VM implementation for broadcasting operations where arrays
with different dimensions are combined element-wise by dimension name.

For example, `A[DimA, DimB] * B[DimA]` produces a 2D result where B is
broadcast across DimB. Matching is by dimension ID (name), not position.

Key additions:
- BroadcastSourceInfo: tracks how each source maps to result dimensions
- BroadcastState: maintains iteration state for multi-source broadcast
- BeginBroadcastIter: computes result shape from dimension union,
  creates dim_map for each source
- LoadBroadcastElement: maps result indices to source indices using
  dim_map, handles broadcasting (missing dims)
- StoreBroadcastElement: writes to destination temp array
- NextBroadcastOrJump: advances result indices in row-major order
- EndBroadcastIter: cleans up broadcast state

This completes the VM-side array bytecode support. The compiler does not
yet emit these opcodes.
@bpowers

bpowers commented Dec 29, 2025

Copy link
Copy Markdown
Owner Author

@codex please review

@claude

claude Bot commented Dec 29, 2025

Copy link
Copy Markdown

Code Review: Array Bytecode Infrastructure

I've reviewed PR #135 which adds comprehensive bytecode and VM infrastructure for array operations. This is a substantial and well-structured infrastructure PR. Here's my detailed feedback:

Strengths

✅ Excellent Code Organization

  • Clear separation of concerns with well-commented sections
  • Logical grouping of related opcodes (view stack, iteration, reductions, broadcasting)
  • Comprehensive documentation with clear doc comments

✅ Strong Test Coverage

  • 25+ unit tests covering all new data structures (DimensionInfo, SubdimensionRelation, RuntimeView)
  • Tests cover both simple and complex cases (1D, 2D, 3D arrays, sparse mappings, transpose)
  • Good test naming that clearly indicates what's being tested

✅ Type Safety

  • Use of type aliases (ViewId, DimId, TempId, etc.) improves clarity
  • SmallVec usage is appropriate for small, stack-allocated collections
  • Proper use of debug_assert! for preconditions

✅ Memory Efficiency

  • SmallVec avoids heap allocations for common cases (≤4 dimensions, ≤8 element names)
  • Temp storage allocated once and reused
  • Pre-computed flat offsets for sparse iteration avoids repeated calculations

✅ Well-Architected

  • Clear distinction between static (compile-time) and runtime views
  • Support for both contiguous and sparse array access patterns
  • Proper handling of row-major memory layout with strides

Issues & Concerns

🔴 Critical: Potential Integer Overflow

In RuntimeView::flat_offset (bytecode.rs:232):

flat += actual_idx * self.strides[i] as usize;

For large arrays with negative strides (after transpose), casting i32 to usize could cause issues. Consider:

let stride = self.strides[i];
flat = if stride >= 0 {
    flat + actual_idx * stride as usize
} else {
    flat - actual_idx * (-stride) as usize
};

🔴 Critical: Missing Bounds Checking

Several places lack bounds checking that could cause panics:

  1. RuntimeView::flat_offset (bytecode.rs:228):
offsets[idx as usize] as usize  // No bounds check on idx
  1. RuntimeView::apply_single_subscript (bytecode.rs:250):
let parent_idx = mapping.parent_offsets[index as usize];  // Could panic

While debug_assert checks dimensions, release builds could panic. Consider returning Result or adding explicit bounds checks.

🟡 Performance: Sparse Lookup Inefficiency

In RuntimeView::flat_offset (bytecode.rs:216-223), you rebuild the sparse_lookup SmallVec on every call:

let sparse_lookup: SmallVec<[Option<&[u16]>; 4]> = (0..self.dims.len())
    .map(|i| { /* ... */ })
    .collect();

This is called in tight loops during iteration. Consider:

  1. Caching the lookup in RuntimeView
  2. Or iterate sparse directly since it's usually very small (≤2 elements)

🟡 Code Quality: Inconsistent Error Handling

In vm.rs:840:

panic\!("StoreIterElement without write_temp");

This should be unreachable if the compiler is correct. Use unreachable\!() macro instead to make intent clearer and get better error messages in debug builds.

🟡 Potential Bug: Stride Calculation with Signed Overflow

In RuntimeView::for_var (bytecode.rs:161):

stride *= dim as i32;

For a 4D array with dimensions [1000, 1000, 1000, 1000], stride would overflow i32. Consider:

  • Using i64 for strides
  • Or adding overflow checks and returning Result
  • Document the maximum supported array size

🟡 Code Smell: Dead Code Annotations

Multiple #[allow(dead_code)] annotations throughout:

  • bytecode.rs:49 (DimensionInfo impl)
  • bytecode.rs:90 (SubdimensionRelation impl)
  • bytecode.rs:356 (Opcode enum)
  • bytecode.rs:678 (ByteCodeContext fields)

While the PR description explains "The compiler does not yet emit these opcodes", having this much dead code can:

  1. Make it hard to detect actual unused code later
  2. Create maintenance burden
  3. Hide potential issues until the code is actually used

Recommendation: Consider either:

  • Removing the dead_code allows and having CI ignore these specific warnings temporarily
  • Adding integration tests that exercise the bytecode (even if hand-constructed)
  • Using a feature flag to conditionally compile this code

Best Practices & Style

✅ Good naming: RuntimeView, StaticArrayView, SubdimensionRelation are clear and descriptive

⚠️ Comment clarity: Some comments could be more precise. For example, bytecode.rs:159:

// Build strides from right to left for row-major order

Could be:

// Build strides from right to left for row-major order (rightmost dimension has stride 1)

✅ Test organization: The test module organization is excellent with clear section headers

Security Considerations

⚠️ Array Bounds: The lack of bounds checking in several methods could lead to out-of-bounds access if the compiler generates invalid bytecode. Since this is infrastructure for a simulation engine (not processing untrusted input), this is lower severity, but still worth addressing.

Performance Considerations

✅ The design choices show good performance awareness:

  • Contiguous iteration fast path (vm.rs:767-770)
  • Pre-computed flat offsets for sparse arrays
  • SmallVec for avoiding heap allocations

⚠️ The sparse_lookup rebuild in flat_offset is the main performance concern as noted above.

Documentation

✅ Doc comments are comprehensive and helpful
⚠️ Consider adding module-level docs explaining:

  • The overall array execution model (view stack, iteration, temp storage)
  • How broadcasting works
  • Memory layout conventions (row-major, 0-based vs 1-based indexing)

Test Coverage Gaps

While test coverage is good, consider adding:

  1. Tests for edge cases: empty arrays, single-element arrays
  2. Tests for the interaction between operations (e.g., transpose after sparse subscript)
  3. Tests for the ByteCodeContext helper methods (intern_name, find_dimension_by_name)
  4. Property-based tests for flat_offset correctness

Summary

This is high-quality infrastructure work with thoughtful design and solid test coverage. The main issues to address before merge are:

Must fix:

  1. Integer overflow handling in flat_offset with negative strides
  2. Bounds checking in array access methods
  3. Stride overflow potential in for_var

Should fix:

  1. Sparse lookup performance in flat_offset
  2. Use unreachable!() instead of panic!() for compiler invariants
  3. Consider approach for dead_code annotations

Nice to have:

  1. Module-level documentation
  2. Additional edge case tests
  3. Property-based tests

The architecture is sound and will provide a solid foundation for array bytecode compilation. Great work on the comprehensive test suite! 🎉


Review performed using repository coding standards from CLAUDE.md

@codecov

codecov Bot commented Dec 29, 2025 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 45.49878% with 224 lines in your changes missing coverage. Please review.
✅ Project coverage is 71.73%. Comparing base (5000ac7) to head (41b05ba).

Files with missing lines Patch % Lines
src/simlin-engine/src/vm.rs 19.92% 209 Missing ⚠️
src/simlin-engine/src/bytecode.rs 91.30% 12 Missing ⚠️
src/simlin-engine/src/compiler.rs 75.00% 3 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main     #135      +/-   ##
==========================================
- Coverage   72.72%   71.73%   -1.00%     
==========================================
  Files          41       41              
  Lines       12111    12479     +368     
==========================================
+ Hits         8808     8952     +144     
- Misses       3303     3527     +224     

☔ 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

Copy link
Copy Markdown

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

@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 thread src/simlin-engine/src/vm.rs Outdated
Comment on lines +717 to +719
let rel = &context.subdim_relations[*subdim_relation_id as usize];
let view = view_stack.last_mut().unwrap();
view.apply_sparse(*dim_idx as usize, rel.parent_offsets.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 Update view dim_ids for star ranges

ViewStarRange applies the subdimension relation by only passing parent_offsets into apply_sparse, leaving the view’s dim_ids entry unchanged. Since broadcast matching later relies on view.dim_ids, a star range like *:SubDim will still be labeled with the parent dimension ID and won’t align with arrays indexed by the subdimension, producing incorrect iteration/broadcasting when mixed. The star-range path should update view.dim_ids[dim_idx] to rel.child_dim_id alongside the sparse mapping.

Useful? React with 👍 / 👎.

Comment thread src/simlin-engine/src/vm.rs Outdated
Comment on lines +697 to +701
Opcode::ViewSubscriptDynamic { dim_idx } => {
let index = stack.pop().floor() as u16;
let view = view_stack.last_mut().unwrap();
// Note: assumes 0-based index from stack for dynamic subscripts
view.apply_single_subscript(*dim_idx as usize, index);

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 Validate dynamic subscript indices before applying

ViewSubscriptDynamic pops a runtime index and immediately applies it; the only bounds check is a debug_assert inside apply_single_subscript, which is removed in release builds. That means negative or out-of-range indices will wrap/truncate and compute an invalid offset, reading unrelated memory instead of producing NaN (the legacy PushSubscriptIndex path explicitly validates bounds). Any dynamic subscript expression that evaluates outside the dimension bounds will hit this. Add a runtime bounds check (and consistent 1‑based/0‑based handling) before applying the subscript.

Useful? React with 👍 / 👎.

Fix two issues in the array bytecode VM:

1. ViewStarRange now updates dim_ids for proper broadcast matching:
   - Added apply_sparse_with_dim_id() method to RuntimeView
   - ViewStarRange uses child_dim_id from SubdimensionRelation
   - Fixes broadcast matching when star ranges like *:SubDim are
     mixed with arrays indexed by the subdimension

2. ViewSubscriptDynamic now validates bounds and uses 1-based indexing:
   - Added is_valid field to RuntimeView to track validity
   - Added apply_single_subscript_checked() for bounds-checked subscripts
   - Converts from 1-based XMILE indexing to 0-based internal
   - Returns NaN for out-of-bounds subscripts (consistent with legacy)
   - Updated LoadIterElement, LoadBroadcastElement, and reduce_view
     to return NaN for invalid views

Added 5 new unit tests for the new functionality.
@claude

claude Bot commented Dec 29, 2025

Copy link
Copy Markdown

Pull Request Review: Array Bytecode Infrastructure

This PR adds comprehensive infrastructure for array operations to the simulation engine bytecode and VM. The implementation is well-structured and thoroughly tested.

Strengths

1. Excellent Architecture

  • Clear separation between compile-time structures (StaticArrayView) and runtime structures (RuntimeView)
  • Smart use of type aliases (ViewId, DimId, TempId) for readability and type-safety
  • View stack abstraction cleanly handles complex array subscripting

2. Comprehensive Implementation

  • Broadcasting with dimension name matching (not position) is sophisticated and correct
  • Both contiguous and sparse array iteration are optimized appropriately
  • Proper edge case handling (out-of-bounds subscripts return NaN, consistent with legacy)

3. Excellent Test Coverage

  • 26 new unit tests covering dimension info, subdimension relations, runtime views, bytecode context
  • Tests cover basic cases (1D, 2D, 3D) and edge cases (sparse mappings, transposition)
  • Good property-based thinking (e.g., contiguous detection tests)

4. Documentation

  • Comprehensive comments explaining each struct and opcode
  • Clear commit messages following project conventions
  • Logical organization with section headers

Code Quality Observations

Memory Efficiency: Good SmallVec usage, but RuntimeSparseMapping contains SmallVec with 16 elements which could be large. Profile actual usage patterns.

Opcode Size: 16 bytes is large for bytecode. PushVarView carries DimId array (8 bytes). Consider side tables if memory becomes an issue.

Integer Overflow: In flat_offset() (bytecode.rs:256), multiplication could overflow for large 4D arrays. Consider checked arithmetic.

Stddev Implementation: Two-pass algorithm (vm.rs:908) is stable but slower. Verify matches XMILE spec. Consider Welford algorithm and clarify population vs sample stddev.

Broadcasting Logic: Index reordering (vm.rs:1014) is correct but subtle. Add comment explaining why reordering is needed.

Potential Issues

Panic on Invalid Usage: vm.rs:853 panics on StoreIterElement without write_temp. Consider proper error if compiler could generate invalid bytecode.

NaN Propagation: Consistently returns NaN for invalid views. Verify this matches XMILE spec behavior.

1-Based Indexing: Good handling in bytecode.rs:210. Ensure compiler consistently passes 1-based indices.

Performance Considerations

Pre-computation: Smart optimization (vm.rs:775) avoids redundant offset calculations. Consider memory cost for very large arrays.

View Stack: Capacity of 4 is reasonable but might reallocate for complex operations. Consider tracking max depth during compilation.

Security Considerations

Array Bounds: All accesses use checked bounds or validated offsets. Good.

Resource Limits: No explicit limits on dimensions, temp array sizes, or iteration counts. Add compiler validation for pathological cases.

Testing Recommendations

  1. Integration tests with complete bytecode sequences
  2. Round-trip tests for reversible operations
  3. Fuzz testing for flat_offset calculation
  4. Performance benchmarks for contiguous vs sparse iteration

Minor Suggestions

  1. bytecode.rs:93 - Validate start + count overflow
  2. vm.rs:853 - Replace panic with proper error
  3. Add module-level comment explaining array execution model
  4. Consistent allow(dead_code) placement

Conclusion

This is high-quality infrastructure code with strong domain understanding, edge case handling, good testing, and clear documentation.

Recommendation: Approve with minor suggestions

Only blocking concern: verify NaN-on-error and stddev behaviors match XMILE specification. Everything else is optimization and polish.

@github-actions

Copy link
Copy Markdown

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

@bpowers
bpowers merged commit 5d28234 into main Dec 29, 2025
@bpowers
bpowers deleted the claude/array-bytecode-vm-design-EK8UY branch December 29, 2025 14:44
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