-
Notifications
You must be signed in to change notification settings - Fork 19
Systems format writer groups flows by source stock, breaking round-trip for cross-stock references #400
Description
Problem
The systems format writer (src/simlin-engine/src/systems/writer.rs) groups all flows by their source stock and emits them contiguously. This means it cannot interleave flows from different source stocks. When a model contains cross-stock rate references -- where a flow's rate equation references another stock -- the writer can produce output where the declaration order does not match what the parser expects for correct round-trip fidelity.
Example
Given the model:
A(10) > B @ 1, C(2) > D @ A, A > E @ 8
The writer produces output where C > D @ A appears before all of A's flows are listed, but correct round-trip requires C > D to be positioned between A > B and A > E (because the parser's incremental drain variable mechanism depends on declaration order to correctly resolve the value of A at the point where C > D references it).
Impact
- Correctness: Write -> re-parse -> re-translate -> simulate produces incorrect results for affected models. The simulation translator itself correctly handles cross-stock references via incremental drain variables, so this is purely a writer output formatting issue.
- Developer experience: Round-trip tests cannot cover models with this pattern until the writer is fixed.
Component(s) affected
src/simlin-engine/src/systems/writer.rs
Possible approaches
- Topological ordering: Instead of grouping flows by source stock, determine a valid declaration order that respects cross-stock reference dependencies. Flows referencing another stock's value need to be interleaved at the correct position relative to that stock's outflows.
- Dependency-aware grouping: Build a dependency graph of flows and stocks, then emit flows in an order that ensures referenced stocks have the correct number of prior outflows processed before the referencing flow appears.
Context
Identified during development on the systems-format branch while implementing systems format support.