Skip to content

fix(daemon): bound the whole boot-recovery sequence with one budget (STA-5732) - #17427

Merged
nwparker merged 5 commits into
mainfrom
nwparker/sta-5732-daemon-recovery-budget
Aug 31, 2026
Merged

nwparker merged 5 commits into
mainfrom
nwparker/sta-5732-daemon-recovery-budget

Conversation

@nwparker

@nwparker nwparker commented Aug 30, 2026 •

Copy link
Copy Markdown
Contributor
Files Added Deleted Net
Test 6 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​339 $\color{#cf222e}{\Huge{\mathbf{−}}}$​51 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​288
Prod 6 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​141 $\color{#cf222e}{\Huge{\mathbf{−}}}$​14 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​127

Fixes STA-5732. One of 6 real defects split out of the test-detected-bugs sweep.

ELI5

The app tries to wake a helper daemon on boot. If the daemon is stuck, we politely wait, ask again, wait again… and nobody was holding a stopwatch on the whole sequence. Worst case that's roughly six minutes of an app that looks frozen.

This puts one stopwatch over the entire boot-recovery sequence. When it runs out, we stop being polite and take over.

The interesting part: picking the number

A naive 15 s budget would have silently undone an earlier fix. Commit 840d3277d1d (#8697) deliberately bought a wedged daemon ~20 s of drain grace so a transient stall wouldn't get killed — a 15 s budget preempts exactly that.

The budget has a floor and a ceiling, and both are load-bearing:

Constant Value Why
TRANSIENT_WEDGE_DRAIN_MS 20 s the grace #8697 established — the floor
DAEMON_RECOVERY_BUDGET_MS 32 s everything the fail-open cap can spare after the post-deadline tail — see below
DAEMON_RECOVERY_PROBE_MS 3 s → 8 s strictly more generous than the 3 s health check it second-guesses, so a loaded machine isn't read as a dead daemon

The ceiling is LOCAL_PTY_STARTUP_FAIL_OPEN_TIMEOUT_MS (60 s), because the kill, fork and lease that follow the deadline run inside the same gate. Sized from each stage's own hard cap rather than guessed:

Post-deadline stage Hard cap Source
killStaleDaemon 10.5 s 2× identity inspection (3 s, daemon-process-identity-query.ts) + 3 s SIGTERM wait + 1 s SIGKILL confirm + 0.5 s endpoint probe
launchDaemonChild 10 s readiness IPC timeout
adoption lease + adapter connect 5 s (allowance) runs against a daemon that just reported ready over IPC
total reserve 25.5 s 60 − 25.5 = 34.5 s available; take 32 s, keep 2.5 s margin

daemon-init-wedged-daemon-grace.test.ts pins both bounds, and a behavioral test asserts a daemon draining at the documented 20 s boundary is adopted, not killed.

Proof

Revert the daemon product files to 2daea491b96 and the daemon suite fails:

Test Files  3 failed | 144 passed | 2 skipped (149)
     Tests  9 failed | 1690 passed | 3 skipped (1702)

At HEAD: 147 passed | 2 skipped, 1701 passed.

Notes

  • shouldPreserveDaemonWithLiveSessions still preserves on liveSessionCount === null — an unverifiable live-session count is never read as "no sessions."
  • Post-kill, killOutcome.liveOwnerSurvived still degrades to adopt rather than forking beside an unproven-dead daemon.
  • The added deadline narrows an unbounded probe count to a 32 s wall clock; it does not introduce a new death assertion.
  • The launcher's last-resort rescue probe (outer catch in daemon-out-of-process-launcher.ts) is deliberately not budget-clamped. It runs after the budget by construction — past prepareDaemonReplacement, killStaleDaemon, the fork and the lease — so the remainder is essentially always negative and Math.max(1, ...) would hand a live socket a 1 ms connect window. An earlier revision of this PR clamped it; that turned a recoverable degraded adoption into total daemon loss for the run. It is back on probeDaemonSocket's own 1 s default and pinned by daemon-init-endpoint-adoption.test.ts → "rescues the endpoint owner with a full probe window after the recovery budget is spent".

User-Facing Trade-offs

There is one, and it is a real regression window. An earlier revision of this section claimed "None"; that was wrong.

The grace loop's exit is now a wall clock, so a wedged daemon that drains after the clock expires is killed along with its live PTY sessions — where the old code would have waited and adopted it.

Measured window. For the canonical wedge (socket accepts connections, hello never answers) the old code spent, from launcher entry: ~5 s unbudgeted adoption connect + 3 s health check + ~5 s initial listSessions probe + 11 grace retries at ~5 s each ≈ 65 s of effective grace. The new code stops at 32 s. So a wedge draining between ~32 s and ~65 s is preserved by the old code and killed by the new code. Below 32 s, both adopt. Above ~65 s, both kill — and the old code also blew the 60 s fail-open gate first, so the user lost the sessions and watched the app hang. That is STA-5732.

What was done about it. The window was originally ~24 s–65 s. Auditing the post-deadline tail showed the 24 s budget reserved only 9 s for a tail whose real hard caps total 25.5 s — against a 60 s gate, so 27 s of the gate was simply unused. Widening the budget to 32 s buys back ~8 s of adopt window at zero cost to the fix: it strictly widens the preserve path, and the total still fits the gate by construction (32 + 25.5 = 57.5 < 60).

Why the window cannot be closed entirely. The natural mitigation — "on budget exhaustion, adopt the still-answering daemon in degraded mode instead of killing it" — was considered and rejected:

  • The existing killOutcome.liveOwnerSurvived net already covers every case where the kill is unverifiable: a missing or unparseable PID record, a failed identity inspection, EPERM from another user's daemon, or a SIGTERM/SIGKILL whose exit cannot be confirmed. All of those adopt in degraded mode and keep the sessions (covered by daemon-init-endpoint-adoption.test.ts, "degrades instead of forking beside a daemon that could not be confirmed stopped"). Sessions are only lost when the kill positively succeeds.
  • The kill does positively succeed on the canonical wedge: the daemon registers a SIGTERM handler (daemon-entry.ts:204), a wedged event loop never runs it, so the SIGKILL at t+3 s lands. That is exactly the case the window is about, so the existing net does not cover it.
  • Turning that into a degraded adoption reintroduces [Bug]: DaemonProtocolError: Hello response timed out #8689 verbatim — a permanently wedged daemon adopted forever, on every launch. Worse, DegradedDaemonPtyProvider.discoverDaemonSessions() then runs listSessions against that same never-answering socket with the client's unbudgeted defaults (5 s connect + 30 s request), inside the same 60 s gate. That is a new startup hang, i.e. it reintroduces the bug this PR fixes.

So the residual risk is irreducible without new persistent state to distinguish "wedged this boot" from "wedged every boot", which is out of scope here. The trade is: a ~33 s window in which a slow-draining daemon loses its sessions, in exchange for never again hanging startup for minutes and losing them anyway.

Also residual: the recovery deadline uses wall-clock Date.now(); a clock jump during startup would shorten or lengthen the budget. Not expected during startup and not a proven release issue.

Readiness review

Verdict: PASS after one fix-loop iteration. The review found and fixed a bounded P2 reliability issue: socket liveness probes now use the remaining recovery deadline, so the boot-recovery budget is enforced for the grace loop and post-failure adoption path.

Checklist status:

  • SSH / remote / network: no SSH, relay, or wire changes; no regression found.
  • Crash / retry / growth: recovery probes and requests are deadline-bounded; daemon grace remains capped; no unbounded growth found.
  • Security / supply chain: no new shell/eval, secrets, network sinks, dependency, or updater changes.
  • Performance / resources: probe count and wall-clock recovery are bounded; startup remains within the 60-second fail-open gate.
  • Functional correctness: transient wedges with live sessions remain adoptable up to the 32 s budget; permanent wedges are replaced; rejected handshakes skip grace retries. The narrowing versus fix(daemon): replace a permanently wedged daemon instead of preserving it forever (#8689) #8697's merged ~60 s grace is a real regression for wedges draining in the 32–65 s band — see User-Facing Trade-offs above; it is now pinned by daemon-init-wedged-daemon-grace.test.ts → "replaces a wedge that drains after the recovery budget (accepted trade vs fix(daemon): replace a permanently wedged daemon instead of preserving it forever (#8689) #8697)" rather than left implicit.
  • Backward compatibility / data loss: no persisted schema or RPC/mobile contract touched.
  • Cross-platform / remoting: timeout logic is platform-neutral; no Windows/WSL/path/process changes.
  • Code organization: new budget module is colocated with daemon startup code.

Visual proof: N/A — this is a main-process daemon recovery change with no UI or interaction changes.

Testing

  • pnpm test src/main/daemon/ — 147 files passed, 2 skipped; 1,701 tests passed, 3 skipped
  • pnpm tc — clean
  • oxlint src/main/daemon/ — clean
  • pnpm run check:code-quality:changed — 0 new findings across 12 changed files

Performance Measurement

The previous boot-recovery retry sequence had no whole-sequence deadline (≈9.4 min worst case: 11 retries × unbudgeted 5 s connect + 30 s request). The new DAEMON_RECOVERY_BUDGET_MS bounds it at 32 s, with a further ≤25.5 s of kill/fork/lease before the 60 s startup fail-open gate.

@greptile-apps

greptile-apps Bot commented Aug 30, 2026 •

Copy link
Copy Markdown

Greptile Summary

This PR applies one 32-second wall-clock budget across daemon adoption and replacement preflight while preserving a final full-window endpoint rescue.

  • Adds shared recovery-budget and probe-timeout constants.
  • Bounds daemon handshakes and session-list requests by the remaining recovery time.
  • Converts wedged-daemon grace from an effectively unbounded retry sequence to a deadline-bound loop.
  • Expands coverage for transient wedges, deadline exhaustion, endpoint adoption, and startup failure paths.

Confidence Score: 5/5

The PR appears safe to merge because no blocking failure remains.

No blocking failure remains.

Important Files Changed

Filename Overview
src/main/daemon/daemon-recovery-budget.ts Defines the shared 32-second recovery budget and clamps individual probe attempts to its remaining time.
src/main/daemon/daemon-launch-paths.ts Adds timeout-aware socket probing and bounds daemon handshake plus session enumeration under one probe deadline.
src/main/daemon/daemon-replacement-preflight.ts Threads the absolute recovery deadline through preservation checks and terminates wedged-daemon retries when time expires.
src/main/daemon/daemon-out-of-process-launcher.ts Establishes the recovery deadline at launcher entry while intentionally retaining the final endpoint rescue's independent probe window.
src/main/daemon/daemon-init-wedged-daemon-grace.test.ts Covers both recovery-budget bounds and the adopt-versus-replace behavior around transient and permanent daemon wedges.
src/main/daemon/daemon-init-endpoint-adoption.test.ts Verifies degraded endpoint-owner rescue after replacement failure and recovery-budget exhaustion.

Sequence Diagram

sequenceDiagram
  participant S as Startup gate
  participant L as Daemon launcher
  participant D as Existing daemon
  participant R as Replacement daemon
  S->>L: Start daemon recovery
  L->>L: Set 32-second recovery deadline
  L->>D: Budgeted adoption attempt
  alt Existing daemon is recoverable
    D-->>L: Live sessions
    L-->>S: Adopt existing daemon
  else Recovery budget expires
    L->>D: Kill stale daemon
    L->>R: Launch replacement
    alt Replacement publishes endpoint
      R-->>L: Ready and adopted
      L-->>S: Use replacement daemon
    else Replacement loses endpoint
      L->>D: Full-window rescue probe
      D-->>L: Endpoint response
      L-->>S: Degraded adoption when completed
    end
  end
Loading

Reviews (5): Last reviewed commit: "fix(daemon): name the socket probe defau..." | Re-trigger Greptile

@coderabbitai

coderabbitai Bot commented Aug 30, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

The daemon launcher now uses one absolute recovery deadline for adoption and replacement probes. Connection, listSessions, and socket probes receive bounded timeouts derived from that deadline. Replacement preflight stops grace retries when the deadline expires. Recovery tests model handshake and session-list wedges, transient drain behavior, endpoint adoption, and replacement outcomes. Daemon client mocks now implement ensureConnectedWithin, and request assertions include the explicit timeout argument.

Merge Risk: 🟡 Moderate · up to df1ca

The change bounds the main daemon recovery loop, but some preflight and cleanup waits still use independent timeouts and may continue beyond the intended 32-second recovery budget and 60-second startup fail-open limit. That can prolong startup or allow a late daemon transition, so this should be fixed or explicitly accepted by the owner before merge.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 52.94% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 17 functions across 12 files. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly and concisely describes the main change: applying one budget to the complete daemon boot-recovery sequence.
Description check ✅ Passed The description is complete and directly related to the change. It includes the ELI5 summary, changes, rationale, linked issue, visual proof marked N/A with justification, testing results, review find…
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.
Full details: Description check

Explanation

The description is complete and directly related to the change. It includes the ELI5 summary, changes, rationale, linked issue, visual proof marked N/A with justification, testing results, review findings, trade-offs, and checklist considerations. The required information is present despite using some headings that differ from the template.

  • Fix all pre-merge checks with AI
✨ Finishing Touches 💡 1
📝 Generate docstrings 💡
  • Create stacked PR
  • Commit on current branch

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

❤️ Share

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

@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

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: b140de1f-0c2c-44c8-88f2-0014291695bc

📥 Commits

Reviewing files that changed from the base of the PR and between 89a4d67 and 66e8f7a.

📒 Files selected for processing (12)
  • src/main/daemon/daemon-init-child-startup-failure.test.ts
  • src/main/daemon/daemon-init-endpoint-adoption.test.ts
  • src/main/daemon/daemon-init-fresh-import.ts
  • src/main/daemon/daemon-init-live-session-preservation.test.ts
  • src/main/daemon/daemon-init-packaged-bundle-staleness.test.ts
  • src/main/daemon/daemon-init-replacement-reporting.test.ts
  • src/main/daemon/daemon-init-test-harness.ts
  • src/main/daemon/daemon-init-wedged-daemon-grace.test.ts
  • src/main/daemon/daemon-launch-paths.ts
  • src/main/daemon/daemon-out-of-process-launcher.ts
  • src/main/daemon/daemon-recovery-budget.ts
  • src/main/daemon/daemon-replacement-preflight.ts

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

@pullfrog pullfrog 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.

Important

The 24 s budget narrows the handshake-wedge grace from the ~60 s #8697 actually shipped (11 retries × 5 s hello timeout) down to ~24 s, and the TRANSIENT_WEDGE_DRAIN_MS = 20 s premise this PR leans on is the pre-widening value from #8697's first commit, not what it settled on. A Windows update-relaunch wedge that drains between ~24 s and ~60 s was adopted before and is now killed.

Reviewed changes

  • daemon-recovery-budget.ts — New tuning module: TRANSIENT_WEDGE_DRAIN_MS (20 s), DAEMON_RECOVERY_PROBE_MS (8 s), DAEMON_RECOVERY_BUDGET_MS (24 s), and daemonRecoveryProbeTimeoutMs() which clamps a probe to the remaining deadline.
  • daemon-launch-paths.ts — getAliveDaemonSessionCount now takes a recoveryDeadlineMs, gives the connect + listSessions request one shared probe slice via remainingDaemonRequestTimeoutMs, and uses ensureConnectedWithin so a wedged handshake can no longer absorb its own fresh 30 s request default.
  • daemon-out-of-process-launcher.ts — Computes one recoveryDeadlineMs = now + DAEMON_RECOVERY_BUDGET_MS up front, bounds the adoption ensureConnectedWithin, and passes the deadline into the preflight.
  • daemon-replacement-preflight.ts — Threads recoveryDeadlineMs through getAliveDaemonSessionCount / shouldPreserveDaemonWithLiveSessions and adds Date.now() < recoveryDeadlineMs to the grace loop.
  • Tests — Mirror ensureConnectedWithin across the mock graph, pin the constant relationships, and add a hand-driven-clock suite (runWedgedRecovery) covering the handshake-wedge, listSessions-wedge, and drain-at-the-edge shapes.

⚠️ The previous ~60 s grace floor is removed and not replaced

This change deletes the only test that pinned the grace magnitude — grace budget is generous enough to ride out a ~60s transient wedge, whose comment warned "don't cut without telemetry." The replacement asserts DAEMON_RECOVERY_BUDGET_MS > TRANSIENT_WEDGE_DRAIN_MS (24 s > 20 s), which only rules out budgets below 20 s. Nothing pins the 24 s choice against the ~60 s the old 12-probe loop provided, so the regression range — a handshake wedge draining in 24–60 s — is untested, and a future shrink to 21 s would pass every test while adopting fractionally less.

Technical details
# Grace floor narrowed without a test guarding the 24–60 s range

## Affected sites
- src/main/daemon/daemon-init-wedged-daemon-grace.test.ts — the "~60s transient wedge" guard was deleted; its replacement only pins `budget > TRANSIENT_WEDGE_DRAIN_MS`.
- src/main/daemon/daemon-recovery-budget.ts:6 — `TRANSIENT_WEDGE_DRAIN_MS = 20_000` is described as "the … shape #8697 sized the grace against", but #8697's merged second commit explicitly widened the grace to ~60 s and described ~20 s as the value it was widening *from*.

## Required outcome
- Either back the 24 s number with telemetry showing a transient wedge never drains past ~20 s, or raise `DAEMON_RECOVERY_BUDGET_MS` toward the ~60 s the fail-open cap still absorbs (the test already shows 24 s budget + 9 s relaunch is well under the 60 s cap, leaving ~27 s of headroom).
- Add a behavioral test that asserts a handshake wedge draining in the 24–60 s window is still adopted, so the regression range is guarded rather than incidental.

## Open questions for the human (optional)
- Was the "~20 s drains within" estimate from #8697 ever validated against real Windows update-relaunch events, or was ~60 s chosen purely as "as close to zero loss as possible under the cap"?

ℹ️ Nitpicks

  • The PR title and daemon-recovery-budget.ts describe "the whole boot-recovery sequence" as bounded, but the deadline only fences the adopt/replace probes: checkDaemonHealth (3 s), the macOS resolver/TCC checks, and the kill/fork/lease all run outside it (guarded only by their own 3 s timeouts or the 60 s cap). Not a bug — the code comment already concedes this — just a gap between the title and what the fence actually covers.

Pullfrog  | Fix all ➔ | Fix 👍s ➔ | View workflow run | Using DeepSeek Pro (free via Pullfrog for OSS) | 𝕏

@pullfrog pullfrog 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.

Important

The new recoveryDeadlineMs clamp on the degraded-mode adoption probe (daemon-out-of-process-launcher.ts) is expired by the time that probe runs, which effectively disables the "adopt the daemon that owns the endpoint" safety net in the exact wedge scenario this PR is about.

Reviewed changes

  • daemon-launch-paths.ts — probeDaemonSocket gains a timeoutMs = 1000 parameter so callers can bound the raw socket liveness check.
  • daemon-replacement-preflight.ts — the grace loop's probeSocket now clamps to the remaining recovery deadline, closing the prior ~1 s overshoot past the budget. Correct.
  • daemon-out-of-process-launcher.ts — the catch-all degraded adoption probe is also clamped to recoveryDeadlineMs.

The grace-loop clamp is right. The problem is running the same clamped deadline through the catch-all probe at daemon-out-of-process-launcher.ts:204 (see inline).

Technical details
# Degraded-mode adoption probe is clamped to an already-expired deadline

## Affected sites
- src/main/daemon/daemon-out-of-process-launcher.ts:204 — probeSocket(socketPath, Math.max(1, Math.min(1000, recoveryDeadlineMs - Date.now())))

## Required outcome
- Confirm whether the catch-all adoption probe is meant to stay budgeted. It runs after the adopt-or-replace decision, the fork attempt, and the lease — so recoveryDeadlineMs (24 s from launcher entry) is normally expired at this point, and the clamp yields ~1 ms, causing the probe to nearly always report false and the launcher to throw rather than adopt a live concurrent daemon.

## Open questions for the human (optional)
- Should this probe use a fixed budget (e.g. the previous 1000 ms default) or a fresh deadline, since it guards a late-stage race the budget was not designed to cover?

Pullfrog  | Fix all ➔ | Fix 👍s ➔ | View workflow run | Using DeepSeek Pro (free via Pullfrog for OSS) | 𝕏

@nwparker
nwparker force-pushed the nwparker/sta-5732-daemon-recovery-budget branch from 0055e23 to 75c87a8 Compare August 31, 2026 06:44
@coderabbitai

coderabbitai Bot commented Aug 31, 2026

Copy link
Copy Markdown
Contributor

Note

GitHub couldn't provide a complete incremental comparison for this pull request, so CodeRabbit is performing a full review instead. This review may take a little longer.

@pullfrog pullfrog 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.

Important

This delta cleanly resolves the prior budget-sizing finding, but it does not touch the still-open catch-all adoption-probe clamp at daemon-out-of-process-launcher.ts:203 — that probe still clamps to the (by then expired) recoveryDeadlineMs and collapses to ~1 ms, disabling the degraded-mode adoption fallback. Withholding approval until that is fixed or explicitly confirmed intended.

Reviewed changes

  • Resized the budget against the real post-kill tail — DAEMON_RECOVERY_BUDGET_MS 24 s → 32 s, now justified stage-by-stage (kill 10.5 s + fork 10 s + lease 5 s = 25.5 s; 60 − 25.5 leaves 34.5 s, take 32 s, keep 2.5 s margin).
  • Pinned the floor and ceiling behaviorally — a hand-driven-clock harness (runWedgedRecovery) now asserts a handshake wedge draining at the 20 s boundary is adopted (not killed), and that a never-draining wedge is killed at exactly the 32 s budget.
  • Replaced the deleted ~60 s grace guard — the constant test now asserts budget > TRANSIENT_WEDGE_DRAIN_MS and budget + relaunch tail < LOCAL_PTY_STARTUP_FAIL_OPEN_TIMEOUT_MS, with the probe/health-check and retry/spin-guard relationships.

Pullfrog  | Fix it ➔ | View workflow run | Using DeepSeek Pro (free via Pullfrog for OSS) | 𝕏

The 24s budget reserved only 9s for everything after the deadline, leaving
27s of the startup PTY gate's fail-open cap unused — and every unused second
is one where a daemon that would have drained gets killed with its live PTYs
instead. Reserve each post-deadline stage's actual hard cap (kill 10.5s, fork
10s, lease 5s) and spend the rest: 24s -> 32s of adopt window.
…y budget

The rescue probe in the launcher's outer catch was clamped to the recovery
budget's remainder, but it runs *after* that budget by construction — past
prepareDaemonReplacement, killStaleDaemon, the fork and the adoption lease.
The remainder is therefore essentially always negative, so Math.max(1, ...)
handed a live socket a 1ms connect window. On the loaded machine this path
exists for the probe loses to its own timer, the launcher rethrows, and a
recoverable degraded adoption becomes total daemon loss for the whole run —
the outcome the comment above it exists to prevent. Restore the 1s default
and pin the window with a test that drives the launcher to that catch with
the budget already spent.

Also make the deliberate narrowing legible instead of implicit:

- daemon-recovery-budget.ts: TRANSIENT_WEDGE_DRAIN_MS documented 20s as the
  grace #8697 sized, but #8697's merged second commit (840d327) widened
  it to 11 retries ~= 60s. Record that 20s is the drain estimate and that the
  budget deliberately sits under #8697's shipped grace.
- daemon-init-wedged-daemon-grace.test.ts: pin the trade directly — a wedge
  draining after the budget is replaced and loses its live sessions.
- Rewrite 'preserves a daemon that stays wedged until the LAST allowed grace
  retry' onto the simulated clock. It never mocked Date.now, so its 12 probes
  elapsed ~0ms and asserted a retry grace the wall clock can no longer
  deliver; it now pins the last drain the budget still adopts.
@nwparker
nwparker force-pushed the nwparker/sta-5732-daemon-recovery-budget branch from 75c87a8 to 9a95655 Compare August 31, 2026 08:00
@nwparker

Copy link
Copy Markdown
Contributor Author

Risk-reduction pass (rebased onto origin/main @ 649c188cc4c, force-pushed)

Head is now 9a956551aea. Clean rebase, no conflicts.

Applied

  1. daemon-out-of-process-launcher.ts — un-clamped the last-resort rescue probe. This was the one user-facing regression the PR introduced by accident. The probe in the outer catch was clamped to Math.max(1, Math.min(1000, recoveryDeadlineMs - Date.now())), but it runs after the budget by construction — past prepareDaemonReplacement, killStaleDaemon (3 s + 1 s), launchDaemonChild (10 s) and the adoption lease. The remainder is therefore essentially always negative, so a live socket got a 1 ms connect window, lost to its own timer, and the launcher rethrew — converting a recoverable degraded adoption into total daemon loss for the whole run, exactly what the comment two lines above exists to prevent. Back on probeDaemonSocket's 1 s default.
  2. New test pinning that window (daemon-init-endpoint-adoption.test.ts): drives the launcher to the outer catch with the budget already spent (clock advanced inside killStaleDaemon) and a socket that answers at 500 ms, then asserts mode === 'degraded-new-pty-fallback'. Verified it bites — restoring the clamp makes it fail with Daemon endpoint ownership changed during startup, i.e. the rescue silently doesn't happen.
  3. Made the deliberate narrowing explicit rather than implicit. New test replaces a wedge that drains after the recovery budget (accepted trade vs #8697). Verified it bites: removing both budget bounds (the pre-PR world) turns it red.
  4. Rewrote preserves a daemon that stays wedged until the LAST allowed grace retry onto the simulated clock. It never mocked Date.now, so its 12 mocked probes elapsed ~0 ms and the budget never bound — it asserted a 12-probe grace production can no longer deliver (each real failing probe costs up to DAEMON_RECOVERY_PROBE_MS = 8 s, so ~4 fit in 32 s). It now pins the last drain the budget still adopts. The retry count's exhaustion side stays pinned by the #8689 test. Verified it bites.
  5. TRANSIENT_WEDGE_DRAIN_MS docstring said 20 s was "the grace fix(daemon): replace a permanently wedged daemon instead of preserving it forever (#8689) #8697 sized". fix(daemon): replace a permanently wedged daemon instead of preserving it forever (#8689) #8697's merged second commit (840d3277d1d) widened WEDGED_DAEMON_GRACE_RETRIES 3 → 11 (~20 s → ~60 s) explicitly "to keep live-session loss on the transient-wedge (Windows update-relaunch) path as close to zero as possible". Corrected: 20 s is the drain estimate; the budget deliberately sits under fix(daemon): replace a permanently wedged daemon instead of preserving it forever (#8689) #8697's shipped grace.

Deliberately not applied — the action plan was written against an older tree and two of its items are stale or wrong:

  • "Raise DAEMON_RECOVERY_BUDGET_MS 24 000 → 36 000." Already 32 000 as of cacd7a9842e. And 36 000 is not safe: the plan sized the post-recovery tail at 19 000 ms, but the tree's own accounting is 25 500 ms (kill 10.5 s + fork 10 s + lease 5 s). 36 000 + 25 500 = 61 500 > the 60 000 ms LOCAL_PTY_STARTUP_FAIL_OPEN_TIMEOUT_MS — it would break the existing upper-bound assertion and overrun the gate. Current 32 000 + 25 500 = 57 500.
  • "Correct POST_RECOVERY_RELAUNCH_MS to 3 000 + 1 000 + 10 000 + 5 000." Already corrected in cacd7a9842e to 25 500, which is more complete than the plan's 19 000 (it counts the two identity inspections and the endpoint probe).
  • Most of the PR-body correction was already done by an earlier revision. Added the rescue-probe rationale and made the Readiness "functional correctness" bullet name the narrowing instead of glossing it.

Verification: pnpm test src/main/daemon/ → 147 files passed / 2 skipped, 1 701 tests passed / 3 skipped. pnpm tc clean. oxlint clean, pnpm run check:code-quality:changed → 0 new findings across 12 files. oxfmt --check clean.

Residual risk (unchanged, and I'd call it medium-by-design, not low):

  • The trade itself is irreducible. Bounding the sequence means some drain times previously adopted are now killed, destroying live terminal/agent sessions. Only the window size is tunable and the ceiling is ~34.5 s. The window is now (32 s, ~65 s]; it is pinned by a test and stated in the body, but it is still a real regression for that band.
  • The kill remains silent at runtime — console.warn plus trackDaemonReplaced telemetry, with no renderer surface. That is pre-existing for the whole subsystem (every DEGRADED-MODE and replace path is warn-only), and this PR does not make it more silent — it changes when the silent kill fires. Making it loud needs new IPC + renderer notification plumbing, which is a larger and riskier change than this PR; worth a follow-up, not a blocker here.

@pullfrog pullfrog 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.

✅ No new issues found.

Reviewed changes

  • Unclamped the last-resort endpoint rescue probe — daemon-out-of-process-launcher.ts:207 is back on probeSocket(socketPath) with its 1 s default, since the recovery deadline it was clamped to is normally expired by the time this probe runs (after the kill, fork and lease).
  • Pinned the rescue behaviorally — daemon-init-endpoint-adoption.test.ts adds "rescues the endpoint owner with a full probe window after the recovery budget is spent", which advances the clock past the budget and asserts a late-answering socket is still adopted rather than lost.
  • Rewrote the wedge-drain tests onto the hand-driven clock — the old "last allowed grace retry" test now drains at DAEMON_RECOVERY_BUDGET_MS − 1 s and asserts adoption within budget, and a new test pins the accepted trade of replacing a wedge that drains after the budget.
  • Corrected the TRANSIENT_WEDGE_DRAIN_MS comment — it now distinguishes the 20 s drain estimate from the ~60 s grace #8697 actually shipped, matching the prior review's premise correction.

Pullfrog  | View workflow run | Using DeepSeek Pro (free via Pullfrog for OSS) | 𝕏

…y rationale

Answers the review round on the budget accounting: the outer-catch endpoint
rescue is deliberately outside it, and the preflight clamp no longer duplicates
probeDaemonSocket's default as a bare literal.
@nwparker

Copy link
Copy Markdown
Contributor Author

Review round: every open comment answered

Head is now df1ca9ea33e. Two doc corrections and one constant extraction; no behavior change in this push. Every reviewer comment below was re-read against the code at HEAD, not against the revision it was written on.

Inline comments

1. coderabbitai — daemon-replacement-preflight.ts:160, "Bound probeSocket by the remaining recovery budget" — Correct, and already fixed in 0055e23. The grace loop's probe now clamps to min(DAEMON_SOCKET_PROBE_TIMEOUT_MS, recoveryDeadlineMs - Date.now()), and the listSessions leg inside getAliveDaemonSessionCount shares one slice with its connect (probeDeadlineMs = Date.now() + probeTimeoutMs, then remainingDaemonRequestTimeoutMs(probeDeadlineMs)), so neither leg can outlive the deadline. This push replaces the bare 1000 literal in that clamp with the now-exported DAEMON_SOCKET_PROBE_TIMEOUT_MS, so the clamp cannot silently decouple from probeDaemonSocket's own default.

2. pullfrog — daemon-recovery-budget.ts:31, "24 s budget is smaller than the grace #8697 shipped" — Correct on the premise, and fixed in 75c87a8. 840d3277d1d's second commit did widen WEDGED_DAEMON_GRACE_RETRIES 3 → 11 (~20 s → ~60 s); 20 s was the drain estimate, not the shipped grace. Budget resized 24 s → 32 s against the audited post-kill tail, and the TRANSIENT_WEDGE_DRAIN_MS docstring now says which number is which. I re-derived the ceiling myself rather than trusting the body: killStaleDaemon ≤ 10.5 s (daemon-stale-kill.ts KILL_WAIT_MS 3 s + SIGKILL_CONFIRM_WAIT_MS 1 s, two inspectDaemonProcessIdentity calls at the Windows CIM cap of 3 s each in daemon-process-identity-query.ts:110, plus ENDPOINT_PROBE_TIMEOUT_MS 0.5 s), fork 10 s (daemon-launched-child.ts:206, setTimeout(..., 10000)), lease allowance 5 s = 25.5 s. 32 000 + 25 500 = 57 500 < 60 000. For the record, the 36 000 an earlier plan proposed would be 61 500 — over the gate.

3. pullfrog — daemon-out-of-process-launcher.ts:204, "degraded-mode adoption probe is clamped to an already-expired deadline" — This one found a real defect I had introduced, and it is the most serious comment on the PR. The clamp collapsed to ~1 ms against a live socket, so the outer-catch rescue nearly always reported false and the launcher rethrew — converting a recoverable degraded adoption into total daemon loss for the whole run. Fixed in 9a95655 (back to probeSocket(socketPath) on its 1 s default) and pinned by daemon-init-endpoint-adoption.test.ts → "rescues the endpoint owner with a full probe window after the recovery budget is spent". I re-verified the pin bites this round: re-applying the clamp fails that test with Daemon endpoint ownership changed during startup (see mutation check below).

4 & 5. pullfrog — the two "Addressed in …" replies — pullfrog's own confirmations of 2 and 3; no action. pullfrog's latest review at 9a95655 is "✅ No new issues found."

Review-body findings

6. pullfrog nitpick — "the title says 'the whole boot-recovery sequence' but the fence only covers the adopt/replace probes" — Accurate. checkDaemonHealth (3 s), the macOS resolver/TCC checks, launchDaemonChild, holdDaemonAdoptionLease and the kill all run outside the deadline, on their own caps. The DAEMON_RECOVERY_BUDGET_MS docstring already scopes itself correctly ("adopting-or-replacing whatever daemon already owns the endpoint"); I've left the title, since "boot recovery" is the adopt-or-replace phase and the body table spells out the tail explicitly.

7. greptile P1 — "Rescue exceeds startup budget" (daemon-out-of-process-launcher.ts:207-212) — The arithmetic is right, but it is not a regression from this PR, so I have documented it rather than changed the code. That whole block is byte-identical to main apart from the comment I added — git show origin/main:src/main/daemon/daemon-out-of-process-launcher.ts has the same if (await probeSocket(socketPath)) and the same unbounded preserveDaemon(...). On main this same rescue sits behind an unbounded recovery (≈9.4 min worst case), so it blew the 60 s gate far harder; this PR strictly shortens what precedes it. Greptile is also under-counting: on a socket that accepts but never answers hello, holdDaemonAdoptionLease → client.ensureConnected() costs the client's unbudgeted default, not 5 s. And the fix Greptile implies — clamping the rescue — is exactly the defect comment 3 caught. So: budget cut would widen the session-loss window, clamp would reintroduce a P1. What I did instead is name it in the DAEMON_RECOVERY_BUDGET_MS docstring so the "2.5 s margin" is not misread as covering the rescue, including why the overrun is benign: if the gate fails open first, initDaemonPtyProvider sees signal.aborted and discards the adoption — the same outcome as not rescuing, and strictly better whenever the rescue wins the race.

My own fresh review

Verified independently, nothing new blocking:

  • Every consumer of every changed signature. getAliveDaemonSessionCount gained a 3rd positional param ahead of the optional protocolVersion — all five call sites are in daemon-replacement-preflight.ts and all pass the deadline; no caller passed protocolVersion positionally, so no silent arg shift. probeDaemonSocket's new param is defaulted, and the other three call sites (daemon-protocol-cleanup.ts, daemon-legacy-adapters.ts, the launcher rescue) are unchanged.
  • Mock-graph completeness. Swept every file mocking ensureConnected for a missing ensureConnectedWithin (a missing one would throw a TypeError swallowed by the launcher's catch, silently changing the path under test). Only daemon-init-restart-sequence.test.ts lacks it, correctly — that mock is for the shutdown-RPC path, which still uses ensureConnected.
  • Null-count direction. An 8 s-capped probe biases toward null on a loaded host; every consumer treats null as preserve (!== 0 at :57, === 0 at :123, shouldPreserveDaemonWithLiveSessions), except the health-unhealthy grace path, which is the accepted trade. client.disconnect() is in a finally, so no client leak per probe.
  • Loop ordering. Date.now() < recoveryDeadlineMs is placed before the await probeSocket, so an out-of-budget iteration costs no socket connect.
  • No wire, schema, SSH/relay, or platform-conditional surface is touched; probeDaemonSocket keeps its win32 named-pipe branch; no metaKey, no direct child_process.
  • Comment accuracy fix (this push): the WEDGED_DAEMON_GRACE_RETRIES rationale said the count guards a probe that fails instantly "nothing listening" — that case can't reach the loop body, since probeSocket gates it and returns false. The real spin shape is a socket that accepts and then resets the hello. Corrected.

Verification

  • pnpm test src/main/daemon/ → 147 files passed | 2 skipped; 1701 tests passed | 3 skipped (one unrelated ETIMEDOUT flake in bash-prompt-command-composition.test.ts, which spawns a real interactive bash — passed on the immediately preceding and following runs).
  • pnpm tc clean · oxlint src/main/daemon/ clean · pnpm run check:code-quality:changed → 0 new findings across 12 files · oxfmt --check clean.
  • Mutation checks (both bite):
    • Re-clamping the rescue probe to Math.max(1, Math.min(1000, recoveryDeadlineMs - Date.now())) → daemon-init-endpoint-adoption.test.ts fails with Daemon endpoint ownership changed during startup. This is the strongest evidence that comment 3 was a real defect and that the fix is pinned.
    • Replacing the grace loop's Date.now() < recoveryDeadlineMs with true → two daemon-init-wedged-daemon-grace.test.ts tests fail (expected 32008 to be less than or equal to 32000). Worth stating plainly: the bite is thin because the per-probe clamp inside getAliveDaemonSessionCount is doing most of the enforcement; the loop's clock term is a cheap early exit on top of it, not the sole bound.

Deliberately not changed

@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.

🧹 Nitpick comments (1)
src/main/daemon/daemon-init-wedged-daemon-grace.test.ts (1)

77-77: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Export and reuse HEALTH_CHECK_TIMEOUT_MS in the test.

src/main/daemon/daemon-health.ts keeps the constant private, while the test uses a separate 3_000 value. A future production timeout change can leave the invariant checking a stale value. Export the production constant and import it in the test.


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 4a543a41-8af2-4ac5-b617-94b8dec11f71

📥 Commits

Reviewing files that changed from the base of the PR and between e22c4ee and df1ca9e.

📒 Files selected for processing (12)
  • src/main/daemon/daemon-init-child-startup-failure.test.ts
  • src/main/daemon/daemon-init-endpoint-adoption.test.ts
  • src/main/daemon/daemon-init-fresh-import.ts
  • src/main/daemon/daemon-init-live-session-preservation.test.ts
  • src/main/daemon/daemon-init-packaged-bundle-staleness.test.ts
  • src/main/daemon/daemon-init-replacement-reporting.test.ts
  • src/main/daemon/daemon-init-test-harness.ts
  • src/main/daemon/daemon-init-wedged-daemon-grace.test.ts
  • src/main/daemon/daemon-launch-paths.ts
  • src/main/daemon/daemon-out-of-process-launcher.ts
  • src/main/daemon/daemon-recovery-budget.ts
  • src/main/daemon/daemon-replacement-preflight.ts

Included review availability: Your plan provides up to 10 included reviews per hour; 2 remain after this review.

@nwparker
nwparker merged commit e17c98d into main Aug 31, 2026
34 checks passed
enrick-dev pushed a commit to enrick-dev/orca that referenced this pull request Oct 15, 2026
…STA-5732) (stablyai#17427)

* fix(daemon): bound the whole boot-recovery sequence with one budget (STA-5732)

* fix(daemon): keep socket probes inside recovery budget

* fix(daemon): size the recovery budget against the real post-kill tail

The 24s budget reserved only 9s for everything after the deadline, leaving
27s of the startup PTY gate's fail-open cap unused — and every unused second
is one where a daemon that would have drained gets killed with its live PTYs
instead. Reserve each post-deadline stage's actual hard cap (kill 10.5s, fork
10s, lease 5s) and spend the rest: 24s -> 32s of adopt window.

* fix(daemon): keep the last-resort endpoint rescue outside the recovery budget

The rescue probe in the launcher's outer catch was clamped to the recovery
budget's remainder, but it runs *after* that budget by construction — past
prepareDaemonReplacement, killStaleDaemon, the fork and the adoption lease.
The remainder is therefore essentially always negative, so Math.max(1, ...)
handed a live socket a 1ms connect window. On the loaded machine this path
exists for the probe loses to its own timer, the launcher rethrows, and a
recoverable degraded adoption becomes total daemon loss for the whole run —
the outcome the comment above it exists to prevent. Restore the 1s default
and pin the window with a test that drives the launcher to that catch with
the budget already spent.

Also make the deliberate narrowing legible instead of implicit:

- daemon-recovery-budget.ts: TRANSIENT_WEDGE_DRAIN_MS documented 20s as the
  grace stablyai#8697 sized, but stablyai#8697's merged second commit (6f08017) widened
  it to 11 retries ~= 60s. Record that 20s is the drain estimate and that the
  budget deliberately sits under stablyai#8697's shipped grace.
- daemon-init-wedged-daemon-grace.test.ts: pin the trade directly — a wedge
  draining after the budget is replaced and loses its live sessions.
- Rewrite 'preserves a daemon that stays wedged until the LAST allowed grace
  retry' onto the simulated clock. It never mocked Date.now, so its 12 probes
  elapsed ~0ms and asserted a retry grace the wall clock can no longer
  deliver; it now pins the last drain the budget still adopts.

* fix(daemon): name the socket probe default and correct the grace-retry rationale

Answers the review round on the budget accounting: the outer-catch endpoint
rescue is deliberately outside it, and the preflight clamp no longer duplicates
probeDaemonSocket's default as a bare literal.
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