Repository navigation
LTM usability: discovery exposure, mode visibility, #548 fix, loop pinning - #648
Conversation
The strongest-path discovery (discover_loops_with_graph) rebuilt a HashMap<Ident, ..> and re-sorted each node's edges on every visit at every saved timestep, which dominated runtime on large element-level graphs. Replace it with an integer-indexed graph (IndexedSearch) plus reusable per-call scratch, and move the per-edge score sort out of the per-visit path into one per-timestep sort -- scores are constant within a timestep, so the visited order is unchanged. A differential test pins the result against the prior SearchGraph oracle. Discovery is still infeasible on very large arrayed models (the element graph has tens of thousands of nodes; tracked as #647), so thread an optional wall-clock budget through analyze_model into the per-timestep sweep: it stops early and reports truncated rather than hanging. Callers updated for the new DiscoveryResult return. Also make loop_variables emit the bare node sequence (no trailing repeat of the first node), matching the structural-loop convention so both kinds of loop populate the same Loop type consistently.
Add simlin_analyze_discover_loops + simlin_free_discovery_result, returning the strongest-path discovered loops (each with its per-step importance series), the dominant periods, and a truncated flag from a single analyze_model run. New C structs hold the nested result and the header is regenerated. Returning loops + periods together is a deliberate exception to the small/orthogonal FFI rule: they are the cohesive output of one expensive analysis run, so splitting them would force the caller to run discovery twice.
Model.analyze(timeout=None) -> Analysis runs the engine's strongest-path loop discovery and returns the discovered loops (with their importance series) and dominant periods. It is deliberately separate from run(): discovery can be slow or infeasible on large models, so a timeout maps to the FFI budget and a call cannot hang. Also stop the Link/Loop score aggregates (average_score, max_score, average_importance, max_importance) from leaking numpy "Mean of empty slice" RuntimeWarnings on all-NaN series -- common on large models where most causal links never produce a defined score. They now reduce over the finite subset, keeping the same NaN/None return contract.
…inks Two LTM usability fixes. (1) Surface the resolved loop-enumeration mode: the engine already decides exhaustive vs discovery (the SCC-size gate), so thread an LtmMode out of model_ltm_variables, capture it at simlin_sim_new, and expose it as pysimlin Run.ltm_mode (exhaustive/discovery/disabled) -- a user no longer faces an empty loop set with no signal as to why. (2) get_links() surfaced the raw causal graph, which on macro/module- heavy models is majority synthetic $-internal nodes. collapse_synthetic_ links (an engine-level generalization of the loop-level trim_synthetic_aggs_from_loop_links) folds each chain X -> internal -> Y into one composite edge X -> Y, carrying the composite (largest-magnitude path) link score so the through-contribution is preserved, not dropped (LTM ref 6.3/6.4). Exposed via an include_internal flag on the link FFI (default collapsed in pysimlin get_links; raw kept as the TS default). A characterization test (smooth_macro_..._gh548) documents a separate, tracked gap: in exhaustive mode a macro's composite contribution still stubs to 0 in the parent loop score (GH #548), fixed next.
In exhaustive LTM mode, a feedback loop through a stdlib-macro module
(SMOOTH/SMTH1/SMTH3/DELAY1/DELAY3/TREND/NPV) was silently scored 0. The
real-var -> macro-module link score emits a composite-reference equation
("{module}·$⁚ltm⁚composite⁚{port}") pointing at a synthetic var inside
the LTM-augmented sub-model. The full assembly creates that var, but the
standalone fragment compiler reconstructed the sub-model's metadata via
build_submodel_metadata listing only the sub-model's REAL source vars, so
the composite aux had no entry; the cross-module reference resolved to
DoesNotExist, the fragment was dropped, and the var read a constant 0 --
zeroing the whole loop-score product.
Fix: when ltm_enabled, build_submodel_metadata also registers the
sub-model's LTM synthetic vars (and their implicit helpers) at their
compute_layout offsets, with dimension-appropriate stubs. Both the
standalone fragment and the full assembly read the same cached
compute_layout, so the cross-module read lands on the identical slot --
the link score now equals the macro's internal composite (the
largest-magnitude path score through the macro, LTM ref 6.3) rather than
0, and loops through SMOOTH/DELAY are scored correctly. Gated on
ltm_enabled (zero effect when LTM is off); genuinely-uncompilable
fragments still surface via model_ltm_fragment_diagnostics, not a silent
0. Discovery mode is unaffected (it uses the output-port delta-ratio).
For large models LTM auto-flips to discovery mode, which emits per-link
scores but no per-loop score, and the heuristic may not surface the
specific loop a modeler cares about. This adds the LTM papers' LOOPSCORE
escape hatch -- without a new equation builtin -- by honoring the
existing SetLoopName/LoopMetadata primitive: a user pins a loop by its
variable set and the engine always emits that loop's loop_score
(product of its links' scores, which are emitted in both modes), in
exhaustive AND discovery mode. Pinned loops get a stable pin{n} id, flow
through the existing get_loops / relative-loop-score FFI, and surface in
pysimlin model.loops / run.loops; pysimlin gains ModelPatchBuilder.
set_loop_name to create them.
Resolution paths share one model_ltm_mode salsa query so model_detected_
loops and model_ltm_variables can never disagree on exhaustive-vs-
discovery (honoring both the user discovery flag and the slow-path
late-flip). An invalid pin (not a closed cycle, <2 vars, or no stock)
surfaces a diagnostic, never a silent-zero score. In exhaustive mode a
pin that duplicates an enumerated loop is deduped by canonical rotation,
transferring the pin's name onto the surviving loop. A lone pin sits in
its own single-slot partition, so its relative loop score degenerates to
+/-1 (active/inactive) -- the raw loop_score is the informative series,
documented on the rel-score APIs.
There was a problem hiding this comment.
💡 Codex Review
simlin/src/simlin-engine/src/patch.rs
Lines 377 to 383 in 5b0557a
When SetLoopName is used for a variable set that already has a LoopMetadata entry marked deleted, this branch updates the label but leaves deleted as true. pinned_loops_from_datamodel explicitly filters deleted entries, so re-pinning a loop that a user previously deleted will silently remain invisible and will not emit the expected pinned loop score; this path should clear existing.deleted when reviving the entry.
ℹ️ 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".
ReviewReviewed all 47 changed files (~5.5k additions, ~150 deletions) across the six commits. The work is cohesive and well-tested:
Nothing rises to the level of an actionable correctness bug worth flagging. A few minor cosmetic observations not worth blocking on:
Overall correctness verdictCorrect. The changes are internally consistent, the new behaviors are covered by tests at appropriate levels (unit, integration, equivalence-oracle), and the cross-language surface (Rust FFI, JS, Python) handles ownership and lifetimes correctly. No blocking issues. |
apply_set_loop_name matched an existing LoopMetadata by variable/UID set without checking `deleted`, and on a match updated the label but left `deleted` untouched. A LoopMetadata can be soft-deleted (a user removing a loop name, or a deserialized project carrying `deleted: true`), and the consumers that act on pins filter deleted entries out (`pinned_loops_from_datamodel` for loop-score emission, `build_uid_to_loop_name` for the name display). So re-pinning a previously-deleted loop via SetLoopName silently had no effect -- no loop_score was emitted and the name did not reappear. SetLoopName means "name/pin this loop", so it now clears `deleted` when updating a matched entry, reviving it. Addresses the Codex review comment on PR #648.
Code review[P2]
|
Summary
A cluster of Loops That Matter (LTM) usability and correctness improvements, motivated by an experience report driving LTM through
pysimlinon the C-LEARN v77 model. Six focused commits:IndexedSearch(integer-indexed graph + once-per-timestep edge sort, replacing the per-visit-sort/HashMap hot loop), plus an optional wall-clock budget onanalyze_model/discover_loops_with_graphso a long discovery returnstruncatedinstead of hanging.simlin_analyze_discover_loopsreturning discovered loops (with per-step importance), dominant periods, and a truncated flag from one analysis run.Model.analyzefor opt-in loop discovery —Model.analyze(timeout=None) -> Analysis(deliberately separate fromrun(), since discovery can be slow on large models). Also stopsLink/Loopscore aggregates from leaking numpy "Mean of empty slice" warnings on all-NaN series.Run.ltm_mode(exhaustive/discovery/disabled), andget_links(include_internal=False)collapses macro/module-internal$⁚…nodes into compositeX -> Yedges that carry the composite (largest-magnitude path) link score, preserving the through-contribution (LTM ref 6.3/6.4).build_submodel_metadatanow registers the sub-model's LTM synthetic vars so the composite reference resolves.SetLoopName/LoopMetadataprimitive (no new equation builtin): a pinned loop is always scored, including in discovery mode where nothing else is.model_detected_loopsandmodel_ltm_variablesnow share onemodel_ltm_modequery so they can't disagree on the discovery gate.Notes / follow-ups
loop_scoreis the informative series — documented on the relative-score APIs.Test plan
Run.ltm_modeboundary tests,collapse_synthetic_linksunit tests, the ltm: composite-reference link score into a stdlib-macro module fails to compile in exhaustive mode, so loops through SMOOTH/DELAY stub to 0 #548 SMOOTH/DELAY characterization tests (flipped to assert the contribution now flows), and pinned-loop tests (incl. the discovery-mode pinned-score escape hatch and invalid-pin diagnostics).Model.analyze,Run.ltm_mode,get_links(include_internal=...), andset_loop_nameon a real model.