Skip to content

LTM usability: discovery exposure, mode visibility, #548 fix, loop pinning - #648

Merged
bpowers merged 7 commits into
mainfrom
ltm-discovery-and-pinning
Jun 1, 2026
Merged

bpowers merged 7 commits into
mainfrom
ltm-discovery-and-pinning

Conversation

@bpowers

@bpowers bpowers commented Jun 1, 2026

Copy link
Copy Markdown
Owner

Summary

A cluster of Loops That Matter (LTM) usability and correctness improvements, motivated by an experience report driving LTM through pysimlin on the C-LEARN v77 model. Six focused commits:

  • engine: speed up and budget-guard LTM loop discovery — IndexedSearch (integer-indexed graph + once-per-timestep edge sort, replacing the per-visit-sort/HashMap hot loop), plus an optional wall-clock budget on analyze_model/discover_loops_with_graph so a long discovery returns truncated instead of hanging.
  • libsimlin: expose budget-guarded loop discovery via FFI — simlin_analyze_discover_loops returning discovered loops (with per-step importance), dominant periods, and a truncated flag from one analysis run.
  • pysimlin: add Model.analyze for opt-in loop discovery — Model.analyze(timeout=None) -> Analysis (deliberately separate from run(), since discovery can be slow on large models). Also stops Link/Loop score aggregates from leaking numpy "Mean of empty slice" warnings on all-NaN series.
  • engine,bindings: report LTM mode and collapse macro/module-internal links — Run.ltm_mode (exhaustive/discovery/disabled), and get_links(include_internal=False) collapses macro/module-internal $⁚… nodes into composite X -> Y edges that carry the composite (largest-magnitude path) link score, preserving the through-contribution (LTM ref 6.3/6.4).
  • engine: flow macro composite into exhaustive-mode loop scores (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) — fixes a correctness hole where a feedback loop through a stdlib macro (SMOOTH/DELAY/TREND/NPV) was silently scored 0 in exhaustive mode; build_submodel_metadata now registers the sub-model's LTM synthetic vars so the composite reference resolves.
  • engine,bindings: pin feedback loops so they are always scored — the LTM papers' LOOPSCORE escape hatch via the existing SetLoopName/LoopMetadata primitive (no new equation builtin): a pinned loop is always scored, including in discovery mode where nothing else is. model_detected_loops and model_ltm_variables now share one model_ltm_mode query so they can't disagree on the discovery gate.

Notes / follow-ups

Test plan

bpowers added 6 commits May 31, 2026 13:44
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.

@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

if let Some(existing) = model.loop_metadata.iter_mut().find(|lm| {
let mut existing_uids = lm.uids.clone();
existing_uids.sort();
existing_uids == uids
}) {
existing.name = name;
existing.description = description.unwrap_or_default();

P2 Badge Undelete matching loop metadata when renaming

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

@claude

claude Bot commented Jun 1, 2026

Copy link
Copy Markdown

Review

Reviewed all 47 changed files (~5.5k additions, ~150 deletions) across the six commits.

The work is cohesive and well-tested:

  • IndexedSearch optimization is locked in against the retained SearchGraph reference via an equivalence-oracle test across multiple seeds; the per-step budget check is correctly hoisted out of the DFS.
  • The model_ltm_mode factoring genuinely unifies the discovery gate across model_ltm_variables and model_detected_loops, with the user-forced-discovery-on-small-model regression locked in (user_forced_discovery_suppresses_enumeration_on_small_model, user_forced_discovery_on_small_model_surfaces_pin).
  • collapse_synthetic_links correctly handles the (Unknown, None) sentinel hazard (collapse_folds_two_disagreeing_structural_paths_to_unknown).
  • 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 fix in build_submodel_metadata is exercised by both an existence assertion (smooth_macro_composite_flows_into_parent_loop_score_gh548) and a separate non-degenerate-varies assertion (macro_in_loop_score_varies_over_run_gh548).
  • Pinned-loop FFI surface frees all owned strings/arrays correctly; the (Unknown, None)-as-sentinel hazard in pick_stronger_polarity is the right kind of subtle bug to pin with a regression test.

Nothing rises to the level of an actionable correctness bug worth flagging. A few minor cosmetic observations not worth blocking on:

  • simlin_analyze_discover_loops gracefully handles a poisoned datamodel lock but .unwrap()s the db lock — inconsistent with the gracefully-handled twin, but matches the rest of libsimlin's panic-on-poison pattern.
  • The test name pinned_loop_emits_loop_score_for_distinct_cycle actually exercises the dedup path (the inner comment acknowledges this).

Overall correctness verdict

Correct. 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.
@claude

claude Bot commented Jun 1, 2026

Copy link
Copy Markdown

Code review

[P2] SimlinDiscoveredLoop.variables doc contradicts the new engine behavior

File: src/libsimlin/src/ffi.rs:143-145 (and the generated src/libsimlin/simlin.h:156-158)

The struct comment promises a closed chain:

Variable names around the loop, with the first variable repeated at the end so the chain closes. var_count entries.

But the new loop_variables in src/simlin-engine/src/analysis.rs:276-288 deliberately drops the trailing repeat to match the structural-loop convention — and that vector flows verbatim through to_loop_summary → LoopSummary::variables → discovery_to_ffi into SimlinDiscoveredLoop.{variables, var_count}. So a 2-node cycle now ships [A, B] with var_count = 2, not [A, B, A] with var_count = 3 as the comment (and the cbindgen-generated C header) advertises. Python's Loop.__str__ and pysimlin/tests/test_discovery.py::test_discovered_loop_variables_have_no_trailing_repeat confirm the no-repeat behavior is the intended one. C/Rust consumers reading the header to render or close the cycle themselves will double the closing node or under-iterate; please update the doc on SimlinDiscoveredLoop (and re-run cbindgen) to describe the bare node sequence.

  // Deterministic loop id (`r1`, `b1`, `u1`, ...).
  pub id: *mut c_char,
  /// Variable names around the cycle (each link's `from`), without a
  /// trailing repeat of the first variable. `var_count` entries. Consumers
  /// that render the closed chain should append `variables[0]` themselves;
  /// this matches the structural-loop convention used by `SimlinLoop`.
  pub variables: *mut *mut c_char,

Overall correctness

Correct. The discovery rewrite (IndexedSearch + reusable DfsScratch) mirrors the SearchGraph oracle behavior step for step (per-stock best_score reset, strict-less-than pruning, stable score-descending sort, canonical-rotation dedup on u32 rather than String); the optional budget is checked at the top of each timestep so per-step loop sets stay internally consistent and Some(Duration::ZERO) exits before any DFS work. SimState correctly captures ltm_mode / loop_partitions / loop_element_index while the db lock is held and ltm_enabled is still set, the include_internal=false collapse routes through the engine's collapse_synthetic_links (so VM and wasm-backed FFIs share one impl), and pinned loops surface in both modes via the shared model_ltm_mode gate. The only blocking issue I found is the documentation drift above.

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.

1 participant