Skip to content

fix(terminal): fence detached daemon endpoint ownership - #12709

Merged
nwparker merged 9 commits into
stablyai:mainfrom
nwparker:nwparker/carp-streamer-user-crash
Aug 6, 2026
Merged

nwparker merged 9 commits into
stablyai:mainfrom
nwparker:nwparker/carp-streamer-user-crash

Conversation

@nwparker

@nwparker nwparker commented Aug 5, 2026 •

Copy link
Copy Markdown
Contributor

Summary

  • make the canonical socket name the daemon's endpoint authority, so a departing daemon can never delete a replacement's endpoint
  • publish PID/nonce ownership inside the socket-bind transaction, before token publication makes the endpoint adoptable
  • require positive evidence that a daemon is dead before reclaiming its PID record or endpoint, and confirm SIGKILL rather than assume it
  • retire a daemon that has lost its endpoint, draining rather than killing
  • reconcile stale PID metadata against the authenticated hello identity, carrying the owner's real launch metadata
  • add a real-process handover smoke that reproduces the failure with two daemons racing one endpoint

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:

  • killStaleDaemon removed the PID record unconditionally immediately before every fork, so an 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 read a ps timeout as proof of PID recycling. isDaemonProcess shells out to ps with 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/appVersion from 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

daemonIdentity on the hello response gains optional entryPath and appVersion. Per docs/reference/remote-wire-compatibility.md Rule 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

  • Real-process handover smoke: two built daemons race one endpoint; the survivor must keep a reachable endpoint after the other exits late. Wired into the native-smoke CI job, and correctly skipped on Windows.
  • Unit coverage for the late-close handover, endpoint takeover retirement, exclusive publish, ownership-checked removal, and the bind-name length guarantee.
  • killStaleDaemon: preserves record and endpoint when the owner survives; reclaims a refused endpoint; preserves it when the probe is merely inconclusive.
  • PID repair: republishes the authenticated owner's metadata, and adopts the endpoint anyway when the record cannot be written.
  • Launcher: degrades rather than forking beside a daemon that could not be confirmed stopped.

Known limitations

  • A daemon already running from a build without this change cannot self-retire; it still needs to be cleared once after upgrade.
  • Retirement drains, so an orphan holding permanently-live sessions persists until they end. This is deliberate — killing it would take the user's shells with it.
  • Liveness is still partly inferred for a wedged-but-listening daemon. The durable fix is an OS-held lock acquired before bind, which would also let a large amount of ps-based identity machinery be deleted. Tracked as a follow-up.

Testing

  • pnpm lint
  • pnpm typecheck
  • pnpm build
  • daemon suite (1302 tests) and full unit suite
  • pnpm run check:reliability-gates
  • pnpm run check:max-lines-ratchet
  • node config/scripts/daemon-boot-smoke.mjs
  • node config/scripts/daemon-endpoint-handover-smoke.mjs
  • git diff --check

Screenshots

No visual change.

@coderabbitai

coderabbitai Bot commented Aug 5, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

Note

Reviews paused

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

Use the following commands to manage reviews:

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

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review
📝 Walkthrough

Walkthrough

Daemon 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)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 10.53% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
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 clearly and concisely identifies the main change: enforcing ownership for detached daemon endpoints.
Description check ✅ Passed The description is detailed and covers the change, impact, compatibility, testing, screenshots, limitations, and follow-up; AI Review Report and Security Audit sections are missing.

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: 3

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

198-210: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Make the ownership fence fail closed when the client cannot report an identity.

If readIdentity is undefined, the block skips the comparison and adoption proceeds unvalidated. DaemonClient always defines getDaemonIdentity, 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 when expectedIdentity is 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

📥 Commits

Reviewing files that changed from the base of the PR and between eea0bb6 and 8dd7a15.

📒 Files selected for processing (12)
  • config/scripts/daemon-boot-smoke.mjs
  • src/main/daemon/daemon-endpoint-ownership.test.ts
  • src/main/daemon/daemon-entry.test.ts
  • src/main/daemon/daemon-entry.ts
  • src/main/daemon/daemon-init.test.ts
  • src/main/daemon/daemon-init.ts
  • src/main/daemon/daemon-main.ts
  • src/main/daemon/daemon-server.ts
  • src/main/daemon/daemon-spawner.test.ts
  • src/main/daemon/daemon-spawner.ts
  • src/main/daemon/production-launcher.test.ts
  • src/main/daemon/production-launcher.ts

Comment thread config/scripts/daemon-boot-smoke.mjs Resolved
Comment thread src/main/daemon/daemon-init.ts Resolved
Comment thread src/main/daemon/daemon-spawner.ts Resolved
@nwparker

nwparker commented Aug 5, 2026

Copy link
Copy Markdown
Contributor Author

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.

@nwparker

nwparker commented Aug 5, 2026

Copy link
Copy Markdown
Contributor Author

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.
@nwparker
nwparker merged commit 7da9368 into stablyai:main Aug 6, 2026
49 checks passed
nwparker added a commit that referenced this pull request Aug 8, 2026
…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.
enrick-dev pushed a commit to enrick-dev/orca that referenced this pull request Oct 15, 2026
* 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.
enrick-dev pushed a commit to enrick-dev/orca that referenced this pull request Oct 15, 2026
…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.
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