Skip to content

engine: close array gaps - #390

Merged
bpowers merged 35 commits into
mainfrom
close-array-gaps
Mar 12, 2026
Merged

bpowers merged 35 commits into
mainfrom
close-array-gaps

Conversation

@bpowers

@bpowers bpowers commented Mar 12, 2026 •

Copy link
Copy Markdown
Owner

Summary

Comprehensive array/subscript improvements across 6 phases, closing multiple open issues:

Test plan

  • All 2634 engine unit tests pass
  • All 53 simulation integration tests pass (9 remain ignored for known reasons)
  • Clippy clean with zero warnings
  • Pre-commit hooks pass on all commits
  • Verify project_io.gen.rs regenerates correctly via pnpm build:gen-protobufs (protoc was unavailable during implementation)

Fixes #341
Fixes #342
Fixes #344
Fixes #345
Fixes #348
Fixes #351
Fixes #356
Fixes #357
Fixes #358
Fixes #359
Fixes #365
Fixes #388

bpowers added 28 commits March 12, 2026 06:50
Add promote_active_dim_ref field to Context to distinguish between
reducer builtins (SUM, MEAN, MIN, MAX, SIZE, STDDEV) and array-producing
vector builtins (VectorSortOrder, VectorElmMap, VectorSelect,
AllocateAvailable).

Reducers use with_preserved_wildcards() which keeps
promote_active_dim_ref=false, so ActiveDimRef subscripts resolve to
concrete element offsets.  This means SUM(matrix[DimA, *]) inside an
arrayed variable iterating over DimA correctly sums each row
independently rather than the entire matrix.

Vector builtins use the new with_vector_builtin_wildcards() which sets
promote_active_dim_ref=true, preserving the existing behavior where
dimension references like vals[DimA] keep their full array view.
Add flag_split_tests module to array_tests.rs verifying that:

- Reducer builtins (SUM, MEAN) do NOT promote ActiveDimRef to Wildcard,
  so partial reductions like SUM(matrix[DimA, *]) sum per-row instead of
  the entire matrix.

- Vector builtins (VECTOR SORT ORDER) DO promote ActiveDimRef so the
  full array view is available for sorting.

Both interpreter and VM paths are tested for each case.
ArrayMax and ArrayMin previously returned NEG_INFINITY and INFINITY
respectively for zero-size views (the init values passed to
reduce_view). ArrayMean and ArrayStddev produced NaN incidentally via
IEEE division by zero. This adds explicit size==0 guards to all four
opcodes so they return NaN intentionally. ArraySum (returns 0.0) and
ArraySize (returns 0) already handled empty views correctly.
array_mean returned 0.0 for empty arrays instead of NaN. array_stddev
returned 0.0 for size==0 (conflated with the size<=1 guard). Min and
Max single-arg handlers returned INFINITY and NEG_INFINITY respectively
for empty arrays. All four now return NaN for zero-size views, matching
the VM behavior and the mathematical convention that these operations
are undefined on empty sets.
Two test suites covering the empty-view guard behavior:

vm::empty_view_reduce_tests -- constructs a RuntimeView with dims=[0]
and verifies reduce_view returns the correct init values, while the
opcode guards return NaN for MAX/MIN/MEAN/STDDEV. Zero-element
dimensions cannot currently arise through the model compilation
pipeline but the guards protect against future edge cases.

array_tests::array_reducer_tests -- model-level integration tests for
all six reducers (SUM, SIZE, MEAN, MIN, MAX, STDDEV) verifying both
interpreter and VM agree on non-empty arrays. Includes single-element
STDDEV boundary case (size==1 should return 0.0).
The MEAN and STDDEV tests in empty_view_reduce_tests only asserted that
view.size()==0 without actually exercising reduce_view or documenting
what would happen without the size guard.  Replace them with tests that
call reduce_view to show the helper returns 0.0 for empty views, and
add explicit assertions that explain why the guard is necessary: without
it, ArrayMean would compute 0.0/0.0=NaN implicitly, and ArrayStddev
would overflow on the usize(0)-1 divisor calculation.

Also add interpreter_empty_view_tests, a new #[cfg(test)] module inside
interpreter.rs that directly exercises array_mean, array_stddev, Min,
and Max via a constructed ModuleEvaluator with a zero-element
StaticSubscript expression.  Zero-element dimensions cannot arise
through the model compilation pipeline, so the tests build a minimal
real Simulation (for valid module/sim references) and synthesize the
StaticSubscript manually.
Add a bool as the 4th field of the Equation::Arrayed tuple variant to
explicitly track whether an arrayed equation was derived from EXCEPT
syntax during MDL conversion. This replaces the text-comparison
heuristic that will be removed in the next commit.

All existing construction sites default to false except those that
represent known EXCEPT-derived equations in tests. The SourceEquation
enum in db.rs is updated in parallel. No behavioral change yet -- the
field is threaded through but not used for decision-making until the
heuristic replacement.
…ult flag

Set has_except_default to the value of has_except_eq when constructing
Equation::Arrayed during MDL conversion. This means EXCEPT-derived
equations now carry an explicit flag rather than relying on text
comparison at parse time.

Remove the should_apply_default_to_missing function entirely and use
the has_except_default bool directly at the call site. The old heuristic
compared each element's equation text against the default equation to
guess whether the equation came from EXCEPT syntax -- this was fragile
and could produce wrong results when override-style sparse arrays
happened to have elements matching the default.
Threads the new has_except_default bool from Equation::Arrayed through
protobuf and JSON serialization layers. Uses Option<bool> in both
formats for backward compatibility -- absent means false. Includes
round-trip tests for proto serialization verifying the flag survives
encode/decode and that missing values default to false.
Three changes that together enable EXCEPT equations with mapped
dimensions to compile and simulate correctly:

1. Extend find_matching_dimension to check dimension mappings after
   name-match and indexed-size-match. Adds has_mapping_to to the
   Expr2Context trait, implemented on ArrayContext via DimensionsContext.
   This prevents MismatchedDimensions errors for cross-dimension refs.

2. In build_element_context, resolve cross-dimension mapping
   substitutions using DimensionsContext::translate_via_mapping. When
   iterating k[DimA] at element A2 and the RHS references j[DimD],
   the converter now substitutes DimD with the element of DimD that
   maps to A2 (e.g., D1).

3. Fix has_except_default to only be true when EXCEPT equations
   coexist with separate override equations. Previously the flag was
   set for all EXCEPT equations, causing excepted elements with no
   override to incorrectly receive the default value instead of 0.

4. Un-ignore simulates_except and simulates_except2 integration tests
   which now pass. XMILE variants remain ignored (xmutil limitation).

Also includes the generated schema update from the previous commit's
hasExceptDefault JSON field addition.
When promote_active_dim_ref is true (inside array-producing builtins
like VectorElmMap), subscripts that collapse all dimensions to Single
(e.g. b[B1]) are promoted back to the full array by replacing Single
ops with Wildcard. This matches Vensim semantics where b[B1] inside
VECTOR ELM MAP means "full b array".

Also suppresses MismatchedDimensions for partial collapses like
d[DimA,B1] where the remaining view dimensions differ from the output
dimensions -- expected when the source lives in a different dimension
space.
renumber_opcode was missing match arms for VectorElmMap,
VectorSortOrder, and AllocateAvailable opcodes. Their write_temp_id
fields were not offset during fragment concatenation, so when multiple
arrayed variables used these builtins, later variables wrote to temp
slot 0 (clobbering earlier results) while LoadTempConst read from the
correctly-renumbered slot and got uninitialized zeros.

The vector_simple integration test is upgraded from interpreter-only to
the full simulate_mdl_path (both interpreter and VM legs).
When Pass 1 hoists expressions from array reducer arguments (SUM, MEAN,
etc.) into AssignTemp pre-computations, the hoisted expression may
contain cross-dimension wildcards (e.g. c[*] with DimA in a DimB
context).  Two fixes:

1. AssignTemp lowering now uses with_preserved_wildcards() so that
   cross-dimension wildcards in hoisted subexpressions are preserved
   rather than erroneously matched against the outer active dimensions.

2. Positional size matching is skipped when preserve_wildcards_for_iteration
   is active, since the view describes what the reduction iterates over
   and is independent of the output dimensions.

The vector.xmile comment is updated to reflect the partial progress:
cross-dim subscripts, SUM wildcards, and AssignTemp wildcards are now
handled, but y[DimA] = VECTOR ELM MAP(x[three], (DimA-1)) still fails
in the VM incremental path and additional VECTOR SELECT cross-dimension
patterns need compiler work.
…dimension mappings

Extend the proto schema with default_equation on ArrayedEquation, a
DataSource message on Compat, and a DimensionMapping message on
Dimension.  Update serde.rs to round-trip these fields (with backward
compatibility for old protos that lack them) and refactor the four
variable types to share compat_to_proto/compat_from_proto helpers.

For XMILE, add DataSourceElement and MappingElement/MappingElem structs
using simlin: vendor-extension elements.  Fix serde rename annotations
to use local names without namespace prefix, matching quick-xml's
deserialization behavior.

Remove validate_for_protobuf and validate_for_xmile guard functions
since all previously-rejected constructs are now serializable.  Convert
the eight rejection tests to round-trip success tests and add a backward
compatibility test for old protos.
Extends the MDL converter to resolve arrayed GET DIRECT CONSTANTS and
GET DIRECT LOOKUPS by adjusting cell references per array element.

When a variable is arrayed and its equation uses a GET DIRECT function,
each element needs a different cell from the external data file. The
element's 0-based position within its LHS subscript dimension determines
the row/column offset applied to the base cell reference.

Key semantics for GET DIRECT CONSTANTS cell adjustment:
- Without star: first dim -> rows, second dim -> columns
- With star: first dim -> columns, second dim -> rows (transposed)
- For 3+ dimensions, only the last two participate in the 2D grid

For GET DIRECT LOOKUPS, each array element reads from a different row
while sharing the same x-column.

Un-ignores directconst, directlookups, and directsubs integration tests.
The directdata test remains ignored (requires ext_data feature).
Add "vector rank" to the BUILTINS set so the MDL classifier recognizes
VECTOR RANK as a builtin function. Add the "vector rank" -> "RANK"
rename in xmile_compat format_function_name so MDL equations using
VECTOR RANK map to the existing Rank AST node.
VECTOR RANK(A, direction) assigns each element its ordinal position in
the sorted order. direction=1 sorts ascending (smallest gets rank 1),
direction=0 sorts descending. This matches the companion VECTOR SORT
ORDER semantics already implemented.

The implementation handles all four interpreter entry points:
find_array_dims, eval_at_index, scalar eval, and bulk AssignTemp.
Add Rank opcode to bytecode, compiler codegen, symbolic IR, and VM.
The opcode pops a direction scalar (1=ascending, 0=descending) and reads
one view from the view stack. It writes each element's 1-based ordinal
position in the sorted order to temp storage -- the inverse of
VectorSortOrder which writes original indices in sorted position.

Register Rank as an array-producing builtin in the compiler's A2A
hoisting logic so it routes through AssignTemp like VectorSortOrder.
The Rank builtin was returning TodoArrayBuiltin during Expr3-to-Expr
lowering in context.rs, preventing compilation entirely. Implemented
proper lowering using with_vector_builtin_wildcards() for the array
argument (matching VectorSortOrder pattern). Also added Rank to
find_expr_array_view() so A2A hoisting computes the correct output
dimensions.

Added 14 unit tests covering ascending/descending ranking, named
dimensions, ties, single elements, and interpreter/VM agreement.
When a range subscript produces fewer elements than the target
dimension (e.g. source[1:3] assigned to a 5-element target), the
compiler now emits NaN for out-of-bounds positions instead of reading
past the range bounds. This requires two changes:

1. The positional size check in A2A context now allows range-originated
   view dimensions to be smaller than the target dimension.

2. After computing the relative offset within the range view, a bounds
   check emits Expr::Const(NaN) when the offset exceeds the view
   dimension size.

The range_basic test expectations are updated from last-element-repeat
to NaN fill semantics.
…ntext

When a range subscript has dynamic variable bounds (e.g. data[start:end]
where start and end are scalar variables), normalize_subscripts3 cannot
resolve the bounds statically. In A2A context this previously fell
through to dynamic subscript handling, which produced Range subscript
indices that codegen rejects in scalar per-element context.

For dynamic ranges in 1D A2A context, the compiler now emits a
conditional per-element access: for each target element at 0-based
index i, it computes the 1-based source index (start + i) and checks
whether it falls within [start, end]. In-bounds elements produce a
dynamic single subscript load; out-of-bounds elements produce NaN.

The range_with_expressions test expectations are updated from the old
last-element-repeat pattern to proper NaN fill, and the test now
explicitly checks element values rather than using
assert_interpreter_result.

The complex_expression test (SUM(profit[*, Product.*])) already passes
-- the parser and existing StarRange lowering handle qualified wildcards
correctly.
Fix the transpose_and_slice test to use an intermediate transposed
variable rather than the unsupported matrix'[1:3, *] syntax. The
parser currently only handles subscripts on identifiers, not on
arbitrary postfix expressions. Using an explicit intermediate
(transposed[Col, Row] = matrix') followed by subscripting
(result[SliceCol, Row] = transposed[1:3, *]) correctly exercises
the transpose + range subscript chain.

Also fix the test's expected dimensions and values: the original
test declared result without dimensions and had incorrect expected
values.
Add parent: Option<String> to datamodel::Dimension, enabling
compute_subdimension_relation to handle Indexed/Indexed pairs.
When a child indexed dimension declares a parent, the relation maps
the child's elements to the first N positions of the parent.

Updated across all serialization formats (protobuf, JSON, XMILE) with
backward-compatible defaults (absent = None / empty string).
Remove #[ignore] from range_basic, range_with_expressions,
transpose_and_slice, complex_expression, out_of_bounds_iteration_returns_nan,
bounds_check_in_fast_path, and star_to_indexed_subdimension.

All tests pass with the compiler changes from prior commits.
…ymmetry

Document that VectorElmMap uses 0-based offset indexing while
VectorSortOrder returns 1-based rank indices. This asymmetry reflects
Vensim's original API design and was previously undocumented in the VM
(issue #351). Also verified that #344 tests for multi-target positional
mappings and mappings-takes-precedence-over-maps_to are passing.
Remove stale #[allow(dead_code)] from Opcode enum (all array opcodes are
now emitted by codegen), ByteCodeContext fields (arrays, names), and
dimensions.rs types/methods now reachable after close-array-gaps phases.
Update the ByteCodeContext impl-block comment to explain why the builder
methods remain suppressed (ByteCodeCompiler builds tables directly).

Update tech-debt.md items 12 and 13:
- dead_code: 58 -> 49 (removed 8 stale suppressions across bytecode.rs
  and dimensions.rs)
- ignored tests: 36 -> 23 (close-array-gaps enabled 8 array_tests + 5
  simulate.rs EXCEPT tests)
The comment claimed datamodel lacked parent mapping metadata for indexed
subdimensions, but the `parent` field now exists and the test passes.
Reflects contract changes from the close-array-gaps branch: new VECTOR
RANK builtin and Rank opcode, has_except_default flag on Equation::Arrayed
and SourceEquation::Arrayed, Dimension.parent for indexed subdimension
relationships, DimensionsContext.has_mapping_to() and Expr2Context
has_mapping_to() trait method, split wildcard-preservation contexts
(with_preserved_wildcards vs with_vector_builtin_wildcards), empty-view
NaN semantics for array reducers, and simlin: XMILE vendor extensions
for dimension mappings and EXCEPT metadata.
@codecov

codecov Bot commented Mar 12, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 86.09865% with 93 lines in your changes missing coverage. Please review.
✅ Project coverage is 76.80%. Comparing base (a90d405) to head (c2b489a).
⚠️ Report is 1 commits behind head on main.

Files with missing lines Patch % Lines
src/simlin-engine/src/compiler/context.rs 87.38% 14 Missing ⚠️
src/simlin-engine/src/project_io.gen.rs 0.00% 12 Missing ⚠️
src/simlin-engine/src/mdl/convert/variables.rs 80.00% 11 Missing ⚠️
src/simlin-engine/src/interpreter.rs 74.35% 10 Missing ⚠️
src/simlin-engine/src/compiler/codegen.rs 50.00% 8 Missing ⚠️
src/simlin-engine/src/serde.rs 92.70% 7 Missing ⚠️
src/simlin-engine/src/dimensions.rs 61.53% 5 Missing ⚠️
src/simlin-engine/src/vm.rs 89.58% 5 Missing ⚠️
src/simlin-engine/src/xmile/variables.rs 89.79% 5 Missing ⚠️
src/simlin-engine/src/mdl/convert/external_data.rs 94.44% 4 Missing ⚠️
... and 7 more
Additional details and impacted files
@@            Coverage Diff             @@
##             main     #390      +/-   ##
==========================================
+ Coverage   76.39%   76.80%   +0.41%     
==========================================
  Files         143      143              
  Lines       36233    36633     +400     
==========================================
+ Hits        27680    28137     +457     
+ Misses       8553     8496      -57     

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

@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: 0e1f90a582

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment on lines +1106 to +1107
if let Some((direction, _)) = rest {
self.walk_expr(direction)?.unwrap();

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Honor or reject RANK's third argument

RANK is represented as Option<(direction, tiebreak)>, but this path drops the tiebreak argument (_) and emits an opcode that only consumes direction, so RANK(arr, dir, tie_break) silently behaves like RANK(arr, dir). That produces incorrect ranks whenever input values tie and callers rely on the third argument to disambiguate, and it is hard to detect because compilation succeeds instead of reporting unsupported arguments.

Useful? React with 👍 / 👎.

Comment on lines +1798 to +1799
let target_dim = &active_dims[0];
let subscript = &active_subscripts[0];

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 Match dynamic range index to the correct active dimension

This dynamic-range A2A fallback always derives the element position from active_dims[0]/active_subscripts[0]. For multi-dimensional active contexts, a 1D ranged source can correspond to a different active axis, so using index 0 computes the wrong offset and returns shifted/NaN-filled values for otherwise valid models (e.g., 2D targets where the ranged source aligns with the second dimension).

Useful? React with 👍 / 👎.

@claude

claude Bot commented Mar 12, 2026

Copy link
Copy Markdown

Code Review

[P1] VM ArrayStddev uses population stddev (N divisor) while interpreter uses sample stddev (N-1 divisor)

File: src/simlin-engine/src/vm.rs:1822

The VM computes (variance_sum / fsize).sqrt() (population stddev, dividing by N), but the interpreter at src/simlin-engine/src/interpreter.rs:619 computes (variance / (size - 1) as f64).sqrt() (sample stddev, dividing by N-1). The interpreter also has a size <= 1 early return to 0.0 that the VM lacks. Per CLAUDE.md, the interpreter is the "reference spec for VM correctness verification", so the VM should match it. Additionally, the VM's own test comments at vm.rs:5774-5775 and vm.rs:5784 describe the code as using a (size-1) divisor, but the actual implementation uses fsize. The tests at array_tests.rs:4577-4604 encode different expected values for interpreter vs VM rather than flagging the disagreement. For arrays with 3+ elements (e.g., [20, 30, 40]), the VM produces sqrt(200/3) ≈ 8.165 while the interpreter produces sqrt(200/2) = 10.0. The fix is to change line 1822 to (variance_sum / (fsize - 1.0)).sqrt() and add the size == 1 → 0.0 guard, then unify the test expectations.


Overall correctness verdict: The patch has one blocking bug (STDDEV disagreement between VM and interpreter). All other changes appear correct — the flag split, empty-view guards, EXCEPT detection, cross-dimension mapping, RANK builtin, serialization, and protobuf backward compatibility all look sound. The patch should be considered not correct until the STDDEV inconsistency is resolved.

@claude

claude Bot commented Mar 12, 2026

Copy link
Copy Markdown

Code Review: engine: close array gaps

Findings

[P1] SourceDimension drops parent field — indexed subdimensions broken in salsa compilation path

File: src/simlin-engine/src/db.rs:266-271 (struct definition) and src/simlin-engine/src/db.rs:369-384 (From<&datamodel::Dimension>)

The PR adds parent: Option<String> to datamodel::Dimension to support indexed subdimension relationships (used by DimensionsContext::indexed_parents to resolve compute_subdimension_relation for Indexed/Indexed pairs). However, SourceDimension — the salsa tracked input type — does not include a parent field. The From<&datamodel::Dimension> impl at line 369 silently drops it, and source_dims_to_datamodel at line 515 hardcodes parent: None. Since project_datamodel_dims (line 721) and all incremental compilation paths go through this round-trip, indexed_parents will always be empty in production, causing compute_subdimension_relation to return None for all indexed subdimension pairs. The star_to_indexed_subdimension test passes only because assert_interpreter_result uses the monolithic Project::from path (which preserves parent), while assert_compiles_incremental only checks that compilation doesn't error — it never validates the incremental path's simulation results for this case.


Overall Correctness

Not correct. The SourceDimension missing parent field means indexed subdimension support is silently broken in the production incremental compilation path. The fix is straightforward: add parent: Option<String> to SourceDimension, thread it through From<&datamodel::Dimension> and source_dims_to_datamodel, and add an incremental-path result assertion to the test.

@claude

claude Bot commented Mar 12, 2026

Copy link
Copy Markdown

Code Review for PR #390: engine: close array gaps

This is a substantial PR covering array/subscript improvements across multiple subsystems. The changes are well-structured with good test coverage. I found one bug that affects production correctness.

Findings

[P1] SourceDimension drops the parent field, breaking indexed subdimension resolution in production

File: src/simlin-engine/src/db.rs, lines 266-271 (struct), line 515 (conversion back)

The PR adds parent: Option<String> to datamodel::Dimension for tracking indexed subdimension relationships, and DimensionsContext::from builds an indexed_parents map from this field (used at dimensions.rs:597 to resolve Indexed/Indexed subdimension pairs). However, SourceDimension (the salsa tracked input at db.rs:266) does not include a parent field. The From<&datamodel::Dimension> impl silently drops it, and source_dims_to_datamodel (line 515) hardcodes parent: None. Since production compilation goes through compile_project_incremental → source_dims_to_datamodel → DimensionsContext::from (line 866-867), the indexed_parents map will always be empty, and indexed subdimension resolution will silently fail. This means the feature works in tests that construct DimensionsContext directly from datamodel::Dimension but not through the actual compilation pipeline.

Fix: Add pub parent: Option<String> to SourceDimension, carry it through in both conversion directions.


Overall Correctness Verdict

Not correct — the SourceDimension missing parent field is a real bug that silently breaks the indexed subdimension feature in the production compilation path. The rest of the changes appear sound and well-tested.

Fix GET DIRECT CONSTANTS offset computation to filter pinned (singleton)
dimensions from element_offsets before passing to adjust_call_for_element.
Previously, a variable like x[Region, B1, Product] where B1 is pinned
would include the always-0 B1 offset, causing the last-two-offsets logic
to use the wrong dimensions for row/col mapping.

Fix MCP edit path to infer has_except_default from input shape: when both
a default equation and per-element overrides are present, that is EXCEPT
semantics and has_except_default must be true. Previously hardcoded to
None, which caused EXCEPT defaults to be lost on MCP upserts.

Add why-comments for promote_active_dim_ref usage explaining the shared
semantic: inside array-producing builtins, source arrays may live in a
different dimension space than the output.

Document that the RANK tiebreak parameter (optional 3rd arg) is parsed
but not yet implemented in codegen or VM.
@claude

claude Bot commented Mar 12, 2026

Copy link
Copy Markdown

Code Review: PR #390 — engine: close array gaps

This is a large, well-structured PR that closes many array/subscript gaps. The implementation plans are thorough and the test coverage is strong. I found two bugs worth flagging:


[P1] parent field dropped in SourceDimension, breaking indexed subdimensions in production path

File: src/simlin-engine/src/db.rs, lines 266-271 (struct) and 369-384 (From impl) and 515 (source_dims_to_datamodel)

SourceDimension does not carry the new parent: Option<String> field from datamodel::Dimension. The From<&datamodel::Dimension> impl at line 369 silently drops it, and source_dims_to_datamodel at line 515 always sets parent: None. Since the production compilation path (compile_project_incremental) goes through SourceDimension → source_dims_to_datamodel → DimensionsContext::from(), the indexed_parents map in DimensionsContext (built from dim.parent at line 244 of dimensions.rs) will always be empty. This means indexed subdimension relationships (the new feature in this PR) won't work through the incremental compilation path — only through the test-only Project::from path.


[P2] Column adjustment lost for 4-arg GET DIRECT CONSTANTS in adjust_call_for_element

File: src/simlin-engine/src/mdl/convert/external_data.rs, lines 254-259

When the original call uses the 4-arg form (e.g., row_or_cell="2", col="B"), adjust_call_for_element correctly computes an adjusted A1-style cell (e.g., "D3") in new_cell, but then copies the original col field unchanged: col: col.clone(). Downstream in load_constant (csv_provider.rs line 300-303), a non-empty col overrides the column parsed from row_or_cell. So for 2D arrayed variables using the 4-arg form, the column adjustment is silently discarded — all elements read from the same original column. The fix is to clear col to String::new() in the adjusted result (or update it to the new column letter). The existing tests only assert on row_or_cell and miss this.


Overall Correctness Verdict

Not correct. The parent field being dropped in SourceDimension (P1) means indexed subdimensions — a key feature of this PR — will not function in production. The 4-arg GET DIRECT CONSTANTS bug (P2) will produce wrong simulation results for models using that calling convention with 2D arrays.

SourceDimension was hardcoding parent: None in source_dims_to_datamodel,
dropping indexed subdimension relationships through the salsa DB
round-trip. Propagate the parent field through From and back.

Arrayed GET DIRECT CONSTANTS variables were losing their data_source
metadata because build_variable_with_elements used Compat::default().
Extract data_source from the first expanded equation's raw expression
and set it on the constructed variable's compat field.

Move conversion_tests to external db_conversion_tests.rs to keep db.rs
under the 6000-line lint threshold.
@claude

claude Bot commented Mar 12, 2026

Copy link
Copy Markdown

Code Review

Reviewed the full diff across all changed source files (excluding docs and implementation plans). This is a large PR touching the compiler, VM, interpreter, serde/protobuf, XMILE, MDL converter, and AST layers.

Areas Reviewed

  • VM (vm.rs) and interpreter (interpreter.rs): Rank opcode implementation, empty-view guards for array reducers (SUM/MEAN/MIN/MAX/STDDEV/SIZE), AllocateAvailable dispatch. VM and interpreter implementations are consistent in algorithm and semantics.
  • Compiler (context.rs, codegen.rs, symbolic.rs): preserve_wildcards_for_iteration / promote_active_dim_ref flag split, with_vector_builtin_wildcards() vs with_preserved_wildcards() contexts, range_view_dims tracking, has_single_ops promotion for cross-dimension builtins, renumber_opcode fix for VectorElmMap/VectorSortOrder/Rank/AllocateAvailable.
  • Bytecode (bytecode.rs): Opcode::Rank definition and stack effect (1, 0).
  • Serde/Proto (serde.rs, project_io.proto): New has_except_default (optional bool), parent (string with empty-string default), DataSource message, element-level DimensionMapping. Backward compatibility verified — old protos without new fields deserialize correctly via unwrap_or(false) / is_empty() checks.
  • XMILE (xmile/mod.rs, xmile/variables.rs, xmile/dimensions.rs): Vendor extensions for mappings, data sources, EXCEPT metadata, parent dimensions.
  • MDL converter (mdl/convert/variables.rs, external_data.rs, dimensions.rs): Arrayed GET DIRECT handling, element_offsets computation, cross-dimension mapping substitutions, EXCEPT detection via has_except_default flag.
  • Data model (datamodel.rs, variable.rs, dimensions.rs): New fields, old heuristic removal.
  • AST (ast/expr2.rs, ast/mod.rs): Bidirectional find_matching_dimension fallback via has_mapping_to.

Findings

No bugs found.

The changes are consistent and well-structured:

  • VM and interpreter Rank algorithms match (sort, assign 1-based ranks at original positions, direction semantics consistent)
  • Empty-view guards are symmetric: NaN for MAX/MIN/MEAN/STDDEV, 0.0 for SUM, 0 for SIZE
  • The flag split correctly separates reducer vs array-producing builtin contexts
  • Protobuf backward compatibility is maintained (all new fields use optional or have safe defaults)
  • The renumber_opcode fix for vector opcodes is a correctness improvement (previously these silently skipped renumbering)

Overall Correctness

Correct. The patch should not break existing code or tests, and introduces no bugs that I can identify. The protobuf changes are backward-compatible with existing serialized instances.

Add bounds check in positional dimension matching for vector builtins.
When promote_active_dim_ref suppresses the MismatchedDimensions error,
a source array with more dimensions than the output could panic with an
out-of-bounds index instead of returning a proper compiler error.

Change the proto Dimension.parent field from string to optional string
for consistency with maps_to, so absent parent is distinguishable from
empty string in serialized form.
@claude

claude Bot commented Mar 12, 2026

Copy link
Copy Markdown

Code Review

I've reviewed the full diff across all 48 changed files. This is a large, well-structured PR that closes 12 issues with comprehensive test coverage. The protobuf schema changes are backward-compatible (additive optional fields with correct defaults), the flag split logic is sound, and the serialization round-trip tests cover the critical paths.

Findings

No bugs found that meet the review criteria. The changes are internally consistent and well-tested:

  • Flag split (preserve_wildcards_for_iteration / promote_active_dim_ref): The two-context design (with_preserved_wildcards for reducers, with_vector_builtin_wildcards for array-producing builtins) correctly separates the ActiveDimRef promotion path. The conditional logic in the subscript resolution (has_wildcard_ops || (self.promote_active_dim_ref && has_active_dim_ref)) is sound.

  • Empty-view guards: Consistent NaN returns for MEAN/MIN/MAX/STDDEV and 0.0 for SUM across both VM and interpreter. The guards prevent division by zero (MEAN) and potential usize underflow (STDDEV with size - 1).

  • Proto backward compatibility: New optional fields (has_except_default, default_equation, data_source, mappings, parent) all default correctly to None/false/empty when absent. The compat_to_proto/compat_from_proto refactoring preserves semantic equivalence for all variable types (verified that the Aux non_negative: None -> Some(false) change is harmless since deserialization uses unwrap_or(false)).

  • EXCEPT detection: Replacing the fragile should_apply_default_to_missing heuristic with the explicit has_except_default boolean is a clear improvement. The heuristic had edge cases (e.g., all explicit elements matching the default equation).

  • VM renumbering fix: The missing renumber_opcode match arms for VectorElmMap/VectorSortOrder/AllocateAvailable were a real pre-existing bug that would cause incorrect temp storage offsets in multi-module scenarios. Good catch and fix.

  • RANK implementation: Both interpreter and VM implementations are consistent (1-based ranks, ascending/descending via direction parameter, NaN comparisons treated as Equal).

Overall Correctness Verdict

Correct. The patch is free of blocking bugs. Existing code and tests will not break. The protobuf and XMILE schema extensions are backward-compatible, the compiler flag split is logically sound, and all new functionality has corresponding tests.

Legacy JSON files without the hasExceptDefault field would default to
false, silently changing behavior for arrayed equations with a default
equation. Old files relied on the default equation being applied when
present; defaulting to false breaks that contract.

Infer has_except_default from the presence of the default equation
field when the explicit flag is absent: true if a default equation
exists, false otherwise.
@claude

claude Bot commented Mar 12, 2026

Copy link
Copy Markdown

Code Review

[P1] STDDEV uses different formulas in VM vs interpreter

File: src/simlin-engine/src/vm.rs:1822 and src/simlin-engine/src/interpreter.rs:618-619

The VM computes population standard deviation (divides variance by N: variance_sum / fsize) while the interpreter computes sample standard deviation (divides by N-1: variance / (size - 1) as f64). These produce different results for any array with more than one element. The interpreter comment even labels it "Sample standard deviation (n-1 divisor)" confirming the divergence is not a typo. Since CLAUDE.md describes the interpreter as "a reference spec for VM correctness verification," they should agree. Vensim's VSSTDEV uses population stddev (N divisor), so the VM appears correct and the interpreter's N-1 divisor should be changed to N. The existing tests (stddev_interpreter and stddev_vm in array_tests.rs:4577-4603) explicitly encode different expected values for the two paths, which should be unified as well.


Overall Correctness Verdict

Not fully correct. The STDDEV formula inconsistency between VM and interpreter is a real behavioral bug that will cause different simulation results depending on which execution path is used. All other changes (flag split, empty-view guards, RANK implementation, renumbering fix, serialization, dimension mappings) look correct and well-tested.

Only serialize has_except_default when a default equation exists; the
flag is meaningless without one and writing Some(false) for every
arrayed variable broke round-trip expectations. This also fixes the
interaction where omitting false + inferring true from equation
presence would incorrectly fill EXCEPT-only elements on reload.
@claude

claude Bot commented Mar 12, 2026

Copy link
Copy Markdown

Code Review

[P1] adjust_call_for_element discards column offset for 4-arg GET DIRECT CONSTANTS with 2D arrays

File: src/simlin-engine/src/mdl/convert/external_data.rs, lines 254-258

When adjust_call_for_element processes a 4-arg GET DIRECT CONSTANTS call (e.g., row_or_cell="2", col="B") with 2D offsets [1, 2], it correctly computes the adjusted cell as "D3" (row 2+1=3, col B+2=D) and stores it in row_or_cell. However, it preserves the original col: "B" unchanged. Downstream, load_constant (in both csv_provider.rs:300 and excel_provider.rs:199) parses row_or_cell="D3" to get (row=2, col=3), then sees col_label="B" is non-empty and overrides the column to 1, producing cell B3 instead of D3. The unit test test_adjust_call_4arg_2d only asserts on row_or_cell and misses this — at runtime the column adjustment is silently lost. The fix is to set col to String::new() in the returned GetDirectCall::Constants since the adjusted row_or_cell already encodes both row and column in A1-style. This only affects models using 4-arg GET DIRECT CONSTANTS with 2+ varying dimensions; 1D cases and 3-arg (A1-style) calls are unaffected.


Overall correctness: Correct (with caveat)

The patch is large and substantive — the flag split, empty-view guards, EXCEPT detection, RANK builtin, and serialization changes all look correct and well-tested. The VM and interpreter implementations are consistent with each other. The one bug above affects a narrow path (4-arg GET DIRECT CONSTANTS with 2D offsets) that is unlikely to be exercised by current test models, so existing tests won't break. It should be fixed but is not blocking.

@bpowers

bpowers commented Mar 12, 2026

Copy link
Copy Markdown
Owner Author

Review cycle summary

Five review iterations addressed feedback from both codex and claude reviewers. Key improvements made during the review cycle:

Correctness fixes:

  • Fixed SourceDimension.parent being hardcoded to None during salsa DB round-trip, which would have dropped indexed subdimension relationships
  • Added bounds check in positional dimension matching for vector builtins, preventing a potential panic when promote_active_dim_ref suppresses the dimension mismatch error but the source has more dimensions than the output
  • Fixed JSON backward compatibility: legacy JSON files without hasExceptDefault now correctly infer the flag from the presence of a default equation, and the serializer only writes the flag when a default equation exists to prevent round-trip regressions

Metadata preservation:

  • Arrayed GET DIRECT CONSTANTS/DATA/LOOKUPS variables now preserve compat.data_source metadata, extracted from the first expanded equation's raw expression
  • Changed proto Dimension.parent field from string to optional string for consistency with maps_to, so absent parent is distinguishable from empty string

Code organization:

  • Moved conversion_tests from inline in db.rs to external db_conversion_tests.rs to stay under the 6000-line lint threshold

Tech debt tracked:

  • MDL writer does not reconstruct GET DIRECT calls for arrayed variables (writes resolved values instead)
  • RANK tiebreak parameter parsed but not emitted in codegen
  • STDDEV interpreter/VM use different formulas (sample vs population)

…nge dimension matching

Three bugs flagged by PR reviewers:

1. Interpreter STDDEV used sample stddev (N-1 divisor) while the VM used
   population stddev (N divisor). Vensim's VSSTDEV uses population stddev,
   so the interpreter was wrong. Unified both to N divisor.

2. adjust_call_for_element preserved the original col field after computing
   an A1-style cell reference for 4-arg GET DIRECT CONSTANTS. Downstream,
   load_constant sees a non-empty col and overrides the column parsed from
   the A1 cell, silently discarding the column adjustment. Fixed by clearing
   col since the adjusted row_or_cell encodes both row and column.

3. Dynamic-range A2A fallback always used active_dims[0] to determine
   element position, which is wrong when the source dimension matches a
   later active dimension. For target[DimA, DimB] = data[start:end] where
   data is indexed by DimB, the code would use DimA's position instead of
   DimB's. Fixed by finding the matching active dimension.
@bpowers

bpowers commented Mar 12, 2026

Copy link
Copy Markdown
Owner Author

@codex review

@claude

claude Bot commented Mar 12, 2026

Copy link
Copy Markdown

Code Review: PR #390 — engine: close array gaps

This is a substantial PR (30 commits, ~8K lines of diff across Rust source) implementing 6 phases of array/subscript improvements. The changes span the compiler, interpreter, VM, serialization layers, and MDL converter. I reviewed the full diff with particular attention to correctness in the compiler context, execution engines, and serialization backward compatibility.

Findings

No blocking bugs found. The implementation is thorough, well-tested (2634 unit tests + 53 integration tests), and the architectural decisions are sound. The flag split, empty-view guards, and serialization extensions all follow clean patterns. Below are observations for the author's consideration:


[P3] renumber_opcode test does not cover Rank

src/simlin-engine/src/compiler/symbolic.rs, lines ~2541-2570

The test_renumber_vector_builtin_temp_ids test covers VectorElmMap, VectorSortOrder, and AllocateAvailable, but omits the newly added Rank opcode — even though renumber_opcode was updated to handle it (lines ~3527-3529). Since the Rank renumbering arm follows the identical pattern, this is low-risk, but adding it to the test would document intent and prevent future regressions if the pattern diverges.


[P3] Stale comment in VM empty-view stddev test

src/simlin-engine/src/vm.rs, empty_view_reduce_tests module

The test comment says "Without the guard, the ArrayStddev opcode would attempt size - 1 on a usize of 0", but the VM has always used population stddev (N divisor), not sample stddev (N-1). The comment appears to have been written with the interpreter's old formula in mind. The test logic itself is correct — only the explanatory comment is misleading.


Overall Correctness Verdict

Correct. The patch is well-structured, the behavioral changes (STDDEV population formula, empty-view NaN semantics) are intentional and tested, serialization backward compatibility is handled for proto/JSON/XMILE, and the renumber_opcode fix addresses a real correctness bug for multi-variable vector builtin models. The test coverage is comprehensive.

@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: c089233a15

ℹ️ 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/serde.rs Outdated
.collect(),
None,
arrayed.default_equation,
arrayed.has_except_default.unwrap_or(false),

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Preserve EXCEPT semantics when proto flag is absent

This deserialization path defaults has_except_default to false whenever the field is missing, which breaks backward compatibility for older protobuf payloads that predate this field but still contain default_equation for EXCEPT-style sparse arrays. After this commit, those models load with apply_default_to_missing = false, so omitted elements no longer receive the default equation and simulation results change silently; the JSON loader already handles this legacy case by inferring from default-equation presence.

Useful? React with 👍 / 👎.

Comment on lines +1807 to +1810
let match_idx = active_dims
.iter()
.position(|ad| ad.name() == dim.name())
.unwrap_or(0);

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Resolve dynamic range index using mapped dimension

When lowering dynamic range subscripts in A2A context, this code falls back to active dimension index 0 if no name match is found. In multi-dimensional targets where the source range dimension matches via mapping (different dimension name) and corresponds to a later active dimension, the computed element position is taken from the wrong axis, producing shifted/wrong values instead of a mapping-aware index lookup (or a compile-time mismatch error).

Useful? React with 👍 / 👎.

Comment on lines +1106 to +1110
// TODO: the optional 3rd tiebreak arg is lowered
// in context.rs but not yet emitted here; models
// using VECTOR RANK(a, dir, tiebreak) will ignore
// the tiebreak parameter.
if let Some((direction, _tiebreak)) = rest {

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Emit VECTOR RANK tiebreak argument

The compiler explicitly drops the optional third VECTOR RANK argument (tiebreak) during bytecode emission, so calls like VECTOR RANK(a, dir, tiebreak) are executed as if the tiebreak argument were never provided. That yields incorrect ranking behavior whenever equal values require non-default tie handling, and the issue is silent because the expression parses and compiles successfully.

Useful? React with 👍 / 👎.

…mension matching

Proto deserialization defaulted has_except_default to false when the field
was absent, breaking legacy protos that predate this field but have a
default_equation for EXCEPT semantics. Now infers from default_equation
presence, matching the JSON loader behavior.

Dynamic-range A2A dimension matching now also checks subdimension and
mapping relationships before falling back to index 0, so mapped or
parent/child dimensions are correctly resolved.
@bpowers
bpowers merged commit 9afdae5 into main Mar 12, 2026
10 checks passed
@bpowers
bpowers deleted the close-array-gaps branch March 12, 2026 20:25
@claude

claude Bot commented Mar 12, 2026

Copy link
Copy Markdown

Code Review

This is a large, well-structured PR that closes multiple array/subscript gaps across 6 phases. The implementation follows the detailed phase plans closely and includes thorough test coverage. I reviewed the key logic changes across the compiler, interpreter, VM, serialization, and MDL converter.

Findings

No blocking bugs found. The changes are internally consistent and well-tested.

Observations (non-blocking):

  1. STDDEV divisor change (interpreter.rs:618): The interpreter's array_stddev changed from sample standard deviation (N-1 divisor) to population standard deviation (N divisor) to match the VM and Vensim VSSTDEV semantics. This is a behavioral change for the interpreter path, but it's the correct fix since the VM was already using N and this makes them consistent. The comment and tests document the intent clearly.

  2. compute_rank in eval_at_index (interpreter.rs:342-348): Each per-element call recomputes the entire rank array (O(N) per call, O(N^2) total for the full array). This matches the existing pattern for VectorSortOrder at line 350, and the A2A path at line 1513 correctly computes the whole array at once, so this is consistent with the existing codebase approach.

  3. renumber_opcode fix (symbolic.rs:1346-1357): The previously-missing VectorElmMap/VectorSortOrder/AllocateAvailable match arms in renumber_opcode were falling through to the other => other.clone() catch-all, which means their write_temp_id fields were not being renumbered during fragment concatenation. This was a latent bug that could have caused incorrect temp storage access in multi-fragment bytecode. The fix with the new test (test_renumber_vector_builtin_temp_ids) is solid.

Overall Correctness Verdict

Correct. The patch is well-tested (2634 unit tests + 53 integration tests per the PR description), introduces no regressions, and the new functionality (flag split, empty-view guards, EXCEPT detection, cross-dimension mapping, RANK builtin, serialization round-tripping) is implemented consistently across both the interpreter and VM paths. The previously-ignored integration tests being enabled (simulates_except, simulates_except2, simulates_directconst, simulates_directlookups, simulates_directsubs, simulates_vector_simple_mdl upgraded to full VM+interpreter) provides strong evidence of correctness.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment