Skip to content

fix(daemon): back off relay-only legacy rechecks; skip legacy daemons that already retired - #52598

Merged
brennanb2025 merged 14 commits into
mainfrom
brennanb2025/drained-legacy-retire-fence
Nov 29, 2026
Merged

brennanb2025 merged 14 commits into
mainfrom
brennanb2025/drained-legacy-retire-fence

Conversation

@brennanb2025

@brennanb2025 brennanb2025 commented Nov 29, 2026 •

Copy link
Copy Markdown
Contributor

ELI5

After an update, Orca shuts down old background processes once they are empty. One that only holds chat agents used to be checked every minute, forever. Now it's checked less and less often, down to every 30 minutes. Orca also stops asking an old process that has already agreed to shut down whether it owns a terminal, so reopening a terminal after a restart doesn't trip over it.

What Changed

  • The relay-only recheck backs off: 60 s doubling to a 30 min cap, reset by a session exit or discovery. It used to be a fixed 60 s.
  • Owner lookup (findLegacySessionOwner) treats a legacy daemon that accepted idle retirement as owning nothing, instead of probing it as it closes.
  • An attach-only reattach first detaches legacy daemons that already retired. That includes a router built by a restart, which otherwise still lists the old daemon and fails resolving through it.

Why

Follow-up to #52112, which retires drained legacy daemons.

  • Recheck backoff: the fixed poll was a steady idle wakeup for as long as an old daemon held a chat relay.
  • Retired daemons: after a daemon accepts retirement it never serves again, so probing it can only fail. A router built by a restart missed the old router's detach and could fail an attach-only reattach as "owner unverified".
  • Not in this PR: a reattach that races the retirement decision itself can still fail once, as on main; a second reopen works. Fixing it needs an explicit "retiring" refusal reason from the daemon and cancellation in the shared probe code, which is tracked separately.

Linked Issue

None. Follow-up to #52112; it replaces #51325, which built the same feature another way.

Visual Proof

N/A: no UI change.

Testing

  • I manually tested these changes (packaged build; QA running)
  • Automated tests added/updated
  • Every added test fails without this change and avoids the test anti-patterns
  • daemon-router-retired-legacy-attach.test.ts: in a router built by a restart, an attach-only reattach skips a legacy daemon that already retired and lands on the current daemon. Without this change it fails with "owner unverified".
  • daemon-router-drained-legacy.performance.test.ts:
    • the relay recheck follows the backoff;
    • a relay that stays live gets at most 51 inventory reads in 24 h, where the fixed poll did 1,440.

Performance

Fewer wakeups: a relay-only legacy daemon is now checked about 51 times a day instead of 1,440. The trade-off is that, after its last chat relay ends, such an idle old daemon can linger up to 30 min before it is retired, instead of up to 1 min; the next app start resets this. Skipping retired daemons removes probes; the attach-only check loops over the few legacy adapters, with no I/O.

Risk

Level: Low. The riskiest part is an idle relay-only old daemon staying up to 30 min after its last relay ends. A plain revert restores #52112's behavior.

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

Cross-platform: the logic is the same on all three platforms. SSH, mobile and WSL: unchanged.

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)

@brennanb2025

Copy link
Copy Markdown
Contributor Author

Perf scan: PASS (no findings)

Head 08a78fe0c9395b9231786118409ebe70b4276063, diff against merge base bb06913c8ac. Shipped files: daemon-pty-router.ts and daemon-router-drained-legacy.ts (the other two changed files are tests). The surface detector reported no surfaces ([]). It missed the new setTimeout calls, so I covered them by hand below. Everything here comes from reading the source. Nothing was run.

Reference fleet: a few hundred live terminals, and a restore burst of about 300 reattaches through router.spawn. L means the number of legacy daemon generations, usually 1 to 3 and only a handful even after many upgrades.

Changed paths

Path Trigger Work per trigger Bound Disposition
legacyForSpawn fast path (daemon-router-drained-legacy.ts:54-68, called at daemon-pty-router.ts:97) every router.spawn, including attach-only decisions.size check, one Map.get, one legacy.filter over L adapters (a boolean hasRetiredForIdle() each), one extra await O(L) per spawn: about 300 × 3 = 900 boolean reads for a 300-reattach burst, on main constant and tiny. The filter drops retired generations, so findLegacySessionOwner makes fewer probePtyLiveness/listProcesses IPCs. When nothing is left it returns early and skips the probe of the current daemon. Net IPC is the same or lower.
legacyForSpawn fence (:55-67) a spawn arrives while a requestIdleRetirement decision is in flight one unref'd 2 s timer, plus Promise.allSettled over at most L decisions, per waiting spawn; timer cleared on settle decisions start only when spawnInFlight === 0 (:199, :225), so at most L are in flight. In a burst, up to about 300 short-lived timers, all cleared after one decision IPC round trip. The wait is capped at 2 s if the daemon hangs necessary. Without the fence the reattach would probe a daemon that is closing. One IPC round trip of latency, only in the window right after a retirement decision starts. Not an interaction stall at fleet scale.
decisions map (:26, set :232, delete :249) each retirement decision one entry per adapter at most L entries; removed in finally. Not cleared in dispose, but the decision settling still removes it, so a hung one holds at most L promises bounded, no leak
Relay-only recheck backoff (:146-158) legacy daemon with 0 PTYs and more than 0 live chat relays one unref'd timer per adapter; on fire, one listSessionsAndRelays IPC before: 1 wakeup/min/adapter, 1,440 IPCs/day. After: 1, 2, 4, 8, 16 min, then every 30 min, about 51/day (matches the contract test :271-286). Steady idle wakeups go from 1/60 s to 1/1800 s per relay-only adapter, at most L improvement. No new idle wakeup.
relayRecheckDelays map (:24) set on schedule; reset on retireAll, noteLegacySessionExited, detach; cleared on dispose one number per adapter at most L entries, removed on detach (:173) and dispose (:47). Resets happen only on legacy PTY exits, which are finite, so the backoff cannot keep falling back to 60 s bounded
noteSpawnsDrained now called on every spawn exit (daemon-pty-router.ts:113) each spawn's finally an early-return guard (spawnInFlight > 0) is the first check (:106) O(1) same behavior as the old caller-side === 0 gate

Tradeoff noted, not a finding

When the last relay on a relay-only legacy daemon ends, retirement can now take up to 30 min instead of up to 1 min. During that window one idle legacy daemon process stays alive. This costs a fixed amount per generation, at most L processes. It does not grow with time or the fleet, and the next retireAll (startup or handoff) resets the backoff. The old daemon emits nothing when a relay ends, so the alternative was polling once a minute forever.

Regression classes touched

  • Fixed-cadence poll that never settles: matched and disproved. The poll backs off to a 30 min cap and stops on retirement, detach or dispose. It is covered by the new 24 h fake-timer contract (at most 51 inventory reads).
  • New idle wakeups: matched and disproved. Wakeups drop from 1/min to 1/30 min per relay-only adapter, and none are added.
  • Per-entity state outlives the entity: matched and disproved. decisions and relayRecheckDelays are keyed by legacy adapter and removed in detach and finally. dispose clears the delays.
  • Unbounded fan-out under load: matched and disproved. The fence is O(spawns) with short-lived timers and at most L awaited decisions.
  • Hot-path rescans: matched and disproved. The per-spawn filter covers L (a handful), not the session or terminal count.

Six questions

  1. Unused work before the gate: reviewed. The fence is gated on decisions.size > 0 and the session not already being on the current daemon. Attach-only spawns pay the O(L) filter even though they don't use the result. That costs a few boolean reads, which is negligible.
  2. Ownership multiplication: reviewed. There is one DaemonDrainedLegacyRetirement per router. Its timers and decisions are per legacy adapter, not per terminal.
  3. Thread/storage: reviewed. All of this runs on Electron main and is async. No sync fs or SQLite is added.
  4. Growth and progress: reviewed. Every structure is capped by L, and the backoff advances to its cap.
  5. Host: not applicable. This is local daemon IPC, and nothing here is platform-specific (timers are unref'd where supported).
  6. Teardown: reviewed. dispose clears the recheck timers and delays. Fence timers are cleared after the race. In-flight decisions remove their own entries.

Residual: I made no runtime measurements. Pre-existing and unchanged: during a burst of reattaches that run one after another, each gap where spawnInFlight reaches 0 can re-run a deferred legacy inventory IPC. That behavior is the same at base.

@greptile-apps

greptile-apps Bot commented Nov 29, 2026 •

Copy link
Copy Markdown

Confidence Score: 3/5 · The PR should not merge yet because terminal lookups can still fail when they overlap legacy retirement.RetriggerView in GreptileConfidence Score: 3/5

[Medium impact] The changes affect terminal reattaches and retirement timing for legacy daemons.

The PR should not merge yet because terminal lookups can still fail when they overlap legacy retirement.

Findings

  1. P1 Retirement still breaks terminal reopening ▶
  2. P1 Retirement can hide the retry ▶

Summary

The PR backs off relay-only checks from one minute to a thirty-minute cap and drops already-retired daemons before attach-only lookups.

  • Terminal reattaches skip legacy daemons that have accepted retirement.
  • Relay-only legacy daemons get checked less often as they stay idle.

Reviews (10) · Last reviewed commit: "refactor(daemon): cut the reattach-race ..." · Reviewed by Greptile

… own pending retirement so a restart handoff keeps it
@brennanb2025

Copy link
Copy Markdown
Contributor Author

Perf scan update: PASS (no findings)

Head b8aeb5b9acb132ee53a607a8ce90c279b2bdf9bb. I re-read the changes since 08a78fe; nothing was run. The surface detector again reported no surfaces ([]).

L means the number of legacy daemon generations, usually 1 to 3.

  • legacyForSpawn gate (daemon-router-drained-legacy.ts): routed spawns, new sessions and spawns without a sessionId now skip the fence with a few constant checks and one Map.has. Before, new sessions also waited on an in-flight decision, so the fence now covers fewer spawns.
  • Unrouted reattach: one flatMap over L adapters reading pendingIdleRetirement() (a field read), then the existing filter over L. A restore burst of 300 unrouted reattaches costs about 300 × 2L, roughly 1,800 cheap getter calls at L=3, on main. That is constant per spawn and does not depend on how many terminals or sessions are open.
  • Fence timer: unchanged. It is created only when a decision is pending, unref'd, capped at 2 s, and cleared after one decision round trip.
  • pendingIdleRetirement() (daemon-pty-event-subscriptions.ts): it returns the adapter's existing idleRetirementPromise. That promise is set in the same turn as the request and cleared in its own finally, so this adds no new state, timer or IPC.
  • Router-side decisions map: removed. The router now holds no per-adapter state for the fence, which leaves one fewer structure to retain or tear down.
  • Relay recheck backoff and relayRecheckDelays: unchanged from the previous scan. Wakeups go from 1/min to at most 1 per 30 min per relay-only legacy daemon, and the delays map holds at most L entries, cleared on detach and dispose.

Regression classes (fixed-cadence poll, idle wakeups, per-entity state, unbounded fan-out, hot-path rescans) are disproved as before. Every cost is bounded by L and none grows with the fleet.

@coderabbitai

coderabbitai Bot commented Nov 29, 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

No actionable comments were generated in the recent review.

Walkthrough

The router now coordinates legacy owner lookup with idle-retirement decisions. It can wait for pending decisions, detach adapters that have retired, and retry ownership checks. Relay-only inventory rechecks now back off from 60 seconds to a 30-minute cap, with delay state cleared during specified retirement events.

Merge Risk: Low · up to 2f658

This change stops unrouted reattaches from failing while a legacy daemon is deciding to close, and it reduces repeated inventory checks for relay-only daemons. A rare edge case remains: if retirement takes longer than the 2-second wait, a reattach can still be rejected with an unverified-owner error. The reattach succeeds on retry, so this is low risk to merge.

Pre-merge checks: Passed 4

Check name Status Explanation
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.
Title check Passed The title names the two changes in the PR: relay-only legacy rechecks now back off, and legacy daemons that already retired are skipped during owner lookup and attach-only reattach. It is specific and…
Description check Passed The description follows the template: it has ELI5, What Changed, Why, Linked Issue, Visual Proof, Testing, Performance, Risk, and Checklist sections, and it explains the mechanism, the trade-off, and …
Full details: Title check

Explanation

The title names the two changes in the PR: relay-only legacy rechecks now back off, and legacy daemons that already retired are skipped during owner lookup and attach-only reattach. It is specific and matches the changeset and the stated objectives. The conventional-commit prefix fits the fix. The title is slightly long at 90 characters, which is acceptable.

Full details: Description check

Explanation

The description follows the template: it has ELI5, What Changed, Why, Linked Issue, Visual Proof, Testing, Performance, Risk, and Checklist sections, and it explains the mechanism, the trade-off, and the revert path. Gaps: the Linked Issue section says 'None' and points to follow-up #52112 instead of an issue, which the template calls required for outside contributors. The Testing checklist marks 'Automated tests added/updated' and 'Every added test fails without this change' as done, but the manual test box is unchecked and the author notes packaged-build QA is still running. The AI Disclosure and Review sections are empty. The Performance line is filled in. Most required content is present, so the check passes, but the linked issue and the empty AI Disclosure section should be reviewed.

  • 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

Recent 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: 2158ccbc-62fb-4266-8941-91de06de4de5
Commits

Reviewing files that changed from the base of the PR and between 4cc9f52 and 2f658a5.

Files selected for processing: 3

  • src/main/daemon/providers/routing/daemon-router-drained-legacy.ts
  • src/main/daemon/providers/routing/daemon-router-legacy-owner.ts
  • src/main/daemon/providers/routing/daemon-router-retiring-owner-lookup.test.ts
Files skipped from review as they are similar to previous changes: 1

  • src/main/daemon/providers/routing/daemon-router-legacy-owner.ts

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

@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: a05bb4d3-c90d-4914-836f-fb318269855a
Commits

Reviewing files that changed from the base of the PR and between bb06913 and 08a78fe.

Files selected for processing: 4

  • src/main/daemon/providers/routing/daemon-pty-router.ts
  • src/main/daemon/providers/routing/daemon-router-drained-legacy-fence.test.ts
  • src/main/daemon/providers/routing/daemon-router-drained-legacy.performance.test.ts
  • src/main/daemon/providers/routing/daemon-router-drained-legacy.ts

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

@brennanb2025

Copy link
Copy Markdown
Contributor Author

Perf scan update: PASS (no findings)

Head 6d62f37476e8605ef184b266482ced7e44c955e4. I re-read the changes since b8aeb5b without running anything. The surface detector again reported no surfaces ([]).

  • legacyForSpawn now calls dropAlreadyRetired() on every spawn (daemon-router-drained-legacy.ts).
    • The walk is one legacy.slice() and one hasRetiredForIdle() read per legacy adapter. It replaces the earlier filter, which was also one array and L reads per spawn.
    • A restore burst of 300 reattaches costs about 900 getter reads and 300 small arrays at L=3, all on main. That is the same as at b8aeb5b, and it doesn't depend on how many terminals or sessions are open.
    • Detaching an adapter (fanout and resolver drops, plus disconnectOnly) happens once per retired adapter, because the adapter leaves the list. It never repeats across spawns.
  • findLegacySessionOwner skips retired adapters (daemon-router-legacy-owner.ts). Each skipped adapter saves one probePtyLiveness IPC and a possible listProcesses fallback per reattach. The spawn now passes the live list, so an adapter that retires during the lookup drops out of it. Net IPC is the same or lower.
  • Unchanged since b8aeb5b: the fence gate, the 2 s unref'd cap timer, pendingIdleRetirement() with no new state, and the relay recheck backoff. Wakeups are still at most 1 per 30 min per relay-only legacy daemon, and the delays map holds at most L entries.

Regression classes (hot-path rescans, per-entity state, fixed-cadence polls, idle wakeups, unbounded fan-out) are disproved. Every per-spawn cost is bounded by L, which is usually 1 to 3.

@brennanb2025

Copy link
Copy Markdown
Contributor Author

Perf scan update: PASS (no findings)

Head 117b90198e463e31a283a61b6d58e8eea3c96f75. I re-read the changes since 6d62f37 without running anything. The surface detector again reported no surfaces ([]).

  • The fence moved into findLegacySessionOwner (daemon-router-legacy-owner.ts). The new fenceLegacyLookup callback now runs only when all of these hold:

    • the spawn has a sessionId and is not a new session;
    • the spawn is not attach-only;
    • at least one legacy daemon exists;
    • the current daemon's existing liveness probe says it does not own the session.

    In a restore burst, reattaches owned by the current daemon now skip the fence entirely: no O(L) walk and no wait. Those are the common case once legacy daemons have drained. Fewer spawns pay the fence than at 6d62f37.

  • Router per-spawn cost (daemon-pty-router.ts): one small closure per non-attach spawn. The call that unrouted reattaches already made at 6d62f37 (the pendingIdleRetirement() read across legacy adapters, the dropAlreadyRetired() slice and the 2 s capped timer) now runs at most once, and only on the legacy-lookup path. A burst of 300 unrouted reattaches still costs at most about 900 cheap getter reads at L=3, and much less when the current daemon owns them.

  • Attach-only spawns still call the fence up front, at the same O(L) cost as at 6d62f37.

  • No new IPC. The current-daemon probe was already there. Retired daemons are still detached before the legacy probes, so they cost no probe IPC.

  • Unchanged: pendingIdleRetirement() adds no new state, and the relay recheck backoff still allows at most 1 wakeup per 30 min per relay-only legacy daemon, with its map holding at most L entries.

Regression classes (hot-path rescans, per-entity state, fixed-cadence polls, idle wakeups, unbounded fan-out) are disproved. Every cost is bounded by L, which is usually 1 to 3.

@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: 1

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: 3cf75ad7-8893-442c-a66d-093301c1cdef
Commits

Reviewing files that changed from the base of the PR and between 08a78fe and 6d62f37.

Files selected for processing: 5

  • src/main/daemon/providers/adapter/daemon-pty-event-subscriptions.ts
  • src/main/daemon/providers/routing/daemon-pty-router.ts
  • src/main/daemon/providers/routing/daemon-router-drained-legacy-fence.test.ts
  • src/main/daemon/providers/routing/daemon-router-drained-legacy.ts
  • src/main/daemon/providers/routing/daemon-router-legacy-owner.ts

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

@brennanb2025

Copy link
Copy Markdown
Contributor Author

Perf scan: head 2e4369f (merged onto main 9257b2f)

Verdict: clean. No P0 or P1 findings.

Scope: router.spawn with the new retryAfterRetirement wrapper, noteSpawnsDrained, the relay-only recheck backoff (scheduleRelayRecheck / relayRecheckDelays), the hasRetiredForIdle skip in findLegacySessionOwner, pendingIdleRetirement() on the adapter, and the teardown paths (detachRetiredAdapter, dispose, retireAll, noteLegacySessionExited). Callers checked: init and restart discoverLegacySessions, reconcileOnStartup, and the subscription fanout exit callback. Static source trace only. Nothing was run.

Reference fleet: a few hundred live terminals, restarts restoring hundreds of tabs at once, and 1 to 3 legacy daemon generations per router (one per older protocol generation still alive).

Priced work

Work Trigger Population Cost per trigger Bound
Healthy spawn wrapper every router.spawn hundreds per restore burst one extra async closure/frame; noteSpawnsDrained is now called on every spawn exit but returns O(1) while spawnInFlight > 0 or deferredAfterSpawn is empty 0 extra IPC, 0 timers, 0 waits (daemon-router-drained-legacy.ts:55-57)
Failed spawn, not retryable any spawn rejection rare legacy.flatMap(pendingIdleRetirement) plus legacy.some(hasRetiredForIdle): two getter calls per legacy adapter (≤3), then rethrow O(legacy), no I/O
Refused spawn retry refusal (TerminalSessionOwnerUnverifiedError or the adapter's 'Terminal daemon is decommissioning') while a legacy decision is pending or accepted spawns that probe the legacy daemon during its decision window, at most a burst of hundreds one 2 s unref'd timer (cleared on settle), waits on the shared adapter decision promise, then one re-run of attempt(): one extra probePtyLiveness to the current daemon (or one extra attach-only resolve). The retired legacy is detached or skipped, so it is not probed again at most 1 retry per spawn, wait ≤ 2 s, once per legacy retirement (a daemon retires once). Worst case: a one-time burst of N extra current-daemon probes. Does not repeat
Owner lookup skip findLegacySessionOwner per non-new reattach hundreds per restore skips probePtyLiveness + listProcesses (2 s deadline) for a daemon that has already accepted retirement removes work compared with base
Relay-only recheck timer per relay-only legacy adapter ≤3 adapters one listSessionsAndRelays IPC to the legacy daemon 60 s doubling to a 30 min cap; timer is unref'd

Idle wakeups on main, per legacy daemon that is still serving a relay:

  • Before: 1/60 s = 0.017/s, plus the same rate of inventory requests reaching that daemon.
  • After: 5 wakeups in the first 31 min, then 1/1800 s = 0.00056/s, about 30x fewer.

There are no new idle wakeups on main, the renderer or the daemon. The 2 s fence timer exists only on the refused-spawn path. When no legacy adapter is relay-only, both base and head have 0 wakeups.

Per-adapter map entries. relayRecheckDelays holds at most one number per legacy adapter (≤3). Entries are deleted in four places:

  • detachRetiredAdapter (:186)
  • dispose (:46)
  • retireAll (:102)
  • noteLegacySessionExited (:110)

An entry for an adapter that becomes busy again stays until that adapter is detached or the router is disposed. It is bounded by the legacy count and does not grow with terminals, time or restarts. Calling noteLegacySessionExited for current-daemon exits costs one no-op Map.delete per PTY exit, which is O(1).

Retention and progress checks

  • Hung decision: if the 2 s cap fires first, each refused spawn leaves one allSettled reaction on the shared decision promise until it settles. That promise is bounded by the client connect timeout (5 s) plus the request timeouts (30 s + 30 s). Cost: a few hundred bytes per refused spawn, for at most about 65 s.
  • Spawn census: spawnInFlight stays raised during the ≤2 s wait, so the current daemon's retirement and other legacy retirement checks are deferred for that long. noteSpawnsDrained re-runs the deferred checks afterwards, so progress is kept.
  • Reclaim latency tradeoff (not a finding): a relay-only legacy daemon whose last relay ends can now stay connected up to 30 min before the next recheck retires it. Base allowed up to 60 s. This is one idle process per legacy generation, held for a fixed bound that does not grow, and the trade buys a 30x cut in steady wakeups. Worth knowing; it does not block.

Regression classes touched

  • Fixed-cadence poll that never settles: matched, and fixed by this PR (backoff with a cap). The perf contract test checks ≤51 reads in 24 h.
  • New wakeups in steady idle: matched and disproved. Wakeups go down, as shown above.
  • Per-entity state outlives the entity: matched and disproved. The four deletes listed above sit alongside the sibling sets.
  • Unbounded fan-out or queues under load: matched and disproved. One retry per spawn, a shared decision promise and a 2 s cap.
  • Expensive code newly reachable past a gate: disproved. The retry gate is !disposed && !admissionClosed && legacy retiring && refusal raised before anything was sent. The owner-lookup change only removes probes.

Six questions

  1. Unused work before the gate: reviewed. The healthy path builds nothing extra, and the retry gate is evaluated only after a rejection.
  2. Ownership multiplication: reviewed. The decision promise is per adapter and shared across routers (pendingIdleRetirement). A router built by a restart reuses it.
  3. Thread and storage: main-process async only. No sync fs or SQLite was added.
  4. Growth and progress: reviewed. The retry runs once, the backoff is capped, and the deferred retirement re-runs on drain.
  5. Execution host: not applicable beyond base. These are local daemon IPCs, and the timer behaviour is the same on mac, linux and windows. Not measured on Windows.
  6. Teardown: reviewed. dispose clears the timers and both maps. The fence timer is cleared after the race and is unref'd. disposed is checked before a retry.

Residual gaps

  • No runtime measurement. The burst figure (N extra current-daemon probes, once per legacy retirement) is a source-proven count, not a timing.
  • The attach-only re-resolve cost on retry depends on spawnDaemonAttachOnly inventory behaviour, which is unchanged in this PR. It is bounded to one extra call per refused spawn.

…used it is deciding retirement; never retry a spawn

@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: 1

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: 87f1fee6-fc54-4270-aafe-af6baffe4e30
Commits

Reviewing files that changed from the base of the PR and between 2e4369f and 4cc9f52.

Files selected for processing: 4

  • src/main/daemon/providers/routing/daemon-pty-router.ts
  • src/main/daemon/providers/routing/daemon-router-drained-legacy.ts
  • src/main/daemon/providers/routing/daemon-router-legacy-owner.ts
  • src/main/daemon/providers/routing/daemon-router-retiring-owner-lookup.test.ts

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

@brennanb2025 brennanb2025 changed the title fix(daemon): fence reattaches against legacy retirement decisions; back off relay-only rechecks fix(daemon): back off relay-only legacy rechecks; skip legacy daemons that already retired Nov 29, 2026
@brennanb2025

Copy link
Copy Markdown
Contributor Author

Perf scan: f70b670 (merged onto main 07fe2c8)

Verdict: clean. No new or amplified work. The relay-only recheck now runs less often, and owner lookup sends fewer probes than main.

Hot paths

Path Trigger / population Work per event, bound Before → after
router.spawn attach-only → dropAlreadyRetired() (daemon-pty-router.ts:98, drained-legacy.ts:47) one call per attach-only restore. A few hundred run concurrently at startup or restart. L = legacy daemon generations (bounded by upgrades whose daemons still hold sessions or relays, usually 1–3) one legacy.slice() plus L calls to hasRetiredForIdle(), which is a field compare (daemon-pty-event-subscriptions.ts:158). A retired adapter is detached once: it is spliced out of legacy, so later spawns skip it. No IPC, no I/O. Reference fleet: 300 × 3 = 900 field reads in the whole burst new but small, done once per spawn with no wakeups or I/O. It also stops an attach from resolving through a daemon that is closing
noteSpawnsDrained() now runs after every spawn (daemon-pty-router.ts:113) every spawn O(1) gate on spawnInFlight > 0 or an empty deferredAfterSpawn (drained-legacy.ts:81). Past the gate it behaves exactly like the old === 0 branch the same work
findLegacySessionOwner (daemon-router-legacy-owner.ts:24) spawn of a known session ID that is not attach-only and not new, across L legacy adapters retired adapters skip probePtyLiveness and the listProcesses fallback (2 s deadline). They return {live:false}, so they cannot hit the owner-unverified throw fewer IPCs: up to 2 fewer round trips and up to 2 s less waiting per retired adapter per lookup
Relay-only recheck timer (drained-legacy.ts:121-133) one timer per legacy adapter that has no PTYs, at least one live chat relay and no routed session. Main process, unref'd one listSessionsAndRelays IPC per fire. The delay goes 60 s, then doubles each fire up to a 30 min cap. It resets on retireAll (discovery or startup reconcile), on a legacy session exit, and on detach see wakeups below

Steady-idle wakeups, per relay-only legacy daemon

The same numbers apply on the Electron main process and on the legacy daemon, because each fire is one IPC.

  • main: 1/60 s ≈ 0.017 wakeups/s, every minute for as long as the relay lives (1,440 per day).
  • this PR: 5 fires in the first 31 min (1+2+4+8+16), then 1/1800 s ≈ 0.00056 wakeups/s. That is about 51 per day, which matches the new contract test's bound of 51 reads in 24 h.

This is a decrease, not 0 → >0. The renderer has none before or after. A reset only happens on discovery, startup reconcile, or a session exiting on that adapter. A relay-only legacy daemon gets no new sessions, so resets are limited by its remaining PTY exits and cannot keep the timer at 60 s.

Per-adapter state and deletion

relayRecheckDelays is a new Map<adapter, number> holding at most one entry per legacy adapter (≤ L). Entries are deleted in:

  • detachRetiredAdapter, alongside its sibling sets and the timer
  • retireAll
  • noteLegacySessionExited
  • dispose, which dispose, disposeRouterOnly and disconnectOnly all call

This keeps pace with relayRecheckTimers and relayMonitored. For the current adapter, noteLegacySessionExited does an O(1) delete on a key that is never present.

Regression classes

  • Fixed-cadence poll that never settles / new idle wakeups: matched and disproved. The poll now backs off to a 30 min cap, and its cadence is lower than main's.
  • Per-entity state outlives the entity: matched and disproved. The new map is cleared in every teardown path listed above.
  • Expensive code reachable past a gate: no match. The diff adds gates (it skips probes) and removes none.
  • Unbounded fan-out: no match. Promise.all over the legacy adapters is unchanged, has L ≤ a few entries, and now does less work per entry.
  • Hot-path rescans: matched and disproved. The O(L) scan per attach-only spawn has a tiny L and no I/O.

Six questions

  1. Unused work before the skip gate: checked. The skip is decided before any IPC.
  2. Ownership multiplying work: checked. There is one timer per adapter, and the relayRecheckTimers.has guard stops duplicates.
  3. Which thread pays: main, with no synchronous fs or SQLite.
  4. Growth and progress: checked. The timer advances to its cap and stops when the daemon retires.
  5. Execution host: not applicable. The change has no host-specific path, and the IPC goes to a local daemon socket.
  6. Teardown: checked. Timers are cleared and the map is emptied on dispose and detach.

Not done: static review only. No benchmark or app run.

@brennanb2025

Copy link
Copy Markdown
Contributor Author

Status: ready at f70b670

Problem: #52112 retires empty legacy terminal daemons, but an old daemon still serving chat relays was rechecked every 60 s for as long as it lived. Also, after a restart a new router could still list a legacy daemon that had already retired, so an attach-only reattach would fail resolving through it with "owner unverified".

User-facing change: none visible. Fewer background wakeups (about 51 rechecks a day instead of 1,440 per relay-only old daemon), and reopening terminals after a restart no longer trips over an old daemon that already shut down.

What shipped:

  • The relay-only recheck backs off: 60 s doubling to a 30 min cap, reset on a session exit or discovery.
  • Owner lookup treats a legacy daemon that accepted idle retirement as owning nothing.
  • An attach-only reattach first detaches legacy daemons that already retired.

Scoped out: a fix for a reattach racing the retirement decision itself. Four blinded audits rejected client-side versions of it: an up-front wait, retrying the spawn, and wait-then-re-probe. A correct fix needs the daemon to report "retiring" as an explicit refusal reason, plus cancellation in the shared probe code. That stays as on main; a second reopen works. Tracked in STA-19905.

Verified:

  • Blinded regression audit on the final head: SAFE, no findings.
  • Code review: clean.
  • Perf scan: clean, with less work than main (see the perf comment above).
  • Remote gate and CI: green.
  • QA on Linux, upgrading an old build (protocol 63) to this head (64):
    • Flow A, all four steps: old terminals reattached with their scrollback on their original shells; the old daemon retired 7 ms after its last terminal exited; new terminals worked on the current daemon; the current daemon stayed up while empty.
    • Flow B: 3 restore runs. Every terminal came back with its scrollback on its original shell, with no error toasts.
    • Earlier heads also passed 8 restore runs.
  • No screenshots: no UI change.

Deferred:

  • STA-19906: if an old terminal's shell ends after the app connects to the old daemon but before that terminal reattaches, the old daemon is never retired while the app runs. QA saw it in timed race runs; main behaves the same.
  • Trade-off: an idle relay-only old daemon can linger up to 30 min after its last relay ends, instead of up to 1 min. The next app start resets this.
  • Review P2s:
    • Dropping a retired daemon on one tab's attach-only reattach can fail another tab's reattach that is resolving at the same moment. It's the same narrow race as STA-19905, on another tab.
    • The owner-lookup skip has no dedicated test.
    • The attach test reaches its start state by a shortcut; the same state is reachable in production another way.
    • The new test duplicates a fake adapter.
    • A legacy daemon whose process exited keeps one backoff entry, bounded per exited daemon. An existing set already leaked the same way.

@brennanb2025

Copy link
Copy Markdown
Contributor Author

QA evidence: Linux, f70b670, an old build (protocol 63) upgraded to this head (64).

  • Flow A, all 4 steps passed:
    • Old terminals reattached with their scrollback on their original shells (same PIDs) and took input.
    • After the last old terminal exited, the old daemon logged shutdown {"reason":"idle"} 7 ms later and exited.
    • A new terminal opened 1.2 s later on the current daemon, with no error toast.
    • With every terminal closed, the current daemon stayed alive for 3 min 21 s, and the next terminal reused its PID.
  • Flow B, 3 relaunch-restore runs passed: in each, all four current-daemon terminals came back with their scrollback on their original shells and took input, with no toasts or failed-reopen messages.
  • Real config file hashes were unchanged before and after.

@brennanb2025
brennanb2025 merged commit ea0daaf into main Nov 29, 2026
65 checks passed
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