Repository navigation
engine: VM vector operations - #361
Conversation
There was a problem hiding this comment.
💡 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".
| let first_ast = first_ast.unwrap(); | ||
| expand_a2a_with_hoisting(ctx, dims, first_ast, off) |
There was a problem hiding this comment.
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 👍 / 👎.
| 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); |
There was a problem hiding this comment.
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 👍 / 👎.
Code Review: engine: VM vector operationsSummaryThis 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 Detailed AnalysisCorrectness verified across key areas:
Design observations (not bugs):
FindingsNo bugs found. The implementation is correct, well-tested (structural + edge case + parity tests), and the approach is sound. Overall CorrectnessCorrect. 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 Report❌ Patch coverage is 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. 🚀 New features to boost your workflow:
|
Code Review[P2]
|
Code Review: engine: VM vector operationsSummaryThis PR adds VM support for four array-oriented builtins (VECTOR SELECT, VECTOR ELM MAP, VECTOR SORT ORDER, ALLOCATE AVAILABLE), extracts shared allocation helpers into FindingsNo bugs found that meet the review criteria. Detailed AnalysisI verified the following aspects across the ~1900 lines of new/modified code:
VerdictOverall 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. |
Code Review: engine: VM vector operationsSummaryThis 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 FindingsNo bugs found. The implementation is thorough and well-tested. Specific areas I verified:
Overall Correctness VerdictCorrect. The patch is well-implemented with extensive test coverage. Existing code and tests will not break. No bugs or blocking issues found. |
Code Review: engine: VM vector operationsI 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
FindingsNo bugs found. The implementation is correct for all supported patterns and the test coverage is thorough. Overall CorrectnessCorrect. 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. |
Code Review: engine: VM vector operationsSummaryThis 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
FindingsNo bugs found. The implementation is correct and well-tested. VerdictOverall 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. |
Code Review: engine: VM vector operationsSummaryThis 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 I reviewed all changed files in detail: FindingsNo blocking bugs found. The implementation is correct across all the areas I examined:
Overall Correctness VerdictCorrect. 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 |
Code Review: engine: VM vector operationsI 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
FindingsNo 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:
VerdictCorrect. 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.
Code Review: engine: VM vector operationsI 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. FindingsNo bugs found. AnalysisOpcode 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 ( VM dispatch (vm.rs): The Compiler hoisting (compiler/mod.rs): The A2A hoisting correctly handles: top-level array-producing builtins (AssignTemp + TempArrayElement reads), nested builtins ( 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 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 VerdictCorrect. 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.
Code Review: engine: VM vector operationsI'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 Key Verification PointsView stack ordering: Codegen push order matches VM dispatch read order for all four operations:
Stack effects: All four opcodes have correct declared stack effects matching their implementations:
Allocation algorithm ( 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 VectorElmMap: Both paths use 0-based offset indexing with identical bounds checking (NaN, negative, out-of-range → NAN). A2A hoisting: Profile parsing: Both interpreter ( FindingsNo 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 VerdictCorrect. 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.
Code Review: engine: VM vector operationsI reviewed the full diff (~3000 additions) covering the new VM opcodes ( FindingsNo bugs found. The implementation is correct and well-structured:
VerdictCorrect. 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.
Code Review: engine: VM vector operationsI 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 FindingsNo bugs found that meet the review criteria. The code is correct and well-tested. Key observationsCorrectness verified:
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 VerdictCorrect. 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.
Code Review: engine: VM vector operationsI 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
Verification Summary
FindingsNo 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 VerdictCorrect. 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).
Code Review: engine: VM vector operationsReviewed ChangesI reviewed the full diff across all files:
Verification SummaryCodegen/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 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 StaticSubscript view.offset fix: The addition of fill_temp_nan: Correctly uses A2A hoisting: The dimension-dependent detection ( FindingsNo blocking bugs found. Overall Correctness VerdictCorrect. 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. |
Code Review: engine: VM vector operationsSummaryThis 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 ReviewI 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 VectorSelect action values: VM and interpreter use identical action-to-reduction mapping (0/default=sum, 1=min, 2=mean, 3=max, 4=prod), same VectorSortOrder: Both VM and interpreter use 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 Stack effects: All four opcodes have correct Bounds safety: All
FindingsNo 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 VerdictCorrect. Existing code and tests will not break. The patch is free of bugs and blocking issues. |
Review cycle summaryThis 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. Temp ID safety: Fixed incomplete traversal in Robustness: Two items were deferred as pre-existing issues unrelated to this PR: the |
Summary
erfc_approx,normal_cdf,alloc_curve,allocate_available) into sharedalloc.rsmodule used by both interpreter and VM.datexpected output validationTest plan
docs/test-plans/2026-02-27-vm-vector-ops.md