Skip to content

engine: exact LTM discovery with a shortest-path fallback - #1023

Merged
bpowers merged 55 commits into
mainfrom
ltm-discovery-enumeration
Aug 20, 2026
Merged

bpowers merged 55 commits into
mainfrom
ltm-discovery-enumeration

Conversation

@bpowers

@bpowers bpowers commented Aug 18, 2026 •

Copy link
Copy Markdown
Owner

LTM discovery: exact enumeration as the sole primary path, shortest-path fallback

Discovery-mode LTM finds the loops that matter after a simulation by generating candidate cycles from the recorded link-score series, scoring each candidate exactly, then retaining, ranking and capping the result. Only candidate generation was ever lossy, and it was lossy silently: the per-step strongest-first DFS saturated its per-node expansion cap on World3 without saying so, and the loops it dropped were not a characterizable set. A ground-truth audit found the births -> population-aging family, which peaks at 27% partition dominance, entirely absent from a report that still looked full at 200 loops (47/200 overlap with the true top-200; the step-dominant loop missing at 57% of steps).

This finishes the transition begun by docs/design-plans/2026-08-10-ltm-discovery-union-enumeration.md and implements docs/design-plans/2026-08-17-ltm-discovery-exact.md:

  • The union-graph enumeration is the only exact generator. It emits the full universe of ever-simultaneously-active elementary cycles at saved-step resolution (min-root Tiernan with per-root induced SCC and activity-bitset pruning, edge-row emission, contiguous per-edge score rows, single-pass retention with a bound and a confirm step), and every downstream statistic -- retention denominators, competing-vs-solo classification, relative scores -- is computed against that universe.
  • The DFS is deleted and replaced by a shortest-path fallback: per (seed, saved step) forward and reverse Dijkstra over w = max(0, -ln|link score|) with every-edge closures, used when the enumeration's budgets or the caller's deadline trip. The wall-clock budget contract (partial results plus truncated) is preserved and re-tested independently of the deleted code, with one test arm per clock-read site in every phase.
  • The pipeline is cheap, robust and coverage-aware. World3 end-to-end discovery goes from 5.2 s to 0.40 s in release; NaN/Inf products, module-override mass and reported-cycle dedup are handled in the denominators; the MAX_LOOPS cap guarantees each step's dominant loop per competing partition a slot (World3 step-dominant coverage 382/399 -> 399/399).
  • Completeness is observable end to end: enumeration_complete, retained_loops and universe_loops reach libsimlin (simlin.h), pysimlin Analysis, and the MCP read/edit outputs.

Non-obvious decisions

  • Self-loops are not loops. A one-variable cycle is not feedback in the SD sense and the exhaustive enumerator already contracted circuit.len() > 1; the two surfaces must agree on what a loop is. Since an elementary cycle never repeats a node, a self-edge can never be part of a longer one, so self-edges are dropped at graph-build time. This is why C-LEARN's reported count falls 200 -> 153: 48 of the old 200 were PREVIOUS-latch self-loops (and they had displaced a real stock-decay loop under the cap).
  • A partial enumeration is discarded, not merged with the fallback. It is biased by node-id root order and cannot supply universe denominators; the fallback is the principled sample.
  • The budget splits 50/50 (ENUM_BUDGET_FRACTION): the two phases are sequential and only the second yields partial results, so an undivided budget is one the fallback never sees.
  • Fallback strategy chosen by measurement (examples/ltm_fallback_eval, four axes): every-edge closures are the lever (C-LEARN recall@153 97 -> 150, World3 top-200 recall 8 -> 31); AllSccNodes seeding did not earn its 2.5x cost; ShiftedLogAbs (keeping the gain the clamp discards) measured worse because the per-hop ln(max) term dwarfs the product term and the arm degenerates into a hop count -- kept selectable as a documented negative result; the tie-break axis is measurement-neutral and Hops stays for what it does inside the zero-weight plateau.
  • Anchor escalation is bounded by ANCHOR_SHARE_OF_CAP (one half). k = 1 is the guarantee; unbounded escalation anchored 140 of World3's 200 slots and crowded out the ranking claim; the bound settles at k = 2 (96 anchors).
  • Competing-vs-solo uses the universe. A retention non-survivor still holds mass in its partition's denominator, so it still makes that partition a place where loops compete; the loop counts follow the same corrections as the mass they accompany.
  • Retention is exact for every candidate, on its reported series. Module-traversing circuits are scored through the same per-exit-port ModuleOverrideCache materialization reads; circuits that trim to the same reported cycle (a direct pathway and its hoisted-reducer twin) are grouped by trimmed identity before any mass is banked and only the strongest representative counts; stitched cross-aggregate loops are pushed into the candidate set BEFORE retention so the same dedup, bank/confirm and universe count cover them. Nothing is added to or subtracted from a partition total after the fact.
  • Module-input edge activity is read through the composite's NaN shadow. A module composite's max-abs fold can be NaN where one exit pathway is finite; edges entering a module carry their pathway slots and are active where any pathway is, while the score row keeps the recorded composite so retention never banks a value materialization cannot report.
  • Memory is bounded by ONE meter across every phase (MAX_DISCOVERY_MEMORY_BYTES, 768 MB, held by a MemoryMeter each allocating phase charges BEFORE it allocates and yields to when refused): the union graph's rows and bitsets (scratch row included), each enumerated and stitched circuit's edge rows (the count bound MAX_DISCOVERY_ENUM_EDGE_ROWS stays as a volume bound), the retention survivors' future FoundLoop series (charged before materialization; an enumeration whose report would not fit yields to the fallback with enumeration_complete == false), the module-override cache's series and shared Rc<[usize]> pathway slices, and every fallback kept path and stitched loop (MAX_FALLBACK_PATHS = 20,000 stays as the count bound). An abandoned enumeration releases its charge so the fallback is measured against the whole bound. Per-phase byte caps were the design this replaced -- each bounded its own allocation in isolation and the review history kept finding allocations outside all of them. Solo survivors: retention keeps the strongest MAX_LOOPS while retained_loops counts them all. Partition totals accumulate saturating; the finite-overflow regime is a stated boundary, not a silent cascade.
  • Every phase is deadline-aware (activity build in value blocks, the union SCC pass, per-root pruning, enumeration visits, retention work in edge-steps, the fallback's step rebuild, searches, and closure scans), and an unbudgeted call never reads the clock.
  • enumerationComplete and retainedLoops are always serialized on MCP, unlike aggRecoveryTruncated: here the interesting value is false, and a client that cannot see the field reads a sample as exhaustive. universeLoops is optional and elided on a sample.

Evidence, and what it does not establish

  • cargo test --workspace: 6,949 passed / 0 failed / 20 ignored; clippy -D warnings and fmt clean. Per-AC pins are listed in the design plan's Status table; the stitched +1 solo-to-competing transition is named-uncovered with its structural reason (unconstructible with a symmetric reducer).
  • Independent oracle: notebooks/build_ltm_discovery_audit.py --model wrld3|clearn|cross_agg re-implements the enumerator (activity read through the NaN shadow, cross-aggregate stitching under the engine's own caps, trimmed reported identities), scoring, retention and ranking in pure Python from the design document and reproduces the engine exactly -- World3 150,827 cycles -> 2,979 survivors -> 200 reported, C-LEARN 162 -> 153 -> 153, the reducer fixture 3 petals + 4 stitched -> 7 -> 7; reported lists identical as sets; max difference in raw and relative loop scores 0.000e+00; World3 step-dominant coverage 399/399 within competing groups; each notebook emits a machine-readable AUDIT VERDICT: PASS that the verifier asserts along with the headline values.
  • Performance (examples/ltm_discovery_bench, release, one machine): World3 0.56 s and C-LEARN 0.048 s, both enumeration_complete; the World3 cost above the 0.40 s of the first version is the exact override scoring of the 97.6% of its circuits that pass through a SMOOTH/DELAY module. A wall-clock claim, not a test.
  • Large-model integration: world3_full_run_enumeration_is_complete (release, #[ignore]d for runtime class) asserts completeness, the cap binding, and the presence of the births -> population-aging family the old sampler missed.

Not established: no test asserts World3's universe/retained counts (bench and audit measure them); fallback recall is a lower bound (measured against the exact run's reported list, and both paths normalize against their own candidate sets); sub-save-step activity remains invisible to both generators (GH #309, out of scope); the stockless-cycle rule "costs nothing" is measured only on models with no non-trivial stockless SCC (0/153 and 0/200) and pinned by fixture; no TypeScript/WASM discovery surface exists or was added.

Fixes #481

bpowers added 30 commits August 10, 2026 22:19
Discovery-mode LTM generated loop candidates with a per-step
strongest-first DFS whose per-node expansion cap silently degrades to a
biased sampler on runtime-dense graphs: a ground-truth audit (2026-08-10,
design doc below) showed the cap saturating on 100% of World3's searches,
the report overlapping the true top-200 by only 47/200, and the true
most-dominant loop absent at 57% of steps -- with no observable trace.

Because discovery runs after the simulation, the set of edges that ever
carried a nonzero score is observable, and every scorable loop is an
ever-simultaneously-active elementary cycle of that union graph (a loop
score is the product of its link scores). Candidate generation now
enumerates exactly those cycles once (min-root Tiernan search with
per-edge activity-bitset pruning, so cycles active only at disjoint steps
are never emitted), streams a two-pass retention with full-universe
per-partition denominators (materializing only survivors -- the naive
route would hit the same multi-GB cliff the compile-time circuit cap
guards against), and feeds rank_and_filter external totals so relative
scores normalize against the whole universe while competing-vs-solo is
judged over retention survivors (phantom co-members must not neuter the
solo demotion). Exact mean_rel ties -- every solo loop sits at 1.0 --
now break by raw magnitude so MAX_LOOPS pressure drops the smallest
solos rather than name-ordered ones. Budget or deadline trips fall back
to the unchanged DFS, and the result carries two new flags:
enumeration_complete (the candidate set is provably the full ever-active
universe at saved-step resolution) and expansion_cap_saturated (the DFS
sample is budget-bound -- the previously silent degradation).

Deliberate widenings, pinned by tests: enumeration surfaces self-loop
singletons (PREVIOUS-latch shapes; C-LEARN carries 49 ever-active ones)
and stockless cycles whose state hides in macro/module levels, both
structurally unreachable from the stock-seeded DFS; they resolve to Solo
groups and rank after competing loops.

Measured (examples/ltm_discovery_bench.rs, release): C-LEARN enumerates
its 211-cycle universe in 37ms (faster than the 103ms DFS sweep);
World3 enumerates and scores its 330k-cycle universe in 5.2s vs 0.34s
for the DFS -- and lifts true-top-200 coverage from 47/200 to 155/200
(the residual is ranking-boundary noise plus briefly-dominant loops the
mean-keyed MAX_LOOPS cap drops), with missed-dominant steps falling
from 227/399 to 17/399. examples/ltm_search_graph_dump.rs is the audit
instrument (dumps the exact search graph + score series discovery
consumes, per link_score_offsets' no-re-derivation contract).

Known boundaries, recorded in the design doc: completeness is at
saved-step resolution over the recorded series (sub-save activity and
the module-composite NaN-shadowing blind spot are shared with the DFS),
and FFI/pysimlin exposure of the two new flags (they stop at
analysis::ModelAnalysis) is follow-up work.
Records the design for finishing the union-graph enumeration transition:
enumeration as the sole exact candidate generator (no single-variable
cycles, edge-row emission, single-pass retention over contiguous series,
universe-based denominators and competing classification), deletion of
the per-step strongest-first DFS, a per-(stock, step) Dijkstra fallback
over -log|link score| with a pluggable weight function settled by
measurement against the exact enumeration, a coverage-aware MAX_LOOPS
cap, and end-to-end exposure of enumeration_complete. Baseline
measurements from the review that motivated it are included.
An elementary cycle never repeats a node, so a self-edge can never be part
of one of length >= 2; the only circuit it can produce is the length-1
circuit the enumerator used to emit and report as a loop. Both other LTM
surfaces already say that is not feedback -- compile-time exhaustive mode
refuses a circuit unless `circuit.len() > 1`, and `order_variable_cycle`
rejects a variable set smaller than two -- so discovery reporting a
one-variable "loop" made the two surfaces disagree about what a loop is.
Dropping the edge at `ActivityGraph::build` rather than filtering the
emitted circuits keeps it out of the traversal, the SCC structure, and the
scoring rows alike, at no cost to any longer cycle.

Also corrects the recorded size of World3's candidate universe: ~150k
circuits are ever simultaneously active, which is what the enumerator
materializes and what the budgets have to hold. The ~330k figure quoted in
the budget constants and the World3 integration test is the graph's cycle
count without the activity constraint, which nothing enumerates.
Retention was the whole cost of discovery on World3 (4.7 s of a 5.2 s run):
both of its passes recomputed every circuit's score by multiplying entries
read out of the results slab at a stride of `step_size`, over all 401 saved
steps, for all 6.3M emitted edge rows. Three changes remove that, and none
of them changes which loops survive or what they score.

`ActivityGraph` now owns a contiguous copy of each union edge's signed score
series, so a circuit's score is a straight-line multiply per edge that
vectorizes instead of a strided gather. The enumerator emits circuits as
edge-row sequences rather than node paths, so scoring needs no `(from, to)`
lookup at all -- the `HashMap` both retention and the stitched-loop
accumulator used to rebuild is gone, and a circuit's node path is derived
only where a consumer needs one. And each circuit carries the activity AND
it was emitted with, which bounds scoring to the steps where the circuit can
be nonzero: outside that window some link is exactly 0 or NaN, so the score
is 0 or NaN and contributes to neither the totals nor retention whichever it
is. On World3 that window averages 79 of 401 steps.

Two more enumerator changes ride along. The running activity AND is written
straight onto its stack instead of into a per-visit buffer, which removes the
heap allocation wide bitsets used to take on every edge visit. And each root
now explores only its own strongly-connected component within the subgraph
induced by the nodes above it -- Johnson's A_k, exact because every cycle
rooted at a node lives inside that component -- which is what stopped World3
from spending two thirds of its 20M descents on branches that could not
return to the root.

Circuits are stored compressed-row style, so the new
`MAX_DISCOVERY_ENUM_EDGE_ROWS` budget is a direct bound on enumeration
memory. A circuit count alone never was: the cost scales with count times
mean length, and mean length is a property of the graph (World3's is 42),
not of the budget.

Scoring the finished product rather than testing each link for NaN also
fixes a defect: a circuit whose product overflows to Inf and then meets a 0
link is NaN with no NaN link anywhere, and the old short-circuit called that
step a number, so `NaN.abs()` entered the partition total and poisoned the
denominator for every sibling loop at that step.

World3 discovery goes from 5.19 s to 0.49 s in release, with the same
survivors; the enumerated set is checked against a brute-force reference
that shares no code with the enumerator.
Retention asks whether a circuit's |score| ever reaches 0.1% of its
partition's total, which needs totals the pass is still accumulating -- so it
used to score every circuit twice, once to build the denominators and once to
test against them. The first pass now also records `max_t |s(t)| /
running_total(t)`, taking the running total AFTER adding the circuit's own
mass so the ratio is defined at the first circuit of a partition. Since the
total only grows, that ratio is an upper bound on the circuit's true peak
share, so a circuit that falls short of the threshold against it is dropped
without a second look. Only the circuits the bound admits are rescored
against the final totals.

The bound is deliberately loose where a circuit arrives early -- the first
circuit of a partition bounds at exactly 1.0 -- which is why the confirm step
is not optional: without it the answer would depend on emission order rather
than on the retention rule. On World3 the bound settles the great majority of
the 150k circuits outright.

Retention also now reports how many circuits each partition holds in the
enumerated universe, non-survivors included. How much company a loop has in
its partition is a fact about the model rather than about what cleared a
threshold, and it is the population the competing-vs-solo classification is
entitled to ask about.
Enumeration banks every circuit's RAW link-score product as its partition's
denominator mass, and two classes of loop do not report that number. A
module-traversing loop reports the per-exit-port override series, while its
raw product multiplies in the module COMPOSITE, which max-abs-selects across
every output port of the module -- on a module whose ports carry different
magnitudes those are different numbers entirely. And two circuits that trim
to the same reported loop (a direct reference and its aggregate-routed twin,
which differ only in the synthetic node the report hides) each bank mass,
while only the surviving representative's score is reported. Either way the
partition's loops end up normalized against mass no reported loop carries.

Retention now withholds a module-traversing circuit's raw mass, and
materialization adds back the series such a loop actually reports; the
reported-cycle dedup subtracts what it discards. The two halves use the same
module-traversal predicate, so the mass denied and the mass granted are
exactly complementary. Both fixtures assert the property directly -- the
reported loops' relative scores sum to 1 at every active step, which holds
only when the denominator is the sum of what they report -- and each carries
a guard that the fixture really does distinguish the two rules, since a model
whose composite and override happen to agree cannot tell them apart.

The per-exit-port recompute is also memoized per (module-input source, module
instance, exit-port reader), which is the whole of what its answer depends
on. An arrayed loop through a module appears once per element, and each
appearance was re-enumerating the same sub-model pathway map over the same
sorted port set.
The module docs and the engine CLAUDE.md entry still described the enumerator
as a node-path emitter with a two-pass retention over strided slab reads, and
pointed at the union-enumeration plan rather than the one the current
mechanics follow. Rewrite them around what the code does: edge-row emission,
the per-root induced-subgraph SCC, contiguous score rows read inside each
circuit's activity window, the bound-and-confirm retention, the edge-row
memory budget, the memoized per-exit-port recompute, and the rule that the
universe denominators carry the mass the reported loops carry.

Record Phase 1's measured numbers in the design plan alongside the baseline
they replace, including where World3's remaining 0.40 s and C-LEARN's 36 ms
go, so the next phase starts from a real profile rather than a total.
Discovery's union-graph enumeration is exact but cannot always finish: a
dense runtime graph can exceed its circuit/visit budgets, and a caller with
a wall-clock budget can cut it off part way. A partial enumeration is not a
usable candidate set -- it is biased by node-id root order and its
per-partition totals are not the universe's -- so a second generator has to
produce candidates under a bound that is known before the work starts.

This is that generator: per saved step and per seed stock, a Dijkstra over
the step's active edges recovers the cycles through that stock cheapest
first. One search is O(E log V) whatever the graph looks like, so the sweep
has no cliff and the deadline can be honored between searches rather than
only between steps; and what the search drops is characterizable (one tree
expresses one path per node) rather than being a fact about traversal
order. The weight function is selectable because loop scores are recomputed
exactly afterwards either way -- the formulation only decides which cycles
are proposed, so it is settled by measurement rather than by argument.

Landed with its unit tests and no call site yet, so the Dijkstra, the three
weight arms and the deadline schedule are pinned independently of the
wiring that follows.
A caller's wall-clock budget bound only the candidate sweep: the activity
graph build read the clock nowhere, and the enumeration and retention passes
read it but had no test arm for it. On a model saved at many steps the build
alone can outlast a small budget, so a budget that only the last phase
honoured would be spent entirely inside the phases before it -- exactly on
the model that needed the budget.

`ActivityGraph::build` now returns `Option`, so a caller whose budget is
already spent abandons it rather than copying a score slab it will discard,
and the interval it checks at is counted in VALUES rather than edges because
either factor of `edges x steps` can be the large one. Retention's interval
gets a name, and the enumerator's gets a test-only override so a
two-triangle fixture can exercise the in-search check.

The clock itself becomes an injectable `Clock`, shared with the fallback
module. That is what makes "an unbudgeted call never reads the clock" a
testable claim rather than an inspection of the source -- a per-value clock
read would swamp the work it guards -- and it makes each phase's expiry a
deterministic fact about its structure instead of a race against a real
`Duration`, which is flaky on a loaded machine and slow on an idle one.
Discovery's second candidate generator was the paper's per-step
strongest-first DFS, bounded by refusing node re-expansions. On a dense
runtime graph that bound collapses into "whatever the first few thousand
expansions happened to reach" -- a fact about traversal order that no caller
can interpret, and one the World3 audit caught degrading silently. The
shortest-path fallback replaces it: what a Dijkstra tree drops is
characterizable (one path per node), which is the standing requirement on
anything that stands in for the exact enumeration.

The budget is now split. The two generators are sequential and only the
second yields partial results, so an undivided budget was a budget the
fallback never saw: the enumeration would spend all of it, be abandoned for
being incomplete, and discovery would return nothing. `ENUM_BUDGET_FRACTION`
gives the enumeration half and the fallback the caller's full deadline.

`expansion_cap_saturated` is removed rather than renamed: it reported a
degradation mode that no longer exists, and `enumeration_complete == false`
already says the candidate set is a sample. Distinguishing a budget trip
from a deadline expiry would not help a caller -- the report is equally a
sample either way.

Both generators now hand node-id paths to one cross-agg stitching helper and
one materialization, so what the two report about a reducer model differs
only in the petals they found, never in how those petals combine. The
diamond and stockless-cycle tests pin where they legitimately differ, with
the reason: a shortest-path tree expresses one route to a shared node, and a
stock-seeded sweep cannot reach a cycle that touches no stock.
The DFS is gone from the code, so every place that named it -- the engine
CLAUDE.md paragraph, the libsimlin FFI and C header, the pysimlin
docstrings, the auto-flip warning a user reads, the benchmarks and the
integration-test prose -- was describing an implementation that no longer
exists. A model that auto-flips to discovery mode had the warning message
tell its author about a heuristic search that is not what runs.

Most of the wording did not need a replacement algorithm named at all: what
matters to a caller of `analyze` or a reader of an auto-flip warning is that
discovery finds loops AFTER the run from the recorded link scores, not which
search it uses to propose candidates. Those now say that, so the next change
of generator does not re-open the same set of files.

`docs/tech-debt.md` #24 and the "Strongest-Path Algorithm" section of
docs/design/ltm--loops-that-matter.md still describe the deleted code; they
are the design plan's Phase 6 and are deliberately left for it rather than
half-rewritten here.
The plan's AC3.1 is a claim about wall-clock on two real models, so it is
settled by numbers rather than by review: World3 enumerates in 0.409 s and
C-LEARN in 0.038 s, both complete, and every fallback weight is well under a
second on both.

The loop counts are recorded alongside but explicitly NOT read as recall: a
fallback run reports fewer loops both because it proposes fewer candidates
and because its retention denominators are its own discovered set rather
than the universe, and separating those two is Phase 3's harness. Saying so
here keeps the table from being mistaken for the measurement that picks the
default weight.
Discovery-mode LTM's docs made two false claims a review caught. First,
several comments said the external retention totals are "the mass the
REPORTED loops carry" -- they are not: rank_and_filter's own rustdoc
correctly states the totals are the full enumerated universe's raw mass
(retention non-survivors included, GH #310), corrected only so a
module-traversing loop's raw product is replaced by its reported override
series and a trimmed duplicate's raw mass is subtracted back out. Every
other circuit keeps its raw enumerated product untouched. Restating the
claim precisely everywhere it appeared (ltm_finding.rs, CLAUDE.md) also
lets retain_circuits' own rustdoc be honest about a real, bounded gap:
that pass is evaluated against the PRE-correction totals, so a non-module
circuit whose share only clears MIN_CONTRIBUTION after a duplicate's mass
is subtracted can be dropped before rank_and_filter ever sees it again.

Second, three places disagreed about what a link score looks like at step
0: two said NaN, one said exactly 0. Tracing the actual guard every
link-score equation generator emits settles it -- `if (TIME = INITIAL_TIME)
then 0 else ...` is a literal constant, not NaN, not a SAFEDIV(0,0). The
two wrong claims (ltm_finding_fallback.rs, a stale test comment) are
corrected to match, and the `ActivityGraph` bits doc is rewritten to state
the actual (and previously glossed-over) consequence: a circuit active ONLY
at step 0 is never emitted at all, not merely windowed out of scoring, so
its mass is excluded from the universe entirely. A defense-in-depth fixture
(`a_circuit_active_at_step_0_too_is_windowed_from_step_0`) pins both the
`head & !1u64` mask and `active_window`'s `lo == 0` case against a
hand-built edge that IS active at step 0 -- a shape no real run produces,
but one the code does not get to assume away.

Also fixes a dangling reference to `IndexedSearch::load_step_scores`, part
of the per-step DFS Phase 2 deleted, and removes residual changelog
phrasing ("used to emit... is now scored...") from the CLAUDE.md paragraph
Phase 2 had already mostly rewritten.
Three findings on the dedup/module-mass correction path in
discover_loops_with_deadlines, all in the direction of "a regression here
must fail loudly rather than silently mis-normalize a partition":

- subtract_reported_mass_from_totals asserted (in its doc, not in code)
  that a duplicate's partition always already carries a total, and that
  the subtraction cannot drive it negative. Both are now debug_assert!s:
  a missing partition entry and a negative result both fire loudly instead
  of silently no-oping or drifting. Also documents why the partition
  derived here (via loop_info.stocks) and the partition the mass was
  originally banked under (via the enumerated circuit's node ids) cannot
  disagree -- they read the same CyclePartitions, computed once per call.

- The dedup-correction loop's `if !*traverses_module` guard on the
  subtraction arm was untested for its own arm: a dropped MODULE-traversing
  duplicate must be left alone, since retain_circuits never banked it any
  raw mass to begin with, and unconditionally subtracting its reported
  score would drive the partition's total negative (as verified by
  temporarily removing the guard, which trips both the new debug_assert
  and the new test's ratio check). A fixture that gives one element both a
  direct and an agg-routed reference into a module's scalar input --
  needing an asymmetric-population trick so the module's input variable
  actually changes over time, since a constant target zeros every link
  score into it by the guard's own "target didn't change" rule -- exercises
  exactly this arm.

- The stitched-cross-agg-loop skip (module mass added after materialization
  rather than double-counted here) has no end-to-end fixture: a module
  can only be wired to a NAMED aux today, and any such aux sitting between
  a synthetic agg and its per-element consumers is necessarily shared
  across every element's petal, which makes stitch_cross_agg_petals'
  disjointness test refuse to combine them -- so no stitched sequence can
  reach a module under the current module-instancing shape. Documented at
  the skip site rather than faked with an unreachable fixture.

Also adds a defensive `reported_links.len() >= 2` guard at loop
materialization (AC1.1): a 2-node `agg -> x -> agg` circuit's synthetic-agg
trim can algebraically collapse to a single `x -> x` self-link, which no
compiling model reaches today (the enumerator never emits a length-1
circuit) but which nothing upstream proves can never happen.
…eadlines

retention_confirms_a_circuit_whose_running_bound_overstates_its_share hand-
built its link_offsets in an order production never produces: a real
parse_link_offsets output is sorted by (from, to) name, but the fixture put
the tiny loop's edges (a<->c) before the dominant loop's (a<->b), the
reverse of sorted order. The test happened to still exercise the intended
"running bound overstates the tiny circuit's share" arm only because
IndexedSearch::build walks a node's out-edges in link_offsets' own order,
so an unsorted fixture just meant the test was pinning DFS visitation order
on data no real run supplies. Renaming so the tiny loop's partner sorts
first (b) and the dominant loop's partner sorts second (c) makes the
fixture's shape identical to what parse_link_offsets actually emits while
keeping the same behavior under test.

enumerate_active_circuits amortizes its deadline check over
DEADLINE_CHECK_INTERVAL (8192) edge visits, checked only when `visits` is a
multiple of that interval. An already-expired deadline passed in before the
call therefore went uncaught on any graph whose total visit count never
reaches 8192 -- true of nearly every real model -- so the enumeration would
run to completion on a budget already spent, unlike ActivityGraph::build
and retain_circuits, which both catch this case on their very first unit of
work. Adding a `visits == 1` first-visit check closes the gap without
touching the periodic arm that catches a deadline expiring mid-search.
Two new tests pin the two arms separately: one drives an already-expired
deadline through the production interval with no override, and one uses a
scripted clock to expire between the first and fourth visit so only the
periodic check (not the first-visit one) can catch it.
Three small efficiency fixes to the per-loop materialization pass, all
nits that cost nothing to fix once found:

- petal_circuits called circuit_nodes (which allocates a Vec) for EVERY
  enumerated circuit just to count its agg nodes, then discarded the
  allocation for all but the rare circuit with exactly one. The agg count
  is now taken directly off the circuit's edge rows via a new zero-cost
  ActivityGraph::edge_source accessor, and circuit_nodes is called only
  for the circuits that pass the count test -- on World3's ~150k-circuit
  universe, almost all of which touch no agg node at all, this drops the
  allocation from every circuit to a small fraction of them.

- The module-input-edge recompute's memoization gate delegated to
  recompute_module_input_edge_series (which re-strips and re-interns the
  same names before reaching an identical `?`) whenever there was no
  module graph for the link's target, even though that answer is fully
  decided by the check already performed at the call site. Answering
  `None` directly for that arm skips the redundant work; the other decline
  arm (non-sequential link list) still delegates, since the recompute's
  own guard there does real additional work the call site does not
  duplicate.

- module_series_cache's insert-then-return went through `insert` (a
  second hashmap operation after the `get` that found no entry) plus a
  clone to keep a copy in the map. `entry(key).or_insert(series).clone()`
  does the insert and the return from one hashmap operation.
examples/ltm_fallback_eval measures each FallbackWeight's recall of the
exact enumeration's top-K and its step-dominant coverage on real models,
so the fallback's weight and sampling strategy are chosen by measurement
rather than argument; the first measurement (recorded in the design doc)
shows ClampedLogAbs weakly dominating and World3 recall at 7/200, which
sizes the sampling work the fallback still needs.

notebooks/build_ltm_discovery_audit.py replaces the hand-assembled
docs/audits notebooks with the repo's generator convention: it dumps the
engine's exact edge set (ltm_search_graph_dump, whose JSON now carries the
result flags and per-loop rel_scores/partition/scores), re-enumerates the
loop universe in pure Python, and diffs universe size, scores, ranking and
per-step dominance against the engine; the executed notebook is a
gitignored artifact so an audit is always re-derived. Its first run
reproduces World3's 150,827 / 2,979 / 200 and both score series bit for
bit and pins the 17-step coverage gap the coverage-aware cap must close.
The build's deadline check divided a fixed value budget by the step count to
get a stride in edges, which floors at one edge. A model saved at more steps
than the budget -- the libsimlin and pysimlin wall-clock fixtures save 200,001
-- therefore checked once per edge, and one edge is milliseconds of copying, so
a millisecond-scale budget was spent entirely inside the enumeration half and
the fallback was handed a deadline that had already passed. Discovery returned
nothing where the contract promises partial results.

Counting values directly and splitting one edge's series into blocks makes the
interval the same amount of work in either shape, which is what the constant's
doc always claimed. The first check now happens before any value is copied
rather than at the first edge, so an already-expired deadline still costs
nothing.
…buffers

The two candidate generators each carried their own copy of "is this edge
active at this step". They agreed, but a cycle one generator considers active
and the other does not would make `enumeration_complete` mean different things
about the same model, so the rule is now stated once and called from both.

The fallback ran Tarjan once per saved step and allocated its six node-sized
vectors each time -- on C-LEARN, whose search graph carries tens of thousands
of nodes, that dominated the SCC pass. `tarjan_scc_ids_into` writes into
caller-owned buffers and the sweep keeps one set; the allocating wrapper stays
for the one-shot callers. Measured with `ltm_discovery_bench` in release:
C-LEARN's fallback drops from 0.069 s to 0.060 s, World3's is unchanged at
0.019 s (15 stocks over a 258-node graph allocates too little to matter).

Also splits the budget arithmetic into a pure `split_budget` so the split is
testable without racing a clock, and stops the two empty-universe early
returns from reporting `enumeration_complete` under `FallbackOnly` -- that
flag names the generator that ran, and a caller pinning the fallback asserts
the enumeration never claims to have run.

Three rustdoc claims are corrected rather than reworded. The clamp in
`ClampedLogAbs` gives an UPPER bound on the true `-ln` cost, not an admissible
optimistic one: it discards a super-unit link's gain, and the consequence is a
zero-weight plateau on models with many such links. `edge_weight`'s clamp is
not guarding a negative weight (a sole determinant's share is exactly 1.0); it
normalizes `-0.0` so the heap's tie-break does not depend on which arm
produced a zero. And the budget bounds candidate generation only --
materialization and ranking run afterwards, so a run can exceed the budget by
that tail and still report `truncated == false`.
Discovery's candidate generation is a union-graph enumeration of every
ever-simultaneously-active elementary cycle, with a shortest-path sample when
that cannot complete, and it reports which of the two ran. Calling it a
"heuristic" -- in the engine's own mode enum, in libsimlin's rustdoc, and in
three pysimlin docstrings a user reads -- says the opposite: that the result
is a guess with no stated completeness. The wording now says what discovery
does and what bounds it, one clause each.

Also drops "per-timestep sweep" from pysimlin's `analyze(timeout=...)`
documentation. The timeout bounds the search for candidate loops; scoring and
ranking them run afterwards, so a call can outlast the timeout, and the
docstring now says so.
…rategies

The shortest-path fallback ran one Dijkstra per (stock, saved step) and closed
only the seed's own in-edges. That recovers the minimum-weight cycle through
each stock, and nothing else: one shortest-path tree holds one route per node,
so two parallel routes to the same node collapse to the cheaper however many
seeds or steps are swept, and a cycle through no stock at all has no seed to
start from. On World3 it recovered 7 of the exact enumeration's top 200; on
C-LEARN, 97 of 153.

The strategy is now three axes on a `FallbackConfig`, and each was settled by
`examples/ltm_fallback_eval.rs` measuring recall against the exact enumeration
on World3 and C-LEARN rather than by argument. The harness sweeps the space
and the design doc's Measured section holds both tables.

CLOSURES. A reverse Dijkstra to the seed, beside the forward one from it,
turns every edge `u -> w` that both trees reach into a candidate: the cycle
`path(seed..u) + (u -> w) + path(w..seed)`, which is the minimum-weight cycle
through the seed AND that edge -- the strength-weighted analogue of edge
coverage, and the thing that reaches the arm a single tree cannot express. A
closure whose two halves share a node is not elementary; it is skipped rather
than spliced at the repeat, because a spliced walk is no longer the minimum
through its edge and so is not the thing the family claims to emit. Measured:
World3's recall of the exact top-200 goes 7 -> 23 and its step-dominant
coverage 41 -> 55 of 399; C-LEARN's goes 97 -> 150 of 153, with recall@1, @10,
@50 and @100 all exactly 1.00. Cost 0.021 -> 0.141 s and 0.063 -> 0.148 s,
against a 0.398 s exact World3 run.

SEEDS. One extra seed per non-trivial component holding no stock reaches the
cycles whose state hides in a module level or a `PREVIOUS` lag between auxes,
which no stock-seeded search can. It is measurement-neutral on both models --
every column matches the stock-only policy, which is evidence that neither
carries such a component -- so it is adopted for the class of model it closes
rather than for a number. Seeding the whole cyclic core instead costs 1.031 s
on World3, more than the exact enumeration it stands in for, for recall@200 of
32 against 23; it stays selectable and unused.

ORDER. Both searches order by `(weight, hops)`. Under `ClampedLogAbs` a
super-unit link weighs exactly 0 and World3 has 37-91 of them per step, so a
large share of the graph is a zero-weight plateau on which the weight decides
nothing; without a hop term the winner among tied cycles is node-id order,
which is deterministic but says nothing about the model. Every recall column
of the in-edge rows is unchanged from before the tie-break, so it costs
nothing measured.

Dedup moved off canonical rotations, which allocated a `Vec` per candidate:
after the first few saved steps nearly every candidate is a duplicate, and the
every-edge family proposes one per active edge per (seed, step). An elementary
cycle is determined by its SET of directed edges, so an order-independent fold
over those edges fingerprints it whatever rotation it was found in; bucket
hits are resolved by a linear rotation comparison, so the dedup stays exact
rather than probabilistic and costs no allocation for a duplicate.

Two tests change direction because the fallback does: the diamond's second arm
is now recovered, and the stockless cycle is now reached. Both keep an arm
pinning the narrower setting that still cannot, so what the wider one buys is
stated rather than assumed.
ShiftedLogAbs (w = ln(max active |s|) - ln|s|) keeps the relative gain
among super-unit links that ClampedLogAbs discards, which is the
distinction World3's long high-gain dominant loops turn on, so it was
the natural hypothesis for the clamp's low recall there. Measured with
examples/ltm_fallback_eval at the production seeds and closures it is
worse on both models (World3 recall@200 10 vs 23, C-LEARN 138 vs 150 of
153, identical to HopCount): with per-step maxima of 1e4-1e14 the
ln(max)-per-hop term dwarfs any product term and the arm degenerates
into a hop count. It stays selectable as a documented negative result.

The tie-break among equal-weight routes becomes an explicit axis
(FallbackTieBreak::{Hops, NodeId}); both arms measure identically on
both models, and Hops stays the default because inside ClampedLogAbs's
zero-weight plateau it decides on cycle length rather than on interning
order. The design doc's Measured section records both results.
…y cap

Ranking by mean relative score alone lets MAX_LOOPS drop loops that
dominate their partition briefly: on World3 the loop with the largest
relative score in its competing partition was enumerated, retained, and
then cut at 17 of 399 saved steps, so dominance analysis named the wrong
loop there. rank_and_filter now anchors, per competing normalization
group and per step, the top-k retained loops by relative score (k rising
from 1 to MAX_ANCHOR_K = 3 while the anchors still fit), fills the
remaining slots in the existing competitive-first mean-relative order,
and keeps that order for presentation; a step where no retained loop
carries weight anchors nobody, and ties anchor the earlier-ranked loop.
World3 coverage is 399/399 for 3.5 ms; C-LEARN's cap does not bind.

Competing-vs-solo classification on the enumeration path is decided by
the universe: a partition holding two or more ever-active circuits is
competing even when only one survives retention (its relative score is
then genuinely below 1 against universe totals), while a partition whose
whole universe is one reported cycle stays solo. The loop counts follow
the same corrections as the mass they accompany (a stitched cross-agg
loop adds one, a dedup-dropped duplicate removes one), so a partition
that is one loop plus its trimmed twin does not read as competing with a
denominator that is its own mass. The audit notebook's independent
ranking implements the same rule and reproduces the engine's 200/200.
`enumeration_complete` says which generator produced the candidates but not
how much of what it found survived: a report capped at MAX_LOOPS is
indistinguishable from a model that genuinely has that many loops, and the
population a loop's importance is a share of is invisible. Add
`retained_loops` (survivors of the MIN_CONTRIBUTION filter, read before the
cap truncates) and `universe_loops` (the enumerated ever-simultaneously-active
circuit count) to `DiscoveryResult` and `ModelAnalysis`.

`universe_loops` is `Some` exactly when `enumeration_complete`, set at the one
site that sets that flag: a fallback sample and an abandoned enumeration alike
have no universe to report, and the degenerate early returns say the universe
is EMPTY rather than unknown so the pair reads as one statement everywhere.
It deliberately excludes the cross-agg stitched loops, which are combinations
of enumerated petals rather than circuits of the union graph.

`rank_and_filter` now returns a `RankOutcome` because the retained count is
only knowable inside it, between the retention filter and the cap.
A C caller of `simlin_analyze_discover_loops` had no way to tell an exact
analysis from a sampled one, so an absent loop read as "this model has no
such feedback" whether or not the enumeration finished. Copy
`enumeration_complete`, `retained_loops` and `universe_loops` from
`ModelAnalysis` onto `SimlinDiscoveryResult` (appended additively, header
regenerated).

`universe_loops` is an `i64` with `-1` for the engine's `None` rather than a
`usize` read only when `enumeration_complete`: the sentinel keeps "the
fallback sampled" distinct from a genuinely empty universe without making the
decode depend on a second field agreeing. It saturates on an unrepresentable
count instead of falling back to `-1` the way the optional `partition` indices
do, since here `-1` carries meaning.
`Model.analyze()` is the entry point users reach for on exactly the models
where the exact enumeration can fail to finish, so it is the surface that most
needs to say whether the loop list is exhaustive. Add `enumeration_complete`,
`retained_loops` and `universe_loops` to `Analysis`, decoding the FFI's `-1`
sentinel back to `None` so a caller never mistakes it for a count.

`None` and `0` are deliberately different claims on `universe_loops`: `None`
means a sample was taken and there is no universe to describe, `0` means the
model genuinely has no scorable loop. The `analyze()` docstring and the README
say what a `False` `enumeration_complete` licenses a reader to conclude --
notably that a missing loop is then not evidence of a missing feedback.
An assistant reading `loopDominance` had no way to know whether the list was
the model's whole feedback structure or a sample, which is the difference
between "this model has no such loop" and "I did not look at every loop".
Carry `enumerationComplete`, `retainedLoops` and `universeLoops` on both
`ReadModelOutput` and `EditModelOutput`, and describe them in the MCP
instructions alongside `loopDominance`.

`enumerationComplete` is always serialized, unlike `aggRecoveryTruncated`
next to it: that field elides its `false` because the interesting value is
`true`, whereas here the interesting value IS `false`, and a client that
cannot see the field reads a sample as exhaustive. `retainedLoops` is
likewise unconditional, since `0` is a real statement and no absence would
say anything a `0` does not. `universeLoops` is the only optional one --
elided when the analysis sampled, because a sample has no universe to report.
Two independent correctness/robustness findings on the fallback and
ranking paths, plus their test coverage and doc drift:

- MAX_FALLBACK_PATHS (200,000, checked at every dedup insert) bounds the
  shortest-path sweep's candidate volume; a trip stops the sweep and
  reports truncated, the same signal a deadline expiry already gives.
  Nothing else bounded it: EveryEdge closures propose roughly one
  candidate per active edge per (seed, step), and a caller can run with
  no wall-clock budget at all. Sized with ~90x headroom over what the
  corpus produces (World3 2,150, C-LEARN 159 under the default config).
  The sweep's own candidate count is exposed via a new
  DiscoveryResult::fallback_candidates field (Some exactly when the
  fallback ran, mirroring universe_loops on the enumeration path) so
  examples/ltm_discovery_bench and examples/ltm_fallback_eval can print
  proposed-vs-reported volume instead of only the final count.
- select_reported's coverage-aware escalation past k=1 is now bounded to
  ANCHOR_SHARE_OF_CAP (one half) of MAX_LOOPS: on World3 the prior
  unbounded rule let k rise to MAX_ANCHOR_K and anchored 140 of 200
  reported slots, leaving only 60 (30%) for the ordinary mean-relative
  ranking -- a coverage guarantee crowding out the ranking claim far past
  what AC5.1 requires (its guarantee is k=1; further escalation is a
  bonus). The bound keeps k=1's guarantee unconditional while capping how
  far escalation may crowd the report; World3 now anchors 96 of 200 slots
  (k=2) and reports 25 of 200 loops differently than a plain mean-relative
  truncation, down from 49 under the old rule. The Python audit
  notebook's independent reimplementation is updated with the identical
  rule so it keeps reproducing the engine's selection exactly.

Also: two regression tests pin the OBSERVABLE effect of UniverseStats'
loop_counts corrections (the dedup "-1": a partition whose universe is a
reported loop plus its trimmed hoisted-reducer twin classifies Solo, not
Competing, and ranks behind a genuinely competing loop despite a perfect
1.0 relative score) -- the stitched "+1" arm is left explicitly uncovered
with the structural reason (a symmetric reducer's petals always already
populate loop_counts before any stitched addition, so isolating the
transition needs a mixed stock/stockless element pair this fixture family
can't express without disproportionate new construction). The
UniverseStats field docs are corrected to state the loop_counts/totals
correspondence's actual (one-directional, conservative) boundary instead
of an exact one. The fallback's reverse-tail closure walk gains the same
node-universe termination guard its forward twin already has, and
collect_closings' rustdoc is corrected to name its actual return shape.

Why: found in code review of the exact-enumeration discovery design
(docs/design-plans/2026-08-17-ltm-discovery-exact.md); see that doc's
"Measured" section for World3/C-LEARN before/after numbers.
examples/ltm_fallback_eval's step-dominant coverage statistic was a
GLOBAL argmax over the exact path's reported loops: a loop alone in its
partition has |rel_scores[t]| == 1 at every active step by construction,
so it wins any global argmax it is active for regardless of raw
magnitude. On both corpus models the global argmax named a non-competing
loop at literally every step, so the statistic measured nothing --
C-LEARN read a suspicious, uniform "250/250" for every strategy
including the score-blind HopCount control, which is what gave it away.

Coverage is now counted per (competing group, saved step) pair: a group
is competing iff at least two REPORTED exact loops share its partition,
and within a competing group at a step where some member is active, the
pair is covered iff the fallback reported that group's step-max loop.
This matches AC5.1's own "within a competing partition" framing and is
what the design doc's independent Python audit already measured
correctly (it was never the audit that had the bug, only this harness's
own comparison logic).

Also prints each strategy's proposed candidate count
(DiscoveryResult::fallback_candidates) alongside its reported loop count,
so volume is observable independent of what retention and the cap kept.
Two paragraphs in the engine CLAUDE.md's ltm_finding.rs entry had drifted
from the shipped code: the competing-vs-solo classification sentence was
inverted (it read as if classification stayed computed over the
survivors, when on the enumeration path it is universe-based via
UniverseStats.loop_counts and only falls back to the discovered set on
the fallback path), rank_and_filter's totals parameter was still named
external_totals (renamed to universe: Option<&UniverseStats> when
UniverseStats was introduced), the FallbackWeight list was missing
ShiftedLogAbs, FallbackConfig was described as three axes instead of
four (weight, seeds, closures, tie_break), and the MAX_LOOPS sentence
did not mention the coverage-aware selection (select_reported, anchors,
MAX_ANCHOR_K, and now ANCHOR_SHARE_OF_CAP). Fixed only those
inaccuracies; a full pass is Phase 6's job. Also renamed two other
"heuristic search"/"discovery heuristic" mentions (pysimlin's
test_pinned_loops.py, the same CLAUDE.md file) to "post-simulation
discovery" -- discovery is an exact algorithm with a sampled fallback,
not a heuristic.

The design doc's Architecture section described the ORIGINAL plan rather
than the shipped design: the Fallback subsection is rewritten around the
actual FallbackConfig axes (including the corrected claim that
ClampedLogAbs's clamp is an upper bound on the true -ln cost, not an
"admissible optimistic bound" -- it discards super-unit gain rather than
expressing it), the candidate-count bound, the deadline sites, and what
recall ceiling the sweep's optimality restriction implies; the Ranking
subsection now states the shipped coverage-aware cap rule including the
anchor-share bound.

The Measured section is updated with fresh numbers from a clean release
build reflecting every fix in this branch: examples/ltm_fallback_eval's
corrected step-dominant-coverage tables (both models, all strategies,
candidate counts added) and the anchor-share bound's effect on World3
(k stops at 2 instead of escalating to MAX_ANCHOR_K; 96 of 200 slots
anchored instead of 140; 25 of 200 reported loops move relative to a
plain ranking instead of 49), with the original Phase 4 measurements left
as the historical record and the fix's effect appended as its own dated
block, matching this document's existing chronological convention. The
audit notebook script (notebooks/build_ltm_discovery_audit.py) gets the
same ANCHOR_SHARE_OF_CAP rule as its Rust twin so its independent
reimplementation keeps reproducing the engine's selection exactly
(re-verified: 200/200 and 153/153 reported-list overlap on both models).

@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

Here are some automated review suggestions for this pull request.

Reviewed commit: ded785123e

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

Comment on lines +1295 to +1299
let sum = totals[t] + mass;
totals[t] = if sum.is_infinite() && mass.is_finite() && totals[t].is_finite() {
f64::MAX
} else {
sum

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Normalize overflowing totals instead of saturating them

When a partition contains enough large finite loop scores for their sum to exceed f64::MAX, replacing the sum with f64::MAX does not preserve normalized shares: for example, 10,000 loops scoring 1e308 each really contribute about 0.01% apiece and should fail the 0.1% retention threshold, but each is compared with f64::MAX and appears to contribute about 56%, so all survive and receive incorrect relative scores. Fresh evidence after the earlier overflow report is that the replacement guard avoids Inf but still uses a compressed denominator rather than an overflow-safe scaled normalization.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Considered and not changed: saturating at f64::MAX keeps shares finite (and compressed) where a sum of finite masses would overflow, which only happens for loop scores around 1e308 -- no recorded link-score series in the corpus comes within 1e290 of it. Exact shares there would mean log-domain accumulation everywhere totals are read (retention, confirm, ranking, relative scores), which is not worth its cost for a regime the method never reaches. Recorded as a stated boundary in the design plan (Additional Considerations, 'Finite-overflow boundary').

Comment on lines +190 to +192
let scores: Vec<f64> = (0..results.step_count)
.map(|s| results.data[s * results.step_size + offset])
.collect();

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Dump pathway-aware activity for module edges

For a module-input edge whose composite is NaN-shadowed while an exit pathway is finite, production discovery marks the edge active through IndexedEdge::value_at after attach_module_pathways, but this dump serializes only the raw composite slot; the notebook then derives activity directly from that raw series and can omit a real cycle from its supposedly identical universe. Fresh evidence beyond the earlier metadata comment is that the enriched constructor is now used, yet the serialized edge rows still bypass the production pathway-aware accessor; expose the pathway activity needed to reproduce that accessor.

AGENTS.md reference: AGENTS.md:L100-L100

Useful? React with 👍 / 👎.

Comment on lines +839 to +842
self.rows.extend_from_slice(open_rows);
self.rows.push(closing_row);
self.starts.push(self.rows.len());
self.activity.extend_from_slice(and_bits);

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Bound per-circuit activity storage by saved-step volume

On a high-resolution run, this stores a full ceil(step_count / 64) bitset for every emitted circuit, but none of the circuit, edge-row, or activity-graph byte limits account for that product. For example, 100,000 circuits over 100,000 saved steps consume about 1.25 GB in activity alone while remaining within the 1,000,000-circuit and 20,000,000-row limits, and a modest edge graph can still remain below MAX_ACTIVITY_GRAPH_BYTES; enumeration can therefore OOM before retention. Include circuits × words in a byte budget or retain only the per-circuit active window that downstream code actually reads.

Useful? React with 👍 / 👎.

Comment on lines +319 to +320
if let Some(p) = fl.partition
&& exact.partitions[p].loop_count >= 2

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Classify benchmark competition from the universe

When retention or the 200-loop cap leaves only one reported loop from a partition that contains multiple mass-bearing universe loops, DiscoveredPartition::loop_count is 1 because it explicitly counts only returned loops, while that loop's rel_scores was normalized against the full universe and is not pinned to ±1. This filter consequently drops all dominance pairs for a genuinely competing partition and can make a fallback strategy look better by omitting exactly the steps where it misses that sole reported loop; derive competition from the universe population rather than the returned count.

AGENTS.md reference: AGENTS.md:L86-L86

Useful? React with 👍 / 👎.

truncated = true;
break 'steps;
}
scratch.load_step(search, results, step, config.weight);

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Check the fallback deadline while loading each step

With a very large active edge set, load_step performs two complete edge scans plus a full Tarjan SCC pass before the next deadline check at the seed loop. A short discovery timeout can therefore be exceeded by an arbitrarily expensive step-graph rebuild even though no Dijkstra search has started, contradicting the candidate-generation budget; thread the deadline or a work counter through edge loading and SCC construction so this phase can abort into a truncated result.

Useful? React with 👍 / 👎.

Comment on lines +617 to +619
n_cyc = len(circuit_rows)
lens = np.array([len(c) for c in circuit_rows], dtype=np.int64)
print(f"elementary cycles ever simultaneously active: {n_cyc}")

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Stitch cross-aggregate loops into the audit universe

On an array-reducer model, a recovered loop can traverse the same synthetic aggregate node more than once, so it is not an elementary cycle and this Tiernan enumeration can never add it to circuit_rows; production discovery explicitly stitches these loops from single-aggregate petals before retention. Treating n_cyc as the complete loop universe therefore makes the audit omit stitched mass and report false universe, retention, ranking, and overlap results; run the same petal-stitching semantics over the independently enumerated cycles before scoring them.

AGENTS.md reference: AGENTS.md:L100-L100

Useful? React with 👍 / 👎.

Comment thread notebooks/verify_ltm_discovery_audit.py Outdated
Comment on lines +112 to +114
ok = not (errors or missing or silent or figures == 0)
print("OK" if ok else "FAILED")
return ok

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Fail verification when audit values disagree

If an executed notebook reports enumeration_complete: False, nonzero absent engine loops, a low reported overlap, or score differences above tolerance, every required marker is still present and this expression returns success. The documented audit evidence can therefore be labeled OK even when its own outputs explicitly say discovery and the independent calculation disagree; parse and assert the expected marker values, or have the notebook emit a machine-readable pass/fail predicate that contributes to ok.

AGENTS.md reference: AGENTS.md:L86-L86

Useful? React with 👍 / 👎.

Comment thread notebooks/build_ltm_discovery_audit.py Outdated
Comment on lines +1193 to +1194
exact_set = (len(not_in_universe) == 0 and overlap == len(engine_set))
scores_exact = raw_max <= 1e-9 and rel_max <= 1e-9

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Compare independent counts before declaring the audit exact

When the engine omits universe cycles that fall below retention or outside the reported top 200, all returned loops can still belong to cycle_of_key and overlap py_top_set, making exact_set true even though analysis.universe_loops differs from the independent mass-bearing count or analysis.retained_loops differs from len(survivors). The resulting verdict can claim exact candidate generation and reproducible selection without checking the two counts that expose such omissions; include both independent count equalities in the pass predicate.

AGENTS.md reference: AGENTS.md:L86-L86

Useful? React with 👍 / 👎.

… loops

Each emitted circuit stores its activity AND bitset, so the enumeration's
storage bound is charged in row-equivalents that include those words;
the fallback's per-step graph rebuild is charged against the deadline
like a search (a rebuild over a very large active edge set was the most
expensive thing between two clock reads); the recall harness classifies
a partition as competing from the engine's universe-normalized scores
rather than from the returned loop count; and every surface qualifies
the coverage guarantee to the case where the step-dominant loops fit
the cap.

The audit instrument now reproduces the engine on reducer models, not
only on the two corpus models: the dump carries the NaN-shadow-repaired
activity series where it differs from the recorded one (read through the
new public link_activity_series, so the notebook derives activity from
what discovery reads), the notebook stitches cross-aggregate loops from
petals with the engine's own petal priority and subset walk and keys its
independent universe by trimmed reported identity, and a three-element
reducer fixture (test/cross_agg_ltm) exercises all of it -- seven loops,
reproduced exactly. The notebook emits a machine-readable pass predicate
folding completeness, set exactness, score agreement and the independent
count equalities, and the verifier fails unless it reads PASS and the
headline values agree. The design plan records the finite-overflow
saturation as a stated boundary.
@bpowers

bpowers commented Aug 19, 2026

Copy link
Copy Markdown
Owner Author

@codex review

@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

Here are some automated review suggestions for this pull request.

Reviewed commit: 1166703f1e

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

survivors.extend(
solo_ranked
.iter()
.take(super::max_loops())

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Count Solo survivors before applying the cap

When an exact stockless universe contains more than MAX_LOOPS mass-bearing Solo circuits, this truncation materializes only the first 200 and rank_and_filter consequently reports retained_loops == 200, even though every remaining Solo circuit passed retention by having nonzero mass. Callers therefore see retained_loops == loops.len() and cannot tell that the report was capped. Fresh evidence beyond the earlier Solo-materialization report is that distinct_circuits counts all of these loops while the public pre-cap survivor count is derived only from this truncated list; carry the full Solo survivor count separately.

AGENTS.md reference: src/simlin-engine/AGENTS.md:L185-L185

Useful? React with 👍 / 👎.

let mut valid = 0usize;
for (i, &is_nan) in nan_mask.iter().enumerate() {
if !is_nan {
sum += scratch[i].abs();

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Compute loop averages without overflow

When finite loop products are large over multiple saved steps, this sum can overflow to Inf even though their mathematical mean is representable. Two trimmed-cycle twins with different finite means can then both compare as Inf, causing circuit index rather than strength to choose the representative whose mass enters the exact universe; the analogous Solo accumulator can also select the wrong top-200 set. Use an overflow-safe online or scaled mean so finite averages preserve their ordering.

AGENTS.md reference: src/simlin-engine/AGENTS.md:L185-L185

Useful? React with 👍 / 👎.

}
}

let scc_of = tarjan_scc_of(&adj, n_nodes);

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Check the deadline during the union SCC pass

On a large union graph that remains below the activity-storage limit, this full Tarjan traversal scans every node and active edge without consulting the discovery deadline. A short timeout that expires after the score rows are copied can therefore be exceeded substantially before enumeration yields to the fallback. Fresh evidence beyond the earlier per-root SCC report is that this is the separate union-wide SCC pass inside ActivityGraph::build; thread the deadline/work counter through tarjan_scc_of rather than checking only during row copying and later root pruning.

AGENTS.md reference: src/simlin-engine/AGENTS.md:L185-L185

Useful? React with 👍 / 👎.

Comment thread notebooks/build_ltm_discovery_audit.py Outdated
is_agg_node = [node_names[n].startswith(AGG_PREFIX) for n in range(NN)]
U_FROM_ = [u for u, _ in U]
MAX_AGG_PETALS = 16
CROSS_AGG_LOOP_BUDGET = 10_000

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Mirror the engine's aggregate stitching limits

On a reducer graph with more than eight petals or more than 256 valid stitched combinations, this audit enumerates candidates production never considers: the engine uses MAX_AGG_PETALS = 8 and a model-wide MAX_CROSS_AGG_LOOPS = 256, while the notebook uses 16 and 10,000 (and its inner-loop break does not stop later aggregates). The independent universe can therefore exceed the engine's by thousands of loops and publish false count, score, and selection disagreements. Fresh evidence beyond the earlier missing-stitching report is that stitching is now present but runs under different limits; consume the production limits or reproduce both caps exactly.

AGENTS.md reference: AGENTS.md:L86-L86

Useful? React with 👍 / 👎.

Comment thread notebooks/build_ltm_discovery_audit.py Outdated
Comment on lines +1318 to +1319
audit_pass = bool(analysis.enumeration_complete and exact_set and scores_exact
and counts_agree)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Reject truncated aggregate recovery in the audit verdict

When cross-aggregate recovery hits its petal or loop budget, enumeration_complete can remain true while agg_recovery_truncated is true. If the independent audit mirrors the same bounded stitching selection, all set, score, and count comparisons can agree and this predicate still emits AUDIT VERDICT: PASS, incorrectly certifying an inexact universe. Fresh evidence beyond the earlier verifier-value report is that the new machine-readable predicate omits the engine's separate aggregate-completeness signal; require not analysis.agg_recovery_truncated and verify that value.

AGENTS.md reference: AGENTS.md:L86-L86

Useful? React with 👍 / 👎.

@claude

claude Bot commented Aug 19, 2026

Copy link
Copy Markdown

Review

I inspected the highest-risk surfaces of this PR — the new enumeration and fallback modules (ltm_finding_enum.rs, ltm_finding_fallback.rs), the reshaped ltm_finding.rs orchestration, the libsimlin FFI (ffi.rs/analysis.rs/simlin.h), pysimlin (analysis.py/model.py), and the MCP read/edit outputs — and did not find a discrete, high-confidence correctness bug introduced by this PR that the author would want to fix.

Points I verified against the PR body's claims:

  • Dijkstra weight max(0, -ln|score|) is safe: IndexedSearch::is_active filters zero/NaN before edge_weight is called, and the ClampedLogAbs arm handles super-unit and infinite scores correctly.
  • Completeness plumbing is consistent: the fallback path leaves enumeration_complete = false and universe_loops = None; the Ok(None)/Err arms in analysis.rs reset those fields; MCP always serializes enumerationComplete/retainedLoops while universeLoops is skip_serializing_if = Option::is_none; pysimlin decodes the -1 sentinel for universe_loops back to None.
  • All new #[no_mangle] symbols in analysis.rs/lib.rs are declared in simlin.h, and simlin_free_discovery_result frees analysis_error, loops, periods, and partitions (each helper is null-guarded).
  • Constants match design: ENUM_BUDGET_FRACTION = 0.5 (ltm_finding.rs:2460) and ANCHOR_SHARE_OF_CAP = 0.5 (ltm_finding.rs:3868); the select_reported k-escalation correctly breaks when count_at(k) > anchor_cap.

One informational nit (not a code bug):

  • The PR description says MAX_FALLBACK_PATHS (200,000), but the constant at src/simlin-engine/src/ltm_finding_fallback.rs:1165 is 20_000, and the nearby rustdoc self-consistently references "~90x below the old 200,000." Consider updating the PR body to 20,000 so the design record matches the constant.

Two observations that are missing surface area rather than defects: SimlinDominantPeriod.combined_score is exposed in the C FFI but not in pysimlin's DominantPeriod (run.py:23) or MCP's DominantPeriodOutput (types.rs:204); and model.py:670's if result_ptr == ffi.NULL branch is dead because check_out_error would have raised. Neither affects correctness.

Overall correctness verdict

Correct. No blocking correctness issues identified in this review.

(Reviewed at high confidence on the priority surfaces above; I did not read every line of the two ~1500–1800 line new modules end-to-end, and I did not run the test suite or reproduce the audit-oracle numbers.)

… the SCC pass

retained_loops now counts the mass-bearing Solo loops retention passed
but did not hand over for materialization (only the strongest MAX_LOOPS
Solo loops are), so a capped stockless report reads retained_loops >
len(loops) rather than as the whole retained set. The mean |score|
statistic that decides a twin's representative and a Solo loop's rank,
and FoundLoop::avg_abs_score, are one running (Welford) mean, so a sum
of large finite products cannot overflow where the mean is
representable, and a NaN product with no NaN link is excluded from the
materialized mean exactly as retention's product-derived mask excludes
it. The union-wide SCC pass inside the activity-graph build is charged
against the deadline like every other phase.

The audit instrument reads the engine's own cross-aggregate stitching
caps from the dump (cross_agg_stitching_limits) instead of re-stating
them, stops the stitch walk across every aggregate when the budget is
hit as the engine does, and its pass predicate also requires
agg_recovery_truncated to be false; the verifier checks that value.
All three audits still reproduce the engine exactly.
@bpowers

bpowers commented Aug 19, 2026

Copy link
Copy Markdown
Owner Author

@codex review

@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

Here are some automated review suggestions for this pull request.

Reviewed commit: 5b06246a4b

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

continue;
}
n += 1;
mean += (series[i].abs() - mean) / n as f64;

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Preserve infinite observations in the online mean

When a valid loop-score series contains Inf followed by another valid value, this update produces NaN (Inf + (finite - Inf), or immediately Inf - Inf for a second infinite value). The resulting NaN makes trimmed-cycle representative selection and Solo top-cap ranking fall through to circuit/content order instead of treating the divergent loop as strongest; the mirrored abs_mean accumulator during materialization has the same problem. Handle any infinite observation explicitly—e.g. make the mean remain Inf—while retaining the overflow-safe finite calculation.

AGENTS.md reference: src/simlin-engine/AGENTS.md:L185-L185

Useful? React with 👍 / 👎.

Comment thread src/simlin-engine/src/ltm_finding.rs Outdated
Comment on lines +2817 to +2821
(0..candidates.len())
.filter(|&ci| {
candidates
.circuit(ci)
.iter()

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Check the deadline while collecting aggregate petals

When a reducer-heavy exact enumeration produces a large candidate set, this scan can traverse up to the full 20-million-row enumeration allowance and materialize every single-aggregate path without checking the enumeration deadline; the subsequent stitching call is also reached before retention performs its first check. If the half-budget expires during this work, discovery can spend most or all of the fallback's remaining wall-clock allowance here before noticing, despite the pipeline's bounded-phase contract. Check the deadline/work counter during petal collection and before or within stitching so the fallback receives its intended share.

AGENTS.md reference: src/simlin-engine/AGENTS.md:L185-L185

Useful? React with 👍 / 👎.

&mut scratch[..],
&mut nan_mask[..],
);
work.record(rows.len() as u64 * step_count as u64);

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Interrupt scoring within a single oversized circuit

When one circuit spans many edges or saved steps, score_steps performs the entire len × step_count calculation before this work is recorded, and the deadline is checked only before a later circuit. A single long circuit can therefore exceed the work interval by an arbitrary amount; if it is the final or only circuit, no later check occurs and the run can return enumeration_complete=true and truncated=false even though the deadline expired during retention. Chunk the scoring loop with deadline checks, or at minimum check immediately after oversized work before accepting the enumeration as complete.

AGENTS.md reference: src/simlin-engine/AGENTS.md:L185-L185

Useful? React with 👍 / 👎.

Comment thread src/simlin-engine/src/ltm_finding.rs Outdated
let window = active_window_of(&s);
(Rc::new(s), window)
});
self.cache.entry(key).or_insert(series).clone()

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Bound module-override cache storage by saved-step volume

On a run with many saved steps and many distinct (source, module, exit reader) combinations across candidate loops, every first lookup inserts another full step_count-long Vec<f64> here. Neither the activity-graph byte limit nor the candidate/materialization limits account for this cache, so a multi-output module with thousands of source/reader combinations can allocate gigabytes during retention even while all existing budgets remain below their thresholds. Bound the cache's aggregate series bytes or canonicalize/share entries by the resolved entry/exit pathway before retaining another full series.

AGENTS.md reference: src/simlin-engine/AGENTS.md:L185-L185

Useful? React with 👍 / 👎.

…means

The module-override cache retains one step-count-long series per
distinct (source, module, exit reader); past an aggregate byte budget a
lookup still computes and returns its series but does not retain it, so
a module-dense, many-step model trades memoization for recomputation
instead of growing without bound. Retention reads the clock once more
for work recorded after its last per-circuit check (a final oversized
circuit must not let an expired deadline report success), and the
enumeration path reads it once after petal collection and stitching so
a reducer-heavy universe yields to the fallback with its share intact.
The running mean of |score| treats an infinite observation as an
infinite mean rather than folding it into the update (Inf - Inf is NaN),
in retention and materialization alike.
@bpowers

bpowers commented Aug 19, 2026

Copy link
Copy Markdown
Owner Author

@codex review

@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

Here are some automated review suggestions for this pull request.

Reviewed commit: f193a8440c

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

return false;
}
bucket.push(paths.len() as u32);
paths.push(cycle.to_vec());

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Bound fallback storage by total cycle length

On a large SCC that yields many long distinct cycles, the 20,000-path cap bounds only the number of vectors, while this copies every node in every cycle without charging those bytes to any budget. For example, 20,000 paths averaging 50,000 nodes retain roughly 4 GB of u32 data before score-series materialization begins, so an unbudgeted fallback can OOM despite remaining within the advertised candidate and materialization limits. Track aggregate path-node bytes (or edge rows) and return a truncated sample before copying beyond that bound.

Useful? React with 👍 / 👎.

Comment thread notebooks/build_ltm_discovery_audit.py Outdated
Comment on lines +1332 to +1333
audit_pass = bool(analysis.enumeration_complete and agg_complete and exact_set
and scores_exact and counts_agree)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Require dominant-loop coverage in the audit verdict

When the engine and the mirrored Python selector both miss a step-dominant loop even though the distinct anchors fit the report cap, covered < total_steps is printed but none of exact_set, scores_exact, or counts_agree becomes false, so the notebook and verifier still publish AUDIT VERDICT: PASS. Fresh evidence after the earlier verifier-value issue is that the machine-readable predicate now checks several values but still omits the separately computed gap; include the conditional coverage guarantee in audit_pass so this artifact actually establishes the PR's coverage claim.

AGENTS.md reference: AGENTS.md:L83-L86

Useful? React with 👍 / 👎.

Comment thread src/libsimlin/src/analysis.rs Outdated
Comment on lines +973 to +974
.and_then(|s| CString::new(s).ok())
.map_or(ptr::null_mut(), |s| s.into_raw());

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Preserve analysis errors containing interior NULs

When an invalid protobuf/JSON model contains an interior NUL in a model, module, variable, or equation string that is echoed by the compile diagnostic, CString::new fails here and silently turns the new analysis_error into NULL. The caller then receives exactly the successful-looking empty sampled-result shape this field was added to distinguish from “analysis never ran”; sanitize or escape embedded NULs, or fail the whole FFI conversion rather than discarding the sole diagnostic.

Useful? React with 👍 / 👎.

…sert coverage

The fallback's dedup charges the node ids its kept paths hold against a
byte budget alongside the path count, so many long distinct cycles
cannot retain gigabytes of u32 before any series is materialized; the
sweep reads one "budget spent" predicate for both. libsimlin converts an
analysis diagnostic to a C string with interior NULs replaced rather
than dropped, so a message echoing user-authored model text can never
turn the "analysis never ran" signal into a NULL that reads as a
successful empty sample. The audit notebook's pass predicate includes
the coverage guarantee where it is unconditional (every step's dominant
loop per competing group reported while the k=1 anchors fit the cap).
@bpowers

bpowers commented Aug 19, 2026

Copy link
Copy Markdown
Owner Author

@codex review

@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

Here are some automated review suggestions for this pull request.

Reviewed commit: 7e5b0d40dc

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

Comment on lines +1283 to +1285
if paths.len() >= self.cap || self.nodes + cycle.len() > MAX_FALLBACK_PATH_NODES {
self.full = true;
return false;

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Deduplicate before declaring the node budget full

When retained paths leave less than cycle.len() capacity and this candidate is a rotation of an already-stored cycle, this check marks the dedup full before consulting the fingerprint bucket. The fallback routinely rediscovers cycles across steps and seeds, so a duplicate that consumes no additional storage can prematurely terminate the sweep and omit later shorter candidates even though capacity remains. Check duplicate identity first and apply the node budget only to genuinely new paths; the accompanying test directly assigns dedup.nodes, so it never exercises this production duplicate path.

AGENTS.md reference: AGENTS.md:L100-L100

Useful? React with 👍 / 👎.

Comment on lines +1037 to +1039
out.push(&edge_path, row, &and_stack[base + words..]);
and_stack.truncate(base + words);
if out.len() >= max_circuits || out.total_rows() as u64 > max_edge_rows {

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Enforce the edge-row budget before copying a circuit

When the enumerator is at or near MAX_DISCOVERY_ENUM_EDGE_ROWS, this appends the entire closing circuit and its activity bitset before testing the limit; the strict > check also guarantees another circuit is appended when the previous one lands exactly on the cap. Because a single cycle can contain a large fraction of the graph's nodes, the nominal 20-million-row storage bound can be exceeded by one arbitrarily long circuit and allocation can fail before discovery falls back. Compute the added row-equivalents and reject the circuit before extending out.

AGENTS.md reference: src/simlin-engine/AGENTS.md:L185-L185

Useful? React with 👍 / 👎.

Comment thread notebooks/build_ltm_discovery_audit.py Outdated
Comment on lines +1155 to +1156
both = (~np.isnan(e_raw)) & (~np.isnan(p_raw))
if both.any():

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Validate non-finite masks before passing the audit

If the engine produces NaN at a step where the independent calculation is finite, or vice versa, this intersection simply removes the disagreement from comparison; the relative-score branch repeats the same pattern. The maxima can therefore remain zero and scores_exact can let the notebook publish AUDIT VERDICT: PASS despite different score availability, including the extreme case where there are no jointly finite observations. Assert matching NaN/non-finite masks before comparing the shared finite values.

AGENTS.md reference: AGENTS.md:L86-L86

Useful? React with 👍 / 👎.

The enumerator charges the closing circuit's rows and bitset against the
storage bound before appending it, so one cycle spanning a large share
of the graph cannot carry the bound past its limit; the fallback's dedup
checks a candidate's identity before its storage budget, so a
rediscovered cycle -- routine across steps and seeds -- costs nothing and
cannot end the sweep early for candidates that would have fit. The audit
notebook counts steps where the engine and the independent calculation
disagree about whether a score EXISTS (one NaN, one finite) and fails
its scores on any, instead of comparing only the jointly-finite steps.
@bpowers

bpowers commented Aug 19, 2026

Copy link
Copy Markdown
Owner Author

@codex review

@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

Here are some automated review suggestions for this pull request.

Reviewed commit: 215dfc3e7e

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

Comment thread src/simlin-engine/src/ltm_finding.rs Outdated
Comment on lines +2854 to +2855
for seq in &stitched {
candidates.push_node_path(seq, &activity);

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Charge stitched cycles against the candidate row budget

When an aggregate has several long disjoint petals, stitching reuses each petal across many of the up to 256 emitted subsets, but these push_node_path calls append every stitched edge row and activity bitset without checking MAX_DISCOVERY_ENUM_EDGE_ROWS or the circuit cap. Thus an elementary enumeration that stayed within its 20-million-row allowance can still expand by gigabytes before retention—for eight similarly long petals, each petal can appear in roughly half of the 247 combinations. Fresh evidence after the ordinary-circuit precharge is that stitched additions occur afterward and bypass that check; charge them against the same budget and fall back rather than allowing unbounded allocation.

AGENTS.md reference: src/simlin-engine/AGENTS.md:L185-L185

Useful? React with 👍 / 👎.

Comment on lines +1044 to +1049
while cursor != seed {
if self.path_mark[cursor as usize] == path_generation {
elementary = false;
break;
}
cycle.push(cursor);

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Check the deadline while rebuilding long closure tails

With the production EveryEdge fallback, one reverse-tree tail can contain an arbitrarily large fraction of the graph, yet the deadline is checked only before every 8,192nd closure and never inside this parent-chain walk. If the deadline expires while reconstructing an early very long tail, the fallback continues through the entire tail—and potentially thousands more—before noticing, so the caller's candidate-generation timeout can be exceeded substantially. Count tail hops as work or check the deadline periodically inside this loop.

AGENTS.md reference: src/simlin-engine/AGENTS.md:L185-L185

Useful? React with 👍 / 👎.

…l hops

A stitched cross-aggregate loop is pushed into the candidate set only if
its rows and bitset fit the enumeration's storage bound -- stitching
reuses each petal across many subsets, so the additions can be a
multiple of the petals' own rows -- and a refusal makes the enumeration
incomplete rather than allocating past the bound. The fallback's closure
scan counts each reverse-tail hop as work, so a deadline expiring inside
one very long tail is reached from within the walk.
@bpowers

bpowers commented Aug 19, 2026

Copy link
Copy Markdown
Owner Author

@codex review

@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

Here are some automated review suggestions for this pull request.

Reviewed commit: 6ea83fb198

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

Comment on lines +2883 to +2887
let survivors: Vec<Vec<u32>> = retention
.survivors
.iter()
.map(|&ci| activity.circuit_nodes(candidates.circuit(ci)))
.collect();

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Bound partitioned survivors before materialization

When an exact run has many saved steps and hundreds of partitioned loops that each clear the 0.1% threshold, this forwards every survivor to materialization, where each receives a full step_count-long Vec<(f64, f64)> before the 200-loop report cap runs. The new top-200 retention bound applies only to Solo loops; for example, 639 equally weighted partitioned survivors over one million steps fit the 20-million row-equivalent candidate bound but require roughly 10 GB for score vectors, so discovery can OOM despite its candidate-storage limits. Apply a materialization byte budget or perform cap-aware ranking without retaining every full series.

AGENTS.md reference: src/simlin-engine/AGENTS.md:L185-L185

Useful? React with 👍 / 👎.

Comment on lines +518 to +519
let mut edge_bits = vec![0u64; words];
let mut edge_series = vec![0.0f64; step_count];

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Reject oversized activity rows before allocating scratch

When one saved-step score row is itself larger than MAX_ACTIVITY_GRAPH_BYTES—for example, a sufficiently high-resolution run with tens of millions of saved steps—these scratch vectors allocate the entire row and bitset before any byte-budget check occurs. The process can therefore allocate beyond the stated 512 MB activity-graph bound or OOM instead of abandoning enumeration for the slab-reading fallback; compare bytes_per_edge with the budget before constructing these buffers.

AGENTS.md reference: src/simlin-engine/AGENTS.md:L185-L185

Useful? React with 👍 / 👎.

Comment on lines +1441 to +1444
rebuild_work_since_check += scratch.load_step(search, results, step, config.weight);
if rebuild_work_since_check >= u64::from(DEADLINE_CHECK_INTERVAL) {
rebuild_work_since_check = 0;
if expired(deadline, clock) {

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Check the deadline inside each fallback graph rebuild

On a step with a very large active edge set, load_step still performs both edge scans and the full Tarjan pass before this new work counter can check the deadline, so a short timeout may be exceeded by an arbitrarily expensive rebuild. Fresh evidence after the earlier report is that the attempted fix charges the returned work only after load_step has completed; pass the deadline into the rebuild and check it at bounded intervals instead.

AGENTS.md reference: src/simlin-engine/AGENTS.md:L185-L185

Useful? React with 👍 / 👎.

Comment thread notebooks/build_ltm_discovery_audit.py Outdated
Comment on lines +1160 to +1165
mask_mismatch_steps += int((np.isnan(e_raw) != np.isnan(p_raw)).sum())
both = (~np.isnan(e_raw)) & (~np.isnan(p_raw))
compared_steps += int(both.sum())
if both.any():
denom = np.maximum(np.abs(e_raw[both]), 1e-300)
worst = float((np.abs(e_raw[both] - p_raw[both]) / denom).max())

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Compare infinity signs before passing the audit

When one calculation reports +Inf and the other -Inf, both pass this np.isnan availability check, while the relative error becomes Inf / Inf = NaN; Python's max(raw_max, NaN) then retains the prior finite maximum, and both relative scores can also be NaN after normalization, allowing scores_exact to remain true despite opposite divergent loop signs. Fresh evidence after the earlier mask report is that the added mask checks only NaNs rather than all non-finite classes and signs; compare matching finite/NaN/+Inf/-Inf classifications before the numeric tolerance calculation.

AGENTS.md reference: AGENTS.md:L83-L86

Useful? React with 👍 / 👎.

Comment thread src/simlin-engine/src/ltm_finding.rs Outdated
Comment on lines +2937 to +2941
let (stitched, stitch_truncated) = stitch_cross_agg_node_paths(&search, &outcome.paths);
agg_recovery_truncated = stitch_truncated;
let stitched = new_paths_by_rotation(&outcome.paths, stitched);
node_paths = outcome.paths;
node_paths.extend(stitched);

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Charge fallback stitching against the path-node budget

When the fallback retains several long petals for one aggregate, stitching can reuse each petal in most of the up to 256 combinations, but these new paths are appended without consulting MAX_FALLBACK_PATH_NODES. With eight petals already occupying the allowed 64 million source nodes, subset stitching can copy the same storage roughly 127 times—tens of gigabytes—before score-series materialization, even though the original fallback candidates respected their 256 MB node bound. Enforce the aggregate node budget while constructing stitched paths and mark the sample truncated when it binds.

AGENTS.md reference: src/simlin-engine/AGENTS.md:L185-L185

Useful? React with 👍 / 👎.

Comment on lines +1650 to +1652
let to = self.adj[from][k].to;
let extra = pathways(&self.idents[from], &self.idents[to as usize]);
self.adj[from][k].extra_offsets = extra;

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Share pathway-offset storage across expanded module edges

When an array-expanded module has many element edges sharing the same subscript-stripped (from, module) key, pathway_offsets returns a cloned Vec<usize> for every edge and this assignment retains every clone. A module at the 4,096-pathway allowance with 10,000 expanded edges therefore consumes roughly 320 MB solely for duplicate offsets, outside MAX_ACTIVITY_GRAPH_BYTES, and larger dimensions can OOM before either candidate generator reaches its storage fallback. Store a shared slice/Rc per cache key or include these vectors in a pre-allocation byte budget.

AGENTS.md reference: src/simlin-engine/AGENTS.md:L185-L185

Useful? React with 👍 / 👎.

Comment thread src/simlin-engine/src/ltm_finding.rs Outdated
// per-exit-port override is finite there must not be dropped as inactive
// before retention ever scores it (that shadow was this pipeline's one
// stated blind spot; `IndexedEdge::value_at` closes it).
search.attach_module_pathways(&mut |from, to| module_override_cache.pathway_offsets(from, to));

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Check the deadline while attaching module pathways

On a module-heavy model, this pre-enumeration pass can run the bounded-but-large internal pathway DFS for every distinct module-input key and output-port set without consulting either phase deadline. A short discovery timeout can therefore be exceeded substantially before ActivityGraph::build performs the first clock check, even though pathway attachment is required to build the candidates both generators use; thread the enumeration deadline through this pass and stop at a bounded work interval.

AGENTS.md reference: src/simlin-engine/AGENTS.md:L185-L185

Useful? React with 👍 / 👎.

Discovery had one memory constant per allocation site -- an activity-graph
byte cap, a fallback materialization cap, a path-node cap, an override-cache
cap -- and review kept finding allocations outside all of them (the shared
pathway-offset clones, stitched fallback loops, the survivors' materialized
series, an oversized activity row's scratch). Each cap bounded its own phase
in isolation, so the phases' sum was unbounded. Replace them with a single
MemoryMeter capped at MAX_DISCOVERY_MEMORY_BYTES that every allocating phase
charges before it allocates and yields to when refused: the activity build
abandons, the enumeration reports incomplete (its graph and candidate charge
is released so the fallback is measured against the whole bound), the
fallback truncates. Pathway offsets are shared as Rc<[usize]> per module
edge key instead of cloned per element edge.

The remaining per-phase deadline gaps close too: attach_module_pathways and
the fallback's per-step graph rebuild read the clock inside their passes at
the shared check interval, so a module-heavy model or a step with a very
large active edge set cannot run past a short budget before the first check.

The audit's score comparison classifies each step as finite/NaN/+Inf/-Inf
before the numeric tolerance, so opposite-sign divergence can no longer pass
as Inf/Inf = NaN. All three audits regenerated and PASS; World3 discovery
0.58 s release. Pipeline tests derive their memory thresholds from the
production phases rather than hand-computing them.
@bpowers

bpowers commented Aug 19, 2026

Copy link
Copy Markdown
Owner Author

@codex review

@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

Here are some automated review suggestions for this pull request.

Reviewed commit: 8d4b8436f0

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

Comment thread src/simlin-engine/src/ltm_finding.rs Outdated
Comment on lines +2482 to +2486
.charge(offsets.len() * std::mem::size_of::<usize>())
{
self.pathway_cache.insert(key, Rc::clone(&offsets));
}
offsets

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Stop retaining pathway offsets after the meter refuses them

When the meter is full, this returns the newly allocated Rc<[usize]> even though it was not charged or inserted into pathway_cache; attach_module_pathways then retains it on the current edge. Subsequent array-expanded edges with the same key miss the cache, recompute another full offset list, and retain that too, so a module with thousands of expanded edges can again grow far beyond the 768 MB bound. Fresh evidence after the earlier pathway-sharing report is that the refusal path bypasses both sharing and accounting; propagate the refusal and abandon candidate generation rather than returning storage the meter rejected.

AGENTS.md reference: src/simlin-engine/AGENTS.md:L185-L185

Useful? React with 👍 / 👎.

Comment on lines +1773 to 1775
if scanned & (DEADLINE_CHECK_INTERVAL - 1) == 0 && expired(deadline, clock) {
return false;
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Reattach all pathways before running the fallback

If the enumeration deadline expires here, the pass leaves only a prefix of search edges with extra_offsets; discovery skips enumeration but runs the fallback over that partially initialized graph. For an unprocessed module-input edge whose composite is NaN while an exit pathway is finite, IndexedEdge::value_at consequently treats the edge as inactive and the fallback can miss a real loop despite having time remaining under its own deadline. Either resume attachment against the fallback deadline or avoid searching a partially attached graph.

AGENTS.md reference: src/simlin-engine/AGENTS.md:L185-L185

Useful? React with 👍 / 👎.

Comment on lines +3128 to +3132
let all_paths: Vec<Vec<Ident<Canonical>>> = node_paths
.iter()
.map(|path| {
path.iter()
.map(|&n| search.idents[n as usize].clone())

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Charge structural loop materialization to the memory meter

On a fallback sample containing many long cycles, the meter charges only each path's compact u32 node IDs and future score series, but this creates a simultaneous Ident clone for every node, and the following materialization creates and retains Link objects containing two more Idents per edge. For example, 20 million admitted path nodes cost only about 80 MB in the charged representation but hundreds of megabytes in all_paths and still more in the returned loops, allowing the advertised 768 MB bound to be exceeded substantially. Fresh evidence after the earlier fallback-node-budget report is that the compact paths are now metered while these larger production representations remain uncharged; account for them or consume paths without building this duplicate collection.

AGENTS.md reference: src/simlin-engine/AGENTS.md:L185-L185

Useful? React with 👍 / 👎.

Comment thread notebooks/build_ltm_discovery_audit.py Outdated
for label, value in verdict_rows:
print(f"{label}: {value}")

exact_set = (len(not_in_universe) == 0 and overlap == len(engine_set))

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Require equality with the independently selected set

If the engine omits one independently selected loop—or returns a duplicate in its place—engine_set is merely a smaller subset of py_top_set, yet overlap == len(engine_set) still makes exact_set true. The new universe and survivor count checks do not catch this because retained_loops is a pre-cap count and can remain correct while the final report contains fewer distinct loops, so the notebook can still publish AUDIT VERDICT: PASS for an incomplete top-200 selection. Fresh evidence beyond the earlier independent-count report is that the final selected-set cardinality is still never compared; require engine_set == py_top_set and reject duplicate engine entries.

AGENTS.md reference: AGENTS.md:L86-L86

Useful? React with 👍 / 👎.

…ach or stop

A kept candidate was charged to the discovery meter at its compact u32 node
ids plus its future score series, but on the way to the report it becomes an
Ident path and a Link per edge, so a sample of many long cycles cost several
times what the meter saw. materialized_loop_bytes now takes the node count
and charges that structure too, on both generators' paths and for stitched
loops.

The pathway-offset cache charged a slot list after constructing it and, when
refused, still returned the uncharged list for the edge to retain, so every
later edge of the same key recomputed and retained another. It now charges
first and returns None on refusal, and the attach pass stops there. The
attach pass is a prerequisite of both generators and runs under the caller's
whole deadline instead of the enumeration's share: a partially attached graph
reads some module-input edges as inactive where they are not, so neither
generator may search one, and stopping at the enumeration's share denied the
fallback a graph it still had time to search. Anything but a complete attach
reports an empty, truncated sample.

The audit verdict requires the engine's reported set to EQUAL the independent
selection (not be contained in it) so a post-cap omission cannot pass.
@bpowers

bpowers commented Aug 19, 2026

Copy link
Copy Markdown
Owner Author

@codex review

@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

Here are some automated review suggestions for this pull request.

Reviewed commit: 35dfe15f0c

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

Comment thread src/simlin-engine/src/ltm_finding.rs Outdated
Comment on lines +3052 to +3053
let (stitched, stitch_truncated) =
stitch_cross_agg_node_paths(&search, &petal_circuits);

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Meter stitched loops before building the output vector

When a reducer graph has many long aggregate petals, stitch_cross_agg_node_paths clones the petals into hash sets and fully materializes up to 256 stitched paths before the meter is consulted. The new push_node_path check therefore cannot prevent this allocation: source paths can already occupy the 20-million-row allowance, and cloning them across stitched subsets can consume hundreds of additional megabytes or OOM before the first checked push. Stream or meter the stitching allocations inside the shared stitcher; the fallback call has the same post-construction ordering.

AGENTS.md reference: src/simlin-engine/AGENTS.md:L185-L185

Useful? React with 👍 / 👎.

Comment thread src/simlin-engine/src/ltm_finding.rs Outdated
Comment on lines +2554 to +2562
let series = recompute_module_input_edge_series_for(
self.causal_graph,
self.results,
&key.0,
&key.1,
&key.2,
self.step_count,
self.sub_model_output_ports,
)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Reserve module override space before recomputing it

On a module-traversing run with many saved steps, this recomputation allocates a full step_count series—and multiple simultaneous series when max-abs folding several pathways—before line 2570 asks the meter for space. If the meter is already near its cap, the refusal path still returns and holds the uncharged series while scoring, so discovery can exceed the advertised 768 MB bound or OOM despite the cache itself being bounded. Precharge a scratch/output allowance before recomputation or fold the slab rows in place under a reserved allocation.

AGENTS.md reference: src/simlin-engine/AGENTS.md:L185-L185

Useful? React with 👍 / 👎.

Comment on lines +1338 to +1340
let sum = totals[t] + mass;
totals[t] = if sum.is_infinite() && mass.is_finite() && totals[t].is_finite() {
f64::MAX

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Use overflow-safe partition normalization

When two or more finite loop masses at one saved step sum above f64::MAX, replacing their denominator with f64::MAX does not preserve their shares. For example, two 1e308 loops each receive a relative magnitude of about 0.556 rather than 0.5, so relative scores no longer sum to one and the error can change retention, ranking, and coverage-anchor selection. Compute ratios with a scaled sum (for example, divide all masses by the step maximum before summing) rather than saturating the denominator.

AGENTS.md reference: src/simlin-engine/AGENTS.md:L185-L185

Useful? React with 👍 / 👎.

@bpowers bpowers Aug 19, 2026 •

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Declining this one, and it is the standing finite-overflow boundary rather than a new decision: the design doc ("Additional Considerations -> Finite-overflow boundary") records that saturating the per-step total compresses shares past f64::MAX (your 0.556 vs 0.5 example is exactly that compression) and that it is accepted because no recorded link-score series comes within 1e290 of the regime. An exact fix is not a local scaled sum: the running total is streamed across circuits in one pass (the bound that lets a non-survivor never be scored twice), so "divide by the step maximum before summing" needs the per-step maximum before the pass, i.e. a second pass over every circuit's product -- and the exported partition totals are what rank_and_filter, the pysimlin relative scores and the audit all divide by, so the scale would have to travel with every consumer of a total. That is the log-domain/scaled-accumulation-everywhere cost the note declines for a regime where the loops' own products are already at the overflow edge and their relative ranking is not meaningful. Kept as a documented boundary; it is not silent (the note names it and the test a_finite_partition_total_saturates_instead_of_overflowing_to_inf pins the saturating arm).

Comment thread src/simlin-engine/src/ltm_finding.rs Outdated
Comment on lines +2849 to +2855
enumeration_complete: enumeration_ran,
retained_loops: 0,
// Discovery bails before either generator runs, so the universe
// is EMPTY rather than unknown -- and only the enumeration path
// may say so, keeping `universe_loops.is_some()` equal to
// `enumeration_complete` on every path out of this function.
universe_loops: enumeration_ran.then_some(0),

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Do not certify missing instrumentation as an empty universe

When Model.analyze runs on a conveyor or queue model, analysis.rs compiles the expanded SourceProject with ltm_enabled false, so the results contain no link-score variables even if the model has feedback. That makes parse_link_offsets empty here, and this branch now reports enumeration_complete=true and universe_loops=0 although no candidate generator ran and the empty result is only the documented LTM degradation. Surface this as unavailable/unknown, or establish from the causal graph that the universe is genuinely empty before certifying exactness.

AGENTS.md reference: src/simlin-engine/AGENTS.md:L185-L185

Useful? React with 👍 / 👎.

Two discovery phases still allocated before asking the meter. The cross-agg
stitcher cloned every single-agg candidate circuit into petal structures
(on a reducer-heavy universe, the whole universe) before the first metered
push; the collector now streams the candidate paths and keeps only the
MAX_AGG_PETALS + 1 smallest petals per agg, which is exactly enough for the
stitcher to reproduce the unbounded output and its truncation flag, charging
each kept petal as it goes and the stitched output at its upper bound before
it is built. The internal-set representative is the smallest node sequence
rather than the first seen, so the collection is a function of the circuit
set and the bounded stream is exact. The module-override cache recomputed a
series (and a per-pathway copy each) before charging it and, when refused,
returned it anyway; it now charges one step_count buffer first, folds the
pathway rows in place into it, and answers a distinct OutOfMemory that
abandons retention or drops the loop as truncated, since scoring the edge
on its composite instead is a wrong number.

A run with no recorded link score on a model that has causal edges was not
instrumented (LTM off, or a conveyor/queue model); discovery now reports the
unknown shape for it instead of certifying an empty universe, which only an
edgeless model earns.
@bpowers
bpowers merged commit 9fdfb5e into main Aug 20, 2026
16 checks passed
@bpowers
bpowers deleted the ltm-discovery-enumeration branch August 20, 2026 02:18
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-finding: SearchGraph clones Ident<Canonical> in per-timestep DFS hot path

1 participant