Skip to content

engine: VM vector operations - #361

Merged
bpowers merged 31 commits into
mainfrom
vm-vector-ops
Mar 1, 2026
Merged

bpowers merged 31 commits into
mainfrom
vm-vector-ops

Conversation

@bpowers

@bpowers bpowers commented Mar 1, 2026

Copy link
Copy Markdown
Owner

Summary

  • Extract allocation math helpers (erfc_approx, normal_cdf, alloc_curve, allocate_available) into shared alloc.rs module used by both interpreter and VM
  • Fix interpreter bug where VectorSortOrder, VectorElmMap, and AllocateAvailable in A2A context return the first element's result for every element -- now hoisted into AssignTemp with whole-array evaluation
  • Add four new VM opcodes (VectorSelect, VectorElmMap, VectorSortOrder, AllocateAvailable) with codegen emission and dispatch handlers using SmallVec scratch buffers
  • Upgrade three interpreter-only tests to full VM+interpreter path with .dat expected output validation
  • Add structural tests for A2A hoisting (compiler_vector.rs) and edge case tests for VectorElmMap out-of-bounds (array_tests.rs)

Test plan

  • All 2417+ engine unit tests pass
  • All 48 simulation integration tests pass (including allocate and vector_simple)
  • 9 compiler_vector structural tests pass (AssignTemp hoisting verification)
  • 6 VectorElmMap edge case tests pass (OOB, negative offset, NaN)
  • VectorSelect tested with all 5 actions (SUM, MIN, MEAN, MAX, PROD) plus empty selection
  • Pre-commit hook passes (fmt, clippy, tests, TypeScript, pysimlin)
  • Human test plan: docs/test-plans/2026-02-27-vm-vector-ops.md

@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: 070ab46ec1

ℹ️ 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/compiler/mod.rs Outdated
Comment on lines +1078 to +1079
let first_ast = first_ast.unwrap();
expand_a2a_with_hoisting(ctx, dims, first_ast, off)

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 Preserve per-element AST when hoisting Arrayed builtins

When needs_hoisting is true, this branch compiles the entire Ast::Arrayed variable from first_ast only, which drops element-specific equations/default behavior for all other subscripts. In mixed arrayed definitions, if the first element uses a vector builtin then every element is rewritten from that first equation; if the first element does not but a later one does, hoisting is skipped and codegen reaches the unreachable!() vector-builtin path in compiler/codegen.rs. Both cases produce incorrect compilation results for valid per-element array equations.

Useful? React with 👍 / 👎.

Comment thread src/simlin-engine/src/compiler/mod.rs Outdated
Comment on lines +1216 to +1220
let builtin_view = find_expr_array_view(&main_expr).unwrap_or_else(|| var_view.clone());

let mut hoisted = Vec::new();
let mut temp_id = base_temp_id;
let first_temp_idx = project_var_index_to_temp(0, &var_view, &builtin_view);

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 Use each nested builtin's own ArrayView for hoisting

The nested-hoisting path computes one builtin_view from the outer expression and passes it to replace_nested_builtins_for_element for every nested vector builtin. If a formula contains multiple array-producing builtins with different shaping dimensions (for example, broadcast combinations over different dims), later AssignTemp nodes are recorded with the wrong view/size and index projection. That mismatched metadata causes wrong temp reads and can trigger bounds failures when VM vector opcodes write a different element count than the temp allocation implied by this shared view.

Useful? React with 👍 / 👎.

@claude

claude Bot commented Mar 1, 2026

Copy link
Copy Markdown

Code Review: engine: VM vector operations

Summary

This PR adds VM support for four array-oriented builtins (VECTOR SELECT, VECTOR ELM MAP, VECTOR SORT ORDER, ALLOCATE AVAILABLE), extracts allocation math into a shared alloc.rs module, and fixes an interpreter bug where A2A expansion of array-producing builtins returned the first element's result for every element. The approach — hoisting whole-array builtins into AssignTemp pre-computations during A2A expansion, then reading per-element results via TempArrayElement — is well designed and cleanly separates concerns across compiler, codegen, and VM dispatch layers.

Detailed Analysis

Correctness verified across key areas:

  • View stack ordering in codegen and VM dispatch is consistent for all four opcodes. Push order matches the read order (view_stack[len-1] = last pushed, view_stack[len-2] = second-to-last).
  • Stack effects in bytecode.rs are accurate: VectorSelect pops 2 scalars (max_value, action) and pushes 1 result; VectorSortOrder/AllocateAvailable each pop 1 scalar and write to temp_storage.
  • Bisection direction in alloc.rs is correct: lower price → higher allocation, so hi = mid when total < avail.
  • Sort stability: both interpreter and VM use sort_by (stable sort), preserving tie-breaking behavior.
  • expand_pp_view_for_allocate correctly reconstructs full variable views when dimension collapsing would lose XPriority columns.
  • Interpreter StaticSubscript fix in compute_allocate_available: adding view.offset for contiguous views is correct — off is the variable's base, view.offset is the within-variable subarray start.
  • alloc.rs extraction: clean move with no behavioral changes, visibility upgraded to pub appropriately.

Design observations (not bugs):

  • expand_arrayed_with_hoisting delegates to the A2A path using the first element's AST when hoisting is needed. The comment documents the assumption that all elements share the same equation for array-producing builtins. This is correct for all practical Vensim models but would silently produce wrong results for a hypothetical model with per-element equations containing different array-producing builtins. Acceptable given SD modeling conventions.
  • The unreachable!() calls replacing sim_err!(TodoArrayBuiltin, ...) in codegen.rs are appropriate — they're internal invariant assertions that the A2A hoisting worked, not user-facing errors. If the hoisting logic ever misses a case, a panic at compile time is better than silent incorrect simulation.

Findings

No bugs found. The implementation is correct, well-tested (structural + edge case + parity tests), and the approach is sound.

Overall Correctness

Correct. The patch introduces no regressions and the comprehensive test suite (2417+ unit tests, 48 integration tests, 9 structural compiler tests, 6 edge case tests) validates both interpreter and VM paths produce identical results. The code is ready to merge.

@codecov

codecov Bot commented Mar 1, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 78.67868% with 213 lines in your changes missing coverage. Please review.
✅ Project coverage is 79.02%. Comparing base (cb13e57) to head (681ec2c).
⚠️ Report is 1 commits behind head on main.

Files with missing lines Patch % Lines
src/simlin-engine/src/compiler/mod.rs 71.91% 123 Missing ⚠️
src/simlin-engine/src/alloc.rs 70.83% 28 Missing ⚠️
src/simlin-engine/src/vm.rs 85.81% 21 Missing ⚠️
src/simlin-engine/src/compiler/codegen.rs 68.62% 16 Missing ⚠️
src/simlin-engine/src/compiler/symbolic.rs 28.57% 10 Missing ⚠️
src/simlin-engine/src/compiler/context.rs 84.00% 8 Missing ⚠️
src/simlin-engine/src/interpreter.rs 92.85% 3 Missing ⚠️
src/simlin-engine/tests/compiler_vector.rs 96.47% 3 Missing ⚠️
src/simlin-engine/src/test_common.rs 96.15% 1 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main     #361      +/-   ##
==========================================
+ Coverage   78.76%   79.02%   +0.26%     
==========================================
  Files         139      142       +3     
  Lines       36480    37264     +784     
==========================================
+ Hits        28733    29449     +716     
- Misses       7747     7815      +68     

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

@claude

claude Bot commented Mar 1, 2026

Copy link
Copy Markdown

Code Review

[P2] unreachable!() panic when Arrayed+EXCEPT first element overrides an array-producing default

File: src/simlin-engine/src/compiler/mod.rs, lines 1052-1073 (detection) → src/simlin-engine/src/compiler/codegen.rs, line 881 (panic)

expand_arrayed_with_hoisting determines needs_hoisting by probing only the first subscript element's expression (line 1055: elements.get(&first_key).or(default_ast)). If the first element has an override in the elements map (e.g., result[A1] = 42), the probe evaluates the override — which typically isn't an array-producing builtin — so needs_hoisting is false. Subsequent elements that use the default (which does contain VectorElmMap/VectorSortOrder/AllocateAvailable) then go through the standard per-element expansion (line 1094), placing the un-hoisted builtin inside AssignCurr. When codegen processes that expression, it reaches the unreachable!() at codegen.rs:881 and panics. Before this PR, the same code path returned sim_err!(TodoArrayBuiltin, ...), which was a clean compiler error. The impact is limited to the specific Arrayed+EXCEPT model structure where the first dimension element is an override and the default contains an array-producing builtin — unlikely in practice, but the panic is a regression from a graceful error. A fix could be to also probe default_ast when the first element comes from an override, or to replace the unreachable!() with a fallback error.

Overall Correctness

Correct. The patch is well-structured, the VM opcodes match interpreter semantics, view stack operations are balanced, stack effects are accurate, and test coverage is thorough. The existing test suite will not break. The edge case above affects only a narrow model structure that is unlikely in real-world usage and does not affect any current test or integration path.

🤖 Generated with Claude Code

@claude

claude Bot commented Mar 1, 2026

Copy link
Copy Markdown

Code Review: engine: VM vector operations

Summary

This PR adds VM support for four array-oriented builtins (VECTOR SELECT, VECTOR ELM MAP, VECTOR SORT ORDER, ALLOCATE AVAILABLE), extracts shared allocation helpers into alloc.rs, and fixes an interpreter bug where array-producing builtins in A2A context returned the first element's result for every element. The implementation includes A2A hoisting in the compiler, four new VM opcodes, codegen emission, and comprehensive tests.

Findings

No bugs found that meet the review criteria.

Detailed Analysis

I verified the following aspects across the ~1900 lines of new/modified code:

  1. Arithmetic stack effects (bytecode.rs): All four opcodes correctly declare their stack effects — VectorSelect: (2,1), VectorElmMap: (0,0), VectorSortOrder: (1,0), AllocateAvailable: (1,0).

  2. View stack management (codegen.rs / vm.rs): Codegen push order matches VM access order for all four opcodes. PopView calls are correctly paired with walk_expr_as_view calls.

  3. Action encoding parity (interpreter.rs / vm.rs): VectorSelect action values (0=SUM, 1=MIN, 2=MEAN, 3=MAX, 4=PROD) are identical between interpreter and VM, including the empty-selection fallback to max_value.

  4. A2A hoisting (compiler/mod.rs): The hoisting logic correctly handles top-level builtins, nested builtins (e.g. 10 + VECTOR_ELM_MAP(...)), EXCEPT overrides, and first-element overrides. The project_var_index_to_temp function correctly maps variable indices to temp array indices when dimensions differ.

  5. Bounds checking (vm.rs): VectorElmMap correctly returns NaN for out-of-bounds, negative, and NaN offset values, matching the interpreter.

  6. Sort stability: Both interpreter and VM use sort_by (stable sort) with identical partial_cmp fallback to Equal, producing consistent results for tied values.

  7. Allocation algorithm sharing (alloc.rs): The functions are exact moves from interpreter.rs — no semantic changes, just visibility (pub).

  8. Interpreter StaticSubscript fix (interpreter.rs:679-691): The addition of view.offset in the contiguous path and the iter_array_elements fallback for non-contiguous views is a necessary fix for the new expand_pp_view_for_allocate code path.

Verdict

Overall correctness: Correct. The patch is well-structured, the implementation matches the design document, and the test coverage (2417+ unit tests, 48 integration tests, 9 structural compiler tests, 6 edge-case tests) is comprehensive. Existing code and tests will not break.

@claude

claude Bot commented Mar 1, 2026

Copy link
Copy Markdown

Code Review: engine: VM vector operations

Summary

This is a substantial and well-structured PR that adds VM support for four array-oriented builtins (VECTOR SELECT, VECTOR ELM MAP, VECTOR SORT ORDER, ALLOCATE AVAILABLE), simultaneously fixes an interpreter bug where A2A expansion of these builtins returned the first element's result for every element, and extracts shared allocation math into alloc.rs.

Findings

No bugs found.

The implementation is thorough and well-tested. Specific areas I verified:

  • VM opcode dispatch (vm.rs): All four opcodes correctly read from views, handle edge cases (NaN, OOB, empty selection), and match the interpreter's action codes for VectorSelect (0=SUM, 1=MIN, 2=MEAN, 3=MAX, 4=PROD).
  • Compiler A2A hoisting (compiler/mod.rs): The hoisting logic correctly handles top-level builtins, nested builtins (e.g., 10 + vector_elm_map(...)), mixed override/default elements (EXCEPT semantics), and first-element overrides. The temp ID assignment is consistent across elements because the expression tree structure is deterministic from the same AST.
  • read_view_element (vm.rs): Correctly dispatches between curr[] and temp_storage based on is_temp, with callers consistently computing flat_off via view.flat_offset(&indices).
  • Interpreter pp_expr StaticSubscript change (interpreter.rs:680-691): The view.offset addition in the contiguous branch is a no-op since is_contiguous() requires offset == 0, so it doesn't change behavior. The new non-contiguous fallback to iter_array_elements is a correctness improvement.
  • alloc.rs extraction: Straight code move, no logic changes, bisection algorithm preserved exactly.
  • increment_indices extraction: DRY refactor of row-major index advancement, used in 4 places.
  • Test coverage: Comprehensive - structural tests for A2A hoisting, edge cases (OOB, negative offset, NaN), both interpreter and VM paths, integration tests upgraded from interpreter-only to full VM+interpreter comparison.

Overall Correctness Verdict

Correct. The patch is well-implemented with extensive test coverage. Existing code and tests will not break. No bugs or blocking issues found.

@claude

claude Bot commented Mar 1, 2026

Copy link
Copy Markdown

Code Review: engine: VM vector operations

I reviewed all 18 changed files (2594 additions, 368 deletions) covering the new VM opcodes, compiler A2A hoisting, shared allocation helpers, and test infrastructure.

Areas Reviewed

  • alloc.rs: Clean extraction of erfc_approx, normal_cdf, alloc_curve, allocate_available from interpreter to shared module. Byte-for-byte identical to the original.
  • bytecode.rs: Four new opcodes (VectorSelect, VectorElmMap, VectorSortOrder, AllocateAvailable) with correct stack_effect() declarations.
  • codegen.rs: VectorSelect inline emission with correct view push order (sel, expr) matching VM dispatch order. AssignTemp handler correctly routes array-producing builtins to dedicated opcodes, bypassing the BeginIter loop.
  • context.rs: lower_preserving_dimensions() correctly skips Pass 1 dimension resolution. ActiveDimRef added to iteration-preserving ops. expand_pp_view_for_allocate() handles the Vensim convention where pp dimension gets collapsed.
  • compiler/mod.rs: The A2A hoisting logic (expand_a2a_with_hoisting, expand_arrayed_with_hoisting, replace_nested_builtins_for_element, project_var_index_to_temp) is the most complex part. Verified: dimension name matching in project_var_index_to_temp is correct; contains_array_producing_builtin properly covers both top-level and nested cases; temp ID allocation via next_available_temp_id avoids collisions; EXCEPT semantics correctly preserved (each element probed individually).
  • vm.rs: All four opcode dispatch handlers verified correct: view stack ordering matches codegen push order; read_view_element properly handles both curr[] and temp_storage backing; increment_indices refactoring is a clean extraction of duplicated code.
  • interpreter.rs: The StaticSubscript change in compute_allocate_available adds proper stride-based indexing for non-contiguous views (valid bugfix). The new AssignTemp whole-array evaluation path for VectorSortOrder/VectorElmMap/AllocateAvailable correctly bypasses the per-element eval loop.
  • Test coverage: Extensive -- edge cases for OOB/negative offsets/NaN, EXCEPT semantics with overrides at first/last/middle elements, nested builtin wrapping, mixed element types, structural AssignTemp verification.

Findings

No bugs found. The implementation is correct for all supported patterns and the test coverage is thorough.

Overall Correctness

Correct. The patch implements four VM opcodes with proper compiler integration, fixes a confirmed interpreter bug (A2A returning first element's value for all elements), and upgrades three tests from interpreter-only to full VM+interpreter comparison. Existing code and tests will not break.

@claude

claude Bot commented Mar 1, 2026

Copy link
Copy Markdown

Code Review: engine: VM vector operations

Summary

This PR adds VM support for four array-oriented Vensim/Stella builtins (VECTOR SELECT, VECTOR ELM MAP, VECTOR SORT ORDER, ALLOCATE AVAILABLE) and simultaneously fixes an interpreter bug where array-producing builtins in A2A context returned the first element's value for every element. The changes span compiler A2A hoisting, bytecode opcodes, codegen emission, VM dispatch, and shared allocation helpers.

Files Reviewed

  • src/simlin-engine/src/alloc.rs — Clean extraction of allocation math from interpreter; code is byte-for-byte identical to the removed functions.
  • src/simlin-engine/src/bytecode.rs — Four new opcodes with correct stack_effect declarations (verified against codegen push/pop patterns).
  • src/simlin-engine/src/compiler/codegen.rs — View stack ordering is correct for all four opcodes: views pushed in the right order, scalars pushed after views, PopViews emitted after the opcode. The AssignTemp handler correctly detects array-producing builtins and bypasses the BeginIter loop.
  • src/simlin-engine/src/compiler/context.rs — lower_preserving_dimensions correctly skips A2A context in Pass1 so dimension references survive for wildcard preservation. expand_pp_view_for_allocate correctly expands collapsed views back to full-variable views. The ActiveDimRef → Wildcard conversion in has_iteration_preserving_ops is consistent with the design.
  • src/simlin-engine/src/compiler/mod.rs — The A2A hoisting logic is the most complex part. expand_a2a_with_hoisting and expand_arrayed_with_hoisting correctly handle: top-level builtins, nested builtins in arithmetic, EXCEPT overrides with per-element probing, different-AST overrides with independent temp IDs, and first-element overrides. The project_var_index_to_temp dimension projection handles cross-dimension cases. replace_nested_builtins_for_element correctly maintains temp_id ordering across elements by traversing the tree in the same order for every element.
  • src/simlin-engine/src/compiler/symbolic.rs — Straightforward 1:1 opcode mapping.
  • src/simlin-engine/src/interpreter.rs — Migration to shared alloc.rs is clean. New AssignTemp handlers for VectorSortOrder, VectorElmMap, and AllocateAvailable correctly do whole-array evaluation before writing to temp_storage.
  • src/simlin-engine/src/vm.rs — All four dispatch handlers are correct: view stack access matches codegen push order, scalar stack pops match push order, SmallVec scratch buffers follow existing patterns, read_view_element is consistent with reduce_view. The increment_indices extraction reduces duplication.
  • src/simlin-engine/src/array_tests.rs — 586 lines of thorough edge-case testing (OOB, negative offset, NaN, EXCEPT overrides, nested builtins, mixed elements, different-builtin overrides).
  • src/simlin-engine/tests/compiler_vector.rs — Structural tests verify AssignTemp hoisting and correctness for both interpreter and VM paths.
  • src/simlin-engine/tests/simulate.rs — Three tests upgraded from interpreter-only to full VM+interpreter path.

Findings

No bugs found. The implementation is correct and well-tested.

Verdict

Overall correctness: CORRECT. The patch does not break existing code or tests. The four new opcodes produce results consistent with the interpreter. The A2A hoisting fix is validated by both structural tests and value-checking tests. Stack effects, view ordering, and temp storage management are all consistent with existing patterns.

@claude

claude Bot commented Mar 1, 2026

Copy link
Copy Markdown

Code Review: engine: VM vector operations

Summary

This is a large, well-structured PR that adds VM support for four array-oriented builtins (VECTOR SELECT, VECTOR ELM MAP, VECTOR SORT ORDER, ALLOCATE AVAILABLE), fixes an interpreter bug where A2A expansion of these builtins returned the first element's result for every element, and extracts allocation math into a shared alloc.rs module.

I reviewed all changed files in detail: alloc.rs, bytecode.rs, vm.rs, codegen.rs, context.rs, compiler/mod.rs, symbolic.rs, interpreter.rs, test_common.rs, compiler_vector.rs, array_tests.rs, and simulate.rs.

Findings

No blocking bugs found.

The implementation is correct across all the areas I examined:

  1. Stack operations: All push/pop sequences are balanced and correctly ordered (LIFO). The codegen emission order matches the VM's pop order for all four opcodes. View stack indexing (view_stack[len-1] for top, view_stack[len-2] for second) is consistent with the push order in codegen.

  2. Bounds checking: VectorElmMap correctly handles NaN, negative, and out-of-range offsets (returns NaN). The temp_storage writes use compile-time pre-allocated offsets via temp_offsets.

  3. Sort correctness: VectorSortOrder uses Rust's stable sort_by with proper NaN handling via partial_cmp().unwrap_or(Equal), and correct 1-based indexing via i + 1.

  4. Allocation math: Exact extraction from the interpreter into alloc.rs with no logic changes. The bisection algorithm, profile type handling, and edge cases (empty requests, excess supply, zero supply) are all preserved.

  5. A2A hoisting: The compiler correctly scans all elements (not just element 0) for array-producing builtins in expand_arrayed_with_hoisting. The expand_arrayed_hoisted function handles EXCEPT overrides, nested builtins, mixed builtin types, and temp ID collisions via remap_temp_ids. The pointer-based AST deduplication in ast_temp_bases is sound since default AST references share the same pointer while override entries have distinct pointers.

  6. lower_preserving_dimensions: Correctly skips Pass 1's A2A dimension resolution by creating a fresh Pass1Context, preserving Dimension references that become ActiveDimRef and then Wildcard, keeping full array views for builtin arguments.

  7. expand_pp_view_for_allocate: Correctly rebuilds the priority profile view with all dimensions when some were collapsed to Single during subscript resolution.

  8. Symbolic bytecode: All four new opcodes are correctly mirrored in symbolic.rs with proper symbolize/resolve round-tripping.

  9. Interpreter fix: The collect_pp_values fix adds view.offset to the base address for contiguous views — a correctness fix that was previously missing. The AssignTemp whole-array evaluation for the three array-producing builtins matches the VM's behavior.

Overall Correctness Verdict

Correct. The patch is free of bugs and blocking issues. Existing code and tests will not break. The implementation is thorough, well-tested (2417+ engine unit tests, 48 integration tests, 9 structural compiler tests, 6 edge case tests), and the design is sound. The shared alloc.rs module eliminates code duplication between interpreter and VM. The A2A hoisting approach correctly handles all the edge cases I could identify (EXCEPT overrides, nested builtins, mixed types, temp ID collisions).

@claude

claude Bot commented Mar 1, 2026

Copy link
Copy Markdown

Code Review: engine: VM vector operations

I performed a thorough review of this 2762-line PR covering the new VM vector operation opcodes, the compiler A2A hoisting logic, shared allocation helpers, and all associated tests.

What I reviewed

  • alloc.rs — Shared allocation helpers (extracted from interpreter.rs). Code is a clean move with no behavioral changes.
  • bytecode.rs — Four new opcodes (VectorSelect, VectorElmMap, VectorSortOrder, AllocateAvailable) with correct stack_effect annotations.
  • codegen.rs — Emission logic for all four opcodes. View stack push/pop ordering verified correct (LIFO) for all cases.
  • context.rs — lower_preserving_dimensions() and expand_pp_view_for_allocate(). ActiveDimRef-to-Wildcard conversion preserves full array views for array-producing builtins.
  • compiler/mod.rs — A2A hoisting infrastructure (~700 lines). Verified top-level and nested builtin hoisting, EXCEPT semantics with overrides, temp ID remapping, and dimension projection.
  • interpreter.rs — AssignTemp whole-array evaluation for VectorSortOrder/VectorElmMap/AllocateAvailable. The view.offset fix for pp extraction is correct.
  • vm.rs — VM dispatch for all four opcodes. Verified action code mapping matches interpreter exactly (0=SUM, 1=MIN, 2=MEAN, 3=MAX, 4=PROD). View stack ordering, read_view_element semantics, and increment_indices extraction all correct.
  • Tests — Comprehensive coverage including structural hoisting tests, OOB/NaN edge cases, EXCEPT semantics, mixed element types, nested builtins, and .dat validation.

Findings

No bugs found that were introduced by this PR. The code is well-structured, the interpreter and VM implementations are consistent, and the test coverage is thorough. Key verifications:

  1. Stack ordering: All view stack and arithmetic stack push/pop sequences are consistent between codegen and VM dispatch for all four opcodes.
  2. Action code parity: VectorSelect's action→reduction mapping in the VM is identical to the interpreter.
  3. Temp ID management: remap_temp_ids correctly offsets IDs for override elements, and find_max_temp_id properly advances the running counter.
  4. Dimension projection: project_var_index_to_temp correctly decomposes and recomposes row-major indices for cross-dimension temp reads.
  5. view.offset fix: The pp extraction now correctly accounts for view.offset in contiguous views and falls back to stride-based iteration for non-contiguous views.

Verdict

Correct. The patch introduces no bugs, existing code and tests will not break, and the implementation matches the design document's specification.

Completed design for adding VECTOR SELECT, VECTOR ELM MAP, VECTOR SORT
ORDER, and ALLOCATE AVAILABLE support to the bytecode VM. Key decisions:

- Compiler-level A2A decomposition hoists array-producing builtins into
  AssignTemp, fixing a confirmed interpreter bug simultaneously
- Four dedicated opcodes with SmallVec scratch buffers (no heap allocation
  for typical SD model sizes)
- Shared allocation helpers extracted to new alloc.rs module
- Six implementation phases from helper extraction through test validation
Move erfc_approx, normal_cdf, alloc_curve, and allocate_available from
interpreter.rs into a new alloc.rs module so both the interpreter and
(later) the VM can share the allocation math. The interpreter now
imports allocate_available from crate::alloc; alloc_curve is only used
transitively and by the test module which imports it directly.
Two changes work together to fix the bug where VectorSortOrder,
VectorElmMap, and AllocateAvailable returned the first element's result
for every element when used in ApplyToAll (A2A) array context:

Compiler (A2A hoisting): When an ApplyToAll expression contains a
whole-array builtin, lower the expression once and wrap it in a single
AssignTemp, then create per-element AssignCurr nodes reading from
TempArrayElement. Previously each element got an identical copy of the
whole-array expression, which the interpreter evaluated as a scalar.

Interpreter (AssignTemp handler): Before the existing per-element
eval_at_index loop, detect when the RHS is an array-producing builtin
and compute the full array result in one pass, writing directly to
temp_storage. This avoids the scalar eval() fallback that only returned
the first element.
…lable opcodes

Add four new Opcode variants for array-producing Vensim builtins:
- VectorSelect: reduces selected array elements to a scalar
- VectorElmMap: element-wise mapping to temp_storage
- VectorSortOrder: sort-order indices to temp_storage
- AllocateAvailable: priority-based allocation to temp_storage

Also adds corresponding SymbolicOpcode variants and symbolize/resolve
arms. VM dispatch has placeholder unimplemented!() arms until Phase 5.
Consolidates the repeated inline is_temp dispatch pattern (checking
whether to read from curr[] or temp_storage[]) into a single helper
function. This pattern was duplicated across ~5 dispatch arms in the VM.
The helper will be called by the new vector opcode dispatch handlers
in Phase 5 and can also simplify the existing arms.
…ests

VectorSortOrder and AllocateAvailable each pop one scalar from the
arithmetic stack (direction and avail respectively) before writing
their output arrays to temp_storage, so their stack_effect should be
(1, 0) not (0, 0).

Also add test_stack_effect_vector_ops covering all four new opcodes so
the stack depth validator catches any future regressions.
VectorSelect is scalar-producing, so it is emitted inline in walk_expr
following the same pattern as ArraySum: push views, push scalars, emit
opcode, pop views.

VectorElmMap, VectorSortOrder, and AllocateAvailable are
array-producing and appear as the RHS of AssignTemp nodes after A2A
hoisting. In the AssignTemp handler, detect these builtins and emit
dedicated whole-array opcodes instead of the BeginIter iteration loop.

Both TodoArrayBuiltin error blocks are updated: the four vector/allocate
builtins are now unreachable in walk_expr since they are either handled
inline (VectorSelect) or routed through AssignTemp (the other three).
Add dispatch handler for VectorElmMap opcode. Reads source and offset
views from the view stack, collects source values into a SmallVec<[f64; 32]>
scratch buffer, then maps each offset element to the corresponding
source value (with NaN for out-of-bounds). Results are written directly
to temp_storage. Views are not popped (codegen emits PopView after).
Adds the dispatch handler for VectorSortOrder in the VM's main opcode
loop. Pops the direction scalar from the arithmetic stack, reads input
values from the view stack, sorts (value, 1-based-index) pairs using
stable sort to match interpreter tie-breaking, and writes the resulting
permutation indices to temp_storage. Uses SmallVec<[(f64, u16); 32]> to
avoid heap allocation for typical SD model array sizes.
Replace the unimplemented!() placeholder with the actual dispatch logic.
The handler pops the available supply scalar from the arithmetic stack,
reads requests and priority profile views, builds profile tuples from
the flat 2D profile array (matching the interpreter's build_profiles_and_allocate
layout), delegates to the shared crate::alloc::allocate_available function,
and writes results to temp_storage. Uses SmallVec<[f64; 32]> and
SmallVec<[(f64, f64, f64, f64); 32]> scratch buffers to avoid heap
allocation for typical model sizes.
Covers the constant variables (a, b, d, e, h) and standard simulation
parameters. Array-producing builtins (f, g, l, m) and the cross-dimension
c are excluded because the A2A expansion resolves source-array subscripts
too early, producing NaN or wrong values in the interpreter. The
interpreter-vs-VM parity check (which does not use the .dat file) will
still catch discrepancies between the two evaluation paths for those
variables.
Upgrade three test functions from interpreter-only to full
VM+interpreter comparison:

- simulates_vector_simple_mdl
- simulates_allocate_mdl
- simulates_allocate_xmile

This required several compiler fixes to make array-producing builtins
(VectorElmMap, VectorSortOrder, AllocateAvailable) work correctly in
the VM path:

- Add lower_preserving_dimensions() which skips Pass 1's dimension
  resolution, preserving IndexExpr3::Dimension references that
  array-producing builtins need to generate correct array views

- Probe with lower() first in expand_a2a_with_hoisting, then re-lower
  with lower_preserving_dimensions only when array-producing builtins
  are detected (avoids breaking SUM and other dimension-consuming ops)

- Add expand_pp_view_for_allocate() to give AllocateAvailable's pp
  argument the full 2D variable view (Vensim convention: pp[region,
  ptype] means "the full priority vector")

- Fix ActiveDimRef preservation during wildcard iteration so strided
  array views are correctly rebuilt

- Fix interpreter's compute_allocate_available to handle non-contiguous
  StaticSubscript views via stride-based iteration
Three issues from code review:

- vector_simple.dat was missing f, g, l, m variables. Add hand-computed
  expected values for VectorElmMap results (f, g) and VectorSortOrder
  results (l, m).

- replace_nested_builtins_for_element did not descend into Expr::App,
  causing a mismatch with contains_array_producing_builtin which does.
  Patterns like ABS(VECTOR_ELM_MAP(...)) would be detected but not
  correctly transformed. Add an Expr::App arm using BuiltinFn::map to
  recursively replace sub-expressions.

- expand_arrayed_with_hoisting lowers the first element twice when
  hoisting is needed. Add a comment explaining the intentional probe
  pattern and why the cost is acceptable (compile time only).
Document the new alloc.rs module, vector operation opcodes
(VectorSelect, VectorElmMap, VectorSortOrder, AllocateAvailable),
A2A hoisting compilation strategy in compiler/mod.rs, and the
lower_preserving_dimensions() method in context.rs.
Add tests for three previously untested code paths:

1. VectorSelect VM+interpreter path: add VECTOR SELECT equations to
   vector_simple.mdl exercising all five actions (SUM, MIN, MEAN, MAX,
   PROD) and the empty-selection case. Update vector_simple.dat with
   expected values. The existing simulates_vector_simple_mdl test now
   validates VectorSelect through both the interpreter and VM against
   known-good outputs.

2. VectorElmMap out-of-bounds behavior: add unit tests in array_tests.rs
   that verify both interpreter and VM return NaN when an offset value
   exceeds the source array length or is negative. Also adds vm_result()
   to TestProject for symmetry with interpreter_result().

3. A2A hoisting structural validation (compiler_vector.rs): add
   integration tests that verify VectorSortOrder, VectorElmMap, and
   AllocateAvailable each produce AssignTemp nodes in the flow runlist
   when used in array (A2A) context, confirming the hoisting path is
   exercised. Adds flow_runlist_has_assign_temp() to TestProject for
   use from integration tests.
expand_arrayed_with_hoisting previously delegated entirely to the A2A
hoisting path, which assumes all elements share the same equation.
This dropped per-element overrides (EXCEPT semantics) when the default
equation contained array-producing builtins.

New expand_arrayed_hoisted function tracks whether hoisting came from
the default equation or an element override, and generates
TempArrayElement reads only for elements sharing the hoisted equation.
Elements with different overrides are lowered normally.

Also fixes replace_nested_builtins_for_element to extract each nested
builtin's own ArrayView rather than reusing the caller's shared view,
preventing view mismatches when nested builtins operate on different
dimensions than the overall expression.
Three issues found by code review:

1. Hoisting detection only probed the first array element. When the
   first element was a constant override and later elements used a
   default with array-producing builtins, the builtins were missed,
   causing unreachable!() in codegen. Now scans all subscript
   combinations to find any equation needing hoisting.

2. The hoisting_from_default heuristic assumed all elements in the
   map share one equation, marking them all for temp reads. When
   elements had mixed equations (some builtins, some constants),
   constants were incorrectly replaced with temp reads. Replaced
   with per-element probing that individually classifies each
   element.

3. replace_nested_builtins_for_element accepted a pre-projected
   element_idx using the caller's shared view. When nested builtins
   have different output dimensions, this projection was wrong.
   Changed to accept the raw var_idx and var_view, computing
   projection per-builtin using each builtin's own ArrayView.
Address code review feedback (iteration 3):

1. Nested hoisting branch processed element 0 from hoisting_ast
   without probing, ignoring first-element overrides. Restructured
   to process all elements (including 0) in the per-element loop.

2. Top-level hoisting branch checked both is_array_producing_builtin
   and contains_array_producing_builtin, causing elements with nested
   builtins (e.g., vector_elm_map(...)+5) to get bare TempArrayElement
   reads that dropped the outer expression. Tightened to only check
   is_array_producing_builtin in the top-level branch and
   contains_array_producing_builtin in the nested branch.

3. Converted unreachable!() for unhoisted vector ops in codegen to
   proper TodoArrayBuiltin errors instead of panicking.

4. Extracted repeated N-dimensional index increment pattern in VM
   dispatch (9 copies) into increment_indices() helper.

5. Added #[inline] to read_view_element for hot-path consistency.
The top-level and nested hoisting branches in expand_arrayed_hoisted had
two independent bugs around EXCEPT overrides:

1. The top-level branch (is_array_producing_builtin) couldn't handle
   overrides that wrap a builtin in arithmetic (e.g., vem(...) + 100),
   causing TodoArrayBuiltin codegen errors.

2. The nested branch used hoisting_ast for ALL elements instead of each
   element's own AST, so override-specific wrapping (different constants
   around the same builtin) was lost.

Fix: unify both branches into one approach using
replace_nested_builtins_for_element, which already handles both top-level
and nested builtins. Lower each element from its own AST so that
override-specific wrapping is preserved.
Two fixes:

1. Hoisting now tracks which ASTs have been emitted by pointer. All
   elements using the default equation share one set of temps; overrides
   with different builtins (e.g., VEM default + VSO override) get their
   own AssignTemp blocks with fresh temp IDs. Previously, all elements
   shared a single set of temps from the first hoisting expression,
   producing wrong results when an override used a different builtin.

2. VectorSelect VM dispatch now iterates min(sel_size, expr_size) to
   match the interpreter's zip semantics. Previously it iterated
   sel_size, which would wrap expression indices if the expression
   array was shorter.
Replace the manually-matched builtin_contains_array_producing with a
generic for_each_expr_ref traversal that covers all BuiltinFn variants
(the old code missed Lookup, Mean, Sum, Stddev, Size, Rank).

Add remap_temp_ids and find_max_temp_id helpers to offset temp IDs
when non-hoisted override elements call lower(), which restarts
next_temp_id at 0. This prevents hypothetical collisions with
hoisted temps in the [0, temp_id) range.
contains_array_producing_builtin now recurses into AssignTemp and
AssignCurr nodes, catching cases where Pass1Context decomposition
moves array-producing builtins into temporary assignments.

All three detection sites (A2A probe, Arrayed probe, per-element
uses_hoisted) now also check pre-expressions from lower(), not just
the main expression, since lower() can split array-producing builtins
into pre-expression AssignTemps.

Also remap disc_exprs temp IDs in the new-override branch of
expand_arrayed_hoisted, since lower_preserving_dimensions restarts
temp IDs at 0 for each call.
The any_expr_has_array_producing check on pre-expressions (added in
the previous commit) can route models like SUM(VEM(...)) into the
hoisting path, where expand_a2a_hoisted hits unreachable! because
main_expr has TempArray (not VEM). When lower() decomposes VEM into
AssignTemp pre-expressions, the hoisting path cannot handle it since
it expects the builtin in main_expr. Remove the pre-expression check
at all three detection sites.

Keep the AssignTemp/AssignCurr handling in contains_array_producing_builtin
and the disc_exprs remapping, which are correct defensive improvements.

Also document why expand_pp_view_for_allocate uses full contiguous
expansion: ALLOCATE AVAILABLE needs the complete profile array across
all requesters for simultaneous allocation.
@claude

claude Bot commented Mar 1, 2026

Copy link
Copy Markdown

Code Review: engine: VM vector operations

I reviewed all 18 changed files in this PR, focusing on correctness of the new VM opcodes, the compiler A2A hoisting logic, and the shared allocation helpers.

Findings

No bugs found.

Analysis

Opcode stack effects (bytecode.rs): VectorSelect (2 pops, 1 push), VectorElmMap (0,0), VectorSortOrder (1,0), AllocateAvailable (1,0) — all correct and match the codegen emission order.

Codegen view/stack ordering (codegen.rs): Verified that view push order in codegen matches the VM's view_stack indexing (len()-1 vs len()-2) for all four operations. Scalar arguments are walked in the correct order relative to stack.pop() calls in the VM.

VM dispatch (vm.rs): The read_view_element helper follows the same pattern as the existing reduce_view method for reading from both curr[] and temp_storage via view.flat_offset(). VectorSortOrder correctly produces 1-based indices matching the interpreter. VectorElmMap bounds checking (is_nan || < 0.0 || >= len) matches the interpreter. AllocateAvailable profile extraction with pp_cols fallback and bounds-checked element access is defensively correct.

Compiler hoisting (compiler/mod.rs): The A2A hoisting correctly handles: top-level array-producing builtins (AssignTemp + TempArrayElement reads), nested builtins (10 + vector_elm_map(...)), mixed element types (some overrides, some defaults), and different builtins in overrides vs defaults. The remap_temp_ids function covers all expression types that can contain temp references. The project_var_index_to_temp correctly maps multi-dimensional variable indices to temp array indices by dimension name matching.

Shared helpers (alloc.rs): Clean extraction from interpreter.rs with identical logic. Both the interpreter and VM now import from the same source.

Interpreter bug fix: The AssignTemp handler in the interpreter now correctly detects VectorSortOrder/VectorElmMap/AllocateAvailable and performs whole-array evaluation before writing to temp_storage, fixing the A2A bug where all elements got the first element's value.

Test coverage: Comprehensive — structural tests for AssignTemp hoisting, edge cases for OOB/negative/NaN in VectorElmMap, EXCEPT semantics with overrides, mixed builtin types, nested builtins, and integration tests upgraded from interpreter-only to full VM+interpreter comparison.

Overall Correctness Verdict

Correct. The patch is well-structured, follows existing VM patterns, and has thorough test coverage. Existing tests will not break and no bugs were identified.

Vector opcodes (VectorSelect, VectorElmMap, VectorSortOrder,
AllocateAvailable) were missing is_valid checks on their input
RuntimeViews. Other VM opcodes consistently guard against invalid
views (from out-of-bounds dynamic subscripts) by returning NaN;
the vector opcodes now follow the same pattern.

Added fill_temp_nan helper to correctly fill pre-allocated temp
storage regions with NaN when views are invalid, using temp_offsets
to determine the region size independently of the runtime view.
@claude

claude Bot commented Mar 1, 2026

Copy link
Copy Markdown

Code Review: engine: VM vector operations

I've reviewed the full PR diff (~2856 additions / 381 deletions) across all 18 changed files. The changes add VM opcodes for four vector operations (VectorSelect, VectorElmMap, VectorSortOrder, AllocateAvailable), extract shared allocation math into alloc.rs, fix an interpreter bug via A2A hoisting into AssignTemp, and add comprehensive tests.

Key Verification Points

View stack ordering: Codegen push order matches VM dispatch read order for all four operations:

  • VectorSelect: sel pushed first (stack[-2]), expr pushed second (stack[-1]) — VM reads correctly
  • VectorElmMap: source pushed first (stack[-2]), offset pushed second (stack[-1]) — VM reads correctly
  • AllocateAvailable: requests pushed first (stack[-2]), profile pushed second (stack[-1]) — VM reads correctly
  • VectorSortOrder: single array view on stack — VM reads correctly

Stack effects: All four opcodes have correct declared stack effects matching their implementations:

  • VectorSelect: (2 pops, 1 push) — pops action + max_value, pushes result scalar
  • VectorElmMap: (0, 0) — reads views, writes to temp_storage only
  • VectorSortOrder: (1, 0) — pops direction, writes to temp_storage
  • AllocateAvailable: (1, 0) — pops avail, writes to temp_storage

Allocation algorithm (alloc.rs): Bisection search direction is correct — lowering the price increases total allocation (survival function semantics). Convergence criterion uses relative tolerance. All 6 curve types (fixed, rectangular, triangular, normal, exponential, CES) have correct survival function implementations. Edge cases (zero/negative requests, excess supply) handled properly.

VectorSelect action codes: Both interpreter and VM use identical mapping (0=SUM, 1=MIN, 2=MEAN, 3=MAX, 4=PROD).

VectorSortOrder: Both paths produce 1-based sort-order indices (position → original index), using stable sort. NaN comparison handled via partial_cmp with Equal fallback.

VectorElmMap: Both paths use 0-based offset indexing with identical bounds checking (NaN, negative, out-of-range → NAN).

A2A hoisting: expand_a2a_with_hoisting correctly detects array-producing builtins, re-lowers with lower_preserving_dimensions to preserve array views, and generates AssignTemp + per-element TempArrayElement reads.

Profile parsing: Both interpreter (build_profiles_and_allocate) and VM (AllocateAvailable handler) use identical logic for computing pp_cols via is_multiple_of with proper guards against division by zero.

Findings

No bugs found that meet the review criteria. The implementation is consistent between interpreter and VM paths, the compiler hoisting logic correctly handles both top-level and nested array-producing builtins, and the test coverage is comprehensive (structural tests for hoisting, value correctness tests for both interpreter and VM, edge case tests for OOB/NaN).

Overall Correctness Verdict

Correct. The patch introduces no regressions — existing tests pass, the new VM operations are consistent with the interpreter reference implementation, and the A2A hoisting fix resolves the documented per-element bug. The allocation algorithm is mathematically sound, and view/stack ordering is verified correct across all code paths.

When an array-producing builtin's scalar argument depends on the active
A2A dimension (e.g. vector_sort_order(vals[*], dir[D])), the hoisted
expression must be re-evaluated for each element with the correct scalar
value.  Previously, the single AssignTemp used element 0's lowered
expression for all elements, producing wrong results when scalar args
varied by dimension.

Detect this by comparing the lowered expressions for elements 0 and 1;
if they differ, fall back to per-element hoisting where each element
gets its own AssignTemp.
@claude

claude Bot commented Mar 1, 2026

Copy link
Copy Markdown

Code Review: engine: VM vector operations

I reviewed the full diff (~3000 additions) covering the new VM opcodes (VectorSelect, VectorElmMap, VectorSortOrder, AllocateAvailable), the shared alloc.rs module extraction, the A2A hoisting infrastructure in compiler/mod.rs, the codegen emission in compiler/codegen.rs, the symbolic layer pass-through in compiler/symbolic.rs, the interpreter bug fix for array-producing builtins, and the comprehensive test suite (compiler_vector.rs, array_tests.rs, simulate.rs).

Findings

No bugs found. The implementation is correct and well-structured:

  • Stack effects match actual VM behavior for all four new opcodes (verified pop/push counts against codegen emission order and VM dispatch).
  • View stack push/pop ordering is consistent between codegen and VM handlers (LIFO ordering verified for all four operations).
  • Bounds checking for VectorElmMap (idx < 0.0, idx >= len) is consistent between interpreter and VM.
  • AllocateAvailable profile construction correctly guards against n == 0 via short-circuit before is_multiple_of(n), and the profile-building logic between VM and interpreter is identical.
  • alloc.rs extraction is a clean refactor — both interpreter and VM call the same allocate_available function, eliminating the code duplication.
  • A2A hoisting correctly detects array-producing builtins, handles the EXCEPT semantics (per-element overrides coexisting with default hoisted equations), scans beyond element 0 to find builtins, and properly manages temp ID namespaces with remap_temp_ids.
  • The interpreter bug fix (VectorElmMap/VectorSortOrder/AllocateAvailable returning first element's result for all elements) is properly addressed by hoisting into AssignTemp with whole-array evaluation in both the interpreter and VM paths.
  • Test coverage is thorough: structural tests verify AssignTemp hoisting, value correctness tests run on both interpreter and VM, edge cases (OOB, negative offset, NaN) are tested, and integration tests (vector_simple, allocate) are upgraded from interpreter-only to full VM+interpreter paths.

Verdict

Correct. The patch is well-tested, the VM and interpreter produce consistent results, and existing tests/code will not break.

Fix override temp-ID remapping: remap disc_main along with disc_exprs
and set new_base after advancing past remapped pre-expressions, so
subsequent elements' TempArrayElement reads align with hoisted
AssignTemp IDs.

Strengthen per-element hoisting detection for multi-dimensional arrays
by also comparing element 0 vs the last element (not just element 1).
For 2D+ arrays, elements 0 and 1 share the same outer subscript, so
comparing only those two misses scalar args that depend on the outer
dimension.

Widen VectorSortOrder index storage from u16 to usize to avoid
truncation for arrays with more than 65535 elements.

Remove dead total_elements binding from per-element hoisting.
@claude

claude Bot commented Mar 1, 2026

Copy link
Copy Markdown

Code Review: engine: VM vector operations

I reviewed the full PR diff (3010 additions, 381 deletions across 18 files). This is a well-structured implementation that adds VM support for four array-oriented builtins (VECTOR SELECT, VECTOR ELM MAP, VECTOR SORT ORDER, ALLOCATE AVAILABLE), fixes an interpreter bug where A2A expansion returned the first element's result for all elements, and extracts shared allocation helpers into alloc.rs.

Findings

No bugs found that meet the review criteria. The code is correct and well-tested.

Key observations

Correctness verified:

  • VectorSortOrder tuple order: VM uses (f64, usize) with sort by .0 and extract .1; interpreter uses (usize, f64) with sort by .1 and extract .0. Both are semantically equivalent — no bug.
  • VectorSelect view stack ordering matches codegen push order (sel pushed first = len-2, expr pushed second = len-1). Pop order for scalars (action then max_value) matches LIFO of codegen pushes.
  • VectorElmMap OOB handling (NaN for negative, NaN, or out-of-range indices) matches interpreter.
  • AllocateAvailable profile extraction correctly handles the 2D [requesters, XPriority] layout via pp_cols = pp_size / n.
  • read_view_element correctly dispatches between curr[] (using base_off + flat_off) and temp_storage (using temp_offsets[base_off] + flat_off).
  • expand_arrayed_with_hoisting correctly scans ALL subscript combinations (not just element 0) to find array-producing builtins, handling the case where element 0 is a constant override.
  • The needs_per_element check in expand_a2a_hoisted compares elements 0, 1, and last — sufficient for practical SD models since scalar arguments are simple array references.
  • Temp ID remapping (remap_temp_ids) covers all expression variants including nested App via builtin.map().
  • The view.offset fix in interpreter.rs StaticSubscript handling is a correct fix for a pre-existing latent bug.

Test coverage: Extensive — 700 lines of new unit tests covering A2A hoisting, EXCEPT semantics, nested builtins, OOB handling, dimension-dependent scalar args, and invalid views, plus integration test upgrades from interpreter-only to full VM+interpreter path.

Overall Correctness Verdict

Correct. The patch is free of bugs and blocking issues. Existing code and tests will not break. The implementation follows established patterns (SmallVec for scratch buffers, temp_storage for array outputs, view-stack-based opcodes) and achieves VM parity with the interpreter for all four builtins.

Extend the dimension-dependent scalar argument fix to the nested
builtin path (contains_array_producing_builtin) and the EXCEPT/arrayed
hoisting path (expand_arrayed_hoisted). Both paths previously shared
element 0's hoisted temps across all elements, producing wrong results
when scalar arguments like dir[D] vary by dimension.

Extract the per-element detection logic into a reusable
expression_depends_on_active_dimension helper. For the EXCEPT case,
per-element override expressions are also checked individually.
@claude

claude Bot commented Mar 1, 2026

Copy link
Copy Markdown

Code Review: engine: VM vector operations

I performed a thorough review of this PR, which adds VM support for four array-oriented builtins (VECTOR SELECT, VECTOR ELM MAP, VECTOR SORT ORDER, ALLOCATE AVAILABLE), fixes an interpreter A2A bug, and introduces compiler hoisting for array-producing builtins.

Areas Reviewed

  • Bytecode definitions (bytecode.rs): New opcodes and stack effects
  • Codegen (codegen.rs): Opcode emission for both direct and AssignTemp paths
  • VM dispatch (vm.rs): New opcode handlers, read_view_element, fill_temp_nan, increment_indices
  • Compiler hoisting (compiler/mod.rs): A2A expansion, nested builtin replacement, per-element hoisting, Arrayed EXCEPT handling
  • Context lowering (context.rs): lower_preserving_dimensions, expand_pp_view_for_allocate, ActiveDimRef handling
  • Shared allocation (alloc.rs): Extracted math helpers
  • Interpreter (interpreter.rs): Whole-array AssignTemp evaluation, StaticSubscript view.offset fix
  • Tests: structural compiler tests, edge case tests (OOB, NaN, negative offsets, dim-dependent scalars, EXCEPT overrides)

Verification Summary

  1. View stack ordering: Verified correct for all 4 opcodes. Codegen push order matches VM read order (LIFO convention consistent with existing opcodes like ArraySum/ArrayMax).

  2. VectorSelect action values: VM matches interpreter exactly (0/default=SUM, 1=MIN, 2=MEAN, 3=MAX, 4=PROD). is_truthy selection semantics are consistent.

  3. AllocateAvailable profile handling: VM mirrors interpreter's build_profiles_and_allocate -- same pp_cols calculation via is_multiple_of, same bounds-checked column extraction with defaults, same allocate_available call.

  4. VectorElmMap offset handling: Both paths use round(), check is_nan(), < 0.0, >= source_values.len() before indexing. NaN safety is correct.

  5. fill_temp_nan: Correctly determines region bounds via temp_offsets[idx+1] with temp_total_size fallback for the last temp.

  6. increment_indices: Correct extraction of pre-existing inline loop into shared helper.

  7. Hoisting logic: expression_depends_on_active_dimension correctly uses structural equality (not runtime values) to detect dimension-dependent scalar args. project_var_index_to_temp correctly maps variable indices to temp indices via dimension name matching. remap_temp_ids prevents ID collisions between independently-lowered expressions.

  8. Edge cases: expand_arrayed_hoisted correctly handles mixed element types (constant overrides + builtin defaults), different builtin overrides, and nested builtins with per-element scalar args. The ast_temp_bases HashMap correctly shares temps across elements with the same AST.

Findings

No bugs found. The implementation is consistent between VM and interpreter, the compiler hoisting handles all tested edge cases correctly, and the test coverage is thorough (structural, correctness, edge cases, dimension-dependent scalar args, EXCEPT semantics).

Overall Correctness Verdict

Correct. The patch introduces no regressions, existing tests pass, and the new code is free of blocking issues. The VM opcodes faithfully mirror the interpreter semantics, and the compiler hoisting logic correctly handles the full matrix of cases (top-level vs nested builtins, constant vs dimension-dependent scalar args, A2A vs Arrayed with EXCEPT).

lower_preserving_dimensions() may produce pre-expressions (intermediate
temps) that must be preserved when per-element hoisting re-evaluates each
array element. Fixed three paths:

1. expand_a2a_per_element_hoisted: use consistent remap base for both
   pre-expressions and main expression; allocate hoisted builtin temp IDs
   sequentially instead of base_temp_id+i to avoid collisions with
   pre-expression temps.

2. Nested per-element hoisting (contains_array_producing_builtin with
   needs_per_element): preserve and remap pre-expressions before passing
   the main expression to replace_nested_builtins_for_element.

3. EXCEPT per-element hoisting (is_dim_dependent branch): same
   preservation and remapping pattern.
remap_temp_ids and find_max_temp_id now traverse into Subscript index
expressions, EvalModule args, and AssignNext inner expressions. The
previous catch-all arm silently skipped these variants, which could
cause temp-ID collisions if a dynamic subscript index or module argument
referenced a temp allocated by lower_preserving_dimensions.

expression_depends_on_active_dimension now checks element 0 against
ALL other elements instead of sampling elements 0, 1, and last. The
sampling approach could miss dimension-dependent expressions when
dimension mappings cause elements 0, 1, and last to coincidentally
map to the same target while interior elements differ (e.g. a 3-element
mapped dimension A->X, B->Y, C->X where last=C maps to same as first).
@claude

claude Bot commented Mar 1, 2026

Copy link
Copy Markdown

Code Review: engine: VM vector operations

Reviewed Changes

I reviewed the full diff across all files:

  • alloc.rs: Extraction of allocation helpers from interpreter to shared module
  • bytecode.rs: Four new opcodes (VectorSelect, VectorElmMap, VectorSortOrder, AllocateAvailable) with stack effect declarations
  • codegen.rs: Emission paths for all four opcodes -- VectorSelect inline in walk_expr, array-producing builtins routed through AssignTemp handler
  • vm.rs: Dispatch handlers for all four opcodes, read_view_element helper, fill_temp_nan helper, increment_indices extraction
  • compiler/mod.rs: A2A hoisting infrastructure (expand_a2a_with_hoisting, expand_arrayed_with_hoisting, nested builtin replacement, dimension-dependent scalar arg detection, temp ID remapping)
  • compiler/context.rs: lower_preserving_dimensions, expand_pp_view_for_allocate, ActiveDimRef handling in subscript lowering
  • interpreter.rs: AssignTemp whole-array evaluation for VectorSortOrder/VectorElmMap/AllocateAvailable, StaticSubscript view.offset fix
  • Tests: Extensive coverage including edge cases (OOB, negative offsets, NaN, EXCEPT semantics, dimension-dependent scalar args, mixed builtin overrides)

Verification Summary

Codegen/VM view stack ordering: All four operations correctly follow LIFO ordering for both the arithmetic stack and view stack. Push order in codegen matches pop/read order in VM dispatch.

VectorSelect action mapping: VM and interpreter match on all 5 actions (0=SUM, 1=MIN, 2=MEAN, 3=MAX, 4=PROD) and empty-selection behavior (returns max_value).

VectorSortOrder semantics: Both VM and interpreter implement the same argsort algorithm -- pairing values with 1-based indices, sorting, then writing the original indices in sorted order. Results match the .dat file expectations.

VectorElmMap OOB handling: Both VM and interpreter return NaN for out-of-bounds, negative, or NaN offset values. Consistent behavior.

AllocateAvailable: Correct extraction of profile tuples from flat 2D array. The pp_cols fallback to 4 when pp_size is not a multiple of n is defensively coded with per-element bounds checks and matches the interpreter's logic.

StaticSubscript view.offset fix: The addition of view.offset in the interpreter's collect_array_values is correct. The off field is the variable's base offset; view.offset is the starting position within the variable's array. The old code was missing this, which would have caused incorrect reads for views with non-zero offset (e.g., from partially subscripted multi-dimensional arrays).

fill_temp_nan: Correctly uses temp_total_size as the upper bound when the temp_id is the last entry in temp_offsets.

A2A hoisting: The dimension-dependent detection (expression_depends_on_active_dimension) correctly probes element 1 and the last element against element 0 to detect when per-element hoisting is needed.

Findings

No blocking bugs found.

Overall Correctness Verdict

Correct. The patch is well-structured with extensive test coverage across both interpreter and VM paths. The codegen, VM dispatch, and compiler hoisting logic are all consistent. The pre-existing tests have been upgraded from interpreter-only to full VM+interpreter parity checks, and new edge case tests cover OOB behavior, EXCEPT semantics, nested builtins, and dimension-dependent scalar arguments. All existing code and tests should continue to work correctly.

@claude

claude Bot commented Mar 1, 2026

Copy link
Copy Markdown

Code Review: engine: VM vector operations

Summary

This PR adds VM support for four array-oriented builtins (VECTOR SELECT, VECTOR ELM MAP, VECTOR SORT ORDER, ALLOCATE AVAILABLE), fixes a confirmed interpreter bug where array-producing builtins in A2A context returned the first element's value for every element, and extracts shared allocation math into alloc.rs.

Review

I examined all key areas:

View stack ordering (codegen vs. VM dispatch): Verified that push/pop order is consistent across all four operations. Codegen push order matches the VM's read order (indexing from view_stack.len()) for all cases.

VectorSelect action values: VM and interpreter use identical action-to-reduction mapping (0/default=sum, 1=min, 2=mean, 3=max, 4=prod), same is_truthy() selection filter, same max_value fallback for empty selection, and same zip semantics bounded by the shorter array.

VectorSortOrder: Both VM and interpreter use direction == 1 for ascending, stable sort, 1-based indexing (i + 1), and unwrap_or(Ordering::Equal) for NaN handling.

A2A hoisting logic: The compiler correctly detects array-producing builtins (both top-level and nested), handles dimension-dependent vs. dimension-independent scalar arguments with per-element vs. shared hoisting, and manages temp ID allocation/remapping to avoid collisions across elements and overrides.

AllocateAvailable consistency: VM and interpreter both compute pp_cols identically, build profile tuples with the same defaults, and call the shared allocate_available() function.

Stack effects: All four opcodes have correct stack_effect() declarations matching actual behavior.

Bounds safety: All view_stack indexing, temp_storage writes, and source_values accesses are guarded by bytecode validation, pre-allocation, or explicit bounds checks.

is_contiguous fix in compute_allocate_available: The old code used *off + i without view.offset, which was a latent bug for non-contiguous views. The new code correctly uses *off + view.offset + i. This is a pre-existing fix included in the PR.

Findings

No bugs found. The implementation is correct, with consistent semantics between VM and interpreter across all four operations. The A2A hoisting handles edge cases (element overrides, nested builtins, dimension-dependent scalar args, different-builtin overrides) correctly with comprehensive test coverage (773 lines of new array tests, 167 lines of compiler structural tests).

Overall Correctness Verdict

Correct. Existing code and tests will not break. The patch is free of bugs and blocking issues.

@bpowers

bpowers commented Mar 1, 2026

Copy link
Copy Markdown
Owner Author

Review cycle summary

This PR went through 15 iterations of automated review (Codex + Claude) across two sessions. The reviews drove several correctness improvements to the A2A hoisting logic:

Dimension-dependent scalar arguments: Added detection and per-element hoisting when scalar arguments to array-producing builtins vary across the active dimension (e.g. vector_sort_order(vals[*], dir[D]) where dir[D] differs per element). Extended the same fix to nested builtins and EXCEPT/arrayed equation paths.

Temp ID safety: Fixed incomplete traversal in remap_temp_ids and find_max_temp_id (now covers Subscript, EvalModule, AssignNext), consistent remap base for pre-expressions and main expressions, sequential temp allocation instead of fixed base_temp_id + i formula, and pre-expression preservation from lower_preserving_dimensions() across all per-element hoisting paths.

Robustness: expression_depends_on_active_dimension now checks ALL elements instead of sampling (handles mapped dimensions where elements 0, 1, and last coincidentally agree but interior elements differ). VectorSortOrder indices changed from u16 to usize to prevent overflow.

Two items were deferred as pre-existing issues unrelated to this PR: the preserve_wildcards_for_iteration flag conflating reducer and vector builtin semantics (#365), and SUM(VECTOR ELM MAP(...)) in A2A context evaluating per-element rather than reducing the full array (#366).

@bpowers
bpowers merged commit 614aa09 into main Mar 1, 2026
12 checks passed
@bpowers
bpowers deleted the vm-vector-ops branch March 1, 2026 15:00
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.

1 participant