Skip to content

engine: move compat fields into Compat struct - #319

Merged
bobby-stripe merged 8 commits into
mainfrom
move-compat-fields-to-compat-struct
Feb 24, 2026
Merged

bobby-stripe merged 8 commits into
mainfrom
move-compat-fields-to-compat-struct

Conversation

@bpowers

@bpowers bpowers commented Feb 24, 2026

Copy link
Copy Markdown
Owner

Summary

  • Move non_negative, can_be_module_input, and visibility fields into a Compat struct in the Rust engine
  • Mirror the change in TypeScript by moving nonNegative, canBeModuleInput, and isPublic into a Compat type in types.ts
  • Consolidates Vensim/XMILE compatibility metadata into a single struct, simplifying variable definitions

Test plan

  • Existing simulation integration tests pass
  • Property-based JSON roundtrip tests pass
  • TypeScript type checking passes
  • All pre-commit checks pass

@claude

claude Bot commented Feb 24, 2026

Copy link
Copy Markdown

Code Review: engine: move compat fields into Compat struct

Reviewed the full diff across all 38 changed files. This is a clean structural refactoring that moves non_negative, can_be_module_input, and visibility into the existing Compat struct, with consistent changes across Rust, TypeScript, JSON serialization, protobuf serialization, XMILE/Vensim conversion, and the Salsa database layer.

Findings

No bugs found.

Key observations

Protobuf backward compatibility is correctly handled: old protos (without the new compat fields) are read by falling back to the top-level fields (stock.non_negative, etc.). New protos write actual values into compat and set the old top-level fields to false/0. The new proto fields in Compat are all optional, and the Module message gains an optional Compat compat = 9 field -- all additive changes consistent with standard protobuf versioning.

JSON serialization correctly moves the fields into the compat object. The is_empty() / emptiness checks ensure compat: null is emitted (and None in Rust) when all compat fields are at their defaults, avoiding empty {} objects in the serialized output.

JSON schema is consistent: the Compat definition at #/$defs/Compat gains the three new fields, and all variable types (Stock, Flow, Auxiliary, Module) reference it via their compat property. The old top-level fields are removed from all variable types.

TypeScript changes are aligned: JsonCompat gains the three fields, JsonStock/JsonFlow/JsonAux lose them from the top level, JsonModule gains a compat field. The core datamodel.ts correctly reads/writes nonNegative via json.compat?.nonNegative.

XMILE conversion uses the updated extract_compat! macro (now parameterized on $access) and correctly populates the new compat fields from XMILE access attributes.

Salsa DB layer (db.rs) properly reads non_negative/can_be_module_input from compat when syncing from the datamodel, and writes them back into compat during reconstruction. Notably, visibility is now preserved through the Salsa round-trip (previously it was hardcoded to Private in reconstruct_variable).

Overall correctness verdict

Correct. The patch is free of bugs. The field migration is consistent across all serialization formats and code layers, with proper backward compatibility for protobufs.

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

ℹ️ 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
Comment on lines +453 to +455
non_negative: false,
can_be_module_input: false,
visibility: 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 Preserve legacy proto flags when writing variables

This serializer now zeroes the legacy protobuf fields (non_negative, can_be_module_input, visibility) and only writes the real values into compat. Because project_io.proto still carries those legacy fields for compatibility, any reader on the previous schema/version (or a rollback) will ignore compat and deserialize changed variables as defaults (negative-allowed, not module-input, private), which changes model semantics after a save. Keep emitting the legacy fields in parallel with compat until old readers are no longer possible.

Useful? React with 👍 / 👎.

@claude

claude Bot commented Feb 24, 2026

Copy link
Copy Markdown

PR Review: engine: move compat fields into Compat struct

Summary

This PR consolidates non_negative, can_be_module_input, and visibility/isPublic fields from the individual variable structs (Stock, Flow, Aux, Module) into the existing Compat struct across the Rust engine, TypeScript engine/core, and Python bindings.

Findings

No bugs found.

Analysis

Backward compatibility (JSON): Handled correctly. The Rust json.rs types retain legacy fields with #[serde(skip_serializing, default)], allowing deserialization of old-format JSON while only writing the new compat-nested format. The From implementations properly fall back to legacy top-level fields when compat is absent. This is also verified by the new test_legacy_json_* and test_compat_fields_take_precedence_over_legacy tests.

Backward compatibility (protobuf): Handled correctly. The protobuf schema adds new optional fields to the Compat message and a compat field to Module. Serialization writes to both the new compat fields and the legacy top-level fields. Deserialization prefers compat when present, falls back to legacy. New tests (test_stock_proto_legacy_fields_populated, test_stock_proto_legacy_only_deserialization) cover both directions.

TypeScript consistency: The engine types (types.ts) and JSON types (json-types.ts) are updated consistently. The core datamodel.ts correctly migrates nonNegative for Stock and Flow (the only variable types where the core layer uses this field). The canBeModuleInput and isPublic fields were never used by the core layer's auxFromJson/moduleFromJson functions, so no changes were needed there.

Python bindings: The json_converter.py includes proper legacy fallback for all variable types, and the model.py high-level API also falls back correctly (compat.get("nonNegative", d.get("nonNegative", False))).

Schema: The simlin-project.schema.json properly moves the fields into the Compat definition and references it from all variable types.

Overall Correctness Verdict

Correct. The patch is thorough and consistent across all layers (Rust, TypeScript, Python). Backward compatibility is maintained for both JSON and protobuf serialization formats. Tests cover legacy deserialization, precedence rules, and roundtrip behavior.

These fields are Vensim compatibility options that belong together in the
Compat sub-struct rather than cluttering the top-level variable types.
The Compat struct now holds active_initial, non_negative,
can_be_module_input, and visibility (previously it only had
active_initial).

This consolidation applies across the full stack: Rust datamodel, JSON
serialization, protobuf schema, TypeScript types, and TypeScript
converters.  Module gains a compat field matching the pattern already
used by Stock, Flow, and Aux.
…ypes.ts

The prior commit moved these fields on the Rust and JSON serialization
side but missed the public TypeScript API types in types.ts. This
completes the migration so the types match the actual serialization
format.
Add legacy field reading for JSON (skip_serializing + default) so old
.simlin files with top-level non_negative/can_be_module_input/is_public
still deserialize correctly. Proto serializer now populates legacy fields
with actual values so old code reading from Firestore sees correct data.

Extract Compat::is_empty() to DRY up duplicated emptiness checks.
Update pysimlin json_types/json_converter/model to match the new nested
compat structure with fallback to legacy top-level fields.
Legacy JSON files can have compat only for activeInitial while boolean
flags (nonNegative, canBeModuleInput, isPublic) remain top-level. The
previous fallback logic only checked legacy fields when compat was
absent; when compat existed (even just for activeInitial), the defaulted
false booleans in compat silently overrode top-level true values.

Fix by OR-merging: the result is true if either compat or the legacy
field says true. This is safe because old files never write compat
booleans and new files never write top-level booleans, so the
contradictory case cannot arise in practice.
@bpowers
bpowers force-pushed the move-compat-fields-to-compat-struct branch from fba88b7 to 3e59757 Compare February 24, 2026 18:00
@claude

claude Bot commented Feb 24, 2026

Copy link
Copy Markdown

Code Review: engine: move compat fields into Compat struct

I reviewed all 42 changed files in this PR, focusing on:

  • Backward compatibility for JSON deserialization (Rust, TypeScript, Python)
  • Backward compatibility for protobuf deserialization
  • Consistency of the Compat struct across Rust, TypeScript, and Python
  • Schema correctness
  • Correctness of the legacy field OR-merge logic

Summary

This is a well-implemented migration that consolidates non_negative, can_be_module_input, and visibility/isPublic into a Compat struct across the Rust engine, TypeScript engine/core, and Python bindings.

Backward Compatibility Analysis

Rust JSON (json.rs): Legacy fields are marked #[serde(skip_serializing, default)] so they are read from old JSON but never written. The From<Stock> for datamodel::Stock conversion correctly OR-merges legacy and compat fields (e.g., c.map(|c| c.non_negative).unwrap_or(false) || stock.non_negative). This handles all combinations: old-format-only, new-format-only, and mixed.

Protobuf (serde.rs): Both legacy top-level fields and the new compat message are populated when serializing. Deserialization prefers compat fields but falls back to legacy (e.g., c.non_negative.unwrap_or(stock.non_negative)). The None branch correctly handles old protos without the compat field. Tests cover roundtrip, legacy-only deserialization, and legacy field population.

Python (json_converter.py): All four variable type structurers (stock, flow, aux, module) correctly OR-merge legacy top-level booleans with compat fields, matching the Rust logic. New tests in TestLegacyCompatMerge verify this.

TypeScript (core/datamodel.ts, engine/src/model.ts): Stock and Flow correctly read json.compat?.nonNegative and write to result.compat.nonNegative. The engine's model.ts passes through the full v.compat for Stock, Flow, and Module. The Aux case only extracts activeInitial from compat, but this is pre-existing behavior unchanged by this PR.

Findings

No bugs found. The migration is thorough and handles all backward compatibility paths correctly across JSON, protobuf, and XMILE serialization formats.

Overall Correctness Verdict

Correct. The patch properly migrates compat fields into a dedicated struct with full backward compatibility for all serialization formats. Existing tests and code will not break.

@claude

claude Bot commented Feb 24, 2026

Copy link
Copy Markdown

Code Review

Summary

This PR consolidates non_negative, can_be_module_input, and visibility/is_public fields from the individual variable type structs (Stock, Flow, Aux, Module) into the shared Compat struct across all layers: Rust datamodel, Rust JSON, Rust protobuf serde, TypeScript types, Python types, and JSON schema.

Analysis

The refactoring is well-executed. Key observations:

  1. Backward compatibility (JSON): Legacy top-level boolean fields are retained as #[serde(skip_serializing, default)] read-only fields in the JSON structs. Deserialization OR-merges legacy fields with the new compat sub-object, ensuring old files round-trip correctly. New files only write fields inside compat.

  2. Backward compatibility (protobuf): Legacy proto fields on Stock/Flow/Aux/Module are still populated during serialization (from compat.*), and the compat message also carries the new fields. Deserialization preferentially reads from the compat message when present, falling back to legacy fields. This handles both old and new proto formats.

  3. Schema consistency: The Compat definition in the JSON schema correctly gains nonNegative, canBeModuleInput, and isPublic. These fields are removed from Stock/Flow/Aux at the top level, and Module gains a new compat field. All consistent with the code changes.

  4. Type-specific handling: Aux correctly omits non_negative (always false), Module correctly omits non_negative and active_initial. The extract_compat! macro properly accepts an $access parameter for can_be_module_input/visibility.

  5. db.rs improvement: The old reconstruct_variable hardcoded visibility: Visibility::Private for all variable types, which was lossy. The new code preserves visibility through the compat struct stored in salsa -- this is a correctness improvement.

  6. Test coverage: Thorough backward-compatibility tests verify OR-merge semantics for legacy JSON, legacy protobuf, and mixed formats.

Findings

No bugs found. The migration is mechanically correct across all layers, backward compatibility is properly maintained, and the test coverage is comprehensive.

Verdict: Correct

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

@codecov

codecov Bot commented Feb 24, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 85.89212% with 34 lines in your changes missing coverage. Please review.
✅ Project coverage is 79.24%. Comparing base (da4171c) to head (6fd838b).
⚠️ Report is 1 commits behind head on main.

Files with missing lines Patch % Lines
src/simlin-cli/src/gen_stdlib.rs 0.00% 18 Missing ⚠️
src/simlin-engine/src/serde.rs 87.09% 12 Missing ⚠️
src/simlin-engine/src/datamodel.rs 63.63% 4 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main     #319      +/-   ##
==========================================
+ Coverage   79.16%   79.24%   +0.07%     
==========================================
  Files         121      121              
  Lines       30832    30954     +122     
==========================================
+ Hits        24409    24528     +119     
- Misses       6423     6426       +3     

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

The aux case manually reconstructed compat from only activeInitial,
dropping canBeModuleInput, isPublic, and nonNegative. This could cause
callers to lose access metadata and unintentionally clear those flags
when writing updates. Fix by passing through v.compat directly, matching
the behavior of the Stock, Flow, and Module cases.
@claude

claude Bot commented Feb 24, 2026

Copy link
Copy Markdown

Code Review

Reviewed the full diff (~6600 lines across 42 files) covering Rust engine, TypeScript, Python, protobuf schema, JSON schema, XMILE/MDL conversion, and test updates.

Summary

This PR consolidates non_negative, can_be_module_input, and visibility/is_public fields from individual variable types (Stock, Flow, Aux, Module) into a shared Compat struct. The migration is thorough and well-structured.

Key Design Decisions (all look correct)

  • Protobuf backward compatibility: Legacy fields are preserved alongside the new compat message. Serialization populates both; deserialization prefers compat and falls back to legacy. This handles existing DB records correctly.
  • JSON backward compatibility: Legacy top-level fields use #[serde(skip_serializing, default)] — readable from old JSON but never written. The From impls OR-merge legacy and compat fields so old files are properly migrated.
  • Python pysimlin: Structure hooks in json_converter.py handle the same OR-merge pattern for legacy field migration.
  • TypeScript simplification: The model.ts removal of the manual activeInitial fallback from arrayedEquation.compat for Aux is correct — the Rust engine already handles this in its From<Auxiliary> impl before the data reaches TypeScript.
  • Type-appropriate field handling: non_negative is correctly hardcoded to false for Aux and Module across all serialization paths (Rust json, serde, XMILE, Python).

Verification Points

  • Protobuf roundtrip: Covered by test_stock_roundtrip, test_stock_proto_legacy_fields_populated, test_stock_proto_legacy_only_deserialization and equivalents for Flow/Aux/Module.
  • JSON roundtrip: Covered by proptest strategies and explicit roundtrip tests for all variable types, including legacy JSON deserialization tests.
  • Legacy merge: Explicit tests for the scenario where old JSON has compat only for activeInitial alongside top-level boolean flags.
  • Schema: #/$defs/Compat correctly includes the new nonNegative, canBeModuleInput, isPublic fields.

Findings

No bugs found. The migration is correct across all serialization formats (JSON, protobuf, XMILE) and all three language implementations (Rust, TypeScript, Python). Backward compatibility is properly maintained for both protobuf (DB records) and JSON (project files).

Overall correctness: correct — existing code and tests will not break, and the patch is free of blocking issues.

…Json

The TypeScript core stockFromJson and flowFromJson read nonNegative only
from json.compat, but legacy JSON still has it at top level. This caused
silent data loss when loading older project files. Add legacy nonNegative
field back to JsonStock/JsonFlow types and OR-merge like the Rust side.
@claude

claude Bot commented Feb 24, 2026

Copy link
Copy Markdown

Code Review

I reviewed the full diff for PR #319 which consolidates non_negative, can_be_module_input, and visibility/is_public fields into a Compat struct across Rust, TypeScript, Python, and protobuf layers.

Findings

[P3] JSON schema inconsistency: Stock retains legacy fields but Flow/Aux do not

doc/simlin-project.schema.json, Stock definition (around line 246)

The Stock schema definition retains legacy top-level nonNegative, canBeModuleInput, and isPublic properties alongside the new compat object. However, the Flow and Auxiliary schema definitions had their equivalent legacy fields removed without adding them back. In the Rust code (src/simlin-engine/src/json.rs), all three types (Stock, Flow, Auxiliary) have legacy fields annotated with #[serde(skip_serializing, default)], meaning they can all accept legacy JSON input. The schema should be consistent - either all types document the legacy fields or none do. If the schema is regenerated from the JsonSchema derive, schemars would include skip_serializing fields since they're still deserializable; if it's manually maintained, this looks like an oversight where Stock was updated but Flow/Aux were not.

Overall Correctness Verdict

Correct. The patch correctly handles backward compatibility across all serialization boundaries (JSON, protobuf, XMILE). Legacy fields are properly OR-merged with the new compat struct fields during deserialization, and the new format is written cleanly with skip_serializing preventing legacy field emission. The protobuf changes are forward/backward compatible (new optional fields, legacy fields still populated). The TypeScript and Python layers handle the migration consistently. The only issue is the minor schema documentation inconsistency noted above.

Document why OR-merging compat booleans with legacy top-level fields is
safe: old code never writes compat booleans and new code uses
skip_serializing on legacy fields, so both cannot be meaningfully set
at once. The contradictory case (compat false + legacy true) cannot
arise through normal serialization paths.
@claude

claude Bot commented Feb 24, 2026

Copy link
Copy Markdown

Code Review

This PR consolidates non_negative, can_be_module_input, and visibility/is_public into the Compat struct across Rust, TypeScript, and Python layers. The migration handles backward compatibility through:

  • JSON: Legacy top-level fields kept with #[serde(skip_serializing, default)] for read-only backward compat; new writes go into compat
  • Protobuf: New optional fields added to the Compat message (backward-compatible wire format); legacy top-level fields still written for old-reader compat
  • OR-merge logic: Consistently applied across all layers (Rust From impls, Python structure_* hooks, TypeScript *FromJson functions) to handle transitional data where compat may exist for activeInitial alongside legacy top-level boolean flags

Findings

No bugs found. The migration is well-structured:

  • All deserialization paths correctly merge legacy top-level fields with new compat fields using OR semantics, which is safe given the invariant that old code never writes compat booleans and new code never writes top-level booleans.
  • The Compat::is_empty() implementations are consistent between datamodel::Compat (using visibility == Visibility::Private) and json::Compat (using !is_public).
  • The protobuf optional field additions are backward-compatible, and the deserialization falls back correctly to legacy top-level fields when compat sub-fields are None.
  • Comprehensive test coverage including legacy format parsing, OR-merge behavior, round-trip tests, and property-based tests.
  • The JSON schema $defs/Compat is correctly updated with the new fields, and all variable type schemas reference it through their compat property.

Verdict: Correct

The patch is free of bugs and handles backward compatibility thoroughly across all serialization formats (JSON, protobuf) and all language layers (Rust, TypeScript, Python).

The generic rule that dropped optional fields unstructuring to {} was
too broad -- it could also drop GraphicalFunction() or other optional
objects that legitimately serialize as empty dicts. Restrict the check
to only the 'compat' field where empty means semantically None.
@claude

claude Bot commented Feb 24, 2026

Copy link
Copy Markdown

Code Review: engine: move compat fields into Compat struct

I reviewed the full diff across all 42 changed files, focusing on data integrity during serialization/deserialization roundtrips, backward compatibility with legacy field formats, and consistency across the Rust, TypeScript, and Python codebases.

Summary

This PR consolidates non_negative, can_be_module_input, and visibility into a Compat struct across the Rust engine, TypeScript types, and Python bindings. The approach is sound: fields are moved to a dedicated struct, legacy top-level fields are preserved as read-only (deserialized but never serialized), and an OR-merge strategy handles the transition between old and new formats.

Findings

No blocking bugs found.

The key correctness properties I verified:

  1. Rust JSON roundtrip (json.rs): Variable-level compat correctly holds all fields. Legacy fields are annotated #[serde(skip_serializing, default)] so they're read from old JSON but never written. The OR-merge pattern (c.map(|c| c.non_negative).unwrap_or(false) || stock.non_negative) is safe since old code never writes compat booleans and new code never writes top-level booleans.

  2. Protobuf serialization (serde.rs): Correctly writes to both legacy wire fields and the new compat message (backward compat for old deserializers). Deserialization prefers compat fields with fallback to legacy.

  3. TypeScript (core/datamodel.ts, engine/src/types.ts, json-types.ts): OR-merge in stockFromJson/flowFromJson (json.compat?.nonNegative || json.nonNegative || false) is correct. New engine types cleanly use compat?: Compat. Legacy nonNegative field properly deprecated in JsonStock/JsonFlow.

  4. Python (json_converter.py): Structure hooks for Stock/Flow/Aux/Module all correctly OR-merge legacy top-level fields with compat. Auxiliary intentionally omits nonNegative handling, matching the Rust engine which hardcodes non_negative: false for Aux.

  5. JSON schema (simlin-project.schema.json): All variable types have compat referencing #/$defs/Compat. Legacy top-level fields removed. Schema is internally consistent.

  6. Property-based tests (json_proptest.rs): Both JSON serialize/deserialize roundtrips and JSON↔datamodel roundtrips are tested with 256 generated cases per type. Strategies generate compat fields with all boolean combinations.

Observations (non-blocking)

  • From<Stock> for datamodel::Stock (json.rs:665-734) does not fall back to arrayed_equation.compat.active_initial, while Flow and Aux do. This is pre-existing and correct since stocks use initial_equation for initial values rather than active_initial, but the inconsistency might be worth a brief comment for future readers.

Verdict

Overall correctness: Correct. The patch maintains full backward compatibility, roundtrip integrity is preserved across all serialization formats, and the consolidation is applied consistently across all three language implementations. The property-based tests provide good coverage for the new structure.

@bpowers

bpowers commented Feb 24, 2026

Copy link
Copy Markdown
Owner Author

Review cycle summary

This PR went through 7 automated review iterations (codex + claude) that drove several backward-compatibility improvements beyond the original structural migration.

The key improvements made during review were: adding OR-merge semantics so that legacy top-level boolean fields (nonNegative, canBeModuleInput, isPublic) are correctly combined with the new compat-nested fields during deserialization -- preventing data loss in transitional documents where compat exists only for activeInitial alongside top-level flags. This was implemented consistently across all three language stacks (Rust, TypeScript, Python) with corresponding test coverage. Additionally, the Python cattrs converter's empty-dict elision was scoped to only the compat field to avoid accidentally dropping other legitimately empty optional objects like GraphicalFunction. The TypeScript model.ts aux path was fixed to pass through the full compat object rather than reconstructing a partial one, and core/datamodel.ts was updated to OR-merge legacy nonNegative in stockFromJson/flowFromJson.

A pre-existing issue with Module visibility being lost during Salsa DB synchronization was identified and tracked separately as #320.

@bobby-stripe
bobby-stripe merged commit fcb1cbf into main Feb 24, 2026
10 checks passed
@bobby-stripe
bobby-stripe deleted the move-compat-fields-to-compat-struct branch February 24, 2026 19:16
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants