Skip to content

Retire an empty older terminal daemon instead of keeping it until quit - #51325

Closed
brennanb2025 wants to merge 35 commits into
mainfrom
brennanb2025/retire-empty-old-daemon
Closed

brennanb2025 wants to merge 35 commits into
mainfrom
brennanb2025/retire-empty-old-daemon

Conversation

@brennanb2025

@brennanb2025 brennanb2025 commented Nov 28, 2026 •

Copy link
Copy Markdown
Contributor

ELI5

After an update that starts a new terminal background process, the old one used to stay running until you quit Orca, even after every terminal and chat agent it held had ended. It used about 100 MB doing nothing. Now it exits by itself as soon as it has nothing left. Terminals you reopen keep working right up to that moment.

Files Added Deleted Net
Test 1 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​755 0 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​755
Prod 19 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​1204 $\color{#cf222e}{\Huge{\mathbf{−}}}$​73 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​1131

What Changed

  • New daemon request retireWhenIdle. The app sends it to an older-generation daemon, naming its own newer protocol. After that, the connection no longer keeps the daemon alive. The daemon's existing idle shutdown retires it the moment it owns no terminals, chat agents (including ended ones with unread output) or in-flight attaches, and it refuses new work in that same step. A daemon refuses the request unless a newer protocol is named, so the current generation never retires this way.
  • App side (DaemonRouterSpawn, DaemonRouterLegacyIdleRetirement): the app forgets an older generation once its endpoint and process are proven gone. A reopen it refused mid-retirement is routed again to the current generation. New terminals always go to the current one.
  • A retired generation gets no new work at once, but stays subscribed until its connection has closed and drained and no watched terminal's exit is still owed (a WSL pane's comes late), bounded at 30 s (daemon-router-retired-exit-delivery.ts). A restart of the current daemon carries such a generation over.
  • Daemons that predate the request (v63 and older) answer it as unknown. For them, the app asks shutdownIfIdle after their exits and holds reattaches that can reach that generation around its decision. Reattaches to other generations don't wait. That transitional path lives in its own file (daemon-router-pre-rpc-retirement.ts), to delete once those daemons are gone.

Why

Old sessions stay on the old daemon until they end, but nothing ended the daemon itself. Only the daemon knows the exact moment its own work reaches zero, so the decision lives there, with no polling.

Linked Issue

None. Follow-ups, each leaving an older daemon running until quit as it does today, are tracked in STA-19443 (pre-request daemon after a transient disconnect) and STA-19444 (degraded mode). A pre-existing stream-drain gap this path relies on is tracked in STA-19477.

Visual Proof

N/A: no UI change.

Testing

  • daemon-router-legacy-idle-retirement.test.ts runs two real daemons through real adapters and the router. It covers:
    • reattach across an app restart, and retirement after the last terminal;
    • the current daemon staying up and refusing retireWhenIdle;
    • a reopen that reaches the old daemon after it decided landing on the current one;
    • reattach fencing on the pre-request path, per generation, and never for terminals on the current daemon;
    • a retired generation kept subscribed until its owed exits and stream are delivered, including across a restart;
    • the transitional recheck existing only while a pre-request daemon remains, and stopping after its cap.
  • I manually tested these changes (packaged builds, below)
  • Automated tests added/updated
  • Every added test fails without this change and avoids the test anti-patterns
  • Packaged builds on Linux and Windows, two flows each: the v1.4.280 release (v63) followed by this PR, and this PR as v64 followed by a test-only v65. All steps passed:
    • old terminals reattached, also after a restart;
    • the old daemon shut down 20 ms to 1.1 s after its last terminal;
    • a terminal opened during that shutdown worked on the current daemon;
    • the empty current daemon stayed up past 2 minutes.

Performance

An empty old daemon (~100 MB, ~0.6 wakeups/s) now exits, and newer daemons need no app-side timer. Only a pre-request daemon that still holds chat agents or unattached terminals is rechecked: every 1 min backing off to 30 min, at most six times, then only on its next exit or refused reopen. No inventory is read while this app still watches one of its terminals. A reopen refused by a retiring daemon waits at most ~4 s before it is routed again; one that went to the current daemon never retries.

Risk

Level: Medium. The riskiest part is a terminal reopen racing the old daemon's exit. The daemon decides atomically, and the app routes a refused reopen to the current daemon. A plain revert brings back today's behavior, where older daemons stay until quit.

AI Disclosure

Review

Agent skill upstream boundary

  • Not applicable, or this change copies or mechanically translates no upstream skill-installer source, tests, fixtures, registry entries, path tables, comments, or documentation.

Notes

Security: the new request only lowers this connection's keep-alive weight. It needs an authenticated client and is refused unless that client names a newer protocol. Cross-platform: the logic is the same on all three; Windows proves exit by the missing pipe, POSIX by the missing endpoint and process. SSH, mobile and WSL: unchanged. Backwards compatibility: older daemons answer the request as unknown and keep the app-driven path.

Checklist

  • This PR is small and focused
  • I explained what changed and why (ELI5, the user-facing before/after, the mechanism, and why over the alternatives)
  • I stated the risk: what could break, for whom, and how to back it out
  • Before/after screenshots or videos attached for UI changes, or N/A with reason
  • Self-reviewed for correctness, security, and performance
  • Cross-platform, SSH/remote, and path/shortcut impact considered (or N/A)
  • pnpm lint, pnpm typecheck, pnpm test, and pnpm build pass (or CI will cover; local preferred)

…; re-ask on every reconnect; drain the last output; settle lost or slow decisions
@brennanb2025
brennanb2025 marked this pull request as ready for review November 28, 2026 05:17
@coderabbitai

coderabbitai Bot commented Nov 28, 2026 •

Copy link
Copy Markdown
Contributor

Explain Change →

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • Resume reviews
  • Trigger review
Walkthrough

The change adds server handling for idle-retirement requests from newer clients. The router tracks retirement of eligible legacy daemons, including a pre-RPC retirement path for older generations. Spawn routing coordinates reattach admission and retries with retirement state. Tests cover retirement, reattachment, transitional generations, and retry timing.

Merge Risk: Low · up to 0f67a

Older daemons now retire when idle. In edge cases a refused terminal reopen can lose a pending exit notification or fail before the retirement check settles. Both are narrow and recoverable, but should be fixed before merge if feasible.

Pre-merge checks: Passed 4

Check name Status Explanation
Title check Passed The title "Retire an empty older terminal daemon instead of keeping it until quit" matches the main change. The PR adds a retireWhenIdle request so an older-generation daemon exits once it owns no ter…
Linked Issues check Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check Passed Check skipped because no linked issues were found for this pull request.
Description check Passed The description follows the repository template and covers the main sections. The ELI5, What Changed, Why, Testing, Performance, Risk, and Checklist sections are substantive and match the change set. …
Full details: Title check

Explanation

The title "Retire an empty older terminal daemon instead of keeping it until quit" matches the main change. The PR adds a retireWhenIdle request so an older-generation daemon exits once it owns no terminals, chat agents, or in-flight attaches, rather than staying alive until Orca quits. The title is specific and concise, and it does not cover the pre-request transitional path, which is acceptable.

Full details: Description check

Explanation

The description follows the repository template and covers the main sections. The ELI5, What Changed, Why, Testing, Performance, Risk, and Checklist sections are substantive and match the change set. The change adds a retireWhenIdle request, app-side retirement logic, and a transitional pre-request path for v63 and older daemons. Gaps: the Linked Issue section says 'None' and names only follow-up issues, and the template requires an actual linked issue for outside contributors. The Visual Proof section is N/A with a reason, which is acceptable. The Review section is blank. The AI Disclosure section is blank, and the template says to fill it in unless the author is a StablyAI team member. The Testing checkboxes are checked, but the description does not list the exact commands run. Some reported packaged-build results are not independently verifiable from the diff.

Finishing Touches

Fix failing CI checks

  • Commit to this branch
  • Create a new PR
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

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

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 6

Additional comments: 1

src/main/daemon/providers/routing/daemon-router-legacy-idle-retirement.ts-129-129: 1

129-129: Major · Stability & Availability · Quick win

Unverified finding
Verification ran but could not confirm this finding. It is shown for review, not as a verified issue.

Recheck controller ownership after confirmation returns.

If disposeRouterOnly() runs while confirmation is reconnecting, the old controller can still call hold() when the result comes back. It can send a retirement request on an adapter the new router has reused. Recheck disposal, legacy membership, and the current confirmation state after the await. Apply the result only if the controller still owns it.

Based on learnings, revalidate an asynchronous result before it writes state or schedules work after a reset.

Source: Learnings

Review info

Run configuration

  • Source mode: Auto
  • Repository: Unavailable
  • Branch: Unavailable
  • File: No configuration file from this repository applied
  • Commit: Unavailable
  • Layers: Repository UI
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: bf6a7dbf-1c90-4a63-8192-a2083f1e8b9d
Commits

Reviewing files that changed from the base of the PR and between ea95a40 and cfbffbd.

Files selected for processing: 16

  • src/main/daemon/providers/adapter/daemon-pty-event-subscriptions.ts
  • src/main/daemon/providers/adapter/daemon-pty-preserved-host-loss.ts
  • src/main/daemon/providers/adapter/daemon-pty-retire-when-idle.ts
  • src/main/daemon/providers/routing/daemon-legacy-exit-proof.ts
  • src/main/daemon/providers/routing/daemon-pty-router.ts
  • src/main/daemon/providers/routing/daemon-router-exited-legacy.ts
  • src/main/daemon/providers/routing/daemon-router-legacy-idle-retirement.test.ts
  • src/main/daemon/providers/routing/daemon-router-legacy-idle-retirement.ts
  • src/main/daemon/providers/routing/daemon-router-pre-rpc-retirement.ts
  • src/main/daemon/providers/routing/daemon-router-spawn.ts
  • src/main/daemon/providers/routing/daemon-session-owner-resolution.ts
  • src/main/daemon/server/daemon-client-connections.ts
  • src/main/daemon/server/daemon-server-lifecycle.ts
  • src/main/daemon/server/daemon-server.ts
  • src/main/daemon/server/daemon-shutdown-requests.ts
  • src/main/daemon/server/daemon-superseded-clients.ts

Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 0 remain after this review.

…d; tie retirement proof to its incarnation; bounded ask retries
@brennanb2025

Copy link
Copy Markdown
Contributor Author

Performance review (head 0a812a4)

Verdict: FAIL. Two P1 findings, both on the transitional path for older daemons (protocol v63 and before) that predate retireWhenIdle. The held path for v64 and later adds no steady idle work and no per-event fleet-scaled work. Everything below comes from reading the source at head against 339594e. Nothing was run. Counts are source-proven; byte sizes are estimates.

Findings

P1-1: new steady idle wakeup on Electron main and on the old daemon (pre-request path)

  • Where: daemon-router-pre-rpc-retirement.ts, checkAgainLater / schedule (RECHECK_MS 60 s, RECHECK_MAX_MS 30 min). retireIfEmpty arms it whenever the inventory shows a live relay or a session the app does not watch (chat agents, unattached terminals).
  • Trigger: one timer per v63-or-older generation, for as long as it holds unwatched work. Each firing sends one listSessions RPC: main parses S rows and the old daemon serializes them.
  • Cadence: 60 s, 2, 4, 8, 16 min, then every 30 min with no end while that work lives. That can be days if an agent stays open.
  • Before: 0 wakeups/s for this owner. After: about 1.7e-2/s at first, settling at 5.6e-4/s per such generation, on main and on that daemon.
  • Why P1: the grading rule treats a new idle wakeup going from 0 to more than 0 as P1, however cheap it is. The PR description says this timer exists.
  • Possible remedy (not verified): bound it the way the ask retries already are (ASK_RETRY_DELAYS_MS). After a few rechecks, only exits, discovery, reattach or quit would look again. The cost is that a v63 daemon whose last work is a chat agent would stay until quit, as it does today.
  • Check that proves it: fake timers, a v63-style adapter whose inventory always returns one unwatched session. Count inventories over 10 simulated hours. Head gives about 25 and keeps growing; a bounded version gives a constant.

P1-2: a full inventory on every exit that cannot retire anything while watched sessions remain

  • Where: daemon-router-pre-rpc-retirement.ts, noteActivity → schedule → check → retireIfEmpty. It calls adapter.listSessionsAndRelays() with no gate. The router's exit fanout (daemon-pty-router.ts, the noteActivity(adapter) call in the subscription callback) triggers it on every exit from that generation, after a 250 ms settle.
  • Work per exit: one RPC returning all S sessions. The old daemon serializes S rows. Main parses them, then filters and spreads each row, copies getActiveSessionIds() into a Set and runs some(): about 3×S operations.
  • Wasted when: while the adapter still watches any live session, the result has sessions.length > 0. It returns without a decision and arms no recheck unless unwatched work exists, so only the last watched exit's inventory can lead to retirement.
  • Price at the reference fleet, right after updating from v63 (every user on that release crosses this path once): S ≈ 300 terminals on the old generation. Closing them one at a time is about 300 inventories and about 45k rows parsed on main over the drain (S²/2). At 10× (S = 3,000) that is about 4.5M rows. At an estimated 0.3 to 0.5 KB per row, that is roughly 1 to 1.5 MB per exit at the end of a close burst. The 250 ms settle merges closes that arrive together (for example closing a worktree), but not closes spread over time.
  • Possible remedy (not verified): skip the inventory while the adapter still has watched sessions and its admission is not closed. Keep the path that asks again when admission is closed. The last watched exit, discovery or a reattach still runs it. One caveat: an exit the app never heard about would then hold the generation until quit, as today. Today an authoritative inventory on a later exit catches that case.
  • Check that proves it: with S watched sessions on a v63-style adapter, fire S−1 exits spaced past the settle window. Count listSessions calls. Head makes S−1; the gated version makes 0, and a final exit still retires the generation.

New or changed work: trigger, population, bound

Work Process Trigger Population Bound / teardown
retireWhenIdle RPC (hold) main → old daemon discovery (noteAll), the first exit or reattach on an unasked generation, every reconnect (connectedListeners) 1 per older generation (G, usually 1 or 2) once per connection; unanswered asks retry 3× (5 s, 30 s, 2 min), then stop
confirmRetired loop main held connection lost; exit on a held generation that is no longer live-held; spawn failure per held generation 7 checks over 3.9 s (isConnected, one connect attempt, one kill(pid, 0); no subprocess); checks disposed each step; no timer afterwards
Pre-request settle timer main each exit from a v63-or-older generation per generation debounced 250 ms; cleared on dispose
Pre-request inventory main ↔ old daemon each settled exit (P1-2) and each recheck (P1-1) S rows per call see findings
Decision fence main an empty v63-or-older generation's shutdownIfIdle 1 per decision reattach spawns wait at most 2 s (DECISION_FENCE_MAX_MS); on a local socket the wait is normally one round trip; then the generation is forgotten
admitReattach main each reattach spawn of a known session per spawn O(1) counter plus one await when there is no fence; 300 restores means 300 microtask hops
Spawn replay (settleHeldRetirements) main spawn failure with a retirement-type error on an older target error path only waits up to about 3.9 s, then one replay; never replays a spawn sent to the current generation
Per-exit noteActivity main every PTY exit, any generation few hundred terminals the current generation returns on the first identity compare; older ones do legacy.includes, O(G)
superseded.answer in request routing every daemon every RPC all requests one string compare plus one closure allocation; O(1)
isSuperseded / onlyClients every daemon reevaluateIdleShutdown: session reaped, live-count or transport change, admission event-driven, not per request or per chunk O(clients) and O(transports × clients), each at most a few; onlyClients runs only after the cheaper idle checks pass
drainStreams retiring daemon idle shutdown per superseded stream socket 1 s deadline each; the drain and close listeners are removed in done
retireProvider → invalidateInventory main each generation retired once per generation one-time

Listener census at head (new ones only)

  • Per older-generation adapter that was asked: 2 × client.onDisconnected (the adapter's own watch, plus the router's lostListeners) and 1 × client.connectedListeners. The current adapter adds 0. Total: 3G, usually 3 to 6.
  • Teardown: the adapter watch is created with ??=, so it is never duplicated, and it is removed in the adapter's dispose. Router listeners are removed in forget and in dispose, disposeRouterOnly and disconnectOnly. A router restart that carries adapters over adds no adapter listeners and replaces the router listener, so nothing grows across restarts.
  • Daemon: no new persistent listeners; drainStreams listeners exist only during shutdown.

Retained state

  • modes, askAttempts and recheckDelays are WeakMaps keyed by adapter.
  • lostListeners is deleted on forget and on dispose.
  • askTimers and pre-request timers are not deleted on forget. A leftover entry lives until its timer fires (at most 2 min or 30 min), and that firing does nothing because isRetirableLegacy / applies returns false. Size is at most G.
  • checking, checkAgain, waitingForQuiet, decisions and fences are cleared in finally or on quiet.
  • The superseded flag on a daemon connection goes away with the connection.
  • Nothing grows with terminals, history or uptime.

Idle wakeups per process, before → after

  • Electron main, older generation v64+ (held path): 0 → 0. Short, bounded bursts follow a connection loss (at most 7 timers) or an unanswered ask (at most 3 timers).
  • Electron main, older generation v63 or earlier, holding unwatched work: 0 → 1/60 s, decaying to 1/30 min per generation, until that work ends (P1-1). Watched terminals only: 0 → 0, driven by exits.
  • Old daemon, empty: about 0.6/s (author-reported) → process exits, so 0. v63 or earlier holding unwatched work: one extra listSessions per recheck, as above.
  • Current daemon: unchanged; the new checks run only on events.
  • Renderer: not touched.

There is also a reduction: once retired, a generation leaves allAdapters(). Every close-time session listing, reconcile and owner resolution then makes one fewer daemon round trip.

Regression classes touched

  • Fixed-cadence poll that never settles: finding P1-1 (the backoff is capped at 30 min but never stops).
  • New wakeups in steady idle: finding P1-1.
  • Re-reading unchanged input: finding P1-2 (a full inventory on each exit while watched sessions guarantee a non-empty result).
  • Per-entity state outlives the entity: checked and ruled out; see Retained state.
  • Unbounded fan-out: checked and ruled out. Promise.all in settleHeldRetirements covers only held older generations (G, usually 1 or 2).
  • Subprocess per item: checked and ruled out. The process-exit proof is a kill(pid, 0) call, and Windows returns early.
  • Update published when nothing changed / whole snapshot: no matching code.

Six questions

  1. Unused work before the skip gate: P1-2.
  2. Ownership multiplication: reviewed. There is one retirement owner per router and at most one per adapter; restarts are deduplicated with ??= and the has check.
  3. Thread that pays: the inventory parse runs on Electron main and serialization on the old daemon. There is no sync fs or SQLite.
  4. Growth and progress: the ask retries are bounded. The pre-request recheck is not (P1-1). Retirement makes progress: a generation is forgotten once proven gone.
  5. Host: the Windows process proof returns early, so endpoint-gone alone decides. SSH or remote relays are not reached; this path is local daemon generations only.
  6. Obsolete work stops: reviewed. All dispose paths clear timers and listeners, loops check disposed, and the fence releases within 2 s.

Paths examined: everything under src/main/daemon that the diff touches, plus listSessionsAndRelays, preservedDaemonProcessExited, the router's allAdapters fanout and the daemon lifecycle callers of reevaluateIdleShutdown. Residual gaps: real row size and parse time per inventory were not measured, and there is no runtime idle-CPU capture.

@brennanb2025

Copy link
Copy Markdown
Contributor Author

Perf review: PR #51325 at 854083c (diff 339594e..854083c)

Verdict: PASS. There are no P0 or P1 findings. Steady-idle wakeups don't change in any process. Every new timer is triggered by an event and stops after a fixed number of runs. All new state is keyed by generation (L = number of older daemon generations, normally 1 and at most a few) and is cleared on dispose. Nothing here scales with worktrees, terminals or agents on a repeated trigger.

Evidence is counts read from the source. Nothing was run.

New or changed work: trigger, population, bound

Work Trigger Population Bound / cleanup
noteActivity on PTY exit (router exit callback) every exit from any generation all terminals The current generation returns at adapter !== current, so O(1). An older generation costs one legacy.includes (O(L)). A held generation that is still connected does no further work.
retireWhenIdle RPC first contact with an older generation, then each reconnect L One RPC per connection. A reconnect can send 2: the connected listener and confirmRetired both ask. If the RPC goes unanswered there are 3 spaced retries (5 s, 30 s, 120 s) per adapter for its lifetime (askAttempts is not reset). After that, each later exit from that generation asks once, so the rate is capped by the exit rate.
confirmRetired loop held connection lost; activity on a held generation that dropped; a spawn refused during retirement L At most 7 checks over about 3.9 s (0 to 2000 ms steps), each at most one connect attempt. It ends as "still tracked" and arms no timer.
Pre-v63 path: settle timer and inventory (listSessionsAndRelays) exit burst on a pre-v63 generation L × that generation's sessions 250 ms debounce, one timer per adapter (cleared before it is re-armed). No inventory runs while the app still watches a terminal there. Rechecks are capped at 6 (60 s doubling to 30 min, about 61 min in total), then stop until the next exit.
Decision fence and shutdownIfIdle one per decision on a pre-v63 generation L Reattach spawns wait for one local RPC, capped at 2 s (DECISION_FENCE_MAX_MS).
admitReattach in spawn spawns that can reach an older generation (a known or reattached session id) restored terminals With no fence open it costs one await and two counter updates. Fresh sessions skip it.
Spawn replay spawn error that matches a retirement refusal per failed spawn At most one replay, and never a replay of a spawn the current generation took. On this error path the error can be delayed by up to about 3.9 s while the retirement is confirmed.
Daemon request routing (superseded.answer) every RPC all RPCs One string compare before requestRouter.route.
Daemon idle evaluation (isSuperseded, onlyClients) reevaluateIdleShutdown (per exit, spawn finish, transport change) C connected clients (normally 1 or 2) anyClient is O(C). onlyClients (O(C + T·C)) runs only after the work checks pass, thanks to && short-circuiting.
Daemon drainStreams idle shutdown only superseded stream sockets One drain and one close listener per socket plus a 1 s deadline, all removed in done.
setImmediate(reevaluateIdleShutdown) each retireWhenIdle request per request One-shot.

Listener census at head (new listeners only)

  • On each older adapter's own client: 1 onDisconnected and 1 connectedListeners entry, installed once (??=) and removed on adapter dispose. The drop path calls disconnectOnly, not dispose, so these two stay on a dropped adapter. They close over that adapter and its own client only, so they keep nothing else alive.
  • Router lostListeners: at most 1 per held adapter per router. Removed on forget and on all three router teardowns (dispose, disposeRouterOnly, disconnectOnly).
  • Daemon: only the drain listeners described above, at shutdown.
  • Total: at most 3·L listeners. Nothing per terminal, worktree or agent.

Retained state

  • WeakMaps (modes, askAttempts, recheckDelays, rechecks) hold per-adapter state without keeping adapters alive.
  • Maps and Sets (askTimers, timers, decisions, checking, checkAgain, waitingForQuiet) delete their own entries when they finish or when applies() fails after a drop, and are cleared on dispose.
  • Daemon side: one superseded flag per client connection, which dies with the connection.

Idle wakeups per process (before → after)

  • Electron main, steady idle: 0 → 0. After an event there is a bounded tail:
    • held path: none (it is driven by socket close);
    • pre-v63 generation still running work this app doesn't watch: at most 6 inventories over about 61 min, then 0;
    • unanswered ask: at most 3 timers over about 2.6 min, per adapter, once.
  • Renderer: 0 → 0 (not touched).
  • Current daemon: 0 → 0.
  • Older daemon: it now exits once empty, so its idle footprint (process, endpoint, sockets) drops to none instead of lasting until quit. This is a net improvement.

Regression classes screened

  • Fixed-cadence poll that never settles: matched (the recheck and ask retry timers) and disproved. They are capped at 6 rechecks and 3 ask retries, the cadence backs off, and both stop.
  • New steady-idle wakeups: matched and disproved. Every timer is triggered by an event and capped, and none fires in steady idle.
  • Per-entity state outlives the entity: matched and disproved. Per-adapter state is in WeakMaps or self-deleting maps, and the router teardowns clear it.
  • Unbounded fan-out: Promise.all in settleHeldRetirements and drainStreams runs over L adapters or C clients, both small.
  • Hot-path rescans: legacy.includes per exit is O(L), with L ≤ a few.
  • Expensive code newly reachable past a gate: the inventory now runs only when no watched terminal remains (the head commit), and it ran on exits before this PR too.
  • Per-exit or per-spawn subprocesses: none.
  • Sync fs or SQLite on main: none.

Six questions

  1. Work paid before the skip gate: checked. Watched sessions skip the inventory, and the current generation skips at the first comparison.
  2. Ownership multiplying work: one retirement owner per router, per-adapter state, and router restarts don't duplicate listeners.
  3. Which thread pays: main does only async RPCs and timers. The daemon adds O(C) checks.
  4. Growth and progress: rechecks and retries are capped. An unproven generation stays tracked until its next event, which is the same as before this PR.
  5. Host differences: on Windows the PID proof fails closed, so held generations are forgotten via accepted retirement or the endpoint check. The loop is still capped at 7 checks.
  6. Teardown: all three router teardowns dispose the new owner. Adapter dispose stops its watch. The daemon drain is capped at 1 s.

Residual gaps

Nothing was measured at runtime. Inventory payload size on a pre-v63 generation scales with that generation's remaining sessions. It runs once per exit burst plus at most 6 rechecks, and the app's own sessions are falling toward zero while it runs.

…arrive; keep asking a fenced one past the recheck cap

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 2

Review info

Run configuration

  • Source mode: Auto
  • Repository: Unavailable
  • Branch: Unavailable
  • File: No configuration file from this repository applied
  • Commit: Unavailable
  • Layers: Repository UI
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: 489f3710-f836-4c15-9627-f193ad63e364
Commits

Reviewing files that changed from the base of the PR and between 854083c and e7ef119.

Files selected for processing: 3

  • src/main/daemon/providers/routing/daemon-router-legacy-idle-retirement.test.ts
  • src/main/daemon/providers/routing/daemon-router-legacy-idle-retirement.ts
  • src/main/daemon/providers/routing/daemon-router-pre-rpc-retirement.ts

Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 1 remain after this review.

@brennanb2025

Copy link
Copy Markdown
Contributor Author

Perf review: PR #51325 at e7ef119 (diff 339594e..e7ef119)

Verdict: FAIL. One P1. The head commit (854083c..e7ef119) lifts the recheck cap for a pre-retireWhenIdle generation (v63 and older) while its admission is fenced by an unanswered decision. That brings back, in that state, the timer the first review flagged as P1-1: it backs off to 30 min and never stops. The test added in this commit asserts that it keeps firing for 24 simulated hours. The other change in the head commit, the one-shot exit-delivery timer, is bounded and fine.

All counts come from reading the source at e7ef119. Nothing was run.

Finding

P1: unbounded 30-min recheck on Electron main while a v63-or-older generation stays fenced

  • Where: daemon-router-pre-rpc-retirement.ts:161-174 (checkAgainLater). The rechecks >= RECHECK_LIMIT exit is now skipped whenever adapter.isIdleRetirementAdmissionClosed() is true. Introduced in e7ef119.
  • Trigger: a shutdownIfIdle RPC to an older generation fails after it was sent (timeout, or the connection drops mid-request). finishIdleRetirementRequest (daemon-pty-event-subscriptions.ts:152-155) then sets the state to unverifiable and leaves admission closed. From there the pre-RPC path reschedules itself in three ways, and none of them stops:
    • retireIfEmpty gets unverifiable again (lines 231-234), when the daemon is connected but keeps failing or timing out on shutdownIfIdle;
    • the inventory throws while the client is still connected, so confirmRetiredWhenIdle returns connected (lines 141-152), as with a hung daemon;
    • the confirm returns unknown. On POSIX that happens when the socket name is gone but the pid is alive, or when the connect error is not "endpoint gone".
  • What stops it: an answer from the daemon (which reopens admission), proof that the generation is gone, an exit, or app quit. A daemon that is hung or unreachable but not provably gone never gives the first two, so the loop runs for the rest of the app's life.
  • Work per firing: one listSessionsAndRelays RPC (S rows parsed on main, bounded by the request timeout), then either a shutdownIfIdle plus a follow-up listSessions, or one connect attempt in confirmRetiredWhenIdle, plus a console.warn on the throw path.
  • Cadence: 60 s, 2, 4, 8, 16 min, then every 30 min. That is about 48 wakeups/day per fenced generation, indefinitely.
  • Idle wakeups on Electron main: before the PR (and at 854083c), 0 per second in this state. Now 5.6e-4 per second per fenced generation, plus one RPC attempt per firing at the old daemon when it is reachable.
  • Population: G fenced older generations, normally 0 and at most 1 or 2. Constant per firing, so it does not scale with the fleet.
  • Why P1: a new steady-idle wakeup going from 0 to more than 0 per second is P1 however cheap it is. The rule allows no exemption for constant cost. It is the same mechanism as the original P1-1, now limited to the fenced state.
  • Is the timer necessary? While fenced, the generation refuses reattaches ("decommissioning"), so something has to ask again eventually. But the only thing that needs the fence open is a reattach routed there, and that is an event. An idle timer is not needed for it.
  • Possible remedy (not verified): keep the fenced re-asks under the same cap. After the cap, have the first spawn refused by this generation's admission (isAdmissionRefusal in settleHeldRetirements, or the router's spawn path) call preRpc.noteActivity(reached), and await the resulting decision before replaying. Exits and discovery already ask again. This keeps the "unverifiable stays fenced" safety and stops the idle timer.
  • Check that proves it: the new test keeps asking a generation fenced by an unanswered decision past the recheck cap already counts calls over 24 simulated hours. Turn that count into an upper bound: at most RECHECK_LIMIT + 1 asks in 24 h while fenced with no events. Then add a control: one refused reattach after the cap leads to exactly one new decision and reopens admission when the daemon answers busy.

Original findings (from the 0a812a4 review)

  • P1-1 (endless recheck): cleared in general. 854083c caps it at 6 rechecks, about 61 min in total. e7ef119 reopens it only in the fenced state (the finding above).
  • P1-2 (inventory on every exit while watched sessions remain): cleared. check() at line 135 returns before any inventory while hasWatchedSessions() is true and admission is open. Exits that drain S watched terminals now cost 0 inventories until the last one, instead of S−1.

Head commit, other changes: priced

Work Trigger Population Bound / teardown
forgetOnceExited exit-delivery timer (30 s) an older generation retires while this app still watches one of its terminals at most 1 per generation (awaitingExits WeakSet) One-shot. When it fires, check() sees hasRetiredForIdle and forgets the generation. If the watched exits arrive first, the legacy noteActivity forgets it, and the leftover timer is a no-op (applies is false). Cleared on dispose. 0 steady wakeups.
Legacy noteActivity, retired branch each exit on a retired older generation its remaining watched terminals O(1) hasWatchedSessions() (a Set size). No timer, no RPC.
Inventory while fenced with watched terminals (line 135) settled exit burst on a fenced generation G 250 ms debounce. Bounded by the exit rate.

Idle wakeups per process, before → after

  • Electron main:
    • held path (v64+): 0 → 0;
    • pre-RPC path, ordinary busy generation: 0 → 0 after a capped tail (at most 6 over about 61 min);
    • pre-RPC path, fenced generation that never answers: 0 → 5.6e-4/s, indefinitely (P1);
    • exit-delivery: one 30 s one-shot per retirement.
  • Older daemon: it exits once it is empty. When fenced but reachable, it receives one RPC per 30 min (P1).
  • Current daemon, renderer: unchanged.

Regression classes screened

  • Fixed-cadence poll that never settles: finding. Fenced recheck.
  • New steady-idle wakeups: finding. Same timer.
  • Re-reading unchanged input: checked and ruled out. Watched sessions skip the inventory. A fenced generation reads only once per settled exit burst plus the recheck above.
  • Per-entity state outlives the entity: checked and ruled out.
    • awaitingExits, rechecks and recheckDelays are weak.
    • timers entries self-delete when they fire. They keep a forgotten adapter alive for at most 30 s.
    • lostListeners and askTimers are cleared on forget and dispose.
  • Unbounded fan-out: checked and ruled out. settleHeldRetirements and drainStreams loop over G generations or C clients.
  • Hot-path rescans: checked and ruled out. Per exit, legacy.includes is O(G), and the current generation returns at the first identity compare.
  • Subprocess per item, sync fs or SQLite on main: no matching code. The pid proof is kill(pid, 0), and Windows returns early.

Six questions

  1. Work paid before the skip gate: reviewed. The watched-session gate comes before the inventory, and the current generation is skipped first.
  2. Ownership multiplying work: reviewed. There is one retirement owner per router and one timer per adapter (it is cleared before being re-armed), and router restarts don't duplicate listeners.
  3. Thread that pays: Electron main runs async RPCs, timers and the O(S) parse. The old daemon serializes. There is no sync fs or SQLite.
  4. Growth and progress: bounded, except the fenced recheck (P1). Request timeouts keep RPCs to a hung daemon from piling up.
  5. Host differences: on Windows a missing pipe counts as proof. On POSIX, a live pid with no socket name leaves the generation fenced and rechecked (P1 path). SSH and relays are not involved.
  6. Teardown: dispose on both classes clears timers, waiters and listeners, and loops check disposed.

Residual gaps

  • Inventory payload size and parse time were not measured.
  • There was no runtime idle-CPU capture.
  • How often a v63 shutdownIfIdle goes unanswered in the field is unknown. That doesn't change the grade.

…retired older generation; re-ask a fenced one when it refuses a spawn instead of rechecking forever
@brennanb2025

Copy link
Copy Markdown
Contributor Author

Perf review: PR #51325 at 0f67af2 (diff b807f1f..0f67af2)

Verdict: PASS. No P0 or P1. The head clears the P1 from the e7ef119 review, the uncapped 30-minute recheck while a pre-retireWhenIdle generation (v63 and older) stays fenced. A fenced generation now stops at the same 6-recheck cap as every other one. After that, only a spawn that its own fence refuses asks it again (askAgain), and that work is driven by events and bounded. I read the source at 0f67af2 and the test assertion that was added. I ran nothing.

Earlier findings

  • e7ef119 P1, fenced recheck never stops: cleared.
    • daemon-router-pre-rpc-retirement.ts:208-213: checkAgainLater now returns at rechecks >= RECHECK_LIMIT with no fenced exemption.
    • The updated test stops rechecking a fenced generation after the cap… asserts exactly 8 decisions in 24 simulated hours (first decision, its 2 s follow-up, 6 rechecks) and getTimerCount() === 0 afterwards. It then checks that one refused spawn causes exactly one more decision, which reopens admission.
  • 0a812a4 P1-1, endless recheck: cleared, as above.
  • 0a812a4 P1-2, an inventory on every exit while watched terminals remain: still cleared. check() at line 182 returns before any inventory while watched sessions remain and admission is open.

Head-commit work, priced

Reference fleet: a few hundred live terminals. G = older generations on the pre-RPC path, normally 0 and at most 1 or 2. S = sessions on that generation, at most a few hundred.

Work Trigger Per trigger Bound / teardown
askAgain (pre-rpc-retirement.ts:85-96, called from legacy-idle-retirement.ts:99-102) a spawn that the fenced generation's own admission refused (decommissioning, target = that generation, mode pre-rpc) 1 listSessions (O(S) parse on main, async), then shutdownIfIdle, plus 1 listSessions if it answers busy Concurrent refusals coalesce through checking / checkAgain (one in-flight check plus one follow-up), so a reattach burst costs O(1) checks, not O(refusals). Only spawns routed to that generation can trigger it. It runs after the spawn has released its reattach slot, so it cannot deadlock the reattach count. The spawn retries at most once (daemon-router-spawn.ts:61).
Recheck tail re-armed by askAgain (it resets rechecks) each refused spawn on a fenced generation that stays unanswered at most 6 timer firings, at the retained 30 min delay (about 3 h), then 0 Ends at the cap. 0 steady idle wakeups.
Decision fence during a re-ask same reattaches that may reach an older generation wait up to 2 s (DECISION_FENCE_MAX_MS) One decision at a time. This is the existing fence, now triggered by an event instead of the earlier uncapped timer.
exitDeliveryTimers one-shot, 30 s (pre-rpc-retirement.ts:99-124) an older generation that retired while this app still watches one of its terminals (now also held-mode ones, via noteActivity) 1 timer per generation (has check) Cleared by release from forget, when it fires, and on dispose. If the generation leaves by the endpoint-loss path, the entry lives up to 30 s, then fires a no-op forget and deletes itself.
Early forget of a retired target in settleHeldRetirements (line 87) a refused spawn on a retired generation O(G) includes No timer, no RPC.

Spawn latency on the re-ask path (checked, not a finding): a refused reattach now waits for the re-ask before it either replays or fails. If the old daemon is hung, that wait is bounded by the request timeouts, up to 30 s each (daemon-client.ts:31). It is async on main, so no thread is blocked. It only affects terminals owned by a generation that refused them; before this change those failed at once with no chance to recover. Other reattaches are held only by the ≤2 s fence.

Idle wakeups per process, before → after

  • Electron main:
    • held path (v64+): 0 → 0;
    • pre-RPC busy generation: 0 → 0 after a capped tail (at most 6);
    • pre-RPC fenced generation: 0 → 0 after a capped tail (was 5.6e-4/s indefinitely at e7ef119);
    • exit delivery: one 30 s one-shot per retirement.
  • Older daemon: it exits when it is empty. A fenced one receives RPCs only during the capped tail or on a refused spawn.
  • Current daemon, renderer: unchanged.

Regression classes screened

  • Poll that never settles, and new steady-idle wakeups: matched and ruled out. Both are capped at 6 per event, test-asserted, with a timer count of 0 afterwards.
  • Re-reading unchanged input: matched and ruled out. Watched sessions skip the inventory, and a fenced generation is inventoried once per settled exit burst, capped recheck, or coalesced refusal.
  • Per-entity state outlives the entity: matched and ruled out.
    • exitDeliveryTimers is cleared on forget, on fire and on dispose, and lives at most 30 s on the endpoint-loss path.
    • rechecks and recheckDelays are weak.
    • timers entries delete themselves when they fire.
    • lostListeners and askTimers are cleared on forget and dispose.
  • Unbounded fan-out: matched and ruled out. settleHeldRetirements runs Promise.all over G held generations only.
  • Hot-path rescans: ruled out. Each per-exit or per-refusal path does an O(G) includes.
  • Subprocess per item, sync fs or SQLite on main: no matching code in the PR's files. The pid proof is kill(pid, 0).

Six questions

  1. Work paid before the skip gate: reviewed. The current generation and watched sessions are gated before any inventory.
  2. Ownership multiplying work: reviewed. There is one retirement owner per router, a timer per adapter is cleared before it is re-armed, and there is one exit-delivery timer per generation.
  3. Thread that pays: Electron main, with async RPCs and an O(S) parse per inventory. The older daemon serializes. There is no sync I/O.
  4. Growth and progress: reviewed. Every loop is capped or driven by events. Request timeouts bound RPCs to a hung daemon, and refusals coalesce.
  5. Host differences: reviewed. On Windows a missing pipe counts as proof. On POSIX, an unproven generation now stops after the cap instead of being rechecked. No SSH or relay per-item work.
  6. Teardown: reviewed. dispose clears recheck timers, exit-delivery timers, waiters and listeners, and the checks look at disposed.

Residual gaps

  • Inventory payload size and parse time were not measured.
  • There was no runtime idle-CPU capture.
  • There is no field rate for v63 decisions that go unanswered. That doesn't affect the grade.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 2

Review info

Run configuration

  • Source mode: Auto
  • Repository: Unavailable
  • Branch: Unavailable
  • File: No configuration file from this repository applied
  • Commit: Unavailable
  • Layers: Repository UI
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: 1c63d8ef-7398-431a-b559-fe97bfd8374a
Commits

Reviewing files that changed from the base of the PR and between 4c3e16c and 0f67af2.

Files selected for processing: 3

  • src/main/daemon/providers/routing/daemon-router-legacy-idle-retirement.test.ts
  • src/main/daemon/providers/routing/daemon-router-legacy-idle-retirement.ts
  • src/main/daemon/providers/routing/daemon-router-pre-rpc-retirement.ts

Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 1 remain after this review.

…eep its exits until delivered; count exits still classifying as watched; fence only reattaches that can reach an older generation
@brennanb2025

Copy link
Copy Markdown
Contributor Author

Perf review: PR #51325 at a5fba93 (diff b807f1f..a5fba93)

Verdict: PASS. No P0 or P1 findings. The head commits (0f67af2..a5fba93) add no steady-idle wakeup in any process and no work that grows with worktrees, terminals or agents on a repeated trigger. The reattach-fence change takes work off the spawn path for current-generation terminals. I read the source at a5fba93 and ran nothing. The counts below come from reading the source; there are no timing numbers.

Reference fleet: a few hundred live terminals and 100+ agents. G = older generations, normally 0 and at most 1 or 2. S = sessions on an older generation, at most a few hundred. R = entries in the session route map, a few hundred.

Earlier findings

  • 0a812a4 P1-1 (endless recheck) and e7ef119 P1 (fenced recheck never stops): still cleared. checkAgainLater (daemon-router-pre-rpc-retirement.ts:203-214) returns at RECHECK_LIMIT (6) with no exemption.
  • 0a812a4 P1-2 (an inventory on every exit while watched terminals remain): still cleared. check() at pre-rpc-retirement.ts:175 returns before any inventory while hasWatchedSessions() is true and admission is open. The head widens hasWatchedSessions to count classifying exits, which skips more inventories, not fewer.

Head-commit work, priced

Work Trigger Per trigger Bound / teardown
DaemonRouterRetiredExitDelivery.settle (daemon-router-retired-exit-delivery.ts:30-42) an older generation retired (accepted, or seen as retired by noteActivity or by a refused spawn) hasWatchedSessions() O(1). If there are no watched terminals it releases at once. Otherwise one unroute (indexOf over G, then retireProvider: one pass over the R routes and one inventory invalidation), plus one 30 s one-shot timer One timer per generation (lingering.has). finish clears it when the last owed exit arrives, when it fires, or on dispose. retireProvider runs once per generation, same as the old drop path.
Per-exit check on a lingering generation (legacy-idle-retirement.ts:70-72, reached from the exit fanout at daemon-pty-router.ts:79) each exit that generation delivers Map.has plus hasWatchedSessions(), O(1) Only exits owed by a retired generation, at most S in total, once. Exits on the current generation pay the same Map.has (O(1)) before the existing isRetirableLegacy gate. That is constant work per exit, not over the fleet.
exitsClassifying counter (daemon-pty-adapter.ts:242,267) a WSL bridge exit with a non-zero proven code one increment and one decrement in finally No new wakeup. It only keeps hasWatchedSessions true for the existing classification window (about 10 s or less). If the exit is then dropped (a replaced incarnation), the 30 s delivery timer still releases the generation.
decisionStart waiter (pre-rpc-retirement.ts:100-117) a spawn refused by a fenced pre-RPC generation while its decision waits for reattaches to go quiet one Set entry and one 2 s one-shot timer per refused spawn The decision start (line 255) or the 2 s timer resolves it. The map entry deletes itself when its set empties, and dispose resolves all waiters. A restore burst of N refused reattaches makes N one-shot timers that all resolve together. That is O(1) per spawn and not repeated; each spawn retries at most once (daemon-router-spawn.ts:69-72). There is no deadlock: the refused spawn has already given up its reattach slot, so reattachesInFlight can reach 0.
Reattach fence gate (daemon-router-spawn.ts:82-89) each spawn or reattach legacy.length check plus one Map.get See below.

Reattach fence and interaction latency (checked, an improvement): before this head, every reattach of a known session went through admitReattach, which waits for any open decision fence (up to 2 s). Now it does so only when an older generation exists (legacy.length > 0) and the session is not already routed to the current generation. So the common case, with no older daemon, skips the await entirely. While an older daemon is still retiring, reattaches of terminals owned by the current generation (focus, tab switch, restore) are no longer held by its fence. Unrouted, non-new sessions are still fenced, as before. That is correct, because they may be owned by the older generation.

Idle wakeups per process, before → after (base → head)

  • Electron main: 0 → 0 in steady idle. One-shot timers are tied to events: a 30 s timer per retirement with watched terminals, and a 2 s timer per refused spawn on a fenced generation. The pre-RPC recheck tail is capped at 6 per event, unchanged from 0f67af2.
  • Current daemon, older daemon, renderer: unchanged from 0f67af2. The older daemon exits once it is empty.

Regression classes screened

  • Poll that never settles, and new steady-idle wakeups: matched and ruled out. All new timers are one-shots that clear themselves; nothing re-arms.
  • Per-entity state outlives the entity: matched and ruled out.
    • lingering is cleared on finish, on fire and on dispose.
    • decisionWaiters deletes itself when its set empties, and is cleared on dispose.
    • lostListeners is now cleared by stopWatching on both release and forget.
    • modes, askAttempts, rechecks and recheckDelays are WeakMaps.
  • Hot-path rescans: ruled out. Per exit, the work is a Map.has. Per retirement, there is one O(R) route pass, once per generation.
  • Re-reading unchanged input: ruled out. Inventories are still gated by watched sessions, and the head adds none.
  • Unbounded fan-out: ruled out. Promise.all covers only the G held generations.
  • Subprocess per item, sync fs or SQLite on main: no matching code in the changed files.

Six questions

  1. Work paid before the skip gate: reviewed. The fence gate now runs before admitReattach, and the exit-delivery check is O(1) before any work.
  2. Ownership multiplying work: reviewed. There is one exit-delivery owner per router and one timer per generation.
  3. Thread that pays: Electron main. The work is O(1) per exit and one O(R) pass per retirement. There is no sync I/O.
  4. Growth and progress: reviewed. Each waiter is bounded at 2 s and each lingering generation at 30 s. Spawn replay happens at most once.
  5. Host differences: reviewed. WSL classification time now counts as watched; it is bounded by the existing classifier. No SSH or relay per-item work.
  6. Teardown: reviewed. dispose finishes every lingering generation, resolves every waiter, and clears timers and listeners.

Residual gaps

  • I did not capture idle CPU at runtime or measure inventory parse time.
  • I did not measure a restore burst through a fenced v63 generation. The source bounds each refused spawn at about 2 s plus request timeouts.

… a restart; end WSL classification in the emit's turn; re-ask behind a running check
…ttle a carried generation after its router is built
@brennanb2025

Copy link
Copy Markdown
Contributor Author

Perf review: PR #51325 at 37db7fa (diff b807f1f..37db7fa)

Verdict: PASS. No P0 or P1 findings. The head commits (a5fba93..37db7fa) add no steady-idle wakeup in any process and no work that grows with worktrees, terminals or agents on a repeated trigger. Every new timer or microtask is a one-shot tied to a manual restart or to a refused spawn, and each clears itself. I read the source at 37db7fa and ran nothing. The counts below come from reading the source; there are no timing numbers.

Reference fleet: a few hundred live terminals and 100+ agents. G = older generations, normally 0 and at most 1 or 2. Gr = retired generations still delivering exits at the moment of a restart (a subset of G, normally 0). S = sessions on an older generation.

Earlier findings

  • 0a812a4 P1-1 (endless recheck) and e7ef119 P1 (fenced recheck never stops): still cleared. checkAgainLater (daemon-router-pre-rpc-retirement.ts:205) still returns at RECHECK_LIMIT. The head does not touch it.
  • 0a812a4 P1-2 (an inventory on every exit while watched terminals remain): still cleared. The hasWatchedSessions() gate in check() (pre-rpc-retirement.ts:179) is unchanged.

Head-commit work, priced

Work Trigger Per trigger Bound / teardown
getRetiringDaemonAdapters → exitDelivery.adapters() (daemon-provider-restart.ts:96, retired-exit-delivery.ts:29) manual restart of the current daemon one Array.from over the lingering map, O(Gr) Once per restart.
New router built when retiring.length > 0 (daemon-provider-restart.ts:169) manual restart while a retired generation still owes exits one router instead of a bare adapter. This is the same build a restart already does when any older generation is live. Once per restart.
Subscription fanout over allAdapters + retiring (daemon-pty-router.ts:78) same one set of exit and data subscriptions per carried adapter Removed by release → dropAdapter when the delivery finishes, times out or the router is disposed. Between building the new router and disposeProviderSubscriptionsOnly on the old one, both routers subscribe. That overlap is the existing one for legacy adapters and lasts one discoverLegacySessions.
adopt → wait (30 s one-shot, unref) plus queueMicrotask(settle) (retired-exit-delivery.ts:34-37) each carried generation, at router construction 1 timer + 1 microtask, then settle: O(1) hasWatchedSessions() The microtask releases at once if nothing is owed. Otherwise the timer stays until the last owed exit, the 30 s limit, or dispose. Repeated restarts re-arm it, so the count is bounded by manual restarts, not by time.
dispose(carried) (retired-exit-delivery.ts:52-60; disposeRouterOnly passes true) restart handoff, or a failed adoption clearTimeout per lingering entry, O(Gr) The old router stops its timers without disconnecting, and the new router owns the release. On a failed adoption the old router was never disposed and keeps its own timers. A settle microtask still queued on the failed router finds its map empty: unroute returns false (the adapter is not in legacy), so no timer is re-armed. Full dispose() / disconnectOnly() (quit) still release every lingering generation.
Re-ask waits behind a running check (pre-rpc-retirement.ts:94-99) a spawn refused by a fenced pre-retireWhenIdle generation's own admission while a check is in flight one entry in the decisionWaiters Set plus one 2 s one-shot timer It resolves when the decision starts (line 259), at 2 s, or on dispose. If the running check ends without a decision (busy, or a failed inventory), the refused spawn waits the full 2 s and then fails as before. That is async on main, once per refused spawn, and the spawn replays at most once (daemon-router-spawn.ts). Only reattaches routed to that one fenced generation pay it.
WSL exitsClassifying moved into finishWslBridgeExit (daemon-pty-adapter.ts:262-268, daemon-pty-retire-when-idle.ts:21-28) each WSL bridge exit with a non-zero proven code one increment and one decrement, the same as before Balanced on both paths: exitClassificationFailed decrements on rejection, and the success path decrements in the emit's turn. No new timer or probe.
getCurrentAdapter / getAllAdapters as arrow properties (daemon-pty-router.ts:359,366) router construction 2 closures per router instance One router per provider. Negligible.

Listener and retained-state census (new only)

  • lingering: at most Gr entries per router. Cleared by finish, by the timer, by dispose(true) (handoff) and by dispose() (quit).
  • Fanout subscriptions on carried adapters: at most Gr per router, removed by dropAdapter on release.
  • Nothing is keyed per terminal, worktree or agent.

Idle wakeups per process, before → after (base → head)

  • Electron main: 0 → 0 in steady idle. The only new one-shots are a 30 s timer and a microtask per carried generation per manual restart, and a 2 s timer per refused spawn on a fenced pre-RPC generation. The pre-RPC recheck tail is still capped at 6 per event.
  • Current daemon, older daemon, renderer: unchanged from a5fba93. A carried generation gets no RPCs from the new router. Its exits are only delivered.

Regression classes screened

  • Poll that never settles, and new steady-idle wakeups: matched and ruled out. adopt arms a single unref'd one-shot that nothing re-arms except another manual restart.
  • Per-entity state outlives the entity: matched and ruled out. lingering and the carried subscriptions are cleared on finish, on timeout, on handoff and on quit. On a failed adoption, the failed router's queued settle cannot re-arm a timer.
  • Unbounded fan-out or queues: ruled out. The carry loop is over Gr adapters. Refused-spawn waiters are capped at 2 s each and resolve together when the decision starts.
  • Hot-path rescans: ruled out. The per-exit cost on a carried generation is Map.has plus an O(1) watched check, at most S exits in total, once.
  • Subprocess per item, sync fs or SQLite on main: no matching code in the changed files.

Six questions

  1. Work paid before the skip gate: reviewed. adopt's settle releases at once when nothing is owed, and the re-ask wait applies only when no decision exists and a check is actually running.
  2. Ownership multiplying work: reviewed. During the restart window, two routers briefly hold a carried adapter, but only the new one keeps its timer after handoff. One exit-delivery owner per router.
  3. Thread that pays: Electron main. The work is O(Gr) per restart and O(1) per exit or refused spawn. There is no sync I/O.
  4. Growth and progress: reviewed. Lingering is bounded at 30 s per restart, waiters at 2 s, and spawn replay happens at most once.
  5. Host differences: reviewed. The WSL counter change does not change probe count or cadence (Windows/WSL). No SSH or relay per-item work.
  6. Teardown: reviewed. Handoff, failed adoption and quit each leave no timer or subscription behind on the router being torn down.

Residual gaps

  • I did not capture idle CPU at runtime and did not measure the restart window with a carried generation.
  • There is no field rate for refused reattaches that land behind a running check. The grade does not depend on it, because each one is bounded at 2 s and does not repeat.

…ained; re-ask fenced generations for attach-only refusals; fence a routed reattach only on its own generation
@brennanb2025

Copy link
Copy Markdown
Contributor Author

Perf scan: b599788 (delta since the passing 37db7fa scan)

Verdict: PASS. No P0/P1 findings.

Scope: git diff 37db7fa..b599788 -- src/main/daemon. Graded files: daemon-pty-retire-when-idle.ts, daemon-router-legacy-idle-retirement.ts, daemon-router-pre-rpc-retirement.ts, daemon-router-retired-exit-delivery.ts, daemon-router-spawn.ts. Callers and consumers traced: DaemonRouterSpawn.spawn/spawnOnce, DaemonClient.onDisconnected/handleDisconnect/disconnect, askAgain → check → retireIfEmpty. All files outside this delta were covered by earlier scans and have not changed since. This is a source-proven work-count review; nothing was measured at runtime.

Population: G = older daemon generations in the router. This is 1–2 after an update, and it only grows with app updates made while terminals stay alive. Tested against a restore burst of R = 500 reattaches and a few hundred live terminals.

Changed triggers, priced

Change Trigger / owner Work per event Bound / teardown Disposition
Fences keyed per generation; admitReattach(route) scans with fencesFor (pre-rpc-retirement.ts:57-88) Each spawn that may reach an older generation (the restore burst) One pass over fences per loop pass, plus one small array. There is at most one fence per generation: check is single-flight per adapter through checking, so fences.size ≤ G. 500 reattaches × G=2 is about 1k map visits for the whole burst Fence is deleted in finally and by its 2 s timer, so no leak. A routed reattach now waits on its own generation's fence only, so burst latency can only go down Disproved
Re-ask fenced generations after an attach-only refusal (legacy-idle-retirement.ts:124-141) One refused attach-only spawn. spawn retries at most once O(G) filter plus askAgain per fenced generation. If K refusals arrive at once: the first runs one check (one listSessionsAndRelays RPC). The rest hit checking → checkAgain (a Set, so they coalesce to one rescheduled check) and wait in decisionStart, which costs one promise plus one unref'd timer each, capped at DECISION_FENCE_MAX_MS = 2 s and cleared when the decision starts. If a decision is already pending, they all share its promise At most 2 inventory RPCs per generation per burst, not K. Waiters drain on decision start, timeout or dispose(). No poll and no retry loop (one replay per spawn) Disproved
Retired generation released only after its connection closes (retired-exit-delivery.ts:43-84, retire-when-idle.ts:145-147) Once per retired generation (per update) One onDisconnected listener plus the existing 30 s unref'd timer per lingering generation. settle per owed exit is O(1) (hasDeliveredOwedEvents reads a Set size and a boolean) The listener is removed in finish (before release, so the disconnect that release causes does not fire it again) and in dispose on both the carried and non-carried paths. The next router re-registers it in adopt. The client has no auto-reconnect, so a closed connection does not lead to reconnect churn. Map entries ≤ G Disproved

Idle wakeups

Daemon / main / renderer: 0 → 0 per second in steady idle. The only new timer is the existing one-shot 30 s exit-delivery bound, which fires once per retired generation and does not repeat. The per-generation fence change adds no timers.

Regression classes touched

  • Per-entity state outlives the entity: fence map (Map<Promise, adapter>), lingering {timer, stopListening}, and decisionWaiters. Each is deleted by its owning teardown, and all are bounded by G. Disproved.
  • Hot-path rescans: fencesFor runs per reattach over ≤ G entries. Constant at 10× fleet, because G does not scale with worktrees or terminals. Disproved.
  • Unbounded fan-out or queues: Promise.all over the fenced generations (≤ G). Burst waiters are bounded by the 2 s cap and coalesced. Disproved.
  • Fixed-cadence poll that never settles: none added. Rechecks stay behind RECHECK_LIMIT with backoff (unchanged). Disproved.
  • New idle wakeups: none. Disproved.

Six questions

  1. Unused work paid before the gate: reviewed. The re-ask runs only on target === 'any' together with an admission refusal, and only for generations in pre-rpc mode with admission closed.
  2. Ownership multiplication: reviewed. One listener and one timer per retired generation, never per terminal or per worktree.
  3. Thread and storage: daemon router on Electron main. No sync fs, no SQLite, no subprocess. The inventory RPC is async and single-flight.
  4. Growth and progress: reviewed. Fences and waiters are bounded by G. A refused spawn makes progress through one replay. A generation past the recheck limit is asked again only by the next refusal, so there is no timer debt.
  5. Execution host: unchanged from 37db7fa. The WSL late exit is still covered by the 30 s bound. The connection-close gate applies on every platform, and the bound handles a connection that never closes.
  6. Obsolete work stops: reviewed. dispose(carried) clears timers and listeners. dispose() on pre-rpc drains the waiters. finish removes the listener before release.

Residual gaps: nothing was measured at runtime, and Windows/WSL was not run live. The 30 s bound and the 2 s fence cap are latency caps for correctness, not recurring work.

@brennanb2025

Copy link
Copy Markdown
Contributor Author

Status: ready for review at b599788

Problem. After an update starts a new terminal daemon, the old one used to stay running until quit, even with nothing left on it (about 100 MB idle).

Change. An older daemon now exits by itself as soon as it owns no terminals, chat agents or pending attaches:

  • Daemons built from this PR retire atomically through the new retireWhenIdle request.
  • Daemons from before it (v63 and older) are asked through shutdownIfIdle on a transitional path, to delete once those daemons are gone.
  • New terminals always open on the current daemon, and it is never retired this way.
  • Old terminals keep reattaching, across app restarts too, until the last one ends.

Fixed during review. Races where a reopen could land on a retiring daemon or be refused without a retry, plus exits or final output that could be lost while a retired daemon was released. A retired daemon now stops getting new work at once but stays subscribed until its connection has closed and drained and no watched exit is still owed, bounded at 30 s. Reattach fences now apply only to reattaches that can reach the deciding daemon.

Deferred (each leaves an older daemon running until quit, as today, or predates this PR):

  • STA-19443: a pre-request daemon after a transient disconnect.
  • STA-19444: degraded mode never retires an empty older daemon.
  • STA-19477: on close, the client can drop stream bytes still in the kernel (pre-existing).
  • Minor follow-ups noted in review: no direct test of the WSL exit-classification count; a reattach whose route is cleared mid-wait can probe another generation once before it retries; an attach-only refusal during the app's own quit re-asks older daemons once.

Verified on b599788.

  • Gate: format, lint, typecheck, the touched tests and ratchets pass; CI green.
  • Blinded regression audit of the change merged on main: SAFE.
  • Packaged builds on Linux and native Windows, two flows each: the latest v63 release followed by this PR, and this PR as v64 followed by a test-only v65. Every step passed:
    • old terminals reattached with their scrollback, also after an app restart;
    • the old daemon exited 18 ms to 1.2 s after its last terminal (v64 logged the retire request first);
    • a terminal opened right after landed on the current daemon and worked;
    • the empty current daemon stayed up past 2 minutes and served the next terminal on the same process.

Performance. Earlier perf scans failed at 0a812a4 (an uncapped recheck and an inventory read on every exit) and at e7ef119 (an uncapped recheck while a daemon stayed fenced). Both are fixed. An independent scan of the final head passes: no new steady idle wakeups in any process, rechecks capped at six, and no inventory read while this app still watches a terminal there.

Old terminal reattached after an app restart (Windows):
windows-old-terminal-reattached-after-restart.png

New terminal opened right after the old daemon retired, on the current daemon (Windows):
windows-new-terminal-after-old-daemon-retired.png

@brennanb2025

Copy link
Copy Markdown
Contributor Author

Closing: superseded by #52112, which merged first with a simpler design for the same feature. The remaining gaps (a reattach racing a retirement decision, and the fixed 60 s relay recheck) are fixed in #52598.

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