Repository navigation
engine: edit arrayed variables field by field, with errors that say where - #1087
Conversation
A chain over two overlapping subranges of one dimension -- an aging chain, the layers of an ocean -- maps the younger subrange onto the older one and reads `stock[Younger]` under an `Older` iteration, so each cohort reads the one before it. Vensim's own subscript mapping example is written this way, and test/test-models/tests/subscript_mapping_vensim holds it with Vensim DSS's output. The engine read each element by its own name wherever the source axis declared it, and used the mapping only for the element left over: `POPULATION[CHILD]` read `aging[CHILD]` against itself and stayed at 900 where Vensim has 920, with no diagnostic. The MDL importer writes a variable defined by more than one equation (`POPULATION[INFANT]` and `POPULATION[ALL BUT YOUNGEST]`) out once per element, with the mapped element substituted, so Vensim's example and every corpus model read right. A variable defined by one equation over a subrange keeps it as written -- `d[older] = c[younger]` imports as that one equation -- and read the wrong elements, as did any model that keeps one equation for every element, as an editor or an agent writes it. The rule is the one Vensim's subscript mapping reference states: "a mapping is an indication to Vensim that a Subscript that appears on the right but not the left of an equation has a valid interpretation" (https://www.vensim.com/documentation/ref_subscript_mapping.html). So: - A subscript naming a dimension the equation does not iterate is on the right alone, and reads through its mapping before any name the two dimensions share (`DimensionsContext::read_through_mapping`). `x[Younger]` under an `Older` iteration, `x` over all of `Age`, reads the `Younger` element the mapping gives, on `x`'s axis (`resolve_dimension_subscript`), and a star range over the subrange, `x[*:Younger]`, does the same (`resolve_iteration_element`). - A subscript naming the iterated dimension is on both sides, and reads each element by its own name, whatever mapping the dimension declares: with `P : c, a, b -> D` and `x` over `D`, `t[P] = x[P]` reads `x[c]` for `t[c]`, while `u[D] = x[P]` reads through the mapping. A bare reference and a stock's flow read as that subscript would (`resolve_mapped_read`). The name decides for the whole dimension or not at all: where the source lacks some iterated element (`target[Older] = y`, `y` over `Younger`), the reference reads through the mapping for every element, so two older cohorts never read one younger cohort twice. Vensim gives that spelling no reading; this is the engine's. - A stock's flow reference resolves each axis against the active axis the allocation paired it with, not the first active axis that declares the element. Over two overlapping subranges the element is in both, and with the mapping read first that search read a transposed flow through the wrong axis. A star range over a subrange, read by an element outside it that no mapping pairs, still reads NaN past the range (`t[Age] = x[*:Older]` at `Young`), never the neighbouring element. The LTM describers read through the same rule: `executed_read_correspondence` for a subscript naming the iterated dimension or none, and a new `mapped_read_correspondence` for one naming the source's own dimension. A subscript naming a mapped subrange of the source's dimension reads through the subrange's mapping, which neither correspondence over `(iterated, source)` states, so `DimensionsContext::mapped_read_partner` declines it and the element graph keeps its cross-product, a superset of the reads. Loop analysis therefore does not score a loop through a chain written Vensim's way (`arrive[Older] = aging[Younger]`, `aging` over `Age`): it warns that the link's score could not be computed and the loops through it will not be scored. The same chain spelled as a stock over `Older` fed by a flow over `Younger` is scored, with exact element edges. Three spellings that read by name before are refused now, each because the mapping it is paired through gives an element the source does not declare: `t[Older] = y[Younger]` with `y` over `Older`, `t[State] = x[Region]` with `x` over `State`, and a positional mapping between subranges of different sizes. Evidence. `mapped_reference_semantics_tests` gains a section for mapped subranges: Vensim's aging chain against Vensim's output (before: 900, 900, 900, 900 for `POPULATION[CHILD]`), every spelling of the chain in both declaration directions (all 14 read each element's own name before), their hoisted and captured twins, the element graph, a transposed flow over both subranges, a subrange on both sides of an MDL equation and on the right alone, and a star range read outside its subrange. The matrix's `SharedElementNames` row, two dimensions with the same element names in different orders, now reads by name for the iterated, bare and flow spellings and through the mapping for the source's own. A star range over a subrange read by a target axis mapped onto it, refused before, reads the mapped rows (the control row of `a_star_range_over_a_subdimension_is_refused_by_a_parent_target`). Every corpus model that declares a mapping (29 files, 50 mapped dimensions, C-LEARN among them), as opened and after a save to XMILE and to JSON, computes bit-identical series before and after; the MDL importer expands variables defined by more than one equation, and no corpus file holds a single-equation read of an overlapping mapped subrange. Five of the 29 do not compile, before and after alike. A single-equation chain read from MDL is a test of its own (`a_single_equation_chain_from_mdl_reads_the_cohort_before`).
A chain reads the element before it with an offset in one equation for every element: `c[Age - 1]`. The first element has nothing before it, so its read is not a number at every step of the run. The model compiled and ran, the NaN flowed on into whatever read it, and no diagnostic said where it came from. A host or an agent that writes such an equation needs to know which element to give an equation of its own. The new warning `SubscriptOutOfRange` says so, one row per element that makes such a read, on the variable, naming the element and spanning the reference in the equation: "the equation for 'young' reads 'c' before the first element of 'age', which is not a number". A scalar equation whose computed index runs off the end (`c[2 + 2]` over three elements) gets the same row with no element. It is a warning, not an error: the model runs as it did, and the row describes that run. `compiler::out_of_range_reads` finds the reads on each element's folded tree, by the VM's own index test (floored, narrowed to `u16`, zero or past the axis is no element). Lowering gives a dimension name its element's position and folding reduces the offset to a constant, so the check sees exactly what the run evaluates; a conditional on the element's own position (`IF Age > 1 THEN c[Age - 1] ELSE 0`) has already dropped its untaken branch, and is not told. Folding leaves `0 AND switch = 1` standing, since `switch` is computed, so the check reads a condition's constant parts too: `IF Age > 1 AND switch = 1 THEN c[Age - 1] ELSE 0` is not told at the first element, which never makes the read, and neither is the `OR` or `NOT` form. A read under a condition that varies as the model runs is told, since it reads no element whenever the condition holds. Both fragment paths report: an explicit variable at the element its slot is, and a builtin's hoisted argument on the variable it was made for, at the element it is one element of -- a per-element helper's element, or for an argument computed over the variable's own dimensions (`PREVIOUS(c[Age - 1], 0)`, `INIT(c[Age - 1])`), the element of the slot it writes. The message says the read is not a number, not the element: a read under `MAX(c[Age - 1], 0)` is told though the element's value is 0. Evidence: `subscript_out_of_range_tests` (an offset before the first and past the last element, two dimensions, one element's own equation, a scalar, a stock's initial value, a hoisted argument, a read under `PREVIOUS` and `INIT`, and the guarded controls, alone and joined to a test of the model); the seven that expect a row fail without the reporting. No model in the corpus (489 files under `test/` and `default_projects/`) gains a row. Not covered: a literal subscript below the first element (`c[0]`) reads the first element on the static subscript path, silently, and an index held in another variable is known only as the model runs; both are left as they are here.
A host that shows a model's run has to decide, after every edit that lands, whether the run still describes the model. With only the project's revision to go on -- which every change advances, a dragged element or a note included -- it simulates again after each one, and a host that also keeps an agent's tool session asks the session for its run only to learn which contents that run was made at. `simlin_project_get_simulation_key(project, out_key, out_error)` answers without a compile or a run. It is the engine's `db::simulation_key`, the number the agent tools already keep their runs fresh by: a hash of the sync's own extractions of what the compiler reads, so equations, specs, dimensions and flows are in it, and units, notes, diagrams and provenance are not. Equal keys mean the same simulation; a respelled equation may take another key, never the reverse. A session's `"current"` run is always of the contents at the key, so a host that holds the key its own run was made at knows whether it and the session see the same model. The key leaves the `agent_tools` feature, since a build without the tools needs it as much. The entry point takes the contents shared and releases the project's lock before it hashes, so it waits for no compile and holds up no edit; it is in the entry-point table with that footprint. The hash is the standard library's, so a key compares contents within one build and is not stored across launches; the header says so. Evidence: `the_simulation_key_moves_when_what_the_model_computes_does` holds a diagram layout, a note and a unit to leaving the key while each advances the revision, an equation and the specs to moving it, and a copy to sharing it; the engine's `simulation_key_tests` row every field the key reads or leaves out, as before. Cost: 5.9 ms per key for C-LEARN, the largest model in the corpus, in a debug build; a release build was not measured.
An arrayed variable's elements can each have an equation of their own, and the diagnostics about them did not say which element they were about. A parse error in one element's equation carried a span into that element's text with nothing naming the text, so a host could not underline it or show it beside the element; when several elements' equations failed to lower, only the first was reported; and the warning for elements with no equation listed them all in one sentence, which a host can show only beside the variable. Every diagnostic whose span indexes an element's own equation now names that element. `EquationError`, `Error` and a unit consistency error (`UnitError::ConsistencyError`, a fourth field) carry `element` -- part of where the error is, like the span -- set by the raising site that knows it: - the parse of an element's own equation (`variable::parse_equation`), and the builtin checks made as it is parsed (`builtins_visitor`, such as too many arguments to a module call); - a name it reads that the model does not define (`UnknownDependency`), located at its first reference: the default's text first, then each element's own in the dimensions' declared order, so the row no longer depends on how the arms are stored, and a reference inside a subscript (`z[nosuch]`) is found too; - its lowering to array bounds (`ast::lower_arrayed_arms`), which now reports every failing element, in the dimensions' declared element order after the default's error, rather than the first alone; - its compile (`compiler::expand_per_element`), and a builtin's argument lowered for it; - its units, where they disagree with the variable's or with the other elements' (`units_check`); - an element with no equation (`MissingElementEquation`, now one row per element), an element entry naming nothing (`UnknownElementSubscript`), and a read past a dimension's end (`SubscriptOutOfRange`). An error in the equation every element follows names no element when every element meets it -- the first element to compile is no more at fault than the rest -- and a read past the end, which only some elements make, names each. The span indexes the element's own equation when it has one, and the equation every element follows otherwise. `Diagnostic::element` reads it, `FormattedError` carries it and cuts the message's snippet from that text, libsimlin's `SimlinErrorDetail` gains a trailing `element_name` (NULL for the variable as a whole; existing field offsets unchanged), and the `@simlin/engine` reader returns it as `elementName`. Evidence: `an_error_in_an_elements_own_equation_names_the_element` holds each stage (parse, builtin arguments, an unknown name in an element's own equation, beside a default, in a subscript and in the default, array bounds, compile, the equation every element follows, a scalar) to the element it names and the text its snippet shows, and `a_unit_error_in_an_elements_own_equation_names_the_element` does the same for units; `every_failing_element_arm_is_reported_in_declared_order` replaces the first-failing-arm test with every arm, in order, on sixteen fresh databases; `a_detail_names_the_element_it_is_about` reads `element_name` through the FFI; the `@simlin/engine` struct-layout test reads the field at its offset. Not covered: a module call whose argument names a variable the model does not define (`SMTH1(nosuch, 1)`) is refused as its helper's assembly failure, with no span, in a scalar equation as in an element's own; the row names the helper, whose name carries the element, but no element. A unit inference error spans variables and names none.
A host that lists a model's dimensions, or reads an arrayed variable's elements in order, needs each dimension's elements in their declared order. libsimlin had no reader for them: a host serialized the whole project to JSON and picked the dimensions out of it. `simlin_project_get_dimensions(project, out_buffer, out_len, out_error)` writes just the dimensions, in declaration order, each in the shape the native project JSON already gives it (`json::Dimension`): named elements in their declared order or an indexed dimension's size, an indexed subdimension's parent, a positional `mapsTo` and the element-level `mappings`, with names spelled as the model writes them. Reusing that shape means a host reads one schema for dimensions wherever they come from. The project's lock is held only to take the contents. Evidence: `the_dimensions_are_read_in_the_project_jsons_shape` reads every kind of dimension -- named elements in an order that is not sorted, an indexed dimension and its subdimension, a positional and an element-level mapping -- and a project with none; the entry-point table holds the function to taking the contents alone and changing nothing.
A native host draws an equation itself -- references a person can select, fractions and powers set out -- and has had only the LaTeX the web app's KaTeX preview reads. Turning that back into a tree means a LaTeX parser on the host, and a second one that undoes the builtins the engine's parse has already made into modules; and an arrayed variable's LaTeX is the literal `TODO(array)`, so a host had nothing to draw an arrayed equation from at all. `simlin_model_get_equation(model, ident, out_buffer, out_len, out_error)` returns a variable's equations as JSON (`engine::equation_view::variable_equation`), one shape for every variable: - `every`, the equation every element follows -- a scalar's equation, a stock's initial value, an apply-to-all equation, or the default of an arrayed equation whose default applies -- and `cells`, one per element in its dimensions' declared order whatever order the file stored them in, each `own` (its own equation or lookup), `follows` or `missing`, with the canonical key a diagnostic's `element_name` names. Element equations naming no element are listed as `unmatched` rather than hidden. - each text with its tree, from the parse alone: a builtin is the call the modeler wrote, and `a // b` the operator they wrote; a reference says how the model spells it and whether it reads anything -- a variable, a module's output (`m.out`), or an element qualified by its dimension (`Age.old`); and each index inside brackets says what it names on its axis (an element first, then a dimension -- the compiler's precedence -- or an expression, as `Age - 1` is the element before). - a `group` node wherever the grouping rule every printer applies puts parentheses (`ast::needs_parens`, extracted from `paren_if_necessary`), so a host needs no precedence table. - spans as UTF-8 byte offsets into each text; the header says so, since a host's strings are often indexed in UTF-16. It reads the contents alone, so it waits for no compile. The LaTeX entry point stays for the web app, unchanged. Evidence: `equation_view_tests` holds a scalar's whole document, a stock's initial value, the grouping cases, calls and conditionals and an unknown name, `//` as the operator it is with its grouping, a qualified element and a module's output as names that read something, every index kind, an apply-to-all variable, a default with exceptions stored out of order, missing cells and an arm naming no element, two dimensions row-major, a text that does not parse, byte offsets past a non-ASCII name, and a dimension used as a value; `an_equation_is_read_as_its_tree_and_cells` reads it through the FFI, and the entry-point table holds it to the contents alone.
A host that changed one thing about a variable -- its units, one element's equation -- read the whole variable, changed the field and sent the variable back as an upsert, which replaces a variable whole: a field the host's copy left out was cleared, and an arrayed equation the host did not model was lost (an edit of an arrayed variable's equation landed on the scalar field the upsert ignores). The agent tools' `edit_model` did the same inside the engine, with its own rules for arrays: setting one element turned the equation every element follows into a copy per element, and setting the equation for every element dropped every element's own. Six model operations change one field of one variable and leave the rest (`engine::patch_fields`), and `edit_model`'s operations are now translations into them, so an agent's edit and a host's mean one thing: - `setEquation`: a scalar's equation -- a stock's is its initial value -- or the equation every element of an arrayed variable follows; each element keeps an equation of its own. - `setElementEquation`: one element's own equation, or with null -- or an empty text -- none, so it follows the equation every element follows again. An empty text stored as the element's own would be one no format but the engine's reads as following: an MDL save wrote `d[old]=` with nothing after it, and the element read 0 on reopen. - `setUnits`, `setNotes`. - `setLookup`: the variable's lookup or one element's. An element given a lookup takes the equation every element follows as its input, written out, so every format keeps it (an MDL element lookup is a `WITH LOOKUP` of its own input). The other elements of a variable with a lookup of its own read through the variable's still: the compiler lays out an element with no table of its own with the variable's (`variable::build_tables`, `db::variable_tables`), as the save check already read it, where it had given such an element no table at all. - `setDimensions`: the dimensions a variable is arrayed over, in order. A dimension added repeats the variable along it -- splitting it by the dimension -- and one removed keeps what every element along it says, or the element `keep` names, and is refused, naming two elements that differ, when the elements differ and none is named. An element kept for its lookup alone reads the equation every element follows through it, as it did. An arrayed variable stays in its smallest form: the equation every element follows (apply-to-all, or a default that applies) and the elements with equations of their own, stored in their dimensions' order; one whose last own element is cleared is apply-to-all again, and one with no dimensions left is a scalar. `edit_model` gains `clear_element` and `set_dimensions` and an `element` on `set_lookup`; its `set_equation` keeps each element's own equation when it sets the one every element follows. The incremental layout and its independent audit name the variable a field edit can change the reads of, as they do for an upsert. Evidence: `patch_fields_tests` covers each operation on each shape of equation, what each refuses, values from a run where a shape's meaning is at stake (an element's lookup beside the variable's, an empty element equation through an MDL save, a scalar kept from an element with a lookup alone), and that what the edits store -- one equation for every element, elements with equations and lookups of their own, elements of two dimensions -- round-trips through XMILE, JSON, MDL and protobuf with the save check finding the same definitions and results. The one thing an MDL save does not keep is an equation for every element that no element follows: `:EXCEPT:` cannot except every element. The sharing property (`patch_sharing_tests`, with an arrayed fixture), the flow-order table and the JSON round trip have rows for every new operation; `edit_tests` has the agent's element edits, a split and its reverse, and rows for the new operations in the table of every operation on every kind of variable; and `a_field_edit_lands_through_the_patch` sends one through the FFI.
…t through it An arrayed variable can give one element a table of its own and no equation, under a default every other element follows. The compiler reads that element as the default fed through its table: an empty element equation is no equation, the default fills the element, and the element's table wraps it. An XMILE graphical function arrayed with one shared `<eqn>` reads this way, and a host that gives one element a table can store it so. The MDL writer kept that reading only when it gave up on the `:EXCEPT:` equation and wrote every element out. When it kept the `:EXCEPT:` equation, it wrote the element as its table alone, `y[Boston]( [(0,0)-(10,100)], ... )`, which Vensim reads as a lookup definition with no value. The writer now gives such an element the default as its table's input on both paths, so the element is written `y[Boston] = WITH LOOKUP(input, ( ... ))` beside the `:EXCEPT:` equation. A variable can also have a table of its own and elements with equations of their own: every element reads through the variable's table. MDL gives a table to an element's equation, not to a variable whose elements have equations of their own, so the writer wrote the elements without it and the table was lost for every element (0.5 became 1.0). The writer now writes such a variable element by element, each through its own table or else the variable's (`with_the_variables_table`). The save check compares what a variable computes, and reads an empty element equation under an applying default as the default, as the compiler does, so the element written with its input reads back as the same variable. Evidence: `an_elements_table_under_an_except_default_reads_the_default` saves such a variable to MDL, finds the element written `WITH LOOKUP` of the default beside the `:EXCEPT:` equation, and finds no change in the save; before, the element was written as a table alone. `a_variables_table_is_written_into_each_element_that_reads_through_it` saves a variable with a table of its own and one element's own equation and finds no change in what it computes.
A host that lets a person make and change dimensions, and an agent that
does the same, had one way to do it: replace the project's dimensions and
leave every variable over them, every element's own equation and every
equation that names a dimension or an element to be repaired by hand.
Renaming an element left each element's own equation keyed by the old name,
read by nothing, and each `x[old]` naming an element that no longer was.
Four project operations, in `engine::patch_dimensions`, each carrying the
edit through the model:
- `upsertDimension {dimension}` adds a dimension, in the shape
`simlin_project_get_dimensions` reads, or sets the elements, their order,
the mappings and the parent of the declared one of its name. An element
removed takes with it every variable's own equation there, a variable
left with none follows its one equation again, and the elements kept stay
in the dimension's new order. An element added follows the equation every
element follows, or is an element with no equation, which the
diagnostics name. Refused when an element removed would be left only in
a subrange or an element map, and when an element added is named as a
variable, so that `c[idx]` would read the element where it read the
variable.
- `renameDimension {from, to}` rewrites every variable's dimension list,
every other dimension's mapping onto it and parent, and every equation
that names it: in brackets, as a star range in either spelling (`*:Sub`,
`Sub.*`), as the element's position (`Age > 1`), and qualifying an
element (`Age.young`).
- `renameElement {dimension, from, to}` renames the element in the
dimension and in each dimension that shares it as one element (its
subranges and the dimensions it is a subrange of, so two overlapping
subranges of one dimension rename it together), in element maps, in the
keys of the elements with equations of their own, and in each subscript
and qualified position that reads it.
- `deleteDimension {name}` removes a dimension nothing uses, and is
refused otherwise, naming the variables, equations and dimensions that do.
A renamed name is spelled as the edit gives it: bare where it reads back
bare, and otherwise in quotes as given (`c["65+"]`). A name in quotes
cannot qualify an element or a star range (`Age.old`, `Age.*`), so a rename
that would have to write one so is refused, naming the equation and what
the modeler can do (a name that needs no quotes, or the equation written
without the qualified name first), rather than leaving a text that does not
parse.
Equations are respelled by the walk a variable rename makes
(`patch::respelled_text`), which now visits a star range's dimension too, so
everything else in the text stays as written. As a variable rename does,
a dimension edit refuses rather than choose a reading: a name that is or
would be both a dimension's or an element's and a variable's, an element
another unrelated dimension declares, or a new name already taken.
The agent's `edit_model` gains `add_dimension`, `change_dimension`,
`rename_dimension`, `rename_element` and `delete_dimension` over these, and
an edit's changes name each dimension it adds, changes or deletes; an edit
that changes only the dimensions is an edit, and checks the dimensions are
as the session read them.
Evidence: `patch_dimensions_tests` runs a model whose equations name a
dimension every way an equation can, before and after each rename, and
finds the same series under the new names; an element map, an element
removed and added, a reordering, a star range in both spellings, a rename
to names written in quotes, and every refusal, each leaving the project as
it was. The JSON round trip carries
each operation, the shared-allocation test applies each to a model, the FFI
test reads a renamed element and dimension back through the equation
reader, and the agent's matrix and a test of its own make each edit.
…eeps `setDimensions` removes a dimension from a variable by keeping what its elements say along it: the equation every element follows, and each element's own. An equation that names the removed dimension -- `m[Region, Age] = Age * 100 + c[Age]`, the commonest arrayed variable there is -- was kept as written, so removing `Age` left `c[Age]` and `Age` in an equation no longer over `Age`: accepted, with or without `keep`, and then an error (`MismatchedDimensions`) for the model to repair. Without `keep` the edit was accepted though the elements along `Age` differ in what they compute. Now a removed dimension the equations name is read at the element `keep` names: in brackets as that element (`c[Age]` at `old` is `c[old]`), and as a value as that element's position, qualified by its dimension (`Age` is `Age.old`, which stays right if the dimension's elements are reordered). A star range over the dimension (`SUM(c[*:Age])`) reads every element wherever it is written, and is left as it is. A kept element whose name needs quotes (`65+`) cannot qualify a position (`Age."65+"` does not parse), so a removal that would write one is refused, saying what the modeler can do; in brackets it stands (`c["65+"]`). Without `keep`, an equation that names the removed dimension in brackets or as a value says something else at each element of it, so the edit is refused as when two elements' own equations differ, naming the equation. Evidence: `a_removed_dimension_the_equation_names_is_read_at_the_kept_element` removes `Age` from `m[Region, Age] = Age * 100 + c[Age]` and finds the edit refused without `keep`, and with `keep: ["old"]` the equation `Age.Old * 100 + c[Old]` computing 330 at each region; a star range over the removed dimension is kept and computes the sum it did; keeping `65+` is refused where the equation reads the position and taken where it reads `c[Age]`.
An equation for every element that reads an element a fixed number of places along -- `x[T] = y[T - 1] + 1` -- lowers each element's index to a constant, but kept it a computed load (`LoadSubscript`). The dependency graph orders a recurrence element by element, and a computed load names only the variable's first element there (`db::dep_graph::ordering_reads`). So in `x[T] = IF T = 1 THEN 1 ELSE y[T - 1] + 1` with `y[T] = x[T] * 2`, `x[t3]` was ordered before `y[t2]` and read the value `y[t2]` had at the step before: `x[t3]` was 1 where the same recurrence written as each element's own equation gives 7, with no diagnostic. Constant folding now turns a subscript whose every index is a constant into a read of that element (`Expr::Var` at its offset), by the VM's own index rule: floored, narrowed to `u16`, 1-based, row-major over the axes. The read is the one the VM made, so a run that was right is unchanged, and the dependency graph sees the element it is. A subscript that comes to no element stays a computed load, which reads not a number, and is what the out-of-range warning reports. An array-producing builtin that reads its operand in whole from where it starts (`VECTOR ELM MAP(arr[T - 1], off[T])`) is the one place a read of one element is not the element alone: the map reads on along the variable from it, and needs the variable's full extent (`codegen::full_source_len`). There the folded subscript is a read of the element of the whole variable (`Expr::StaticSubscript` at the variable's base, the element in the view's offset), as an element written out is lowered there, rather than the element on its own, which read 30 where 20 and not a number where 30. Evidence: `a_recurrence_through_an_offset_is_ordered_by_element` runs the recurrence above written by offset and written element by element, and finds the same series (before: 1 where 7); `a_constant_subscript_reads_its_element` holds the fold to the VM's index rule; `an_offset_mapped_over_by_vector_elm_map_reads_on_along_the_variable` maps over `arr[T - 1]`, `arr[(T - 1) * 1]` and `arr[T - 1 + 0]` and finds the numbers of the elements written out. Not covered: an index the model computes as it runs (`y[idx]`) is still a computed load, and still names only the first element to the dependency graph, so a recurrence through one can be ordered wrongly the same way.
Vensim's reader writes a variable out once per element, each element's names substituted into its copy, wherever more than one equation defines it (`POPULATION[INFANT]` beside `POPULATION[ALL BUT YOUNGEST]`) or an equation has `:EXCEPT:`. A host that shows an arrayed variable as the equation every element follows and the elements that differ showed these as a row of near-identical element equations where the file wrote one, and an agent read them so too. Opening an MDL file now ends with `element_equations::compact_element_equations`. Each element's equation is read with its own element as "this element": a subscript naming the element, on an axis that declares every element of the dimension, is that dimension's name (`INITIAL_POPULATION[CHILD]` at `CHILD` is `INITIAL_POPULATION[AGE]`), which the compiler reads as the element by name. Where every element then reads the same, the variable is that one equation; where most do, it is that equation with the others as exceptions; an `:EXCEPT:` equation's copies of its default follow the default again, and a default that fills no element, every element having an equation of its own, yields to the one most of them read. Anything else stays as it was: elements that say different things, a list of numbers (negative ones too), an element with an initial or a lookup of its own, an equation that does not parse, and a variable some element of which has no equation, which a default would give one. An element that reads one a fixed number of places along (`aging[INFANT]` at `CHILD`) is an offset, `aging[AGE - 1]`, read that way to compare two element equations (`ElementReader`) but not stored: loop analysis scores an element's link through the element's own equation, and its per-element link scores cannot yet read a dimension inside a computed index -- stored, C-LEARN's ocean layers and emission targets compiled 46 link-score helpers to nothing. Such a chain keeps its element equations. The save check reads each element's equation at its element the same way, so `a[A1] * 2` at `A1` and a default `a[DimA] * 2` are one equation, where before the check reported the respelling. An offset a host or an agent writes is saved to MDL once per element, since Vensim has no arithmetic in a subscript (`mdl::writer::arrayed::per_element_for_vensim`): each bracketed dimension name the element itself, each computed index the element it comes to on the axis it indexes, a dimension's name as a value the element's position, and an `:EXCEPT:` default that offsets written into the elements it fills, including an element with a table and no equation of its own, which is the default at the element through its table. An index that comes to no element is written `NaN`, which reads as the read of no element did, with a warning naming the element, since Vensim does not read it. Evidence. Every MDL file in the corpus (238) computes bit-identical series before and after, as opened, after a save to MDL and after one to XMILE. In 18 files, 48 variables open as one equation (41 with no exceptions, 7 with some), and the element equations stored fall from 4,960 to 4,218. In C-LEARN eleven variables are one equation again; its link scores the model declines and every LTM diagnostic it files are the same 23 as before, and the pinned LTM variable count moves from 6,199 to 6,155 and the width from 34,365 to 34,083 slots, the link scores of those variables being arrayed rather than one per element (`clearn_ltm_var_count_guardrail` says so). `element_equations_tests` opens each shape and each that stays; `an_elements_table_under_an_offset_default_reads_the_default_at_the_element` saves an element's table under an offset default and finds it computes the same; `an_offset_is_saved_to_mdl_as_each_elements_own_equation` saves an offset and an offset default, reads the save back under Vensim's subscript rule, and runs it the same. The MDL fixed-point property tests take a generated model in the form an open gives it, and keep the case that found a default filling no element.
…it can read A recurrence that runs through two variables element by element is compiled as one interleaved fragment in the order its element graph gives (`db::dep_graph::symbolic_phase_element_order`). That graph took each read from the compiled code (`ordering_reads`), and a load whose element the model computes as it runs -- `y[idx[T]]`, a computed load (`LoadSubscript`), or a whole-variable view a computed subscript narrows (`PushVarViewDirect`) -- was recorded as a read of the variable's first element alone. So in `x[T] = IF T = 1 THEN 1 ELSE y[idx[T]] + 1` with `idx[T] = T - 1` and `y[T] = x[T] * 2`, `x[t3]` was ordered before `y[t2]` and read the value it had at the step before: 1 where the recurrence gives 7, with no diagnostic. Such a read is now a read of any element of the variable (`ANY_ELEMENT`), which the element graph wires from every element of the member it reads, and which the combined fragment's prologue check requires to have come first in full. A recurrence through a computed index therefore has the cycle it may have at run time, and is refused as `CircularDependency` rather than run in an order the index can break. One whose index is a constant at each element (`y[T - 1]`) reads that element directly and is still ordered element by element. That refuses recurrences that ran correctly too: `x[T] = IF T = 1 THEN 1 ELSE x[idx[T]] + 1` with `idx[T] = T - 1` gave 1, 2, 3, as did a two-variable recurrence through `y[ref]` with `ref = 1`. Element by element they have no circle; no order for them can be fixed before the run, since the element read is whatever the index holds then. The trade is the loud one: a wrong order was silent (the clamp idiom `y[MAX(T - 1, 1)]` gave 1 where 7). So the refusal says why: the diagnostic names the variable that reads another at an element computed as the model runs (`dep_graph::computed_index_read`), and that an index fixed at each element -- an element, or an offset of the dimension -- can be ordered, where "depends on itself" alone would leave a modeler looking for a circle the model does not have. Evidence: `a_recurrence_through_a_computed_index_is_refused_not_misordered` runs the model above, and its one-variable twin, and accepts a run only if it computes the recurrence it states, and a refusal only if it names the computed index; before, it ran and gave 1. Every MDL file in the corpus computes the same series before and after, and the engine's suites pass unchanged.
libsimlin's `SimlinErrorDetail` carries `element_name`, the canonical key of the element of an arrayed variable a diagnostic is about, and the `@simlin/engine` reader returns it as `elementName`. pysimlin's `ErrorDetail` did not read it, so a Python caller could not tell which element's equation an error's span indexes. `ErrorDetail` gains `element_name` (None for the variable as a whole), read from the struct as the other strings are, and `str(detail)` names the element when there is one. The field is added last with a default, so a detail built by keyword or position is built as before. Evidence: `test_an_error_in_one_elements_equation_names_the_element` opens a model whose one element reads a name the model lacks and finds the detail naming that element, with its span into the element's own text.
… are scored An equation for every element can read an element a fixed number of places along -- a diffusion chain's `flux[L] = (c[L - 1] - c[L]) * k`, an aging chain's `aging[AGE - 1]` -- the form a host teaches and an agent writes, and it can decide a branch on the element (`IF L = 1 THEN ...`). Loop analysis describes a read by how its subscript is spelled, and an index computed from a dimension is one it can only take as a read of any element: every element of `c` fed every element of `flux`. On a three-layer diffusion chain that made 39 loops where there are 5, their link scores 0 and one loop score near 3e14, with no diagnostic. Where such an equation's call was hoisted into a helper per element, the helper's link scores did not compile and read 0. And a variable that read one variable in two spellings (`c[L]` beside `c[l1]`), or read by a bare name in a reducer of a per-element equation (`SUM(m)`, which the run reads as the row its element fixes), was scored against reads the run does not make. The describers now see the reads the compiled slot makes: - `db::model_lowered_variables`, the map every LTM describer reads, holds an arrayed variable whose elements read a position they compute as the equations of its elements (`FragmentInput::elementwise_target`). Every read of a variable that one of its equations reads in a spelling the describers would take otherwise -- an offset, a literal element beside the dimension, a reducer's argument -- is pinned by the compiler's own resolution (`Context::pin_element_reads`) to the element its slot reads; a read that comes to no element is the not-a-number it reads. A condition the element decides takes its branch, and a dimension read as a value is the element's position. A variable read only by the dimensions the equation iterates keeps that spelling, which the describers read as the same element and score over the dimensions at once. The compiled model is not touched. The unit pass reads the map without these views (`db::model_written_variables`), so a unit error is still about the equation as written. - `db::model_causal_edges` drops an edge into a described variable whose body does not read the source -- the branch an element does not take, an offset that comes to no element -- so no link score is asked of a read that is not there. - A per-element helper's body is pinned the same way, an active dimension's name inside an index the element's position, so an offset in it is an index of numbers the compiler resolves to one element. - A reducer's body pinned to a row now reads a number on a named axis as the element at that position (`ltm_augment::pin_body_index`), as the compiler does: `SUM(m[1, *])` was scored as if it read one element of the row alone (1.0 where 0.5). Where loop analysis cannot score a read exactly it says so: a read at an element the model computes as it runs (`c[idx[L]]`) is still scored as a read of any element, and the edge now carries a warning that its score is not exact, naming the variable that reads it. Evidence. `ltm_elementwise_tests` generates 40 chains -- three and four layers, offsets of one and two, one and two dimensions with the offset on one axis or both, layers started off a straight line, an offset under SMTH1, under DELAY1 and beside `SUM(c[*])`, the ends written as exceptions or as a guard on the element -- and finds each written with offsets scored as the same chain written element by element: the same loops, the same loop score series bit for bit, the same loops found by the model's analysis, the same diagnostics. Two fixtures where a slot's bare reducer argument reads its row are scored as the rows written out, and a loop through a computed index carries the warning. `an_offset_chain_scores_the_loops_of_its_elements_equations` finds a diffusion chain's 5 loops with bit-identical scores; before, 39 loops and the scores above. Tests that pinned a dimension-named reducer in a slot as declined now find it scored as its literal twin, and the decline they existed for is pinned with a computed index. Across every MDL file in the corpus the LTM diagnostics are the same, but for the beer game (RealBeer4-Sterman13), which files 12 fewer -- 13 link scores that did not compile, and one warning that a read through a computed index is not exact -- and two scientific-revolution models, which each file that warning.
Opening an MDL file stores one equation where a variable's elements say one thing (`element_equations`), and read each element's equation with the element as "this element" -- but stored only a dimension's name, not an offset, because loop analysis could not score a link through one. It now can (the commit before), so an element that reads one a fixed number of places along on the same dimension is stored as that offset: Vensim's aging chain, written out per element by its reader, opens as `aging[AGE - 1] - aging[AGE]` with the youngest cohort as an exception, and C-LEARN's deep-ocean layers and emission targets open the same way. The MDL writer writes an offset back once per element, as before. Read as offsets, the copies of an equation that names a fixed element of its own dimension -- `d[Age] = c[Age] / c[young]`, a base it normalizes by -- differ from one another (`c[Age] / c[Age - 1]` at `adult`), and no longer came back as that equation from an MDL save. So an element follows an equation for every element also where that equation, written out at the element, is its own copy (`written_at`), and the equations tried are each element's read with other elements as offsets and as written. The numbers were the same either way; now the model saved is the model opened. Evidence. Every MDL file in the corpus (238) computes bit-identical series before and after, as opened, after a save to MDL and after one to XMILE. In 22 files, 76 variables open as one equation (42 with no exceptions, 34 with some), and the element equations stored fall from 4,960 to 3,916. `the_corpus_scores_the_same_loops_compacted_or_not` opens every MDL file of the corpus with the compaction and with each variable left as the reader writes it out, and the 198 that run with loop analysis, 500 loops among them, score the same loops, with the same loop score series bit for bit, the same loops found by the model's analysis and the same LTM diagnostics; 18 of them hold a compacted variable, with 172 loops. The test holds floors on both counts, so it cannot pass on a corpus that has lost its loops. In C-LEARN fifteen more variables are one equation with exceptions; a link into one is scored for the element pair the run reads where each element's own equation had a score arrayed over every target element, so the pinned LTM variable count moves from 6,155 to 6,061 and the width from 34,083 to 30,896 slots, with the same 23 declined scores and LTM diagnostics. `an_element_a_fixed_number_of_places_along_reads_an_offset` opens a chain as an offset with an exception and runs it as Vensim does; `an_equation_naming_a_fixed_element_opens_as_one_equation` opens the base normalization as one equation and finds an MDL save of it opens the same; `an_offset_opened_under_vector_elm_map_keeps_its_numbers` opens a file whose elements map over the element before as that offset and computes the file's numbers.
An edit's change line wrote an arrayed variable's equation whole, before
and after: each element's own equation and the default, as
"north: 10; south: 20; others: 5 (was ...)", cut at 240 characters on a
variable of many elements. A host showing an agent's edit to a person, or
an agent reading its own, had to compare the two to learn which elements
the edit touched.
A change of an arrayed variable's equation over the same dimensions is now
said for what changed: the equation every element follows, when it
changed, then each element whose own equation was written, changed or
cleared, spelled as its dimension spells it, with what it was:
North: 0.5 (was the equation for every element, 0.1)
equation for every element 0.2 (was 0.1); North: 0.6 (was 0.5)
North: follows the equation for every element (was 0.6)
A change of dimensions, or between a scalar and an arrayed equation, is
said as before.
A read that runs off a dimension (`c[Age - 1]` at the first age) is
reported as `SubscriptOutOfRange`, with a sentence naming the element, the
variable read and the dimension by their canonical names: "the equation for
'north,young' reads 'aging' before the first element of 'age', which is not
a number". A host that shows the problem beside its element, in its
model's own spelling and in one thought ("there is no Age before Young"),
could only take that sentence apart.
The warning now carries its parts. `EquationError` gains `read_past`, a
`ReadPast` of the dimension's canonical name and whether the read is before
the first element or past the last, set where the read is found;
`Diagnostic::read_past` reads it and `FormattedError` carries it. libsimlin's
`SimlinErrorDetail` gains two trailing fields: `read_past_dimension` (the
canonical name; NULL for every other detail) and `read_past`, a new
`SimlinReadPast` of `NONE`, `BEFORE_FIRST` or `AFTER_LAST`. With
`element_name`, which already names the element, a host words the problem
itself. Existing field offsets are unchanged; the detail is 48 bytes on
wasm32, and the `@simlin/engine` reader returns `readPastDimension` and
`readPast`.
Evidence: `the_warning_names_the_dimension_and_the_end` reads both ends of
a chain; `a_read_past_a_dimension_names_the_dimension_and_the_end` reads
the fields through the FFI, and every other detail names no dimension; the
`@simlin/engine` struct-layout test reads them at their offsets.
… end An MDL file that writes one number for every element and its exceptions (`d[Age] :EXCEPT: [old] = 0.01` beside `d[old] = 0.08`) opened with every element its own number: the reader writes the default into each element it fills, and compaction left any variable whose elements are all numbers as it was, since a list of numbers is its own idiom. A host that shows which elements follow the equation for every element saw none follow, and a project saved as MDL and opened again lost its followers. Compaction now keeps the followers of an applying default whose elements are all numbers, where some element differs from it. Numbers that all say the default stay a list, as written, so a save of such a variable is still a fixed point. An offset's first element, which reads no element (`c[Age - 1]` at the first age), is written to MDL as `NaN`, since MDL has no arithmetic in a subscript. It opened as an element of its own. An element whose own equation is `NaN`, where the equation for every element reads no element, now follows it: both read not a number there. Evidence: `a_number_for_every_element_keeps_its_followers` and `an_element_that_reads_no_element_follows_as_nan` fail before this change. Two converter tests that counted the default written into each element now count the exception alone. The corpus loop-scoring gate passes.
A host that shows a refused edit of the model's dimensions to the person who made it showed the engine's sentence whole: "failed to apply patch: cannot delete 'Age': 'Population' in model 'main', 'Arriving' in model 'main', 'Aging' in model 'main' and 3 more still use it". The prefix says only what the host already knows, that it applied a patch, and a project of one model has no other model to tell its variables from. libsimlin's error for a refused patch is now the engine's reason alone, and a dimension refusal names a variable's model only where the project has more than one: "cannot delete 'Age': 'Population', 'Arriving', 'Aging' and 3 more still use it". One user "still uses it". Evidence: the dimension refusal tests and the edit tool's test now read the shorter sentences; no other caller matched the prefix.
…ge lines An arrayed variable's change line called the equation every element follows "the equation for every element": "North: follows the equation for every element (was 0.6)". A host that lays the elements out names that equation for its dimensions, "Every Region", and a person reading the host's sheet beside an agent's change line met two names for one thing. The change line now names it the same way, each dimension as the project declares it: "equation for Every Region 0.2 (was 0.1)", "North: 0.5 (followed Every Region, 0.1)", "North: follows Every Region (was 0.6)". Over several dimensions it is "Every Region and Age". Evidence: the change-line tests read the new names.
A variable renamed, and one deleted while another took its name, leave
the same names behind, so a host that follows a variable through an edit
-- a selection, a page that shows it, text being typed about it -- cannot
tell from the project the edit leaves which happened, and a guess from
names can carry the host's state onto a different variable or drop it
from the right one. Only the edit knows. Variable uids cannot stand in:
imported models carry none, and a view uid freed by a delete can be taken
by an element created in the same edit.
`apply_patch_reporting` applies a patch and returns a `PatchReport` that
accounts for the identity of every variable the patch touched, against
the project before it and the project after it:
- `renamed`: the variable that was `from` is now `to`, by a
`RenameVariable` or a view edit that relabels its element. A variable
the patch created is never a `from`.
- `deleted`: the variables, by their names before, that no longer exist,
whether deleted outright or renamed and then deleted.
- `created`: the variables, by their names after, that did not exist
before, however they came to have the name.
Every other variable is the same variable under the same name, so a host
follows what it holds through `renamed`, ends it on `deleted`, and keeps
it otherwise, guessing nothing. A name deleted and then taken by another
variable is simply both; `created` also lets a host invert the account,
as an undo of the edit does. The patch follows identities as it applies
each operation (`Identities`), so a chain of renames, a delete of a
renamed variable, or a new variable later renamed all come out right.
libsimlin's `simlin_project_apply_patch_reporting` applies a patch as
`simlin_project_apply_patch` does and writes the report as JSON,
`{"renamed": [{"model", "from", "to"}], "deleted": [{"model", "ident"}],
"created": [{"model", "ident"}]}`, for a patch committed or one a dry run
would commit, and nothing for one refused. The report may gain keys,
which a reader ignores.
An agent's edit carries the same three lists, by identifier, beside its
`changes`, so a host reads one shape from either path. Its change line
for a rename, whose new name was only in the prose of `detail`, also
gains `to`, spelled as `variable` is, for the agent.
After `births` is split by Region, `total = births` reads a value for each Region where it needs one. The compiler said so in six different ways depending on where it noticed, often with no span and sometimes on a hidden helper instead of the person's variable. Now each such read is one MismatchedDimensions error on the variable the person wrote, at the reference, naming the variable read and the dimensions the reader lacks. libsimlin's error detail gains two trailing fields: `mismatched_read_variable` and `mismatched_read_dimensions` (comma-separated). Errors are also smaller, which gives the compiler more stack headroom on long equations.
A model that does not compile still gets a simulation handle from simlin_sim_new; the compile error is reported when the run starts. The header now says so.
A lookup arrayed over Region with a single graphical function shares that table across its elements. Reading it per element (`y[Region] = LOOKUP(g, x)`) gave the right value for the first element and NaN for the rest. Every element now reads the one table.
`x[Age] = v * 2` with `v[Region]`, where Age and Region happen to have the same number of elements, used to read v's elements by position, silently: the first Age got the first Region, and so on. Now it is the same error as any other read whose dimensions disagree, as in Vensim. Two numbered (indexed) dimensions of the same size still pair.
A lookup arrayed over Age with one table applies it at every element, but `LOOKUP(g[Age - 1], 1.5)` at the first Age read the table instead of NaN: the shared-table shortcut skipped the bounds check. It now applies only to an element offset within the variable, and anything outside is NaN as for any other table. Separately, where some elements have tables of their own, an element with no equation and no table was not reported as missing, because the variable's own table filled its slot. Only an element's own table counts as its equation now.
Opening an MDL file merges per-element equations into one where they say the same thing. An element written as NaN was merged whenever the shared equation read no element there. But `d[young] = NaN` beside `d[adult] = IF THEN ELSE(switch, c[young], 5)` became one equation, and with switch at 0, d[young] turned from NaN into 5. An element whose own equation is NaN now keeps it.
…y element An equation that reads an element a fixed number of places along is saved to MDL once per element. Its other references had the element name pasted in, ignoring dimension mappings: with Group mapped onto Age, `d[Age] = x[Age] + c[Age - 1]` over `x[Group]` saved `x[adult]`, which does not reopen. Each reference now reads through the mapping the way the compiler does, so the save has `x[g2]`.
An element can have an initial value of its own. Removing the variable's last dimension and keeping that element dropped its initial: an element with equation 20 and initial 98 became a scalar starting at 20. It now keeps 98 as the scalar's initial. And removing a lookup from an element that has an initial no longer deletes the element's entry with it.
Adding a dimension called `young` when `young` is already an element of Age, or adding an element named like a dimension, was accepted. A subscript that writes the name could then mean either. Renaming a dimension or an element already refuses this; adding one now does too, with the same reason.
The engine's module map still said a per-element slot's bare reducer argument is declined, and named a test since renamed. It is scored as the row it reads. Two long entries now put one sentence on a line. libsimlin's notes gave the old size of the error detail (it is 56 bytes), left out its two read fields, and did not mention `simlin_project_apply_patch_reporting`. The patch report's five types now derive Debug behind `debug-derive`, as the rest of the crate does.
Codex Review SummaryThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
Codecov Report❌ Patch coverage is Additional details and impacted files@@ Coverage Diff @@
## main #1087 +/- ##
==========================================
- Coverage 92.89% 92.88% -0.02%
==========================================
Files 313 318 +5
Lines 194144 198584 +4440
==========================================
+ Hits 180359 184461 +4102
- Misses 13785 14123 +338 ☔ View full report in Codecov by Harness. 🚀 New features to boost your workflow:
|
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: c805732afe
ℹ️ 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".
| (Some(at), None) => { | ||
| arms.remove(at); | ||
| } |
There was a problem hiding this comment.
Preserve active initials when clearing an element equation
When the targeted arm carries a per-element active initial in tuple field 2, clearing its equation removes the entire arm and silently discards that initial too. This changes initialization results even though setElementEquation(..., null)/clear_element only promises to clear the element equation and lookup; retain an arm containing the effective default equation whenever an active initial must survive.
Useful? React with 👍 / 👎.
| (from, arm) | ||
| }) | ||
| .collect(); | ||
| let first = readings[0].1; |
There was a problem hiding this comment.
Handle empty removed dimensions before indexing readings
If a declared dimension has zero elements, removing it without keep makes removed_choices empty. For each remaining element (including the single scalar combination), readings is therefore empty and readings[0] panics, so a valid sequence of the new operations—add an empty dimension, array a variable over it, then remove that dimension—can abort the patch call instead of returning an error or scalar result.
Useful? React with 👍 / 👎.
| let same = |a: Option<&Arm>, b: Option<&Arm>| match (a, b) { | ||
| (None, None) => true, | ||
| (Some(a), Some(b)) => a.1 == b.1 && a.2 == b.2 && a.3 == b.3, | ||
| _ => false, |
There was a problem hiding this comment.
Compare effective equations when collapsing dimensions
When one removed-axis element has no arm and follows the default while another has an explicit arm equal to that default, this matcher treats None and Some as different and refuses setDimensions without keep, despite every element computing the same definition. It also compares equation text byte-for-byte rather than through the repository's canonical equation equivalence; compare each element's effective equation, initial, and lookup after applying the default so redundant or equivalently spelled arms can collapse.
AGENTS.md reference: src/simlin-engine/AGENTS.md:L31-L33
Useful? React with 👍 / 👎.
| let dedup_key = |err: &UnitError| -> (u32, String) { | ||
| match err { | ||
| ConsistencyError(code, _loc, details) => { | ||
| ConsistencyError(code, _loc, details, _) => { | ||
| (*code as u32, details.clone().unwrap_or_default()) |
There was a problem hiding this comment.
Keep the element in unit-error deduplication
When two array elements have the same unit mismatch, their ConsistencyErrors differ only by the newly added element field, but this key discards that field and retains only the first row. Consequently get_errors identifies just one broken cell and fixing it merely reveals the next; include the element in the key now that element-specific diagnostics carry distinct actionable locations.
AGENTS.md reference: src/simlin-engine/AGENTS.md:L147-L150
Useful? React with 👍 / 👎.
| fn origin(&self, model: &str, name: &str) -> Origin { | ||
| self.names | ||
| .get(&(model.to_owned(), name.to_owned())) | ||
| .cloned() | ||
| .unwrap_or_else(|| Origin::Was(name.to_owned())) |
There was a problem hiding this comment.
Normalize the model key used by identity tracking
For an unnamed default model, both "" and "main" address the same model, but identity state is keyed by the patch's literal model string. A patch with one model block renaming x to y under "" and another renaming y to z under "main" therefore reports only y -> z instead of x -> z, so a host following x loses the variable; normalize the default-model alias before reading or writing this map.
AGENTS.md reference: src/simlin-engine/AGENTS.md:L128-L129
Useful? React with 👍 / 👎.
| /// The element of an arrayed variable the error is about, as its | ||
| /// canonical key (`Diagnostic::element`); `None` for an error of the | ||
| /// variable as a whole. When the element has an equation of its own, | ||
| /// `start_offset..end_offset` index that equation, and `message`'s | ||
| /// snippet shows it. | ||
| pub element: Option<String>, |
There was a problem hiding this comment.
Propagate element locations to agent diagnostics
Although this new field identifies the array element whose text a diagnostic spans, the agent-tool path drops it: tools/evidence::describe copies only the variable and reasons, DiagnosticReport/EditDiagnostic have no element field, and quoted_span explicitly returns None for every Equation::Arrayed. Thus read_model and edit_model still cannot tell an agent which cell has an unknown dependency or parse error, even though the engine now knows it; thread element through those reports and use it to select the arm text for the quote.
Useful? React with 👍 / 👎.
| let mut new_arms: Vec<Arm> = new_arms | ||
| .into_iter() | ||
| .map(|(key, text, gf_text, gf)| Ok((key, at_kept(&text)?, gf_text, gf))) | ||
| .collect::<Result<_>>()?; |
There was a problem hiding this comment.
Rewrite per-element initials when removing dimensions
When setDimensions removes an axis with keep, at_kept rewrites references to that axis in each arm's main equation but carries the arm's active-initial text through unchanged. For an initial such as Age * 100, collapsing Age at Old therefore leaves a scalar or lower-rank variable whose active initial still references a dimension it no longer has, causing a new compile error instead of preserving the selected element's initialization; apply the same substitution to the tuple's initial field (and the variable-level active initial) before storing it.
Useful? React with 👍 / 👎.
The MDL reader's last pass (#1087) read structure into a file that the file does not state. Where most of a variable's per-element equations agreed it made one equation for every element with the rest as exceptions, and where each read the element before its own it made an offset (`x[Age - 1]`). An equation for every element also defines the elements a dimension gains later, so the guess changed what a model means. It also changed two XMILE models saved as MDL, which is one of the two gates red on main since that change (`every_save_keeps_its_model_or_is_listed`). The pass now keeps only what is exact: per-element copies that all read the same are one equation, and copies that read as the `:EXCEPT:` default the file wrote follow it. The vote, the offset reading and the fixed-element matching are gone, and so is the offset arm of the save check's element reader. That arm changed no verdict (the corpus sweep passes with its table as it was): an offset written out per element differs from the original somewhere else too, at its first element, which is NaN, or in its default, which is gone. An equation that computes a subscript still cannot be written to MDL as it stands, because Vensim does not allow numeric subscripts; the claim was uncited and now carries its source at `per_element_for_vensim`. The writer keeps writing such an equation once per element and now warns of every variable it does this to, since the file opens with an equation per element. Before, it warned only where an index came to no element. One cost: an `:EXCEPT:` default that names an element of its own dimension (`c[Age] / c[young]`) opens from MDL with one more exception than it needs, at the element it names, and the save check reports that element as written differently. The numbers are the same, and a test holds the behavior so a better comparison shows up as a change. C-LEARN's LTM variable count is 6,155 (34,083 slots), measured with examples/ltm_slot_width.rs.
`clearn_ltm_slot_maxima_digest` pinned seven numbers over every LTM slot of C-LEARN, two of them a sum and a hash of floating-point maxima. It has been red on main since #1087 changed how C-LEARN opens, and it never passed on an aarch64 Mac: the maxima differ in their last places from one platform to another. When it failed it said only that something had moved. `clearn_leading_loops_keep_their_shares` takes its place. It runs the analysis a host runs (`analyze_model`) and holds the three loops that lead each of C-LEARN's carbon-cycle partitions to a table: the loop, its polarity, and its peak and mean share at each climate sensitivity, within one percent. A failure names the rows that moved. The digest was written for a change that zeroes link scores (GH #977), so the new test was checked against that: with every link-score arm treated as a structural zero, all nine rows fail. It sees less than the digest did. A change to scores on no loop of those three partitions passes it; `db::ltm_value_gate_tests` still holds each way a score is zeroed, on small fixtures. That is the trade asked for: the test is there to catch loop analysis breaking on a real model, not to fingerprint it. docs/dev/rust.md gains the rule that a gate compares numbers within a tolerance and names what moved.
Summary
This makes arrayed variables editable through libsimlin, one field at a time, and makes the errors around them say plainly what is wrong and where. It is for a host that shows a variable's equations for editing, and for the agent tools, which share the same edits.
What a consumer gets
simlin_model_get_equationreturns the equation every element follows and the elements that differ, each as a tree a host can draw.simlin_project_get_dimensionsreads the project's dimensions.edit_modelhas the same operations.simlin_project_apply_patch_reportingapplies a patch and reports which variables it renamed, deleted and created, so a host following a variable does not have to guess from names. A simulation key says whether what a model computes changed.total = birthsafterbirthsis arrayed over Region) is oneMismatchedDimensionserror at the reference, naming the variable read and the dimensions the reader lacks. It used to be six different messages.Behaviour changes
x[Age] = v * 2withv[Region]used to read by position silently. Two numbered dimensions of one size still pair. Fixes engine: an iterated-dimension subscript over an undeclared, disjoint-named axis reads by ordinal on the static subscript path and is refused on the dynamic one #1044 for the bare spelling; the explicit one (v[Sex]wherevis over Region) still pairs by position and is left for a follow-up.c[Age - 1]) is read directly, opens from MDL as an offset, and is NaN past the dimension's end.Fixes from review
Six commits at the end fix what two reviews of this branch found, each with a test that failed first: bounds on a shared lookup table, an element's own NaN kept when equations are merged, mapped reads in per-element MDL export, an element's initial kept when its dimension or lookup is removed, and a dimension that could be named like an element.
Not done
c * 2) as it is; it then reports the mismatched read and the equation is fixed by hand.mainas well; it is not addressed here.Testing
Each commit passed the repository's pre-commit hook.