Repository navigation
fix(terminal): fence detached daemon endpoint ownership - #12709
Conversation
|
Note Reviews pausedIt 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 Use the following commands to manage reviews:
Use the checkboxes below for quick actions:
📝 WalkthroughWalkthroughDaemon PID ownership publication now occurs in the daemon child. Launchers pass the PID path, launch nonce, entry path, and app version as arguments. Daemon startup publishes ownership before token creation and removes owned records when startup fails. Adoption validates endpoint identity and repairs mismatched PID records. Ownership changes terminate the launched child. Tests and the boot smoke test cover exclusive publication, rollback, reconciliation, launch metadata, and shutdown cleanup. 🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
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. Comment |
There was a problem hiding this comment.
Actionable comments posted: 3
🧹 Nitpick comments (1)
src/main/daemon/daemon-init.ts (1)
198-210: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winMake the ownership fence fail closed when the client cannot report an identity.
If
readIdentityis undefined, the block skips the comparison and adoption proceeds unvalidated.DaemonClientalways definesgetDaemonIdentity, so production is not affected today, but the fence that this PR adds is disabled by any client object that lacks the method. Treat a missing reader as a mismatch whenexpectedIdentityis supplied.♻️ Proposed fail-closed guard
- if (expectedIdentity) { - if (readIdentity) { - const actualIdentity = readIdentity.call(client) - if ( - !actualIdentity || - actualIdentity.pid !== expectedIdentity.pid || - actualIdentity.startedAtMs !== expectedIdentity.startedAtMs || - actualIdentity.launchNonce !== expectedIdentity.launchNonce - ) { - throw new DaemonEndpointOwnershipError('Daemon endpoint ownership changed during startup') - } - } - } + if (expectedIdentity) { + const actualIdentity = readIdentity?.call(client) + if ( + !actualIdentity || + actualIdentity.pid !== expectedIdentity.pid || + actualIdentity.startedAtMs !== expectedIdentity.startedAtMs || + actualIdentity.launchNonce !== expectedIdentity.launchNonce + ) { + throw new DaemonEndpointOwnershipError('Daemon endpoint ownership changed during startup') + } + }
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro Plus
Run ID: be7bfe42-06fd-414e-9622-31881fa98b35
📒 Files selected for processing (12)
config/scripts/daemon-boot-smoke.mjssrc/main/daemon/daemon-endpoint-ownership.test.tssrc/main/daemon/daemon-entry.test.tssrc/main/daemon/daemon-entry.tssrc/main/daemon/daemon-init.test.tssrc/main/daemon/daemon-init.tssrc/main/daemon/daemon-main.tssrc/main/daemon/daemon-server.tssrc/main/daemon/daemon-spawner.test.tssrc/main/daemon/daemon-spawner.tssrc/main/daemon/production-launcher.test.tssrc/main/daemon/production-launcher.ts
|
Review follow-up: c974d51 also makes the post-ready ownership fence fail closed when the adoption client cannot report endpoint identity. Regression coverage now runs both changed-identity and missing-identity cases. |
|
Windows CI follow-up: the shutdown RPC completed cleanup, but the smoke still held the startup IPC channel open, unlike the production launcher, so the Windows child remained pinned until the timeout. cc98c52 disconnects IPC immediately after ready/PID verification and updates the timeout diagnostic. The same RPC smoke still passes locally; the restarted Windows job will verify the platform-specific handle behavior. |
The reported failure was a live daemon hosting PTYs that nothing could reach: terminals acknowledged input and never ran it, listings diverged from reality, and restarting the app never helped because the detached helper survived. The ownership fence added for it could not fire in the sequence that produces the split brain. libuv unlinks the pathname a server bound to when that server closes, with no ownership check. A daemon that lost its endpoint name therefore deleted whichever socket then sat at that path — including a live replacement's — stranding a daemon that still hosted every session. Bind a private same-directory name and hard-link it into place instead: libuv can only ever unlink our own bind name, the exclusive link is a kernel-enforced endpoint claim, and the canonical name is removed only under an inode ownership check. The bind name replaces the basename rather than extending it, so it cannot overflow sun_path. killStaleDaemon removed the PID record unconditionally immediately before every fork, so the exclusive PID claim was always uncontested at bind time. It also unlinked a live daemon's endpoint whenever a connect probe merely timed out, and treated a `ps` timeout as proof of PID recycling. Now only positive evidence of a dead endpoint authorizes reclaiming it, SIGKILL is confirmed rather than assumed, and a daemon that cannot be proven stopped keeps its record and endpoint while the launcher refuses to fork beside it. A daemon whose endpoint was taken over now retires itself, draining rather than killing, so an unreachable orphan stops being permanent. A repaired PID record re-derives entryPath, appVersion and the Linux incarnation markers from the authenticated owner instead of dropping them; without appVersion a healthy daemon read as a permanently stale bundle and, on Windows, went unpinned against daemon-host pruning. Repair failure now fails open — abandoning a healthy daemon over a pid file write cost every persistent terminal on the machine. Also: treat only ENOENT as an unclaimed record so a Windows file lock is not reported as an ownership conflict; settle start() before close() so an accepted connection cannot defer it forever; sweep abandoned claim and bind names; and type the endpoint-identity seam so a rename cannot silently disable the fence. Adds a real-process handover smoke that reproduces the failure with two daemons racing one endpoint, and wires it into the native-smoke job.
The ownership watchdog read a null identity for any stat failure, so a transient EACCES or EIO on the runtime directory would retire a daemon that was still serving every terminal on the machine. Distinguish "the entry is gone" from "the probe failed" and act only on the former. Also require the loss to persist across two polls: a replacement publishes by unlink-then-link, and a single observation can land in that gap.
…d hello Adversarial review found three defects in the previous two commits. Re-deriving entryPath from the owner's command line truncated it at the first space. A command line is a single space-joined string, so `C:\Program Files\Orca\...` and `/Applications/Orca 2.app/...` came back as `"C:\Program` and `/Applications/Orca`. getDaemonLaunchIdentity treats a present entryPath as authoritative, so a healthy daemon read as `different_app_path` and was killed and re-forked — worse than the missing-metadata case the derivation was added to fix. Carry entryPath and appVersion as optional fields on the daemon hello identity instead: the daemon already has both from its own argv, and per docs/reference/remote-wire-compatibility.md a new optional field is safe because every reader falls back when it is absent. This also removes a synchronous `ps` spawn from the Electron main thread during startup. `start()` rolled back the PID record even when it never published one. Losing the endpoint link now runs that path, and the ownership-checked unlink briefly renames the incumbent's record aside — enough to strand a live daemon's ownership. Roll back only what we actually wrote. publishDaemonSocketPath read its identity from the canonical name after linking, so a concurrent unlink returned null: no ownership watchdog and no endpoint cleanup on any shutdown path. Read it from the bound name before linking, which shares the inode. Refusing to fork beside an unconfirmed daemon left the user with no daemon at all and no in-app recovery, since restart re-entered the same fence. We have just proved something answers the endpoint, so adopt it in degraded mode: live sessions keep working, fresh terminals run locally. SIGTERM is also individually guarded now — an EPERM fell into the blanket catch and reported "nothing alive", authorizing the very duplicate this fence exists to prevent. Also reset the ownership-loss streak on an inconclusive probe so the confirmations are consecutive, and sweep scratch names before the launch so a failed launch still reclaims them.
…arty (#12882) Terminals froze app-wide several times daily, needing a manual pkill. libuv unlinks the pathname a server bound to when it closes, with no ownership check, so a departing daemon deleted whichever socket then sat at the canonical path — including a live replacement's. The replacement kept hosting PTYs no client could reach. #12709 fixed that mechanism; this replaces the shape around it. Two invariants: only a daemon publishing itself onto the canonical endpoint may mutate that entry, and only by replacing one it has itself just proven dead; and no actor removes a name it did not create. Publish binds a private name, takes the canonical one with an exclusive link, and on EEXIST proves the incumbent dead by connecting before replacing it in a single rename. Only 'connected' means occupied and only refused/missing prove death — a timeout proves nothing and declines. Deletes the claim sweeper, the reclaim tail of killStaleDaemon, and three unfenced unlinkSync(socketPath) calls in the launcher. Measured: rename exposed no gap across 6,525 darwin / 8,004 linux probes of a live handover, where unlink-then-link gapped on 200 of 200. Verified on all three platforms: full suite on macOS and Linux, and daemon restart e2e on a real windows-2022 host. Contract in src/main/daemon/AGENTS.md.
* fix(terminal): fence daemon endpoint ownership * fix(terminal): clean failed daemon PID claims * fix(terminal): close daemon ownership review gaps * test(daemon): release startup IPC in boot smoke * test(daemon): mirror production stdio in boot smoke * fix(daemon): exit after rpc shutdown cleanup * fix(terminal): make the socket name the daemon endpoint authority The reported failure was a live daemon hosting PTYs that nothing could reach: terminals acknowledged input and never ran it, listings diverged from reality, and restarting the app never helped because the detached helper survived. The ownership fence added for it could not fire in the sequence that produces the split brain. libuv unlinks the pathname a server bound to when that server closes, with no ownership check. A daemon that lost its endpoint name therefore deleted whichever socket then sat at that path — including a live replacement's — stranding a daemon that still hosted every session. Bind a private same-directory name and hard-link it into place instead: libuv can only ever unlink our own bind name, the exclusive link is a kernel-enforced endpoint claim, and the canonical name is removed only under an inode ownership check. The bind name replaces the basename rather than extending it, so it cannot overflow sun_path. killStaleDaemon removed the PID record unconditionally immediately before every fork, so the exclusive PID claim was always uncontested at bind time. It also unlinked a live daemon's endpoint whenever a connect probe merely timed out, and treated a `ps` timeout as proof of PID recycling. Now only positive evidence of a dead endpoint authorizes reclaiming it, SIGKILL is confirmed rather than assumed, and a daemon that cannot be proven stopped keeps its record and endpoint while the launcher refuses to fork beside it. A daemon whose endpoint was taken over now retires itself, draining rather than killing, so an unreachable orphan stops being permanent. A repaired PID record re-derives entryPath, appVersion and the Linux incarnation markers from the authenticated owner instead of dropping them; without appVersion a healthy daemon read as a permanently stale bundle and, on Windows, went unpinned against daemon-host pruning. Repair failure now fails open — abandoning a healthy daemon over a pid file write cost every persistent terminal on the machine. Also: treat only ENOENT as an unclaimed record so a Windows file lock is not reported as an ownership conflict; settle start() before close() so an accepted connection cannot defer it forever; sweep abandoned claim and bind names; and type the endpoint-identity seam so a rename cannot silently disable the fence. Adds a real-process handover smoke that reproduces the failure with two daemons racing one endpoint, and wires it into the native-smoke job. * fix(daemon): retire only on proven endpoint ownership loss The ownership watchdog read a null identity for any stat failure, so a transient EACCES or EIO on the runtime directory would retire a daemon that was still serving every terminal on the machine. Distinguish "the entry is gone" from "the probe failed" and act only on the former. Also require the loss to persist across two polls: a replacement publishes by unlink-then-link, and a single observation can land in that gap. * fix(daemon): source repaired ownership metadata from the authenticated hello Adversarial review found three defects in the previous two commits. Re-deriving entryPath from the owner's command line truncated it at the first space. A command line is a single space-joined string, so `C:\Program Files\Orca\...` and `/Applications/Orca 2.app/...` came back as `"C:\Program` and `/Applications/Orca`. getDaemonLaunchIdentity treats a present entryPath as authoritative, so a healthy daemon read as `different_app_path` and was killed and re-forked — worse than the missing-metadata case the derivation was added to fix. Carry entryPath and appVersion as optional fields on the daemon hello identity instead: the daemon already has both from its own argv, and per docs/reference/remote-wire-compatibility.md a new optional field is safe because every reader falls back when it is absent. This also removes a synchronous `ps` spawn from the Electron main thread during startup. `start()` rolled back the PID record even when it never published one. Losing the endpoint link now runs that path, and the ownership-checked unlink briefly renames the incumbent's record aside — enough to strand a live daemon's ownership. Roll back only what we actually wrote. publishDaemonSocketPath read its identity from the canonical name after linking, so a concurrent unlink returned null: no ownership watchdog and no endpoint cleanup on any shutdown path. Read it from the bound name before linking, which shares the inode. Refusing to fork beside an unconfirmed daemon left the user with no daemon at all and no in-app recovery, since restart re-entered the same fence. We have just proved something answers the endpoint, so adopt it in degraded mode: live sessions keep working, fresh terminals run locally. SIGTERM is also individually guarded now — an EPERM fell into the blanket catch and reported "nothing alive", authorizing the very duplicate this fence exists to prevent. Also reset the ownership-loss streak on an inconclusive probe so the confirmations are consecutive, and sweep scratch names before the launch so a failed launch still reclaims them.
…arty (stablyai#12882) Terminals froze app-wide several times daily, needing a manual pkill. libuv unlinks the pathname a server bound to when it closes, with no ownership check, so a departing daemon deleted whichever socket then sat at the canonical path — including a live replacement's. The replacement kept hosting PTYs no client could reach. stablyai#12709 fixed that mechanism; this replaces the shape around it. Two invariants: only a daemon publishing itself onto the canonical endpoint may mutate that entry, and only by replacing one it has itself just proven dead; and no actor removes a name it did not create. Publish binds a private name, takes the canonical one with an exclusive link, and on EEXIST proves the incumbent dead by connecting before replacing it in a single rename. Only 'connected' means occupied and only refused/missing prove death — a timeout proves nothing and declines. Deletes the claim sweeper, the reclaim tail of killStaleDaemon, and three unfenced unlinkSync(socketPath) calls in the launcher. Measured: rename exposed no gap across 6,525 darwin / 8,004 linux probes of a live handover, where unlink-then-link gapped on 200 of 200. Verified on all three platforms: full suite on macOS and Linux, and daemon restart e2e on a real windows-2022 host. Contract in src/main/daemon/AGENTS.md.
Summary
User impact and root cause
The reported failure presented as an app-wide terminal freeze: new panes appeared but commands never ran, input calls acknowledged bytes that never reached the visible terminal, live sessions disappeared from listings, and restarting the app never recovered because the daemon is launchd-detached by design.
The captured machine had two detached daemons — one owning the Unix socket, another hosting the sessions the relaunched app had restored — so CLI and automation traffic reached a different terminal host from the visible app.
The mechanism is that libuv unlinks the pathname a server bound to when that server closes, with no ownership check. A daemon whose endpoint name had been reclaimed therefore deleted whichever socket then sat at that path, including a live replacement's. The replacement stayed alive hosting every session while nothing could reach it. Verified directly on Node 24, and reproduced end to end with two built daemons: pre-fix the survivor is left
reachable: false; post-fix it stays reachable.Two decisions upstream of that made it reachable in ordinary use:
killStaleDaemonremoved the PID record unconditionally immediately before every fork, so an exclusive PID claim was always uncontested at bind time.pstimeout as proof of PID recycling.isDaemonProcessshells out topswith a 2s budget; on the loaded machine in the report those probes return false negatives.Fix
The daemon binds a private same-directory name and hard-links it to the canonical path. libuv can then only ever unlink our own bind name; the exclusive link is a kernel-enforced endpoint claim; and the canonical name is removed only under a dev+inode ownership check. The bind name replaces the basename rather than extending it, so it cannot overflow
sun_path. Windows is unchanged — named pipes are not directory entries and the pipe name is already exclusive.Reclamation now requires positive evidence: a refused or absent endpoint, or a confirmed process exit. A daemon that cannot be proven stopped keeps its record and endpoint, and the launcher adopts it in degraded mode instead of forking beside it — live sessions keep working, fresh terminals run on the local provider.
A daemon that observes the canonical name no longer resolving to its own inode retires itself: it drains rather than kills, so an orphan stops being permanent without tearing live sessions away from the user. Only positive evidence retires it, confirmed across consecutive polls.
A repaired PID record takes the owner's
entryPath/appVersionfrom the authenticated hello. Without them a healthy daemon reads as a permanently stale bundle and, on Windows, goes unpinned against daemon-host pruning.Wire compatibility
daemonIdentityon the hello response gains optionalentryPathandappVersion. Perdocs/reference/remote-wire-compatibility.mdRule 1 this is safe: older peers ignore unknown keys, and the reader falls back to its previous behavior when the fields are absent. No RPC parameters, stream opcodes, or protocol version changed.Reproduction and coverage
killStaleDaemon: preserves record and endpoint when the owner survives; reclaims a refused endpoint; preserves it when the probe is merely inconclusive.Known limitations
ps-based identity machinery be deleted. Tracked as a follow-up.Testing
pnpm lintpnpm typecheckpnpm buildpnpm run check:reliability-gatespnpm run check:max-lines-ratchetnode config/scripts/daemon-boot-smoke.mjsnode config/scripts/daemon-endpoint-handover-smoke.mjsgit diff --checkScreenshots
No visual change.