Skip to content

perf(studio): bound the projection host — lifetime-run retention, unbounded unknown-run adoption, seq shape guard, adoption re-arm on respawn - #488

Merged
KnockOutEZ merged 3 commits into
studio-handofffrom
sd-137-perf-studio-bound-the-projection
Aug 26, 2026
Merged

KnockOutEZ merged 3 commits into
studio-handofffrom
sd-137-perf-studio-bound-the-projection

Conversation

@KnockOutEZ

@KnockOutEZ KnockOutEZ commented Aug 26, 2026 •

Copy link
Copy Markdown
Owner

Closes SD1 exit-16 issue #137 (KnockOutEZ/wigolo-studio-run).

Four retention/robustness holes in the projection host, all in apps/studio/src/main/run-view-model.ts.

1 — the only unbounded retention left on the host

seal bounded what a finished run costs (its envelopes go, its projection stays) and left the count
unbounded: there is no logs.delete, no statusRereads.delete and no clear anywhere in the class,
runs are never deleted, and hydrate deliberately keeps runs a later listing did not name. So every
map here gained one entry per run the machine had ever run and gave none of it back for the life of
the app.

MAX_RETAINED_SEALED_RUNS = 500 now evicts terminal, unwatched, sealed runs. That is the one class
that can be dropped without changing an answer, because it can never become listable again —
isListable re-opens only on visibility === 'visible', and applyVisibility refuses to promote a run
that has ended. Anything that does ask afterwards re-adopts from the store via applyEvent's
unknown-run arm. A run that still owns a tab is exempt whatever the bound says: law 4 outranks
memory, because dropping it would drop its rows from the tab index and a tab with no owner is the
human's.

Eviction is ordered by the run's own createdAt, and the cut is batched behind
SEALED_EVICTION_SLACK. Self-review caught filing-order eviction as wrong in the direction that
matters: hydrate pages the listing newest-first (ORDER BY created_at DESC, id DESC), so dropping
the least-recently-filed run would keep the machine's oldest 500 finished runs and evict everything a
human might still be looking for — while live folding files in the opposite order again. No filing rule
is right for both producers; the run's birth is right for both, because it is a fact about the run
rather than about the walk that found it. Ordering by it costs a sort, so the cut is batched — a
per-run sort at boot is the 10,000-run shape that already measured 1.3 s of nothing but map deletion in
tabsByRun's note. hydrate then ends with a cut that takes no slack, because the runs still
sitting in the slack when the last page lands are the oldest on the machine: every cut before it was
correct and the tail undid them.

None of that was reachable from a test until a second bug was fixed: FakeRunStore listed
oldest-first
while the real store lists newest-first. Every host decision about a boot page turns on
the newest runs being the ones it can afford to hold (MAX_BOOT_HYDRATION_EVENTS says so in as many
words), so a fixture listing the other way made those arms exercise the one direction the real store
never takes. See Collateral below.

Before / after: 2,000 terminal + 2 live runs retain 2,002 → ≤ 602 while folding, and an 800-run
boot retains exactly 500, newest-born kept.

2 — listLive walked every retained run per fan-out

Three listeners call it on every fan-out — the state push, the tray menu, the presentation controller —
at up to 60 Hz, on the thread that paints, and the walk was over logs. It now walks a live candidate
set, pruned on the read. Sound because a candidate can only go stale in one direction: listability is
!terminal || visible, a terminal run cannot be promoted, and the clock cannot move either input.

runForSession was the second such scan (per session, per studio_list) and is now an index written
from the same run.created fact the session link is replayed from, first-writer-wins so it
reproduces the scan's answer rather than silently taking the last writer.

3 — unknown-run adoption was unbounded

overBound opens if (!log) return false, so replayOnce's short-circuit could never speak for a run
this process is not holding — which is precisely the path applyEvent's unknown-run arm takes for a
REST-created run. It paged the entire log with no total cap and retain stored every envelope; the
live-run bound then fired only on the next envelope, so a run that went quiet held its whole log.

readLog now takes a total stop and replayOnce passes REMATERIALIZE_MAX_EVENTS, condensing past it
with the store's own projection. Capped at the read as well as at the retention, because skipping the
retention alone would still have paged and parsed the whole log. replayOnce's replace arm is untouched.

Before / after, the exit's own probe (a 2,501-envelope unknown run): retainedEventCount()
2,501 → 0, condensed immediately rather than on a later envelope. A 6,001-envelope run stops paging
within one page of the bound instead of walking all 6,001.

4 — fold-path seq shape guard (hardening; unreachable at tip)

A run-event notify envelope is JSON cast to RunEvent with nothing between the wire and the cast.
seq === undefined passes both comparisons — undefined <= n and undefined > n + 1 are each
false — so it folded and set lastSeq = undefined. Every later comparison against undefined is false
too, so no gap could ever open for that run again: gap detection dead, silently, with no self-heal. One
Number.isInteger(event.seq) early-out routes it to adopt(replace), placed ahead of the unknown-run
arm so the internal fold path is covered by the same guard.

5 — exhausted adoption re-arm on respawn

After MAX_ADOPT_RETRIES (~62 s) the chain pins with a no-op stop, deliberately not re-armed by the
next failing envelope. That bound is right, and it left the hole its own note names: a REST-created run
whose only envelope is its run.created has no later envelope at all, so a brownout longer than the
chain left it invisible until restart.

ADOPT_RETRY_BASE_MS says: "a health signal from the broker would be the sharper trigger, and there is
no such signal to subscribe to… reverse this the day the broker publishes a reachability event."

BrokerClient.onReady is that event — the child's ready notify, at boot and on every respawn — and
exhausted chains re-arm from it at attempt one. Strictly narrower than the trigger the note refuses:
once per respawn, not once per refused envelope.

Demo — test output

before after
retainedRunCount() at 2,000 terminal + 2 live runs 2,002 ≤ 602
retainedRunCount() after an 800-run boot 800 500 (exact — boot cuts with no slack)
retainedEventCount() for the exit's 2,501-envelope unknown run, immediately after adoption 2,501 0 (condensed)
envelopes paged by the unknown-run read, 6,001-envelope run 6,001 ≤ 2,500
walk cost: status reads on 200 finished runs across 10 fan-outs 2,000 0

Seven red probes, each flipping the guard it protects and turning only the intended rows red before
being put back:

=== PROBE: evict ===      (eviction disabled)
     × drops terminal, unwatched, sealed runs past the bound, and keeps every live one
     × keeps the most recently BORN finished runs when boot hands them over newest-first
     × re-adopts an evicted run from the store when a later envelope arrives for it
     × drops the per-run rows the log is not the only one of
      Tests  4 failed | 82 passed (86)
=== PROBE: order ===      (cut reverted to filing order)
     × keeps the most recently BORN finished runs when boot hands them over newest-first
      Tests  1 failed | 85 passed (86)
=== PROBE: boottrim ===   (hydrate's no-slack cut removed)
     × keeps the most recently BORN finished runs when boot hands them over newest-first
      Tests  1 failed | 85 passed (86)
=== PROBE: live ===       (listLive reverted to the `logs` walk)
     × does not touch a finished run's projection on a fan-out
      Tests  1 failed | 85 passed (86)
=== PROBE: adopt ===      (unknown-run read cap removed)
     × condenses a 2,501-envelope unknown run immediately, not on its next envelope
     × stops PAGING the log once it is past the bound, rather than reading it all and discarding it
      Tests  2 failed | 84 passed (86)
=== PROBE: seq ===        (Number.isInteger guard removed)
     × leaves the tail an integer and keeps gap detection alive
     × re-reads the run rather than dropping the envelope on the floor
      Tests  2 failed | 84 passed (86)
=== PROBE: ready ===      (onReady subscription dropped)
     × re-arms an exhausted adoption when the background service comes back, with no further envelope and no restart
     × starts a fresh chain if the service goes down again, rather than re-arming into an exhausted one
      Tests  2 failed | 84 passed (86)

The walk pin is worth naming because it is not a stopwatch: the fixture's store hands back kept
projections whose status getter counts its own reads, so "did this fan-out visit this finished run"
is observable per run. Only a finished run's projection counts — a live one is read on every fan-out by
design, and counting it would have made the bound a number rather than a claim.

Collateral — repaired, never relaxed

The retention bound intercepted one fixture; the fake-store order fix intercepted five more.

  1. ipc-state-payload-cardinality.test.ts asserted the lifetime listing was > 200_000 bytes, which the
    bound now gives a ceiling. Its claim was always the ratio between what a broadcast used to carry
    and what it carries now, so it keeps that and additionally asserts the ceiling — a regression that
    un-bounded retention cannot show up as this arm getting healthier.
  2. Three order-identity assertions (vm.list() order, ownerOf by index position) now state the
    store's real newest-first order.
  3. One asserted the hydration allowance tripped on the last-created run; with the listing the right
    way round it is the oldest run the allowance never reaches. Same claim, correct subject.
  4. The tab-ownership tie-break: when a log holds two tab.attached facts for one tab from two runs,
    indexTabs gives it to whichever run was hydrated last — which under a newest-first listing is
    the run created earlier, not the one whose attach is later in log time. Not reachable through
    attachTab, which refuses at the single seam (law 4), so only a foreign writer can produce it, and
    the index stays internally consistent either way. Out of scope: the test now states the real
    behaviour and it is filed as one line in known-issues.md rather than silently changed.

Gates

root      npm test                  12 067 passed | 20 skipped | 7 todo   exit 0
studio    cd apps/studio && npm test          689 passed (58 files)       exit 0
studio    RUN_STUDIO_E2E=1 e2e      117 passed | 21 skipped               exit 0
          npx tsc --noEmit                                                exit 0
          npm run typecheck:studio                                        exit 0
          npm run gate:studio                                             exit 0
          npm run lint -w apps/studio                                     exit 0

No regression on the #117 / #129 / #131 / #132 perf pins.

Non-goals honoured

No store or broker protocol change. No hydration budget rework. No change to REMATERIALIZE_MAX_EVENTS
semantics for known runs — the constant and its meaning are unchanged; it is now also applied at the one
read that could never reach it.

Decisions and reversal conditions are recorded in internal-docs/superpowers/plans/DECISIONS-AUTO.md
(2026-08-27), including the one real semantic change: list() is now a bounded history read.

Four retention holes in run-view-model, all verified at SD1 exit-16.

Retention: logs and statusRereads gained one entry per LIFETIME run with no
delete anywhere, so memory grew monotonically for the life of the app.
Terminal, unwatched, sealed runs past MAX_RETAINED_SEALED_RUNS are now
evicted — that class can never become listable again, because isListable
re-opens only on visibility and applyVisibility refuses to promote a run
that has ended. A run still owning a tab is never dropped whatever the
bound says. Anything that asks afterwards re-adopts from the store.

listLive walked every retained run on every fan-out, with three listeners
calling it at up to 60 Hz on the thread that paints. It now walks a live
candidate set, pruned on the read — a candidate can only ever be stale in
one direction, so a late prune answers identically. runForSession was the
second such scan and is now an index written from the same run.created
fact the session link is replayed from.

Unknown-run adoption: overBound opens 'if (!log) return false', so no
short-circuit was ever available on applyEvent's unknown-run arm — it read
the ENTIRE log with no total cap and retained every envelope, and the
live-run bound only fired on the NEXT envelope. readLog now takes a total
stop, and replayOnce passes the retention bound and condenses past it.

Seq shape: a run-event notify envelope is cast unvalidated, and seq ===
undefined passes both comparisons, folds, and sets lastSeq = undefined —
gap detection dead for that run with no self-heal, since every later
comparison against undefined is false too. A Number.isInteger early-out
routes it to a replace-adoption, ahead of the unknown-run arm so the
internal fold path is covered by the same guard.

Adoption re-arm: after MAX_ADOPT_RETRIES the chain pins with a no-op stop,
and a REST-created run whose only envelope is its run.created has no later
envelope to re-trigger it — so a brownout longer than ~62s left it
invisible until restart. The bound's own note names broker reachability as
the missing signal; BrokerClient now publishes onReady on every respawn and
exhausted chains are re-armed from it. One trigger per respawn, not one per
refused envelope, so the spin the count bound prevents stays prevented.
… seq bounds

Four arms, each red-probed by flipping the guard it protects.

Retention: 750 finished runs retain 500 plus the live one, oldest evicted
first, an evicted run re-adopts on a later envelope, a run still owning a
tab is exempt, and the session index drops with the run rather than
pointing at one that is gone.

The walk: a store whose kept projections count reads of their own status,
so 'did the fan-out visit this finished run' is observable per run without
a stopwatch. 200 finished runs cost 2,000 status reads across ten fan-outs
before, 0 after. Only a finished run's projection counts — a live one is
read on every fan-out by design, and counting it would make the bound a
number rather than a claim.

Adoption: the exit's own probe, a 2,501-envelope run the projection has
never seen, condensed immediately rather than on its next envelope; a
6,001-envelope one stops paging within a page of the bound; and a short
unknown run still materializes, which is the control for both.

Seq: a seq-less envelope leaves the tail an integer, is not folded, and
leaves gap detection alive — asserted by opening a real gap afterwards,
which is the state that used to be unreachable.

Re-arm: an exhausted chain recovers on the service's ready edge with no
further envelope and no restart; a second brownout restarts the chain at
the base backoff rather than re-arming into an exhausted one; and a chain
that is still retrying is left alone, so a flapping service is not read
once per flap.

ipc-state-payload-cardinality measured the lifetime listing at >200 KB,
which the retention bound gives a ceiling. Repaired rather than relaxed:
it now asserts the ceiling as well, so a regression that un-bounded
retention cannot show up as this arm getting healthier.
@coderabbitai

coderabbitai Bot commented Aug 26, 2026 •

Copy link
Copy Markdown

Important

Review skipped

Auto reviews are disabled on base/target branches other than the default branch.

Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro Plus

Run ID: 0ae0d2b7-710f-4181-b0d7-5e0279dfca20

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

Use the checkbox below for a quick retry:

  • 🔍 Trigger review

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@KnockOutEZ KnockOutEZ closed this Aug 26, 2026
@KnockOutEZ KnockOutEZ reopened this Aug 26, 2026
…ewest-first

Self-review found the eviction order wrong in the direction that matters,
and a fixture-fidelity bug that made it unfalsifiable.

hydrate pages the store's listing NEWEST-FIRST (ORDER BY created_at DESC,
id DESC), so evicting the least-recently-filed run drops the newest
finished run on the machine and keeps the oldest five hundred — the
inverse of the intent, and invisible to any assertion about the count.
Live folding files in the opposite order again, so no filing rule is right
for both producers. The cut now orders by the run's own createdAt, which is
a fact about the run rather than about the walk that found it.

Ordering by it costs a sort, so the cut is batched behind
SEALED_EVICTION_SLACK rather than run per sealed run — at boot a per-run
sort is the 10,000-run shape that already measured 1.3s of nothing but map
deletion in tabsByRun's note. hydrate then ends with a cut that takes no
slack, because the runs still sitting in the slack when the last page lands
are the oldest on the machine: every cut before it was correct and the tail
undid them.

None of that was reachable from a test, because the fake store listed in
insertion order — oldest first. Every host decision about a boot page turns
on the newest runs being the ones it can afford to hold
(MAX_BOOT_HYDRATION_EVENTS says so directly), so a fixture listing the
other way makes those arms exercise the direction the real store never
takes. Fixed, and the five collateral reds it produced are repaired rather
than relaxed: three were order-identity assertions that now state the
store's real order, one asserted the allowance tripped on the last-CREATED
run when it is the oldest that the allowance never reaches, and one is the
tab-ownership tie-break, whose real behaviour is now stated in the test and
filed in known-issues.md rather than silently changed.
@KnockOutEZ
KnockOutEZ merged commit 2e4f0c9 into studio-handoff Aug 26, 2026
25 checks passed
@KnockOutEZ
KnockOutEZ deleted the sd-137-perf-studio-bound-the-projection branch August 26, 2026 23:52
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant