Skip to content

ltm: surface loop polarity variants, confidence, partitions, and truncation signal across all consumers (#488) - #732

Merged
bpowers merged 7 commits into
mainfrom
ltm-ffi-parity-488
Jun 8, 2026
Merged

bpowers merged 7 commits into
mainfrom
ltm-ffi-parity-488

Conversation

@bpowers

@bpowers bpowers commented Jun 8, 2026

Copy link
Copy Markdown
Owner

Summary

LTM (Loops That Matter) epic #488 follow-up. The Rust engine computes rich loop analysis -- runtime polarity (incl. the Rux/Bux "mostly reinforcing/balancing" variants) with a confidence value, cycle-partition membership, and a cross-agg-recovery truncation flag -- but most of it died at the Rust boundary and never reached the C-FFI / WASM / TypeScript / pysimlin / diagram / MCP consumers. This PR surfaces it consistently across the stack: the engine already knew; now the consumers can see it.

Fixes #495, #679, #685, #701.

What landed (one commit per issue, then two cleanups)

  • ltm: discovery results do not say when cross-SUM loop finding was cut off #701 -- agg_recovery_truncated (discovery's cross-agg-loop-recovery completeness signal) now reaches SimlinDiscoveryResult, pysimlin Analysis, and the MCP analyze output. Previously only exhaustive mode surfaced its analogue (via a salsa Warning), so a discovery caller -- exactly the regime large auto-flipped models fall into -- got an incomplete loop list with no signal.
  • ltm: surface MostlyReinforcing/MostlyBalancing in JSON/TS/WASM layers #495 -- MostlyReinforcing/MostlyBalancing (Rux/Bux) added to SimlinLoopPolarity, and polarity_confidence: f64 added to SimlinLoop/SimlinDiscoveredLoop. The FFI no longer coalesces Rux/Bux down to R/B or drops the confidence. Threaded the discovery confidence through the engine (FoundLoop/LoopSummary) and plumbed all the way to @simlin/engine (LoopPolarity enum + Loop.polarityConfidence), pysimlin, and the MCP LoopDominanceSummary.
  • ltm: exhaustive-mode loops never get runtime polarity reclassification (Rux/Bux unreachable) #679 -- reclassify_loops_from_results (added by PR ltm: discovery-mode correctness fixes from deep review #705 with no production caller) gets one: a new sim-bearing FFI simlin_analyze_get_loops_runtime(sim) that reclassifies exhaustive loops to their runtime Rux/Bux/U label + confidence. The structural simlin_analyze_get_loops(model) stays as the no-sim primitive; a shared detected_loops_to_ffi helper keeps the two surfaces from drifting.
  • ltm: exhaustive and pinned loop results lack cycle partition info #685 -- cycle-partition metadata now rides the exhaustive/pinned surfaces too: partition on engine DetectedLoop (+ a partitions list on DetectedLoopsResult), SimlinLoop.partition + SimlinLoops.partitions, pysimlin Model.loop_partitions/Loop.partition, and MCP LoopDominanceSummary.partition. Computed from the same compute_cycle_partitions/partition_for_loop machinery the discovery surface uses.
  • cleanup (review): corrected an over-claimed cross-surface invariant (see decisions) and pinned the real arrayed behavior with a test.
  • cleanup (consolidation): collapsed pysimlin's runtime loop surface onto the engine source of truth (see decisions).

Already-fixed issues closed

While surveying #488 I confirmed three issues were already resolved on main by PR #705 (commit 26a641e) and closed them with verification notes: #696 (discovery cross-agg reducer-loop recovery), #698 (discovery wrong polarity through multi-output modules), #699 (overstated zero-edge-exclusion claim + stale test comment).

Decisions made

  1. Cluster choice. With PR ltm: discovery-mode correctness fixes from deep review #705 having just cleared the discovery-mode correctness gaps, the biggest remaining coherent cluster was this FFI/parity surfacing theme -- repeated across ltm: surface MostlyReinforcing/MostlyBalancing in JSON/TS/WASM layers #495/ltm: exhaustive-mode loops never get runtime polarity reclassification (Rux/Bux unreachable) #679/ltm: exhaustive and pinned loop results lack cycle partition info #685/ltm: discovery results do not say when cross-SUM loop finding was cut off #701/simlin-mcp-core: LTM diagnostics never surface (collect_all_diagnostics runs with ltm_enabled=false) #662/ltm: get_links reports only the first element's link score for arrays #665. Batching the four that share the SimlinLoop ABI into one PR avoids repeated ABI churn (that shared ABI bump is what makes them one cluster).
  2. ltm: surface MostlyReinforcing/MostlyBalancing in JSON/TS/WASM layers #495 diagram rendering deferred to diagram: show feedback loops and their polarity in the editor #731. src/diagram/ has no existing loop-polarity consumer, so rendering Rux/Bux (the LTM-reference "confidence-gray" treatment) is net-new feature/design work, not parity plumbing. The FFI/WASM/TS/pysimlin/MCP plumbing (items 1, 2, 4 of ltm: surface MostlyReinforcing/MostlyBalancing in JSON/TS/WASM layers #495) is complete and the data is now available to the diagram via @simlin/engine; the visual treatment is tracked in diagram: show feedback loops and their polarity in the editor #731.
  3. ltm: exhaustive-mode loops never get runtime polarity reclassification (Rux/Bux unreachable) #679 API shape. Added a sim-bearing simlin_analyze_get_loops_runtime(sim) rather than overloading the structural simlin_analyze_get_loops(model) with a nullable sim -- two orthogonal primitives (structural-from-model, runtime-from-sim) read cleaner than one toggled by a NULL pointer, and it mirrors simlin_analyze_get_links(sim, ...) already taking a sim. The runtime primitive classifies over all element slots of an arrayed loop (the engine's documented semantics), which is more representative than any single element.
  4. pysimlin consolidated to one runtime loop surface. The project has no out-of-tree consumers and owes no API/ABI stability, so rather than keep a duplicate (Run.loops via a Python slot-0 reimplementation plus a separate Run.loops_runtime via the engine), Run.loops now sources polarity/confidence/partition from the engine primitive and attaches the behavior series on top. Removed Run.loops_runtime and the parallel Python reclassification path; kept LoopPolarity.from_runtime_scores only as a standalone pure utility. Scalar loop behavior is unchanged; arrayed loops are now labeled by whole-loop (all-slots) behavior instead of slot 0.
  5. ltm: exhaustive and pinned loop results lack cycle partition info #685 partition granularity is per-surface, and that's correct. The exhaustive/pinned surface partitions at variable granularity (pop); discovery at element granularity (pop[nyc]) -- because they run on different graphs, and a variable-level DetectedLoop must carry a variable-level partition to stay internally consistent. The partition stock-SET is therefore a reliable cross-surface key only for scalar models. An earlier draft over-claimed cross-surface identity for any model; the docs are corrected and an arrayed test (exhaustive_and_discovery_partitions_diverge_in_granularity_arrayed) pins the actual divergence so the contract is tested, not just asserted.
  6. ABI grown freely. SimlinLoop went 20 -> 32 (polarity_confidence f64 @24) -> 40 (partition i32 @32), additively each step; SimlinLoops/SimlinDiscoveryResult grew in trailing fields. All gated at runtime by @simlin/engine's validateStructSizes against simlin_sizeof_loop(). None of these are protobuf, so there's no serialized-format obligation.

Verification

Every commit passed the full pre-commit suite (Rust fmt/cbindgen-freshness/clippy/test, TypeScript lint/build/tsc/test incl. the WASM-backed struct-size validation, pysimlin). The work was implemented by a series of focused sub-agents (one per issue), then put through two independent adversarial review passes; the first found one Important issue (the cross-surface over-claim, decision 5) which was fixed, the second (over the consolidation) returned MERGE-READY. Memory-safety of the new FFI allocations (the partitions array + per-partition stock CStrings, alloc/free pairing on every error path) was specifically audited.

🤖 Generated with Claude Code

bpowers added 7 commits June 8, 2026 12:27
Discovery mode computes a cross-element-through-aggregate reducer-loop
recovery budget (GH #696) and records on ModelAnalysis whether it clipped
some cross-agg loops, but that flag never reached FFI/pysimlin/MCP
consumers. Exhaustive mode surfaces its analogue via a salsa Warning, so
discovery callers were the only ones with NO structural-completeness
signal -- they saw the wall-clock truncated flag but not whether the loop
set was structurally complete. This closes that asymmetry.

Purely additive: a new agg_recovery_truncated bool rides after the
existing time-budget truncated flag on SimlinDiscoveryResult (not
ABI-size-tracked, so free), is populated from ModelAnalysis, regenerated
into simlin.h, and flows to pysimlin Analysis and the MCP read/edit
analyze output (elided from the wire shape when false to keep the stable
JSON byte-identical for the common case). The meaning of truncated is
unchanged.

Refs GH #701.
…M/TS/pysimlin/MCP

The Rust engine already computes 5-variant loop polarity (Reinforcing,
Balancing, MostlyReinforcing/Rux, MostlyBalancing/Bux, Undetermined) and a
polarity-confidence ratio, but the C-FFI/WASM/TS layers coalesced the Mostly*
variants down to R/B and dropped the confidence entirely. This stops the
coalescing and threads the confidence additively all the way out (GH #495).

Engine: FoundLoop now carries polarity_confidence (captured from
from_runtime_scores; for a loop with no runtime scores it mirrors the
structural convention db::analysis uses -- 1.0 when the structural polarity is
determined, 0.0 when Undetermined). LoopSummary carries it through to the
analysis surface.

libsimlin: SimlinLoopPolarity gains MostlyReinforcing=3/MostlyBalancing=4, and
both SimlinLoop and SimlinDiscoveredLoop gain polarity_confidence: f64.
simlin_analyze_get_loops and the discovery path now map all five variants 1:1.
The SimlinLoop ABI grew additively: the 8-byte-aligned f64 lands at offset 24,
so sizeof went from 20 to 32 bytes on wasm32 (regenerated simlin.h; the
@simlin/engine LOOP_SIZE/readLoops offsets and validateStructSizes track it).

@simlin/engine, pysimlin, and MCP all expose the new field; the discovery
surface is the high-value one (Rux/Bux actually appear there from runtime
scores), while the structural surface is 1.0/0.0 by design.

Diagram rendering of Rux/Bux is deliberately deferred -- the diagram has no
existing loop-polarity consumer, so this only makes the data available.
… loops)

`reclassify_loops_from_results` (the LTM papers' Rux/Bux/U runtime
classification with the 0.99 confidence gate) had no production caller
since PR #705 added it -- the exhaustive loops surface
`simlin_analyze_get_loops` takes only a `SimlinModel`, so it can only
ever report the STRUCTURAL polarity (R/B at confidence 1.0, U at 0.0)
and can never express a runtime sign flip even when a loop's post-sim
`loop_score` series genuinely straddles zero.

Add `simlin_analyze_get_loops_runtime(sim, out_error)`: it builds the
same exhaustive `model_detected_loops` set, recovers `loop_partitions`
via `recompute_ltm_snapshots` (the LtmEnabledGuard toggle the
rel-loop-score-from-wasm twin already uses), runs the engine primitive
over the completed sim's `Results`, and marshals through the new shared
`detected_loops_to_ffi` helper that `simlin_analyze_get_loops` now also
uses -- so the structural and runtime surfaces present a loop
identically and can only differ in how the polarity was computed. This
is the primitive's first production caller and the only path on which
the exhaustive surface can report Rux/Bux. `simlin_analyze_get_loops`
stays unchanged (structural).

The engine primitive concatenates ALL element slots of an arrayed
(A2A) loop's `loop_score` before classifying, which differs from
pysimlin `Run.loops`'s slot-0-only reclassification (they agree on
scalar loops). Rather than reroute `Run.loops` through the all-slots
primitive (which would change A2A behavior and risk the #705 regression
test), pysimlin binds the new FFI as a separate `Sim.get_loops_runtime`
/ `Run.loops_runtime` accessor and documents the divergence.

References GH #679.
…rfaces

The DISCOVERY loop surface already carries per-loop cycle-partition metadata
(FoundLoop.partition / DiscoveryResult.partitions and their FFI/pysimlin/MCP
mirrors), but the EXHAUSTIVE/PINNED surface did not -- even though the engine
already computes the per-loop cycle partition. Surface it on
SimlinLoop/simlin_analyze_get_loops (+ its runtime sibling), pysimlin
Model.loops/Model.loop_partitions/Run.loops, and the MCP
LoopDominanceSummary/analyze output.

model_detected_loops now computes the cycle partitions over the SAME
module-aware causal graph it enumerates on and attaches a single
partition: Option<usize> per DetectedLoop plus a DetectedLoopsResult.partitions
list, via resolve_loop_partitions -- a mirror of ltm_finding's
attach_partition_metadata (first-appearance dense remap, reusing
DiscoveredPartition). A single index suffices because a feedback loop's stocks
form one strongly-connected set. The two surfaces are consistent by
construction: they report the SAME partition STOCK SETS for a given model
(the durable cross-surface identity, since the dense indices are
result-scoped and renumber on edits). Cross-surface agreement is pinned by
tests in db/analysis.rs, test_model.py, and test_discovery.py keyed on the
stock set.

ABI: SimlinLoop grows additively (partition i32 at offset 32; wasm32
simlin_sizeof_loop 32 -> 40, LOOP_SIZE 40), and SimlinLoops grows in trailing
fields only (partitions + partition_count appended after loops/count) so the
TS container's existing offsets are unchanged. validateStructSizes enforces
the new size. The MCP half needs no engine/FFI change -- analyze_model's
ModelAnalysis already carried partition/partitions; only the wire types
dropped them.

Reference GH #685.
…-model behavior

The exhaustive/pinned loop surface (model_detected_loops ->
compute_cycle_partitions over causal_graph_with_modules) computes cycle
partitions at VARIABLE granularity (stocks pop, prey), while the discovery
surface (ltm_finding over the element-level graph) computes them at ELEMENT
granularity (pop[nyc]). So the two surfaces' partition stock SETS match exactly
only for SCALAR models; for arrayed (A2A) models they differ in granularity.
Several doc sites over-claimed a durable cross-surface stock-set identity that
holds for any model. Corrected every such claim (the DetectedLoop/
DetectedLoopsResult rustdocs, the SimlinLoop/SimlinLoops FFI docs, libsimlin and
engine CLAUDE.md, the mcp-core PartitionOutput/ReadModelOutput docs, and the
pysimlin loop_partitions docstring) to scope it to scalar models and explain
why (the two surfaces run on different graphs). simlin.h regenerated to match
the updated FFI doc comments.

Finding 2: resolve_loop_partitions's comment implied the .flatten().next()
collapse handled "an A2A loop whose slots share the parent partition". In fact
every exhaustive ltm::Loop is built with dimensions: vec![], so
partition_for_loop always takes the single-slot scalar branch; the collapse is
trivially correct because multi-slot loops never reach this path. Comment fixed.

Renamed the scalar agreement test to ..._scalar and scoped its rustdoc, and
added exhaustive_and_discovery_partitions_diverge_in_granularity_arrayed
(plus the pysimlin docstring scoping) which pins the granularity divergence on
an A2A SUM-coupled model: the exhaustive partition names bare population while
discovery names population[nyc]/population[boston]. The test fails if someone
later changes one surface's granularity to match the other without updating the
documented contract.

GH #685
…e of truth

Run.loops now sources each loop's polarity / polarity_confidence / partition
directly from the engine reclassification primitive (Sim.get_loops_runtime ->
reclassify_loops_from_results), attaching the per-step relative-loop-score
behavior series on top. The redundant Run.loops_runtime accessor and the
parallel Python slot-0 reclassification (LoopPolarity.from_runtime_scores in the
loop path) are removed, so there is a single authoritative runtime loop surface
backed by the Rust engine rather than two that disagreed on arrayed loops.

For scalar loops the all-slots engine classification is identical to the old
slot-0 path; for arrayed (A2A) loops Run.loops is now labeled by the whole
loop's behavior across every element slot (the more representative result)
rather than slot 0. Since the project has no out-of-tree consumers and does not
owe API/ABI stability, this simplification is free.

LoopPolarity.from_runtime_scores is kept as a standalone pure utility (it
classifies an arbitrary score array and is independently tested) but is no
longer the loop-reclassification path, so engine logic is not silently mirrored
for the authoritative surface. Sim.get_loops_runtime stays as the composable
per-sim FFI primitive Run.loops builds on.

GH #679 GH #685
…ack contract

The Run.loops docstring and the LTM-skip warning claimed the surface is empty
when LTM is disabled. In fact Run.loops flows through model_detected_loops
(structural, no LTM dependency), so with LTM off it returns the model's
structural loops with structural polarity and no behavior_time_series; it is
empty only when the model has no enumerable loops. Corrected both texts and
strengthened test_run_loops_property_without_ltm from a vacuous isinstance check
to pin that Run.loops matches Model.loops by id and structural polarity with
behavior_time_series None.

GH #679
@bpowers bpowers mentioned this pull request Jun 8, 2026
1 of 29 tasks
@codecov

codecov Bot commented Jun 8, 2026

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 85.71429% with 64 lines in your changes missing coverage. Please review.
✅ Project coverage is 90.60%. Comparing base (cac628b) to head (8b5df0b).
⚠️ Report is 1 commits behind head on main.

Files with missing lines Patch % Lines
src/libsimlin/src/analysis.rs 71.83% 40 Missing ⚠️
src/simlin-engine/src/db/analysis.rs 92.60% 19 Missing ⚠️
src/simlin-engine/src/ltm_finding.rs 37.50% 5 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main     #732      +/-   ##
==========================================
- Coverage   90.61%   90.60%   -0.01%     
==========================================
  Files         224      224              
  Lines      135889   136247     +358     
==========================================
+ Hits       123136   123447     +311     
- Misses      12753    12800      +47     

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@claude

claude Bot commented Jun 8, 2026

Copy link
Copy Markdown

Review of PR #732

Comprehensive parity work surfacing LTM polarity variants, confidence, partitions, and the agg-recovery truncation signal across the FFI/WASM/TS/pysimlin/MCP stack. The plumbing is largely clean and the test coverage of cross-surface invariants is thorough. A handful of issues worth flagging:


[P2] Docstring claim that runtime FFI requires enable_ltm=true contradicts actual behavior

File: src/libsimlin/simlin.h lines 380-383, src/libsimlin/src/analysis.rs lines 549-552, and src/pysimlin/simlin/sim.py lines 359-360.

The C header and Python docstring both state: "Requires sim to have been created with enable_ltm = true and run to completion (it must hold Results); otherwise an error is reported through out_error." This contradicts the very next sentence ("When LTM was not enabled the loop_score series are absent, so the result degenerates to the structural classification") and the actual behavior verified by test_runtime_loops_empty_without_ltm (an enable_ltm=False sim returns the structural classification without error). The actually enforced requirement is just that Results are present (sim has been run). Users reading the C header are likely to wrap unnecessary error handling around the LTM-disabled path.


[P2] A2A pinned loops silently lose partition assignment on the exhaustive surface

File: src/simlin-engine/src/db/analysis.rs lines 1697-1745 (resolve_loop_partitions).

The docstring asserts: "Every loop that reaches this exhaustive surface is constructed single-slot (Loop.dimensions is always vec![] here -- the enumerated loops are built that way in ltm::graph and the pinned ones are element-subscripted scalar loops)." This is not true for PureSameElementA2A pinned loops. build_a2a_pin_loop (in src/simlin-engine/src/db/ltm/pinned.rs:382-405) produces a Loop with non-empty dimensions AND element-level stock names like pop[nyc]. When resolve_loop_partitions calls partitions.partition_for_loop(l, dims), the A2A branch in partition_for_loop (src/simlin-engine/src/ltm/partitions.rs:169-193) looks up element-subscripted names like pop[nyc] in stock_partition -- but compute_cycle_partitions was run over the variable-level causal_graph_with_modules, so stock_partition is keyed by bare variable names (pop). The lookup misses for every slot, .flatten().next() returns None, and the pin ends up with partition: None and is absent from DetectedLoopsResult.partitions. Stripping the element subscript before the lookup (or routing PureSameElementA2A pins through the scalar branch keyed on pop) would close it. Not exercised by the new tests (pinned_loop_carries_cycle_partition_in_discovery_mode uses a scalar pin).


[P3] Stale references to removed Run.loops_runtime in rustdoc

File: src/simlin-engine/src/db/analysis.rs lines 2038 and 2065.

Per PR decision 4 the pysimlin consolidation removed Run.loops_runtime; Run.loops is now built directly on the engine all-slots primitive. The rustdoc for reclassify_loops_from_results still describes the divergence as "pysimlin surfaces it as Run.loops_runtime, keeping the slot-0 Run.loops path unchanged" -- this contradicts the final pysimlin state and the libsimlin CLAUDE.md ("there is no separate slot-0 reclassification path").


Overall correctness

The patch is largely correct. The misleading enable_ltm=true doc and the stale Run.loops_runtime reference are pure documentation drift. The A2A pinned-loop partition gap is a latent functional issue confined to a specific (untested) configuration -- a modeler pinning a PureSameElementA2A loop -- but it does silently produce wrong output (partition: None instead of the variable-level SCC index). None of these are merge-blocking.

@bpowers
bpowers merged commit d42c8a7 into main Jun 8, 2026
14 of 15 checks passed
@bpowers
bpowers deleted the ltm-ffi-parity-488 branch June 8, 2026 22:02
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.

ltm: surface MostlyReinforcing/MostlyBalancing in JSON/TS/WASM layers

1 participant