Repository navigation
ltm: surface loop polarity variants, confidence, partitions, and truncation signal across all consumers (#488) - #732
Conversation
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
Codecov Report❌ Patch coverage is
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. 🚀 New features to boost your workflow:
|
Review of PR #732Comprehensive 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
|
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)
agg_recovery_truncated(discovery's cross-agg-loop-recovery completeness signal) now reachesSimlinDiscoveryResult, pysimlinAnalysis, 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.MostlyReinforcing/MostlyBalancing(Rux/Bux) added toSimlinLoopPolarity, andpolarity_confidence: f64added toSimlinLoop/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(LoopPolarityenum +Loop.polarityConfidence), pysimlin, and the MCPLoopDominanceSummary.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 FFIsimlin_analyze_get_loops_runtime(sim)that reclassifies exhaustive loops to their runtime Rux/Bux/U label + confidence. The structuralsimlin_analyze_get_loops(model)stays as the no-sim primitive; a shareddetected_loops_to_ffihelper keeps the two surfaces from drifting.partitionon engineDetectedLoop(+ apartitionslist onDetectedLoopsResult),SimlinLoop.partition+SimlinLoops.partitions, pysimlinModel.loop_partitions/Loop.partition, and MCPLoopDominanceSummary.partition. Computed from the samecompute_cycle_partitions/partition_for_loopmachinery the discovery surface uses.Already-fixed issues closed
While surveying #488 I confirmed three issues were already resolved on
mainby 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
SimlinLoopABI into one PR avoids repeated ABI churn (that shared ABI bump is what makes them one cluster).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.simlin_analyze_get_loops_runtime(sim)rather than overloading the structuralsimlin_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 mirrorssimlin_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.Run.loopsvia a Python slot-0 reimplementation plus a separateRun.loops_runtimevia the engine),Run.loopsnow sources polarity/confidence/partition from the engine primitive and attaches the behavior series on top. RemovedRun.loops_runtimeand the parallel Python reclassification path; keptLoopPolarity.from_runtime_scoresonly 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.pop); discovery at element granularity (pop[nyc]) -- because they run on different graphs, and a variable-levelDetectedLoopmust 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.SimlinLoopwent 20 -> 32 (polarity_confidence f64 @24) -> 40 (partition i32 @32), additively each step;SimlinLoops/SimlinDiscoveryResultgrew in trailing fields. All gated at runtime by@simlin/engine'svalidateStructSizesagainstsimlin_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