Skip to content

Fix Windows update-relaunch killing the live terminal daemon (session loss on update) - #7340

Merged
Jinwoo-H merged 1 commit into
orca-performancefrom
Jinwoo-H/windows-update-daemon-adoption
Jul 5, 2026
Merged

Jinwoo-H merged 1 commit into
orca-performancefrom
Jinwoo-H/windows-update-daemon-adoption

Conversation

@Jinwoo-H

@Jinwoo-H Jinwoo-H commented Jul 4, 2026

Copy link
Copy Markdown
Contributor

Summary

Windows-only terminal session loss on app update: the update relaunch could kill the live terminal daemon — and every session it owned — instead of adopting it. Root-caused on the affected machine, fixed, and verified end-to-end against a real wedged daemon.

Root cause

The launcher's unhealthy path in daemon-init.ts was fail-closed. On an update relaunch:

  1. At quit-for-update, disconnectDaemon drains final getSnapshot checkpoint RPCs for every session — with many sessions the daemon's single event loop is grinding through snapshot serialization exactly when NSIS writes the new app and Defender scans it.
  2. The new app's checkDaemonHealth gets 3s for two RPC round-trips → times out → 'unreachable'.
  3. The session-list re-verification (added by an earlier fix for this same symptom) has a 5s hello budget → also times out → null.
  4. The code then fell through to killStaleDaemon(), which CIM-verified the pid (powershell spawns work fine even when the daemon's event loop is wedged) and TerminateProcess'd the live daemon.

The arithmetic matches the production incident exactly: 3s (health) + 5s (hello) + ~1s (CIM query) ≈ the observed 9-second gap between the updated main process starting (2:48:34, --updated) and the replacement daemon being forked (2:48:43) on the machine where rc.1→rc.2 lost 60 sessions.

Why most updates are fine: when the daemon answers within budget, the appVersion-mismatch path already preserves it ("owns N live sessions"). The kill needs the daemon to be unresponsive for ~8 continuous seconds at exactly the relaunch moment — a load-dependent race, worst on machines with many sessions and back-to-back RC installs.

Two adjacent hazards fixed in the same change:

  • startedAtMs: null on Windows pid files: getProcessStartedAtMs had no win32 implementation, so the pid-recycling guard (startTimeMatches) was permanently inert on Windows. Not the kill trigger (it fails open), but a disabled safety on exactly the platform that kills by pid.
  • Legacy daemon cleanup (protocol bumps, e.g. v18→v19): a 1s socket probe timeout on a busy machine deleted the old daemon's pid and token files. Without its token file the daemon can never be adopted again — silently orphaning every session it owns. This matches the second field report (v18→v19 loss on another machine).

Fix

  • Never kill a live daemon on inconclusive data (daemon-init.ts): when both the health check and the session list fail, probe the pipe with a raw connect. A pipe that accepts connections proves a live daemon → adopt it; the adapter reconnects once the daemon drains. A new 'rejected' health state (daemon-health.ts) distinguishes "daemon answered and refused the handshake" (never adoptable → still replaced) from "timed out" (possibly wedged → preserved).
  • Real startedAtMs on Windows: the daemon self-reports its start time in the ready IPC message (daemon-entry.ts); the parent falls back to it when the OS query returns null. Verification piggybacks CIM CreationDate on the existing powershell CommandLine query — zero additional process spawns — with a 10s win32 tolerance for exe-bootstrap skew (pid recycling differs by minutes-to-days, so the guard stays effective).
  • Legacy cleanup only deletes provably-dead daemons' files: pid/token unlink now requires the pid-file process to be gone (process.kill(pid, 0) fails).
  • Belt-and-suspenders resume records (App.tsx, cross-platform): sleepingAgentSessionsByPaneKey is now captured every 60s in addition to beforeunload, so hard kills (crash, forced install, TerminateProcess) still leave a fresh resume record. The store action skips content-unchanged records, so idle ticks write nothing and no scrollback is serialized (respects the PR fix: preserve terminal session state during periodic saves #461 lesson documented in App.tsx).

Verification on the affected machine (Windows 11, the rc.1→rc.2 incident machine)

1. Discriminating experiment (live app) — quit and reopened installed Orca (no update): the relaunched app adopted the existing daemon (pid 26428 unchanged, pid file untouched, sessions reattached — including the very session this fix was authored in). Plain restarts adopt fine; the bug is update-relaunch-specific, consistent with the root cause.

2. Wedge reproduction + fix proof (real daemon, real ConPTY session, real decision functions) — forked a throwaway daemon from this branch, created a live ConPTY session, then suspended the daemon process (NtSuspendProcess) to reproduce the wedge, and ran the branch's actual checkDaemonHealth / DaemonClient / killStaleDaemon against it:

=== PHASE A: pre-fix behavior against a wedged live daemon ===
health check -> 'unreachable' after 3.0s
session-list re-verify -> null (failed) after 5.0s
raw pipe probe -> ACCEPTS CONNECTIONS
phase-a RESULT: killStaleDaemon=true, daemon 26732 alive=false
  -> OLD PATH KILLED A LIVE DAEMON OWNING A LIVE SESSION (bug reproduced)

=== PHASE B: fixed decision against the same wedge ===
health check -> 'unreachable' after 3.0s
session-list re-verify -> null (failed) after 5.0s
raw pipe probe -> ACCEPTS CONNECTIONS
phase-b: NEW preserve condition -> ADOPT (no kill, no respawn)
phase-b: daemon RESUMED (wedge over — checkpoint flush drained)
phase-b: reconnected; 1 live session(s), daemon pid still 27108
phase-b RESULT: session typeable after adopt+resume -> YES (output observed)

This also empirically confirms the linchpin OS assumption: a fully-wedged process's named pipe still accepts raw connections (kernel-side pending instances) even after the health check and the client connect have each consumed one — so the probe is a reliable liveness signal exactly when RPCs are not.

3. Regression tests (all green, plus typecheck/lint):

  • adopts an unresponsive daemon whose pipe still accepts connections (the update-relaunch wedge)
  • replaces a hello-rejected daemon even though its pipe accepts connections
  • adopts a healthy daemon whose pid-file identity cannot be verified (null startedAtMs metadata — the pre-fix Windows pid-file state)
  • writes the daemon self-reported start time to the pid file when the OS query returns null
  • keeps legacy pid/token files when the probe fails but the pid-file process is alive; still cleans up when it is gone
  • classifies a hello-rejected daemon as rejected, not unreachable (real DaemonServer)
  • skips rewriting an unchanged resume record on repeated capture (periodic tick no-op)

Cross-platform notes

  • The preserve-on-live-pipe logic is platform-independent and equally protects macOS/Linux (unix sockets) under load.
  • macOS/Linux startedAtMs derivation is unchanged (ps lstart / /proc); the self-report is only a fallback when the OS query returns null.
  • No new process spawns on any startup path; the win32 CIM query gained a field, not a second spawn.
  • SSH/remote unaffected: all changes are in local daemon lifecycle and renderer session capture.

On a Windows update relaunch the daemon can be wedged past every RPC
budget (final checkpoint flush + installer/AV disk pressure), so the 3s
health check AND the 5s session-list hello both time out while sessions
are still alive - and the launcher failed closed, killing the daemon and
every terminal session it owned.

- Adopt an unresponsive daemon whose pipe still accepts a raw
  connection; a new rejected health state keeps replacing daemons that
  answered and refused the handshake (never adoptable).
- Give Windows pid files a real startedAtMs (daemon self-reports it in
  the ready IPC message) and verify it via CIM CreationDate piggybacked
  on the existing command-line query, so the pid-recycling guard is no
  longer inert on win32.
- Only delete legacy daemon pid/token files when the pid-file process is
  provably dead; deleting a live daemon''s token made its sessions
  permanently unadoptable after a protocol bump.
- Capture agent resume records every 60s in the renderer (skipping
  unchanged records) so hard kills still leave a fresh resume record.
@Jinwoo-H
Jinwoo-H marked this pull request as ready for review July 5, 2026 06:15
@coderabbitai

coderabbitai Bot commented Jul 5, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

Daemon readiness now reports a self-computed startup timestamp, and daemon health checks distinguish a new "rejected" state (handshake refused) from "unreachable." Windows process identity verification switches to a combined CIM query returning command line and start time, validated with tolerance-based comparison. The daemon launcher adopts existing daemons when liveness can't be verified but the socket responds and health isn't rejected, and legacy daemon cleanup now checks process aliveness via pid-file parsing before deleting stale artifacts. Separately, the renderer adds a periodic 60-second timer to capture sleeping-agent resume sessions, with a new equivalence check preventing redundant record rewrites when nothing meaningfully changed.

Sequence Diagram(s)

See diagrams embedded in review stack layers above for Windows identity verification and periodic sleeping-agent capture flows.

Related PRs: None specified.

Suggested labels: daemon, windows, renderer, tests

Suggested reviewers: None specified.

🐰 A daemon wakes and tells the time,
"I'm healthy, or rejected—no crime,"
Windows checks its pulse with care,
While sleeping agents nap somewhere,
Captured softly, sixty seconds' chime.

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
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 is concise and accurately highlights the main Windows daemon adoption fix and its user impact.
Description check ✅ Passed The description covers summary, root cause, fix, verification, and cross-platform notes, but omits several template sections.
✨ Finishing Touches
📝 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.

@Jinwoo-H
Jinwoo-H changed the base branch from main to orca-performance July 5, 2026 06:35
@Jinwoo-H
Jinwoo-H merged commit 4110c29 into orca-performance Jul 5, 2026
4 checks passed
@Jinwoo-H

Jinwoo-H commented Jul 5, 2026

Copy link
Copy Markdown
Contributor Author

Root-cause attribution correction (post-merge investigation): the July update-time session losses were caused by the NSIS installer's install-dir process sweep, unmasked by #6968 moving OpenConsole.exe under resources/ — see #7420 for the harness-verified chain. The update-relaunch wedge-kill path fixed here is a real but distinct mechanism (reproduced in isolation killing a live daemon owning a live session), and becomes the active protection layer at update-relaunch once #7420 keeps the daemon alive through installs. The two fixes are complementary layers; nothing here needs reverting.

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