Repository navigation
fix(daemon): escape the terminal daemon into its own systemd scope so a service restart no longer kills every live PTY - #19430
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:
No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info⚙️ Run configurationConfiguration used: Repository UI Review profile: CHILL Plan: Advanced Run ID: 📥 CommitsReviewing files that changed from the base of the PR and between 1f63ef2d9fb65f05ecc764b627544cac395c2b79 and 244773318a578bab97f5013b1b2cb4032b489dd4. 📒 Files selected for processing (1)
Included review availability: Your plan provides up to 10 included reviews per hour; 8 remain after this review. 📝 WalkthroughWalkthroughThe daemon gains durable systemd cgroup scope support on compatible Linux systems. Launching now selects scoped or direct process creation and retries without a scope when needed. Readiness uses the daemon-reported PID. The daemon records its detected scope unit in the PID record. PID parsing and terminal daemon health now carry Priority: ⬆️ High — Impact reflects high issue severity. Severity of issue fixed: High Merge Risk: ⚪ Minimal · up to This change isolates supported terminal daemons in a sibling systemd user scope while retaining the existing launch path when scoped startup is unavailable or fails. No actionable merge-blocking risk remains. 🚥 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: 1
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Team
Run ID: 4f5c5719-b1ab-4341-9f4f-a067753df702
📥 Commits
Reviewing files that changed from the base of the PR and between c1e15c4 and 90ab765c1ae77bcd2399d4109fd8dbb586dd8c45.
📒 Files selected for processing (12)
src/main/daemon/daemon-adoption-telemetry-event.test.tssrc/main/daemon/daemon-cgroup-scope.test.tssrc/main/daemon/daemon-cgroup-scope.tssrc/main/daemon/daemon-entry.tssrc/main/daemon/daemon-launched-child-spawn.tssrc/main/daemon/daemon-launched-child.tssrc/main/daemon/daemon-pid-file-parse.tssrc/main/daemon/daemon-spawner.tssrc/main/orcad/orcad-health.test.tssrc/main/orcad/orcad-health.tssrc/main/server/serve-readiness.test.tssrc/main/ssh/orcad-activation-gate.test.ts
Included review availability: Your plan provides up to 10 included reviews per hour; 9 remain after this review.
There was a problem hiding this comment.
Caution
This PR records the wrong PID for the daemon on the scoped launch path. Every fresh launch on the exact platform this fixes (Linux under systemd) will fail the adoption ownership check and fall back to degraded-new-pty-fallback, so new terminals run non-persistent — the precise failure mode this change is meant to eliminate.
Reviewed changes
daemon-cgroup-scope.ts(new) — feature-detects a usablesystemd --usermanager, builds asystemd-run --user --scopewrapper command, and self-detects the cgroup scope from/proc/self/cgroup.daemon-launched-child-spawn.ts(new) — extracts the fork/spawn logic; the durable-scope path spawnssystemd-runviaspawn()with the same'ipc'stdio contract instead offork().daemon-launched-child.ts— probes the capability once, attempts the scoped launch, and retries unscoped on failure.daemon-entry.ts/daemon-pid-file-parse.ts/daemon-spawner.ts/orcad-health.ts— thread a nullablecgroupUnitfield through the pid record and health payload.
⚠️ No automated test exercises the scoped launch path
The only new test file (daemon-cgroup-scope.test.ts) covers the pure helper functions; spawnDaemonChildProcess and the scoped branch of launchDaemonChild are untested, and no test drives the holdDaemonAdoptionLease ownership check with a systemd-run child. The PID mismatch below slipped through precisely because the scoped path has no automated coverage — the Docker verification exercised restart survival but not the fresh-launch ownership handshake end-to-end.
Technical details
# Test the scoped launch end-to-end
## Affected sites
- `src/main/daemon/daemon-launched-child-spawn.ts` — `spawnDaemonChildProcess` has no test.
- `src/main/daemon/daemon-launched-child.ts` — scoped attempt/retry has no test.
## Required outcome
- A test (or `*.electron.test.ts`) asserting that a scoped launch produces a `LaunchedDaemonChild` whose `identity.pid` equals the daemon's own pid (not `systemd-run`'s), and that `holdDaemonAdoptionLease` accepts it rather than throwing `DaemonEndpointOwnershipError`.
## Suggested approach (optional)
- Thread the daemon's `process.pid` through the `ready` IPC message and use it as the identity pid in the scoped path, then assert it round-trips.
## Open questions for the human (optional)
- Is a real-systemd integration test in scope for CI, or is a mocked-child unit test sufficient?DeepSeek Pro (free via Pullfrog for OSS) | 𝕏
|
Converted to draft — Pausing pending on-server (mtl-02) empirical validation of the recovery mechanism under a real production restart, before this goes further upstream -- matches the same sequencing used for #18789/#18790 (server-proven before merge consideration). Will mark ready-for-review once mtl-02 confirms live-session survival across a real systemctl restart. |
…he process's own env isDurableDaemonScopeSupported()/buildDurableDaemonScopeCommand() trusted the current process's own XDG_RUNTIME_DIR env var first, falling back to /run/user/<uid> only when that var was unset entirely. On mtl-02, [email protected]'s RuntimeDirectory= hardening directive makes systemd export XDG_RUNTIME_DIR=/run/orca_serve/factory into the unit's process -- a private scratch dir that shares the env var's name but has nothing to do with the user session bus. /proc/<pid>/environ on that host confirmed exactly that path plus DBUS_SESSION_BUS_ADDRESS=disabled:, while the real bus was reachable the whole time at /run/user/985 (confirmed via systemctl --user is-system-running with that dir exported by hand). The probe treated the hardened override as authoritative, found no bus socket there, and reported unsupported on every launch -- so the cgroup-escape fix from stablyai#19408/stablyai#19430 never actually engaged on real hardware, even though tonight's factory deployment picked it up. Fix: resolveUserRuntimeDir() now always tries the conventional /run/user/<uid> path first (computed independently via getuid(), never trusted from env), checking for a genuinely connectable bus socket via statSync(...).isSocket() rather than a bare existsSync. It falls back to the process's own XDG_RUNTIME_DIR only when that canonical path has no reachable bus -- covering hosts that legitimately have no /run/user/<uid> at all but do have a working bus wherever their own environment points. buildDurableDaemonScopeCommand() now explicitly sets XDG_RUNTIME_DIR to whichever path this resolution picked, rather than inheriting the spread env's (possibly hardened-wrong) value. Both isDurableDaemonScopeSupported() and buildDurableDaemonScopeCommand() gained an injectable canonicalRuntimeDir parameter (defaulting to the real computed path) so tests can exercise the hardened-override scenario deterministically with a real, connectable AF_UNIX socket fixture instead of the live host's actual runtime directory. Docker's stock jrei/systemd-ubuntu test container never had this hardening directive, so this gap was structurally invisible to the container-based verification in stablyai#19430 -- only caught against real mtl-02 hardware.
Update: probe fix for a hardened-RuntimeDirectory shadowing bug found on real hardwareThis PR's cgroup-escape fix was deployed to a real Linux headless-serve host, but Root cause: the deployed systemd unit running Fix ( Verified on real hardware, isolated from every live occupant of that host (no live serve instance was touched or restarted throughout — the pre-existing live instance's main PID and active-since timestamp are unchanged from before this verification):
Still draft, unchanged from before: this only proves the escape mechanism now engages correctly despite the hardening; it does not re-run the full live-PTY-survives-a-real- |
|
Fix is now proven on real hardware, not just Docker. What changed since draft: found and fixed a real gap where the daemon's cgroup-escape feature-probe trusted the current process's own Fix: the probe now always tries the conventional Verification:
check-upstream-surface clean. |
There was a problem hiding this comment.
Caution
This PR records the wrong PID for the daemon on the scoped launch path, so every fresh launch on the exact platform it fixes (Linux under systemd) fails the adoption ownership check and falls back to degraded-new-pty-fallback — the precise failure mode this change exists to eliminate. The new head commit (71027da) fixes a different gap (the hardened XDG_RUNTIME_DIR probe) and does not address this.
Reviewed changes
daemon-cgroup-scope.ts(new) — feature-detects a usablesystemd --usermanager, builds thesystemd-run --user --scopewrapper, and self-detects the cgroup scope from/proc/self/cgroup.daemon-launched-child-spawn.ts(new) — extracts fork/spawn; the scoped path launches viaspawn('systemd-run', …)with the same'ipc'stdio contract instead offork().daemon-launched-child.ts— capability probe once, scoped attempt with a retry-unscoped fallback.daemon-entry.ts/daemon-pid-file-parse.ts/daemon-spawner.ts/orcad-health.ts— thread a nullablecgroupUnitthrough the pid record and health payload.71027da— prefers the conventional/run/user/<uid>bus path over the process's ownXDG_RUNTIME_DIR(mtl-02 hardening regression), with injectable runtime-dir params and socket fixtures.
⚠️ No automated test exercises the scoped launch path
The only new test file (daemon-cgroup-scope.test.ts) covers the pure helpers; spawnDaemonChildProcess and the scoped branch of launchDaemonChild remain untested, and nothing drives holdDaemonAdoptionLease against a systemd-run child. The PID mismatch slipped through precisely because the Docker verification exercised restart-survival and post-restart adoption (both of which go through the expectedIdentity === undefined path) but not the cold-start fresh-launch handshake.
Technical details
# Scoped launch records systemd-run's pid as the daemon identity
## Affected sites
- `src/main/daemon/daemon-launched-child-spawn.ts:81` — scoped path `spawn()`s `systemd-run`; `child.pid` is `systemd-run`'s pid.
- `src/main/daemon/daemon-launched-child.ts:151` — `launchedIdentity.pid = child.pid` (unchanged line, now wrong in the scoped case).
- `src/main/daemon/daemon-endpoint-adoption.ts:42` — `actualIdentity.pid !== expectedIdentity.pid` always true → `DaemonEndpointOwnershipError`.
- `src/main/daemon/daemon-out-of-process-launcher.ts:163,174,184` — `terminateLaunchedDaemonChild(launched.child)` / `unlinkOwnedDaemonPidFile(pidPath, launched.child.pid, …)` operate on `systemd-run`'s pid.
- `src/main/daemon/daemon-entry.ts:272` — pid record publishes the daemon's real `process.pid`.
## Required outcome
- On the scoped path, `LaunchedDaemonChild.identity.pid` must equal the daemon's own `process.pid`, so `holdDaemonAdoptionLease` accepts the fresh launch and `terminateLaunchedDaemonChild` / `unlinkOwnedDaemonPidFile` target the real daemon.
## Suggested approach (optional)
- Thread the daemon's `process.pid` through the `ready` IPC message (extend `parseDaemonReadyIdentity`) and use it as `launchedIdentity.pid` in the scoped path; keep `child.pid` for `systemd-run` lifecycle only.
## Open questions for the human (optional)
- `systemd-run --scope` runs the command as its child (`executed by systemd-run itself as parent process` — man systemd-run), so the pids can never match; the module comments at `daemon-cgroup-scope.ts:19` and `daemon-launched-child-spawn.ts:47` describe this as an `exec`, which is the source of the mismatch. Confirm the intended fix is to trust the daemon's self-reported pid rather than `child.pid`.DeepSeek Pro (free via Pullfrog for OSS) | 𝕏
There was a problem hiding this comment.
Actionable comments posted: 1
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Advanced
Run ID: cecd4115-ebe4-4e5a-aa39-2478d9503fce
📥 Commits
Reviewing files that changed from the base of the PR and between 71027da2ada62283db7d39269f53566380411bfa and 2ad57ed9eaee1d0e9ae5a420ecdb23afcacee5d6.
📒 Files selected for processing (14)
src/main/daemon/daemon-entry.tssrc/main/daemon/daemon-health.test.tssrc/main/daemon/daemon-init-child-readiness.test.tssrc/main/daemon/daemon-init-child-startup-failure.test.tssrc/main/daemon/daemon-init-endpoint-adoption.test.tssrc/main/daemon/daemon-init-live-session-preservation.test.tssrc/main/daemon/daemon-init-packaged-bundle-staleness.test.tssrc/main/daemon/daemon-init-replacement-reporting.test.tssrc/main/daemon/daemon-init-wedged-daemon-grace.test.tssrc/main/daemon/daemon-launched-child-identity.test.tssrc/main/daemon/daemon-launched-child-spawn.tssrc/main/daemon/daemon-launched-child.tssrc/main/daemon/daemon-ready-identity.test.tssrc/main/daemon/daemon-ready-identity.ts
💤 Files with no reviewable changes (1)
- src/main/daemon/daemon-entry.ts
Included review availability: Your plan provides up to 10 included reviews per hour; 9 remain after this review.
There was a problem hiding this comment.
✅ No new issues found.
Reviewed changes
- Daemon self-reports its pid over the ready handshake —
readCurrentDaemonReadyIdentitynow includesprocess.pid,parseDaemonReadyIdentityrequires a positive safe-integer pid, andlaunchDaemonChildbuildslaunchedIdentityfrom that self-reported pid instead ofchild.pid, so adoption compares the daemon's own pid on both launch paths. - Corrected the fork-vs-exec documentation — the new comments on
terminateLaunchedDaemonChild,daemon-ready-identity.ts, anddaemon-launched-child-spawn.tsaccurately describesystemd-run --scoperegistering its own pid and thenexecvpe()ing the command (no fork), so signallingchild.pidstays correct on the scoped path. - Added identity and pid-parse coverage — new
daemon-launched-child-identity.test.tsasserts the self-reported pid (not the immediate child's) wins and rejects a ready message with no pid;daemon-health.test.tsassertscgroupUnitround-trips throughcollectTerminalDaemonHealth().
DeepSeek Pro (free via Pullfrog for OSS) | 𝕏
1f63ef2 to
2447733
Compare
There was a problem hiding this comment.
✅ No new issues found.
Reviewed changes
- Fixed the pid-record unlink to use the daemon's self-reported pid —
daemon-out-of-process-launcher.tsnow callsunlinkOwnedDaemonPidFilewithlaunched.identity.pidinstead oflaunched.child.pidat both cleanup sites, matching the pid the daemon actually publishes. - Skipped the unscoped retry on a lost endpoint race —
launchDaemonChildrethrowsDaemonEndpointUnavailableErrorso another daemon owning the endpoint is adopted directly rather than forking a second child to lose the same race. - Refactored runtime-dir resolution to a single module constant —
CANONICAL_USER_RUNTIME_DIRreplaces thecanonicalUserRuntimeDir()helper;resolveUserRuntimeDirtakes the canonical dir explicitly. - Shared the detached child options —
spawnDaemonChildProcessbuilds onechildOptionsobject reused across theforkand scopedspawnbranches. - Tightened ready-pid validation —
parseDaemonReadyIdentitydoes an explicittypeofcheck so theas numbercast can be dropped. - Strengthened the cgroup-scope test fixtures — teardown iterates copies, and the "no runtime dir" case asserts a concrete
falseverdict; thedaemon-init-*suites now feedpidthrough their mocked ready messages.
DeepSeek Pro (free via Pullfrog for OSS) | 𝕏
|
@CodeRabbit review |
|
LesleyMurfin
left a comment
There was a problem hiding this comment.
Review verdict: changes requested
Verified against head 244773318a578bab97f5013b1b2cb4032b489dd4 (merge-base d058da4786701d74574959ab9d602b762d17e523), reviewed from a full checkout at that commit. Zero CI has run on this PR yet (all check-suites are action_required, awaiting maintainer approval) — this review is based on running the repo's own test/lint/typecheck tooling locally against the PR head, not on any CI signal.
Atomic scope: this is one genuine concern (make the terminal daemon survive a systemd unit restart), with the XDG_RUNTIME_DIR probe fix as a necessary sub-fix discovered while building it — not a bundle. Security review of the systemd-run wrapper: every argv element traces to a fixed literal or an internally-generated value (a sanitized launchNonce, userData-derived paths); no shell is used and a -- separator blocks option injection. No user- or network-supplied input reaches that command line.
Two things need to change before this is mergeable:
1. This PR fails an existing repo-enforced test that isn't in its own "Testing" claims
src/main/daemon/daemon-cgroup-scope.ts:18 and src/main/daemon/daemon-launched-child-spawn.ts:1 import node:child_process directly (execFileSync, fork/spawn). Neither file is in src/shared/child-process/__fixtures__/child-process-import-allowlist.txt, and src/shared/child-process/child-process-import-boundary.test.ts's DIRECT_IMPORTER_PIN stays at 155.
Running that test at this PR's head:
Tests 2 failed | Test Files 1 failed
- expected [] for unlisted direct importers, got 2 new offenders
- expected DIRECT_IMPORTER_PIN 155, got 157
The test's own failure message is explicit that raising the pin is not the fix: "Never raise the pin — migrate the file to runProcess/spawnProcess." That's also the project's own stated rule (AGENTS.md, Windows child-process section): child processes route through runProcess/spawnProcess in src/shared/child-process/, specifically because "a ratchet test fails on any new direct import." The existing direct importers in this directory (daemon-launched-child.ts, daemon-process-inspection.ts) are grandfathered allowlist entries, not precedent for adding new ones.
This PR's own "Testing" section names 5 specific test files plus typecheck:tsc:node plus targeted oxlint — none of those is this ratchet test, so the green report doesn't cover it, and nothing in the PR touches the allowlist or the pin. Whoever approves the currently-pending CI workflows will see this fail deterministically.
Suggested fix: route the systemd-run --version probe and the scoped-launch spawn() through runProcess/spawnProcess instead of raw node:child_process. As a side benefit, runProcess would let the version probe go async instead of the current synchronous execFileSync call on the main-process launch path (up to a 2s event-loop block on its own timeout).
2. Two shipped reference docs still describe the exact limitation this PR removes, as permanent
This PR ships no changes under docs/, but:
docs/reference/orcad-operations.md:29-30 still reads: "Service-restart survival requires separately supervised cgroups; the current deployment does not provide them." (and its "What is not covered" list at :204-205 still lists "Systemd-isolated daemon supervision" as unsupported.)
docs/reference/headless-linux-server.md:236-239 still reads: "It does not preserve the detached terminal daemon: the daemon and its PTYs remain in orca-serve.service's cgroup and are killed when the stop completes."
The PR's own "Why" section quotes the orcad-operations.md sentence above, so the fix demonstrably was written with that doc open — but neither file was updated to describe the new durable-scope path, its preconditions (systemd as PID 1, a reachable user bus / lingering enabled), or the fact that the old text remains true only in the unscoped-fallback case. A permanent behavior change landing while the reference docs assert the opposite is a real doc-accuracy gap for anyone deploying from those docs.
Nits (non-blocking)
- The "Testing" section claims 54/54 across the 5 named test files; actually running them gives 58/58 (all passing) — looks like a stale count from before the later cleanup commits added cases, not an inflated one. Worth a quick re-count before merge so the PR body matches reality.
DaemonReadyIdentity.pidjust became a hard requirement (previously-accepted pid-less ready messages are now rejected). Traced this to be safe in practice — the only production sender always includespid, and cross-generation adoption goes through the hello handshake, never this path — but it's not called out in the PR body as a tightened contract, worth one sentence.
What I verified locally rather than trusting the PR's own claims: reran typecheck:tsc:node (clean, though it needed a larger heap than this repo's own CI default to avoid an OOM — worth knowing independent of this PR), oxlint targeted and repo-wide (clean w.r.t. this diff), all 5 named test files (58/58, not 54/54), and demonstrated two of the new tests are load-bearing by temporarily reverting the actual mtl-02-regression fix in daemon-cgroup-scope.ts and confirming real AssertionErrors before restoring the file.
|
Both blocking findings from my review above are fixed in 1. The
Two corrections to what I suggested in the review. I had suggested making the probe async via
2. The docs. Nit: the "Testing" line now reads 58/58 instead of 54/54. I left the Verification (local, since CI still has not run): Still blocked on a maintainer, not on code: all three GitHub Actions suites on this head are |
There was a problem hiding this comment.
✅ No new issues found.
Reviewed changes
A single new commit, c9cb521, resolves both of the prior human review's blocking items (the child-process import-boundary violation and the two stale reference docs).
- Routed the daemon scope launch through the shared child-process chokepoint —
daemon-cgroup-scope.tsnow runs thesystemd-run --versioncapability probe viarunProcessSync, anddaemon-launched-child-spawn.tslaunches viaforkProcess/spawnProcess, dropping the two new directnode:child_processimports that failed the ratchet boundary test (DIRECT_IMPORTER_PINstays 155; allowlist unchanged). - Added
forkProcess— a thinnodeForkwrapper insidesrc/shared/child-process/(the owner directory, hence exempt) that faithfully reproduces the priorforkcontract (module path resolution, conditionalexecPathoverride,'ipc'stdio,detached), so the daemon's Node-module arm now flows through the chokepoint. - Wrote the durable-scope behavior into the reference docs —
headless-linux-server.mdandorcad-operations.mdnow describe thesystemd-run --user --scopelaunch, its preconditions (loginctl enable-linger, systemd PID 1,systemd-runon PATH), and the unscoped-fallback case, replacing the prior "does not preserve" / "not provided" claims.
DeepSeek Pro (free via Pullfrog for OSS) | 𝕏
|
Independently reproduced #19408 and verified this PR against a real Verdict: this works. Before/after traces below. Before — direct
|
|
Independent re-measurement (Docker, Debian 12, systemd 252, cgroup v2, One portability nit, not blocking: three cases in |
There was a problem hiding this comment.
✅ No new issues found.
Reviewed changes
- Corrected the
KillMode=mixedreference docs —headless-linux-server.mdandorcad-operations.mdnow state the cgroup-wideSIGKILLfires the instant the main process exits (never at theTimeoutStopSecdeadline, which only guards the main process), addedKillMode=mixedto the factory unit example, and documented that no in-container setting (lingering, kill mode, or scope) survives adocker restart. - Sealed the capability probe from the host —
isDurableDaemonScopeSupportedgained injectablesystemdBootPathandrunVersionProbeseams (defaulting to the real/run/systemd/systemmarker and arunProcessSync-backedsystemd-run --versionprobe), so theis truecapability tests no longer consult the host's own systemd; added a boot-marker test and a probe-cannot-answer test, both load-bearing.
DeepSeek Pro (free via Pullfrog for OSS) | 𝕏
|
@nwparker Addressed all 4 notes in
|
|
Cross-check against #19831’s live inventory found one follow-up case to cover before calling this complete: Could the PR add either a safe migration path for an adopted legacy daemon or an explicit drain/recreate path, plus an integration assertion that no descendants remain in the old app scope? Fresh launches and fallback behavior look well covered; the missing case is upgrade/adoption of a pre-fix daemon. |
fc4ecdd to
569da82
Compare
The per-UID path cannot change for a live process, so compute it once into a module const instead of threading the same default call through three signatures, and drop the try/catch around a getuid() that cannot throw once it exists. Trims the module prose to the non-obvious facts and corrects the pid-file record comment: an unscoped daemon writes null; only records no daemon wrote are absent.
The cgroup fixture tracked only the file it wrote, leaking one temp dir per case. Drains both fixture lists with splice so the pop-may-be-undefined guards go away, and replaces a not-throw/typeof-boolean pair with the verdict it was circling: no resolvable runtime dir means unsupported.
… paths cwd, detached and stdio were repeated in the fork and systemd-run branches, which left the two comments explaining them hovering over the env block instead. Names them once so each branch carries only its own delta.
typeof-first narrows the value, so the two 'as number' casts the isSafeInteger check needed disappear and the pid guard reads like the startedAtMs guard below it.
…t race A scoped attempt that lost the endpoint to another daemon was retried unscoped: a second doomed fork, a misleading 'cgroup-scope launch failed' warning, and the same DaemonEndpointUnavailableError the caller was already going to adopt on. Rethrows it instead, since no launch mode can win a race that is already lost. Also drops a private alias for DaemonChildSpawnOptions and the two 'as number' casts on child.pid in the startup-failure cleanup.
The record holds the daemon's self-reported pid, so match on that rather than on the immediate child's, which is the systemd-run wrapper's until it execs.
The two files this PR added imported `node:child_process` directly, which `child-process-import-boundary.test.ts` fails on deterministically: the offender count went 155 -> 157 against a pin of exactly 155. Raising the pin or listing the files is what that test explicitly forbids, and the allowlist's own note says a split "moved the import, it did not add one" -- so the fix is to get both new files off the module and put the count back at 155. - `daemon-cgroup-scope.ts`: the `systemd-run --version` probe now uses `runProcessSync` instead of `execFileSync`, so it gets the shared spawn decisions. Kept synchronous deliberately: `launchDaemonChild` attaches the readiness listener in the same tick it is called, and an await before the spawn moves the child past that tick. A non-zero exit is data rather than a throw here, so the verdict now checks `code === 0 && !timedOut`. - `daemon-launched-child-spawn.ts`: the scoped launch uses `spawnProcess`, and the long-standing unscoped launch keeps `fork` semantics through a new `forkProcess`. - `src/shared/child-process/fork-process.ts`: the fork arm of the chokepoint. `spawnProcess` cannot express a Node child with an IPC channel started from a module path under an overridden `execPath`, and the existing launch tests are written against `fork`'s contract, so a spawn rewrite would have changed module resolution, `execPath` and `execArgv` at once. It passes `windowsHide: true` -- the flag every other call site in that directory sets, reachable via an assertion because `ForkOptions` omits it -- which keeps `windows-console-visibility.test.ts` at its pin of 65 too. Both ratchets pass with both pins and both allowlists untouched. Docs: `orcad-operations.md` and `headless-linux-server.md` still described the limitation this PR removes as permanent. Both now describe the durable-scope survival path and its preconditions (systemd as PID 1, a reachable user bus / `loginctl enable-linger`, `systemd-run` on PATH), and scope the old text to the unscoped-fallback case, pointing at `health.terminalDaemon.cgroupUnit` as the way to tell the two apart on a running host.
…ct KillMode=mixed docs The capability probe consulted the host's own /run/systemd/system marker and spawned the real systemd-run binary, so the hermetic unit tests could only pass on a systemd host (and fail closed otherwise, even with faked bus sockets). - Thread systemdBootPath and runVersionProbe as test seams through isDurableDaemonScopeSupported, defaulting to the real boot marker and systemd-run --version probe in production. - Narrow the injected probe to the ProcessResult slice it consumes. - Cover: no-systemd-boot, non-zero probe exit, and probe-timeout cases. - Correct KillMode=mixed semantics in the docs: the cgroup-wide SIGKILL fires the instant the main process exits, not after TimeoutStopSec; document the Docker-container caveat and add KillMode=mixed to the multi-service template.
65ccfa4 to
8e85efb
Compare
There was a problem hiding this comment.
ℹ️ No critical issues — the incremental delta is a rebase plus a test/cleanup commit. One reference-doc sentence the new test pins is out of step with the behavior this PR ships.
Reviewed changes
Since the prior pullfrog review (4a263c0), the branch was rebased onto main (55378fc) with no content change to the PR files, and two commits landed:
- Updated the shutdown PR-gate assertions to match the rewritten docs — the managed Xvfb unit must now carry
KillMode=mixed, and the restart-survival assertion points at the newsystemd-run --user --scopeparagraph; ranconfig/scripts/headless-serve-shutdown-workflow.test.mjsat head, 12/12 pass. - Anti-slop/lint cleanup —
isRecordwidened tounknown, andforkProcesspasseswindowsHidethroughObject.assign({}, options, { windowsHide: true }); behavior-preserving.
ℹ️ The Upgrade section still says a service restart kills every terminal
docs/reference/headless-linux-server.md:462 still reads "The service restart kills every terminal and agent in its cgroup" with no scope caveat, directly contradicting the preservation paragraph this PR adds at :239 (which says the daemon and its live terminals survive a restart). orcad-operations.md:106-111 was qualified for exactly this reason ("Treat a stop as destructive unless health.terminalDaemon.cgroupUnit names an orca-daemon-*.scope"), but this paragraph was not — and the new test now pins the unqualified sentence as a gate, so correcting it means touching both the doc and the assertion. An operator following the Upgrade census rule at :466-480 is currently told two incompatible things about whether live terminals survive the stop.
Technical details
# Unqualified restart-is-destructive claim survives the scope change
## Affected sites
- `docs/reference/headless-linux-server.md:462` — "These guarantees do not preserve live processes. The service restart kills every terminal and agent in its cgroup" is now only true in the unscoped fallback.
- `config/scripts/headless-serve-shutdown-workflow.test.mjs:166` — the new gate assertion keeps that exact sentence, so a doc correction breaks the test unless the string is updated in lockstep.
- `docs/reference/headless-linux-server.md:466-480` — the census-before-stop procedure ("defer the restart" while any terminal is listed) is also unconditional.
- Contrast `docs/reference/orcad-operations.md:106-111`, which the PR did qualify against `health.terminalDaemon.cgroupUnit`.
## Required outcome
- State the restart-survival caveat in the Upgrade section the same way `orcad-operations.md` does: a scope-isolated daemon's terminals survive, the unscoped fallback still loses them.
- Update the gate assertion to whatever sentence replaces it.
## Open questions for the human
- Should the Upgrade census rule stay unconditional, or is it now required only when `cgroupUnit` is `null` on the host being stopped?DeepSeek Flash (free via Pullfrog for OSS) | 𝕏
Align the Upgrade section in docs/reference/headless-linux-server.md with the earlier preservation section and docs/reference/orcad-operations.md: a service restart terminates live processes only when running under the unscoped fallback, and stops should be treated as destructive unless health.terminalDaemon.cgroupUnit names an orca-daemon-*.scope. Update the shutdown workflow test assertion in config/scripts/headless-serve-shutdown-workflow.test.mjs to match.
|
@pullfrog The Upgrade section in |
|
Verified against head
This resolves the body-only finding from the prior pullfrog review (5272736358); that review had no inline threads, so there is nothing to resolve. No code changes needed — working tree clean.
|
LesleyMurfin
left a comment
There was a problem hiding this comment.
Riley-PR-Check Agent Review: Adversarial Domain Reviewer
Target: #19430
Tip SHA: 6c182f0
Repo: stablyai/orca
Verdict: REQUEST_CHANGES (2 Critical Blockers, 1 Major Defect)
Resolution of Prior Requested Changes
- Child-process import ratchet (RESOLVED in c9cb521c47 / 2f9f445):
node:child_processdirect imports indaemon-cgroup-scope.tsanddaemon-launched-child-spawn.tswere replaced withrunProcessSyncand the new sharedforkProcesshelper undersrc/shared/child-process/fork-process.ts.child-process-import-boundary.test.tsis 100% green with 0 unlisted offenders.
- Reference documentation drift (RESOLVED in fc4ecdd57e / c72f410 & 6c182f0):
docs/reference/orcad-operations.mdanddocs/reference/headless-linux-server.mdhave been updated to qualify daemon survival by scope isolation rather than claiming permanent limitation.config/scripts/headless-serve-shutdown-workflow.test.mjspasses.
Adversarial Audit of New Changes (Legacy Scope Migration)
Commit 9a12070a95 introduced legacy scope migration to address upgrade adoption of app-orca-*.scope processes. Zero-trust review identified 3 defects (2 blockers):
-
[CRITICAL] Missing
.scopesuffix inStartTransientUnitD-Bus call (daemon-cgroup-scope.ts:225)- Failure Mechanism: Systemd's
Manager.StartTransientUnitD-Bus API strictly requires full unit names including suffix. Passing bareorca-daemon-<nonce>causes systemd to reject the call withUnit name orca-daemon-... is not valid: missing a suffixor treat it as a.servicewhere thePIDsproperty is illegal. The migration fails deterministically on every real systemd deployment. - Hollow Test:
daemon-cgroup-scope.test.tspassed only because it mocked the execution and hardcoded the broken, suffix-less string into its assertion.
- Failure Mechanism: Systemd's
-
[CRITICAL] Premature
return preserveDaemon()bypasses staleness and health checks (daemon-replacement-preflight.ts:65-71)- Failure Mechanism: If migration succeeds on a healthy adopted daemon,
prepareDaemonReplacementimmediately returnspreserveDaemon(). This bypassesisDaemonStaleForCurrentBundle,getDaemonLaunchIdentity,getMacDaemonSystemResolverHealth, andgetMacDaemonTccAttributionHealth. In an upgrade scenario where the old daemon has 0 live sessions, Orca must retire and replace it. Returning early permanently preserves outdated daemon code.
- Failure Mechanism: If migration succeeds on a healthy adopted daemon,
-
[MAJOR]
cgroupPathFromProcgrabs the first controller line on multi-controller/cgroup v1 hosts (daemon-cgroup-scope.ts:160)- Failure Mechanism:
if (fields.length < 3 && !line.startsWith('0::')) continueevaluates to false for any line with >= 3 fields. On hybrid or v1 systems, it extracts the path from the first controller (e.g.12:memory:/...), missing the systemd hierarchy (1:name=systemd:...) and returningnull.
- Failure Mechanism:
Summary of Risk & Impact
- Impact of PR as a whole: Escapes the detached terminal daemon into an independent systemd transient scope (
systemd-run --user --scope), allowing active PTYs to survive service restarts and updates. - Immediate Risk: If merged with the current legacy migration code, legacy daemon migration will fail due to the missing
.scopesuffix, and any adopted daemon that does migrate will bypass staleness checks, running stale code across app updates.
Recommendation
Apply the 3 code diffs provided in the line comments and re-run verification before approving for merge.
| 'org.freedesktop.systemd1.Manager', | ||
| 'StartTransientUnit', | ||
| 'ssa(sv)a(sa(sv))', | ||
| daemonScopeUnitName(launchNonce), |
There was a problem hiding this comment.
Defect: Unit name missing required .scope suffix
Severity: Critical (Blocker)
Failure Mechanism: Systemd's D-Bus API (org.freedesktop.systemd1.Manager.StartTransientUnit) requires the unit name argument to explicitly include its type suffix (e.g. .scope). daemonScopeUnitName(launchNonce) returns orca-daemon-<nonce>. Without .scope, systemd rejects the call with an invalid unit name error, causing migration to fail every time on real systems.
--- a/src/main/daemon/daemon-cgroup-scope.ts
+++ b/src/main/daemon/daemon-cgroup-scope.ts
@@ -225,1 +225,1 @@
- daemonScopeUnitName(launchNonce),
+ `${daemonScopeUnitName(launchNonce)}.scope`,Also update daemon-cgroup-scope.test.ts:348 to expect 'orca-daemon-new-nonce.scope'.
| const health = await checkDaemonHealth(socketPath, tokenPath) | ||
| if (health === 'healthy') { | ||
| const pidRecord = readDaemonPidRecord(getDaemonPidPath(runtimeDir)) | ||
| if (pidRecord && migrateLegacyDaemonScope(pidRecord.pid, launchNonce)) { |
There was a problem hiding this comment.
Defect: Premature return preserveDaemon() bypasses staleness preflight
Severity: Critical (Blocker)
Failure Mechanism: Returning preserveDaemon() immediately upon migrating an adopted daemon bypasses bundle staleness checks (isDaemonStaleForCurrentBundle), launch identity checks, and TCC health. When upgrading to a new Orca version, an adopted legacy daemon with 0 live sessions is supposed to be replaced with the fresh bundle binary. Returning here keeps stale daemons running indefinitely.
Domain Risk: Code drift across version upgrades; daemons running obsolete binaries never get replaced.
--- a/src/main/daemon/daemon-replacement-preflight.ts
+++ b/src/main/daemon/daemon-replacement-preflight.ts
@@ -64,7 +64,6 @@
const pidRecord = readDaemonPidRecord(getDaemonPidPath(runtimeDir))
if (pidRecord && migrateLegacyDaemonScope(pidRecord.pid, launchNonce)) {
console.warn(
`[daemon] Migrated adopted daemon PID ${pidRecord.pid} out of legacy app scope into a durable scope`
)
- return preserveDaemon()
}|
|
||
| function cgroupPathFromProc(contents: string): string | null { | ||
| for (const line of contents.split('\n')) { | ||
| const fields = line.split(':') |
There was a problem hiding this comment.
Defect: Flawed line filtering in cgroupPathFromProc
Severity: Major
Failure Mechanism: if (fields.length < 3 && !line.startsWith('0::')) continue does not filter lines with >= 3 fields, so it immediately returns the path of the very first line in /proc/<pid>/cgroup (e.g. 12:memory:/...). In cgroup v1 or hybrid environments, it extracts the memory/cpu path instead of the name=systemd hierarchy, returning null for the scope.
--- a/src/main/daemon/daemon-cgroup-scope.ts
+++ b/src/main/daemon/daemon-cgroup-scope.ts
@@ -158,11 +158,13 @@
function cgroupPathFromProc(contents: string): string | null {
for (const line of contents.split('\n')) {
- const fields = line.split(':')
- if (fields.length < 3 && !line.startsWith('0::')) {
- continue
- }
- const path = fields.slice(2).join(':').trim()
- if (path) {
- return path
+ const trimmed = line.trim()
+ if (!trimmed) continue
+ if (trimmed.startsWith('0::')) {
+ return trimmed.slice(3).trim() || null
+ }
+ const fields = trimmed.split(':')
+ if (fields.length >= 3 && fields[1] === 'name=systemd') {
+ return fields.slice(2).join(':').trim() || null
}
}
return null
}There was a problem hiding this comment.
Important
The new legacy-scope migration can never engage: its StartTransientUnit call passes the scope unit name without the required .scope suffix, so systemd rejects every attempt and migrateLegacyDaemonScope() always returns false. Details inline.
Reviewed changes
Since the prior pullfrog review (8e85efb), one commit landed — 9a12070a95 ("migrate adopted legacy scopes") — adding a follow-up that migrates an adopted daemon still sitting in an older app-orca-*.scope:
- Added legacy-scope migration —
readLegacyDaemonScopeProcessesreads the adopted daemon's/proc/<pid>/cgroup, and when it names anapp-orca-*.scope, captures every PID in that scope'scgroup.procs;buildLegacyScopeMigrationCommandbuilds abusctl --user call … StartTransientUnitinvocation andmigrateLegacyDaemonScoperuns it (5 s timeout, fail-closed on any error). - Wired migration into adoption —
prepareDaemonReplacementattempts it on a healthy daemon and returnspreserveDaemon()on success;launchNonceis threaded fromcreateOutOfProcessLauncher. - Taught self-detection to recognize legacy scopes —
detectOwnCgroupScopeUnitnow also returns anapp-orca-*.scopename. - Added coverage — legacy recognition, complete PID-set capture, exact command construction, and the fail-closed path (the file passes 24/24).
ℹ️ Nitpicks
buildLegacyScopeMigrationCommandomitsCollectMode, while the fresh-launch path passes--collect.CollectModedefaults toinactive, so a migrated scope that endsfailedis not collected and lingers untilsystemctl reset-failed/reboot — worth mirroring--collectgiven the scope leak in #19831.- After a migration, the daemon's pid record still holds the
cgroupUnitit detected at startup (the legacy scope) and nothing rewrites it, sohealth.terminalDaemon.cgroupUnitwould not evidence the migration even once it succeeds. - The migration runs before the stale-bundle / launch-identity checks and returns
preserveDaemon(), so a stale daemon sitting in a legacy scope is preserved for one extra launch rather than replaced.
DeepSeek Flash (free via Pullfrog for OSS) | 𝕏
There was a problem hiding this comment.
✅ No new issues found.
Reviewed changes
Since the prior pullfrog review (9a12070), three commits landed — 6ae5718668 ("harden legacy scope migration") and the two doc commits 6c182f08ce + 909bf5dd70:
- Fixed the transient scope unit name —
daemonScopeUnitNamenow returnsorca-daemon-<nonce>.scope, so the migration'sStartTransientUnitname resolves a valid unit type (the previous bare name was rejected by systemd), and the freshsystemd-run --unit=path carries the same suffixed name. Test expectations updated in lockstep;pnpm test daemon-cgroup-scope.test.tspasses 24/24. - Hardened
/proc/<pid>/cgroupparsing —cgroupPathFromProcnow collects every parseable line and prefers the cgroup v2 unified line, then thename=systemdcontroller, over other controllers, instead of returning the first non-empty path. - Stopped short-circuiting after a successful migration — the
return preserveDaemon()immediately after migration is gone, so a migrated daemon still flows through the resolver / stale-bundle / launch-identity checks rather than bypassing them. - Qualified the restart-safety docs — the
headless-linux-server.mdUpgrade section now states that live processes survive only when the daemon is in anorca-daemon-*.scope(unscoped fallback still destructive; census only whencgroupUnitisnull/unverifiable), the factory unit gainedKillMode=mixed, and the shutdown-workflow gate assertions were updated in lockstep (config/scripts/headless-serve-shutdown-workflow.test.mjspasses 12/12).
DeepSeek Flash (free via Pullfrog for OSS) | 𝕏

ELI5
Orca's terminal daemon (the process that actually owns every PTY/shell) is already built to survive when just the main Orca server process restarts — a fresh server "adopts" the still-running daemon and its terminals come right back. But under a real systemd-managed deployment, restarting the service kills the daemon and every terminal too, because the daemon still lives in the same cgroup as the service even though it runs detached. This change puts the daemon in its own cgroup (via
systemd-run --user --scope, only when that's actually available) so asystemctl restartno longer reaches it — the daemon keeps running, and the adoption logic that already exists just works.What Changed
src/main/daemon/daemon-cgroup-scope.ts: feature-detects a usablesystemd --usermanager (isDurableDaemonScopeSupported), builds thesystemd-run --user --scope --unit=orca-daemon-<nonce> --collectwrapper command (buildDurableDaemonScopeCommand), and lets the daemon self-report which cgroup scope it actually landed in by reading/proc/self/cgroup(detectOwnCgroupScopeUnit) rather than trusting the launcher's intent.src/main/daemon/daemon-launched-child.ts/ newdaemon-launched-child-spawn.ts: when the durable scope is supported, the daemon is launched viaspawn()wrapping thatsystemd-runcommand (same'ipc'stdio contractfork()used, so the existing readiness handshake is unchanged) instead of a plainfork(). Any failure of the scoped attempt (no reachable user bus, a D-Bus/polkit rejection, etc.) transparently retries once with the original unscopedfork(), so every platform/environment without this capability keeps today's exact behavior.src/main/daemon/daemon-entry.ts,daemon-pid-file-parse.ts,daemon-spawner.ts,src/main/orcad/orcad-health.ts: thread acgroupUnit: string | nullfield through the daemon's existing pid-record and orcad's health/readiness payload, so a running deployment can observe whether the fix actually engaged (health.terminalDaemon.cgroupUnit).daemon-spawner.ts,daemon-pid-record-quarantine.ts,orcad-entry.ts'srefreshRestoredOrchestrationAuthority()+reconcileLegacyWorkerTerminals()) already implements durable, crash-safe reattachment for a surviving daemon — it simply never got exercised against a full unit restart before, because the daemon never survived one.Why
docs/reference/headless-linux-server.md's own reference systemd unit usesKillMode=mixed: SIGTERM to the main process only, then a cgroup-wideSIGKILLfallback at the stop timeout. The daemon is forkeddetached: true, which escapes the POSIX process group (setsid) but never the systemd cgroup — process-group detachment and cgroup membership are orthogonal. Every PTY the daemon owns is itself an undetached direct child of the daemon. So asystemctl restart/stopof the combined unit reaps the daemon and every live terminal, even thoughdocs/reference/orcad-operations.mdalready documents the daemon as designed to survive a PID-scoped restart oforcad— it says so explicitly: "Service-restart survival requires separately supervised cgroups; the current deployment does not provide them."systemd-run --user --scopeis the smallest fix that actually closes that gap: it registers the daemon in a cgroup that is a sibling of the service unit's cgroup (under the OS user's ownsystemd --usermanager), not a descendant, so the unit's own kill — whateverKillModeit uses — never reaches it.Fixes #19408
Linked Issue
Architectural Context (RFC #21556)
systemd-run --user --scope, allowing background PTY sessions to survive daemon restarts and laptop sleep.Fixes #19408
Visual Proof
N/A — this is main-process/daemon-lifecycle code with no renderer or UI surface. Nothing rendered changes.
Testing
New:
src/main/daemon/daemon-cgroup-scope.test.ts(14 cases — capability probe on/off Linux, systemd-present/absent, reachable/unreachable user bus, thesystemd-runcommand construction, and/proc/self/cgroupparsing for both cgroup v1 and v2 formats via a dependency-injected path). Existing suites updated for the newcgroupUnitfield (daemon-adoption-telemetry-event.test.ts,orcad-health.test.ts— added an explicit assertion that the field round-trips throughcollectTerminalDaemonHealth()—serve-readiness.test.ts,orcad-activation-gate.test.ts).Verified against upstream
main(this branch,fix/durable-daemon-cgroup-scope,git cherry-picked cleanly onto currentmain):pnpm run typecheck:tsc:nodeclean; targetedoxlintclean; the five test files above (58/58) pass.Verified in a systemd-enabled Docker container (Ubuntu 24.04 + systemd as PID 1, a real
Type=simple/KillMode=mixedunit matching the docs' reference unit, a service account withloginctl enable-linger): confirmed via/proc/<pid>/cgroupthat the daemon actually lands in its ownorca-daemon-<nonce>.scope, sibling to the service unit's cgroup — corroborated by the daemon's ownhealth.terminalDaemon.cgroupUnit. A live PTY session (a counting-loop shell, with an independent oracle log) survived a realsystemctl restartof the unit: daemon pid, PTY shell pid, and cgroup scope all unchanged across the restart, while the main process pid changed (confirming the unit genuinely restarted). A fresh write sent into the same terminal post-restart, addressed through the restarted process's own pairing/session, reached the same running shell — the session came back as the same session, not a cold-restore replay — with zero code changes beyond the cgroup escape itself needed for the existing adoption path to do that. A second, brand-new terminal's ordinary create → work → release lifecycle was unaffected.Platforms: Linux only exercises the new code path (feature-detected:
process.platform !== 'linux', no/run/systemd/system, or no reachable$XDG_RUNTIME_DIR//run/user/<uid>bus all fail closed to the unchanged direct-fork()path). macOS and Windows are structurally unaffected — every early-return inisDurableDaemonScopeSupported()is exercised by the new tests. Not tested against a live SSH-remote deployment specifically, but the change is local-process-launch-only and does not touch the SSH transport.AI Disclosure
Investigated, designed, implemented, and tested with an Anthropic Claude coding agent (multi-agent session: codebase investigation, implementation, a Docker-based systemd recovery test, and an AppImage build were run as parallel sub-agents under one coordinating session), with the repository owner directing scope and reviewing the plan before implementation.
Review
Self-reviewed for correctness: the scoped-launch failure path was specifically checked to retry unscoped rather than fail the daemon launch outright, so an environment lacking this capability degrades to exactly today's behavior. The daemon's own
/proc/self/cgroupself-detection (rather than trusting the launcher's intent) was a deliberate choice so an adopted pre-existing daemon, or one where the wrapper silently failed to isolate, never misreports isolation it doesn't have.Agent skill upstream boundary
docs/reference/agent-skill-sharing-upstream-boundary.mdand copies or mechanically translates no upstream skill-installer source, tests, fixtures, registry entries, path tables, comments, or documentation. — N/A: this is core daemon/session-lifecycle code, not the skill-installer system.Notes
launchNonce, an already-random UUID sanitized to the systemd-unit-name alphabet before use, and the daemon's own knownexecPath/forkEntryPath/args) — no user- or network-supplied string is interpolated into thesystemd-runcommand line, and it is invoked viaspawn()with an argv array, never a shell string.systemd-run --useronly reaches the invoking OS user's own session; it grants no new privilege the daemon didn't already have as that user.systemd --usermanager. Every guard is unit-tested.cgroupUnitfield is optional/nullable everywhere it's threaded (pid-record type, health payload); older daemon pid-record files without it parse tonull, not an error.existsSynccalls plus oneexecFileSync('systemd-run', ['--version'])with a 2s timeout; no ongoing polling or background work is added.Checklist
N/Awith reasonpnpm lint,pnpm typecheck,pnpm test, andpnpm buildpass (or CI will cover; local preferred)Author
@LesleyMurfin
Follow-up: adopted legacy scope migration
Fresh launches now use
orca-daemon-*.scope, but an upgrade can adopt a daemon that is still inside an olderapp-orca-*.scope(the state observed in #19831). On a healthy adoption, the launcher reads the daemon's live cgroup membership andcgroup.procs, then asks the same user systemd manager to create the durable scope with the complete PID set. This moves detached descendants together with the daemon; if any capability, identity, or systemd operation cannot be proved, adoption remains conservative and leaves the existing daemon untouched.Added coverage verifies legacy scope recognition, complete PID-set capture, exact
StartTransientUnit(PIDs=...)construction, and fail-closed migration behavior. The rebased branch passespnpm tc:node, changed-code quality, and the daemon adoption/restart suites (84 tests).