Skip to content

fix(daemon): escape the terminal daemon into its own systemd scope so a service restart no longer kills every live PTY - #19430

Merged
OrcaWin merged 19 commits into
stablyai:mainfrom
LesleyMurfin:fix/durable-daemon-cgroup-scope
Sep 22, 2026
Merged

OrcaWin merged 19 commits into
stablyai:mainfrom
LesleyMurfin:fix/durable-daemon-cgroup-scope

Conversation

@LesleyMurfin

@LesleyMurfin LesleyMurfin commented Sep 8, 2026 •

Copy link
Copy Markdown
Contributor

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 a systemctl restart no longer reaches it — the daemon keeps running, and the adoption logic that already exists just works.

What Changed

  • New src/main/daemon/daemon-cgroup-scope.ts: feature-detects a usable systemd --user manager (isDurableDaemonScopeSupported), builds the systemd-run --user --scope --unit=orca-daemon-<nonce> --collect wrapper 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 / new daemon-launched-child-spawn.ts: when the durable scope is supported, the daemon is launched via spawn() wrapping that systemd-run command (same 'ipc' stdio contract fork() used, so the existing readiness handshake is unchanged) instead of a plain fork(). Any failure of the scoped attempt (no reachable user bus, a D-Bus/polkit rejection, etc.) transparently retries once with the original unscoped fork(), 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 a cgroupUnit: string | null field 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).
  • No new session registry. The daemon's existing pid-record + adoption/quarantine machinery (daemon-spawner.ts, daemon-pid-record-quarantine.ts, orcad-entry.ts's refreshRestoredOrchestrationAuthority() + 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 uses KillMode=mixed: SIGTERM to the main process only, then a cgroup-wide SIGKILL fallback at the stop timeout. The daemon is forked detached: 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 a systemctl restart/stop of the combined unit reaps the daemon and every live terminal, even though docs/reference/orcad-operations.md already documents the daemon as designed to survive a PID-scoped restart of orcad — it says so explicitly: "Service-restart survival requires separately supervised cgroups; the current deployment does not provide them."

systemd-run --user --scope is 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 own systemd --user manager), not a descendant, so the unit's own kill — whatever KillMode it uses — never reaches it.

Fixes #19408

Linked Issue

Architectural Context (RFC #21556)

  • Roadmap Phase: Step 3: Reconnect & Attach
  • Severity / Priority: P1 (High)
  • Why It Ties into the Lifecycle: Headless daemon ran directly under systemd service unit, so any service restart or auto-update sent SIGHUP/SIGKILL to every active child PTY.
  • System Impact: Escapes daemon into a dedicated systemd-run --user --scope, allowing background PTY sessions to survive daemon restarts and laptop sleep.
  • Master Tracking RFC: Part of stablyai/orca#21556

Fixes #19408

Visual Proof

N/A — this is main-process/daemon-lifecycle code with no renderer or UI surface. Nothing rendered changes.

Testing

  • I manually tested these changes locally
  • Automated tests added/updated

New: src/main/daemon/daemon-cgroup-scope.test.ts (14 cases — capability probe on/off Linux, systemd-present/absent, reachable/unreachable user bus, the systemd-run command construction, and /proc/self/cgroup parsing for both cgroup v1 and v2 formats via a dependency-injected path). Existing suites updated for the new cgroupUnit field (daemon-adoption-telemetry-event.test.ts, orcad-health.test.ts — added an explicit assertion that the field round-trips through collectTerminalDaemonHealth() — 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 current main): pnpm run typecheck:tsc:node clean; targeted oxlint clean; 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=mixed unit matching the docs' reference unit, a service account with loginctl enable-linger): confirmed via /proc/<pid>/cgroup that the daemon actually lands in its own orca-daemon-<nonce>.scope, sibling to the service unit's cgroup — corroborated by the daemon's own health.terminalDaemon.cgroupUnit. A live PTY session (a counting-loop shell, with an independent oracle log) survived a real systemctl restart of 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 in isDurableDaemonScopeSupported() 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/cgroup self-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

  • Not applicable, or this change follows docs/reference/agent-skill-sharing-upstream-boundary.md and 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

  • Security: the scope-wrapping command is built from fixed argv segments and internally-generated values only (launchNonce, an already-random UUID sanitized to the systemd-unit-name alphabet before use, and the daemon's own known execPath/forkEntryPath/args) — no user- or network-supplied string is interpolated into the systemd-run command line, and it is invoked via spawn() with an argv array, never a shell string. systemd-run --user only reaches the invoking OS user's own session; it grants no new privilege the daemon didn't already have as that user.
  • Cross-platform: no-op on macOS and Windows (no systemd), and a no-op on Linux without a reachable systemd --user manager. Every guard is unit-tested.
  • Remote/SSH: unaffected — this only changes how the local daemon process is launched under the local systemd supervision, not any remote-host transport.
  • Backward compatibility: the new cgroupUnit field is optional/nullable everywhere it's threaded (pid-record type, health payload); older daemon pid-record files without it parse to null, not an error.
  • Performance: the capability probe runs at most once per daemon launch (an infrequent event) and does a couple of existsSync calls plus one execFileSync('systemd-run', ['--version']) with a 2s timeout; no ongoing polling or background work is added.

Checklist

  • This PR is small and focused
  • I explained what changed and why (including ELI5)
  • Before/after screenshots or videos attached for UI changes, or N/A with reason
  • Self-reviewed for correctness, security, and performance
  • Cross-platform, SSH/remote, and path/shortcut impact considered (or N/A)
  • pnpm lint, pnpm typecheck, pnpm test, and pnpm build pass (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 older app-orca-*.scope (the state observed in #19831). On a healthy adoption, the launcher reads the daemon's live cgroup membership and cgroup.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 passes pnpm tc:node, changed-code quality, and the daemon adoption/restart suites (84 tests).

@coderabbitai

coderabbitai Bot commented Sep 8, 2026 •

Copy link
Copy Markdown
Contributor

Review Change StackReview 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

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Advanced

Run ID: 90850972-57cf-4e57-96af-62c491e70945

📥 Commits

Reviewing files that changed from the base of the PR and between 1f63ef2d9fb65f05ecc764b627544cac395c2b79 and 244773318a578bab97f5013b1b2cb4032b489dd4.

📒 Files selected for processing (1)
  • src/main/daemon/daemon-launched-child-identity.test.ts

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


📝 Walkthrough

Walkthrough

The 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 cgroupUnit, with null values for legacy, absent, or unscoped daemons. Tests cover scope handling, readiness identity, and updated data fixtures.

Priority: ⬆️ High — Impact reflects high issue severity.

Severity of issue fixed: High

Merge Risk: ⚪ Minimal · up to 24477

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)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 40.00% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 25 functions across 24 files. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Linked Issues check ✅ Passed The implementation addresses issue #19408 by launching the daemon in a sibling systemd user scope when supported, detecting the actual cgroup, preserving fallback behavior, and reusing existing adopti…
Out of Scope Changes check ✅ Passed The code and test changes remain focused on durable daemon cgroup isolation, startup fallback, daemon identity, PID records, health reporting, and related regression coverage. No unrelated functionali…
Title check ✅ Passed The title clearly identifies the main change: placing the terminal daemon in its own systemd scope so service restarts do not terminate live PTYs.
Description check ✅ Passed The description covers the required sections, explains the user impact and implementation, links issue #19408, provides visual-proof rationale, documents testing and platform considerations, includes …

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

❤️ Share

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

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: 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.ts
  • src/main/daemon/daemon-cgroup-scope.test.ts
  • src/main/daemon/daemon-cgroup-scope.ts
  • src/main/daemon/daemon-entry.ts
  • src/main/daemon/daemon-launched-child-spawn.ts
  • src/main/daemon/daemon-launched-child.ts
  • src/main/daemon/daemon-pid-file-parse.ts
  • src/main/daemon/daemon-spawner.ts
  • src/main/orcad/orcad-health.test.ts
  • src/main/orcad/orcad-health.ts
  • src/main/server/serve-readiness.test.ts
  • src/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.

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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 usable systemd --user manager, builds a systemd-run --user --scope wrapper 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 spawns systemd-run via spawn() with the same 'ipc' stdio contract instead of fork().
  • 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 nullable cgroupUnit field 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?

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

@LesleyMurfin
LesleyMurfin marked this pull request as draft September 8, 2026 03:02
@LesleyMurfin

Copy link
Copy Markdown
Contributor Author

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.

LesleyMurfin added a commit to LesleyMurfin/orca that referenced this pull request Sep 8, 2026
…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.
@LesleyMurfin

Copy link
Copy Markdown
Contributor Author

Update: probe fix for a hardened-RuntimeDirectory shadowing bug found on real hardware

This PR's cgroup-escape fix was deployed to a real Linux headless-serve host, but isDurableDaemonScopeSupported() never actually engaged there — every daemon launch silently fell back to the old direct-fork() path.

Root cause: the deployed systemd unit running orca serve sets RuntimeDirectory= plus an explicit Environment=XDG_RUNTIME_DIR=%t/<runtime-dir-name> (a hardening directive, unrelated to the user-session bus). That makes XDG_RUNTIME_DIR point at a private scratch dir in the running process's own environment — a directory that shares the env var's name but has nothing to do with the real per-UID bus. resolveUserRuntimeDir() trusted that value first, found no bus socket there, and reported the daemon-cgroup-scope capability as unsupported — even though the real bus was reachable the whole time at the process owner's own /run/user/<uid>. Docker's stock jrei/systemd-ubuntu test container never had this hardening directive, so the gap was structurally invisible to the container-based verification described above.

Fix (daemon-cgroup-scope.ts): 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 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. buildDurableDaemonScopeCommand() now explicitly sets XDG_RUNTIME_DIR to whichever path this resolution picked, rather than inheriting the spread env's possibly-hardened value. New tests cover the hardened-override scenario with real, connectable AF_UNIX socket fixtures (not just existsSync-passing files).

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

  • Rebuilt the AppImage with this commit via the same electronuserland/builder:22 Docker process.
  • Launched a disposable transient unit (systemd-run --unit=<scratch-unit-name> --collect) as a normal login user with a linger-enabled session, with RuntimeDirectory= + an explicit Environment=XDG_RUNTIME_DIR= pointing at that RuntimeDirectory — deliberately reproducing the exact hardening condition on a throwaway instance, on an unused port, in a scratch directory outside the live install's instance-config path.
  • Confirmed the reproduction: the scratch process's own XDG_RUNTIME_DIR pointed at the empty hardened directory (no bus there), while the real per-UID bus was genuinely reachable the whole time — the same shape as the live-host bug.
  • Confirmed the fix: the daemon's /proc/<pid>/cgroup showed it registered under the user's own systemd --user manager (user@<uid>.service/app.slice/orca-daemon-<nonce>.scope) — a sibling of the scratch service's own system-unit cgroup, not a descendant. Corroborated independently by the daemon's self-reported pid-record (cgroupUnit round-trips the same scope name) and by systemctl --user list-units against the real user bus showing the scope unit active.
  • Full cleanup: scratch unit stopped, RuntimeDirectory= auto-removed by systemd, scratch directory and AppImage removed, no leftover processes.

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-systemctl restart scenario against the live occupied instance itself. That remains a separate, owner-approved step.

@LesleyMurfin
LesleyMurfin marked this pull request as ready for review September 8, 2026 03:52
@LesleyMurfin

Copy link
Copy Markdown
Contributor Author

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 XDG_RUNTIME_DIR. On a systemd unit that sets a hardened, private RuntimeDirectory=/Environment=XDG_RUNTIME_DIR=... override (common hardening pattern, unrelated to the actual per-UID D-Bus session), that shadows the real bus location and the probe silently fell back to plain fork() -- meaning the whole point of this fix (surviving a service restart) silently didn't engage.

Fix: the probe now always tries the conventional /run/user/<uid> path first (computed independently via getuid()), verified with a real reachable-socket check, falling back to the process's own XDG_RUNTIME_DIR only if that canonical path isn't usable.

Verification:

  • 18/18 unit tests (new cases cover the hardened-override scenario using real connectable AF_UNIX socket fixtures, not just file-existence checks).
  • 12/12 regression tests for the prior reap-leak fix this PR builds on -- unaffected.
  • Reproduced the exact real-world failure mode on a disposable, isolated test instance on real production hardware (not just Docker): replicated the same RuntimeDirectory=/XDG_RUNTIME_DIR hardening shape, confirmed the bug reproduced, then confirmed the patched probe correctly escapes the daemon into its own sibling cgroup scope anyway. Confirmed via /proc/<pid>/cgroup, the daemon's own self-reported pid-record, and systemctl --user list-units all agreeing.

check-upstream-surface clean.

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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 usable systemd --user manager, builds the systemd-run --user --scope wrapper, and self-detects the cgroup scope from /proc/self/cgroup.
  • daemon-launched-child-spawn.ts (new) — extracts fork/spawn; the scoped path launches via spawn('systemd-run', …) with the same 'ipc' stdio contract instead of fork().
  • 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 nullable cgroupUnit through the pid record and health payload.
  • 71027da — prefers the conventional /run/user/<uid> bus path over the process's own XDG_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`.

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

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: 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.ts
  • src/main/daemon/daemon-health.test.ts
  • src/main/daemon/daemon-init-child-readiness.test.ts
  • src/main/daemon/daemon-init-child-startup-failure.test.ts
  • src/main/daemon/daemon-init-endpoint-adoption.test.ts
  • src/main/daemon/daemon-init-live-session-preservation.test.ts
  • src/main/daemon/daemon-init-packaged-bundle-staleness.test.ts
  • src/main/daemon/daemon-init-replacement-reporting.test.ts
  • src/main/daemon/daemon-init-wedged-daemon-grace.test.ts
  • src/main/daemon/daemon-launched-child-identity.test.ts
  • src/main/daemon/daemon-launched-child-spawn.ts
  • src/main/daemon/daemon-launched-child.ts
  • src/main/daemon/daemon-ready-identity.test.ts
  • src/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.

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

✅ No new issues found.

Reviewed changes

  • Daemon self-reports its pid over the ready handshake — readCurrentDaemonReadyIdentity now includes process.pid, parseDaemonReadyIdentity requires a positive safe-integer pid, and launchDaemonChild builds launchedIdentity from that self-reported pid instead of child.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, and daemon-launched-child-spawn.ts accurately describe systemd-run --scope registering its own pid and then execvpe()ing the command (no fork), so signalling child.pid stays correct on the scoped path.
  • Added identity and pid-parse coverage — new daemon-launched-child-identity.test.ts asserts the self-reported pid (not the immediate child's) wins and rejects a ready message with no pid; daemon-health.test.ts asserts cgroupUnit round-trips through collectTerminalDaemonHealth().

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

@svc-orca
svc-orca Bot force-pushed the fix/durable-daemon-cgroup-scope branch from 1f63ef2 to 2447733 Compare September 8, 2026 09:00

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

✅ No new issues found.

Reviewed changes

  • Fixed the pid-record unlink to use the daemon's self-reported pid — daemon-out-of-process-launcher.ts now calls unlinkOwnedDaemonPidFile with launched.identity.pid instead of launched.child.pid at both cleanup sites, matching the pid the daemon actually publishes.
  • Skipped the unscoped retry on a lost endpoint race — launchDaemonChild rethrows DaemonEndpointUnavailableError so 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_DIR replaces the canonicalUserRuntimeDir() helper; resolveUserRuntimeDir takes the canonical dir explicitly.
  • Shared the detached child options — spawnDaemonChildProcess builds one childOptions object reused across the fork and scoped spawn branches.
  • Tightened ready-pid validation — parseDaemonReadyIdentity does an explicit typeof check so the as number cast can be dropped.
  • Strengthened the cgroup-scope test fixtures — teardown iterates copies, and the "no runtime dir" case asserts a concrete false verdict; the daemon-init-* suites now feed pid through their mocked ready messages.

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

@LesleyMurfin

Copy link
Copy Markdown
Contributor Author

@CodeRabbit review

@coderabbitai

coderabbitai Bot commented Sep 8, 2026 •

Copy link
Copy Markdown
Contributor
⚠️ Action not completed

Already reviewed the last commit. Use @coderabbitai full review to rerun a review of the entire changeset.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

@LesleyMurfin LesleyMurfin left a comment

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.pid just 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 includes pid, 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.

@LesleyMurfin

Copy link
Copy Markdown
Contributor Author

Both blocking findings from my review above are fixed in c9cb521c47.

1. The child_process import ratchet. Both new files are off node:child_process, so the offender count is back at exactly 155 and DIRECT_IMPORTER_PIN and the allowlist are untouched. Worth noting the allowlist's own comment turned out to say the quiet part — "daemon-launched-child.ts holds daemon-init.ts's fork() site; splitting that file moved the import, it did not add one" — which is exactly this situation, and the reason the fix is to move the import rather than to list the new filenames.

  • The systemd-run --version probe now goes through runProcessSync.
  • The scoped launch goes through spawnProcess.
  • The unscoped launch keeps fork via a new src/shared/child-process/fork-process.ts.

Two corrections to what I suggested in the review. I had suggested making the probe async via runProcess, and implied both arms could just use spawnProcess. I tried both and backed them out for concrete reasons:

  • Async probe: reverted. launchDaemonChild attaches the readiness listener in the same tick it is called, and daemon-launched-child-identity.test.ts emits 'ready' synchronously right after the call. Awaiting the probe moves the spawn past that tick and those two tests time out. The ≤2s block is real but it is pre-existing behaviour of this probe, and trading it for a changed launch-ordering contract is not a fix I would take on this PR. runProcessSync is the same chokepoint (isPwshAvailable uses it for exactly this "capability probe the caller needs now" shape), so the probe still gets the shared spawn decisions instead of re-deciding them with execFileSync.
  • fork → spawnProcess: reverted. Replacing the unscoped fork with a spawn of the same argv broke 33 tests across 8 files — daemon-init-* and daemon-entry-path-layouts mock child_process's fork through the shared daemon-init-test-harness and pin its contract (module-path resolution, execPath override, execArgv). Rewriting that harness to match a spawn would have been a much larger and riskier change than the finding warranted, so instead the chokepoint grew the arm it was missing: forkProcess, a faithful fork wrapper living in the owner directory where the import is allowed. It passes windowsHide: true (via an assertion, since ForkOptions omits the field while Node still forwards it), which also keeps windows-console-visibility.test.ts at its pin of 65 — that guard resolves fork as nodeFork as an alias, so a bare wrapper would have tripped it.

2. The docs. orcad-operations.md and headless-linux-server.md now describe the durable-scope survival path and its preconditions (systemd as PID 1, a reachable user bus — loginctl enable-linger for a non-login service account — and systemd-run on PATH), and the old "a stop kills the daemon" text is scoped to the unscoped-fallback case. Both point at health.terminalDaemon.cgroupUnit as the way to tell which case a running host is in. I also updated three further spots in orcad-operations.md that asserted the same removed limitation and were not in my original finding: "Process-scoped and cgroup-wide stops", the "Launch." bullet under "orcad supervising the daemon" (it said the daemon is forked, unconditionally), and "Decommissioning".

Nit: the "Testing" line now reads 58/58 instead of 54/54. I left the DaemonReadyIdentity.pid note out of the body rather than rewriting more of it — the tightened contract is described in the review above.

Verification (local, since CI still has not run): child-process-import-boundary.test.ts 4/4 with the pin untouched; windows-console-visibility.test.ts green at its pin; 1954 tests pass across src/main/daemon/, src/shared/child-process/, orcad-health, serve-readiness and orcad-activation-gate — baseline for that scope was the same set green, so nothing regressed; typecheck:tsc:node clean; oxlint, oxlint --config config/oxlint-react-doctor.json and oxfmt --check clean on the touched files. I also confirmed by smoke test that a spawnProcess child with the 'ipc' stdio slot does get a channel (readiness message received, send() accepted, clean exit), since that is what the scoped arm relies on.

Still blocked on a maintainer, not on code: all three GitHub Actions suites on this head are action_required. POST /actions/runs/<id>/approve returns 403 "Must have admin rights to Repository" for me, so the workflows for this fork PR need someone with admin to release them. No CI signal exists on this PR yet.

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

✅ No new issues found.

Reviewed changes

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.ts now runs the systemd-run --version capability probe via runProcessSync, and daemon-launched-child-spawn.ts launches via forkProcess/spawnProcess, dropping the two new direct node:child_process imports that failed the ratchet boundary test (DIRECT_IMPORTER_PIN stays 155; allowlist unchanged).
  • Added forkProcess — a thin nodeFork wrapper inside src/shared/child-process/ (the owner directory, hence exempt) that faithfully reproduces the prior fork contract (module path resolution, conditional execPath override, '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.md and orcad-operations.md now describe the systemd-run --user --scope launch, its preconditions (loginctl enable-linger, systemd PID 1, systemd-run on PATH), and the unscoped-fallback case, replacing the prior "does not preserve" / "not provided" claims.

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

@nwparker

Copy link
Copy Markdown
Contributor

Independently reproduced #19408 and verified this PR against a real systemctl restart, in Docker (Debian 12, systemd 252, cgroup v2, unprivileged orca service account created exactly as headless-linux-server.md prescribes, the documented Type=simple / KillMode=mixed unit). The stand-in for orca serve mirrors the launch primitives: detached: true daemon owning real PTYs (forkpty) as direct undetached children, versus this PR's systemd-run --user --scope wrapper.

Verdict: this works. Before/after traces below.

Before — direct fork(detached: true)

Daemon and PTYs sit in the unit's cgroup despite having their own session:

pid 748  node    0::/system.slice/orca-serve.service
pid 759  script  0::/system.slice/orca-serve.service
pid 760  script  0::/system.slice/orca-serve.service
pid 763  script  0::/system.slice/orca-serve.service

systemctl restart:

08:17:35.769374  Stopping orca-serve.service...
08:17:35.828219  Main process exited, code=exited, status=0/SUCCESS
08:17:35.828248  Killing process 748 (node)   with signal SIGKILL
08:17:35.828296  Killing process 759 (script) with signal SIGKILL
08:17:35.828308  Killing process 760 (script) with signal SIGKILL
08:17:35.828324  Killing process 761 (sleep)  with signal SIGKILL
08:17:35.828339  Killing process 762 (sleep)  with signal SIGKILL
08:17:35.828350  Killing process 763 (script) with signal SIGKILL
08:17:35.828359  Killing process 764 (sleep)  with signal SIGKILL
08:17:35.830324  Control group is empty.

Daemon pids before [748], after [797] — total loss.

After — systemd-run --user --scope

pid 881  node    0::/user.slice/user-996.slice/[email protected]/app.slice/orca-daemon-n1.scope
pid 892  script  0::/user.slice/user-996.slice/[email protected]/app.slice/orca-daemon-n1.scope
pid 894  script  0::/user.slice/user-996.slice/[email protected]/app.slice/orca-daemon-n1.scope
pid 896  script  0::/user.slice/user-996.slice/[email protected]/app.slice/orca-daemon-n1.scope

systemctl restart:

08:17:43.069456  Stopping orca-serve.service...
08:17:43.124902  Main process exited, code=exited, status=0/SUCCESS
08:17:43.125346  Control group is empty.

Zero Killing process lines. Daemon pids before [881], after [881]; all three PTYs unchanged.

Two structural properties I specifically checked, since both would break the pid record silently:

  • The IPC readiness handshake survives the wrapper. --scope execves in place, so NODE_CHANNEL_FD carries through; the ready message arrived normally.
  • child.pid is the daemon, not systemd-run. Measured child.pid=881 against the daemon's self-reported process.pid=881. Same process — the pid record stays correct.

I also tested a hypothesis that would have sunk the approach: cgroup-v2 delegation containment requires write access to the cgroup.procs of the nearest common ancestor when migrating a PID between cgroups, and the common ancestor of system.slice/… and user.slice/… is the root cgroup. It does not bite — a probe run from inside a User=orca system unit landed in /user.slice/user-996.slice/[email protected]/app.slice/orca-daemon-probe.scope. Worth recording so it doesn't get re-raised in review.

Three notes, none blocking

1. Both docs still describe the cgroup SIGKILL as timeout-bounded, and it isn't. headless-linux-server.md keeps "retains systemd's cgroup-wide SIGKILL fallback if shutdown times out"; orcad-operations.md keeps "when the stop timeout expires"; and this PR's new module header repeats it as "at the stop timeout under mixed". Measured, the kill lands 56 ms after the SIGTERM, the instant the main process exits — TimeoutStopSec never enters it (Stopping 49.809611 → Main process exited 49.865983 → Killing process 49.866017). This matters for the fallback path the PR now documents: an operator reading "if shutdown times out" will reasonably raise TimeoutStopSec expecting a grace window that does not exist, and nothing gets a window in which to checkpoint. A cleaner shutdown makes the kill arrive sooner.

2. The managed-Xvfb variant of orca-serve.service has no KillMode line at all, so it silently gets control-group. Measured on that unit: SIGTERM to the entire cgroup at once (every PTY dies immediately), then the unit stalls the full 90 s TimeoutStopSec before the SIGKILL — systemctl restart took 90,435 ms and still lost everything. Since the two "recommended" units differ materially in the fallback case, giving that block the same explicit KillMode=mixed would be worth folding in.

3. Docker isn't covered anywhere. The capability probe correctly fails closed (no /run/systemd/system → direct fork), but neither doc mentions that a docker restart tears down the PID namespace so no in-container setting preserves anything, nor that without --init Orca serves as PID 1 and exited PTY subprocesses accumulate as zombies rather than being reaped.

On the reattach half: the ssh-execution-boundary.md verdict rule looks respected in the fallback case — runtime-legacy-worker-terminal-recovery-runner.ts defers local PTY candidates when canRecoverPersistentLocalPtys() is false rather than resolving them exited. Reading cgroupUnit from /proc/self/cgroup instead of trusting the launcher's intent is the right call for the same reason.

Repro harness (Dockerfile, unit files, stand-ins, escape probes, raw journals) available if useful.

@nwparker

Copy link
Copy Markdown
Contributor

Independent re-measurement (Docker, Debian 12, systemd 252, cgroup v2, User=orca system unit, KillMode=mixed) agrees with the review above: with loginctl enable-linger orca the daemon lands in user.slice/user-996.slice/[email protected]/app.slice/orca-daemon-<nonce>.scope, and systemctl restart logs zero Killing process lines — daemon pid and all three PTY pids unchanged. Without linger every route fails (No medium found / Interactive authentication required / cgroup write Permission denied), so the enable-linger step in the docs is load-bearing, not optional. One detail: XDG_RUNTIME_DIR is unset inside the unit, so the explicit /run/user/<uid> resolution in buildDurableDaemonScopeCommand is what makes it work — systemd-run --user with the inherited env still fails even with linger on.

One portability nit, not blocking: three cases in daemon-cgroup-scope.test.ts fail on a non-systemd dev machine (macOS: expected false to be true for the three isDurableDaemonScopeSupported(... 'linux' ...) = true cases). The tests inject platform: 'linux' and a fake runtime dir, but the function still consults the real existsSync('/run/systemd/system') and runs the real systemd-run --version, neither of which exist off a systemd host. Injecting those two probes the same way the runtime dir is injected would make the suite hermetic; as-is pnpm test src/main/daemon is red for anyone on a Mac (CI on Ubuntu is fine).

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

✅ No new issues found.

Reviewed changes

  • Corrected the KillMode=mixed reference docs — headless-linux-server.md and orcad-operations.md now state the cgroup-wide SIGKILL fires the instant the main process exits (never at the TimeoutStopSec deadline, which only guards the main process), added KillMode=mixed to the factory unit example, and documented that no in-container setting (lingering, kill mode, or scope) survives a docker restart.
  • Sealed the capability probe from the host — isDurableDaemonScopeSupported gained injectable systemdBootPath and runVersionProbe seams (defaulting to the real /run/systemd/system marker and a runProcessSync-backed systemd-run --version probe), so the is true capability tests no longer consult the host's own systemd; added a boot-marker test and a probe-cannot-answer test, both load-bearing.

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

@LesleyMurfin

Copy link
Copy Markdown
Contributor Author

@nwparker Addressed all 4 notes in fc4ecdd57e:

  1. SIGKILL timing: Corrected docs and module header to reflect immediate SIGKILL under KillMode=mixed upon main process exit.
  2. Managed-Xvfb unit: Explicit KillMode=mixed added to template.
  3. Docker caveats: Added notes on PID namespace teardown and docker run --init zombie prevention.
  4. Test portability: Injected systemdBootPath and probe runner seams so daemon-cgroup-scope.test.ts runs hermetically across non-systemd/macOS hosts.

@OrcaWin

OrcaWin commented Sep 21, 2026

Copy link
Copy Markdown
Collaborator

Cross-check against #19831’s live inventory found one follow-up case to cover before calling this complete: detectOwnCgroupScopeUnit() correctly reports null for a daemon adopted from before the durable-scope launch. That means an upgrade can preserve a daemon and its PTYs inside an existing app-orca-*.scope, exactly like the two historical scopes in #19831.

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.

@OrcaWin
OrcaWin force-pushed the fix/durable-daemon-cgroup-scope branch from fc4ecdd to 569da82 Compare September 21, 2026 22:14
LesleyMurfin and others added 11 commits September 21, 2026 16:05
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.
@OrcaWin
OrcaWin force-pushed the fix/durable-daemon-cgroup-scope branch from 65ccfa4 to 8e85efb Compare September 21, 2026 23:06

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ℹ️ No 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 new systemd-run --user --scope paragraph; ran config/scripts/headless-serve-shutdown-workflow.test.mjs at head, 12/12 pass.
  • Anti-slop/lint cleanup — isRecord widened to unknown, and forkProcess passes windowsHide through Object.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?

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

m4air and others added 3 commits September 21, 2026 16:25
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.
@LesleyMurfin

Copy link
Copy Markdown
Contributor Author

@pullfrog The Upgrade section in docs/reference/headless-linux-server.md has been qualified to match line 239 and orcad-operations.md:106-111, clarifying that service restarts terminate live processes only when running under the unscoped fallback, and that stops should be treated as destructive unless health.terminalDaemon.cgroupUnit names an orca-daemon-*.scope on that host. In addition, config/scripts/headless-serve-shutdown-workflow.test.mjs has been updated to assert this matching qualification in the PR gate test.

@pullfrog

pullfrog Bot commented Sep 21, 2026 •

Copy link
Copy Markdown
Contributor

Verified against head 909bf5d of fix/durable-daemon-cgroup-scope — the described qualification is in place and the gate is green.

  • docs/reference/headless-linux-server.md:462-468 now reads "These guarantees preserve live processes only when the daemon is in its own orca-daemon-*.scope… The unscoped fallback remains destructive…", matching the preservation paragraph at :239.
  • config/scripts/headless-serve-shutdown-workflow.test.mjs:163-174 asserts the new sentences; node_modules/.bin/vitest run --config config/vitest.config.ts config/scripts/headless-serve-shutdown-workflow.test.mjs → 12/12 pass.
  • docs/reference/orcad-operations.md:106-111 carries the same health.terminalDaemon.cgroupUnit caveat, and the Upgrade census rule at :470 is now conditional on cgroupUnit being null/unverifiable.

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.

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

@LesleyMurfin LesleyMurfin left a comment

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

  1. Child-process import ratchet (RESOLVED in c9cb521c47 / 2f9f445):
    • node:child_process direct imports in daemon-cgroup-scope.ts and daemon-launched-child-spawn.ts were replaced with runProcessSync and the new shared forkProcess helper under src/shared/child-process/fork-process.ts.
    • child-process-import-boundary.test.ts is 100% green with 0 unlisted offenders.
  2. Reference documentation drift (RESOLVED in fc4ecdd57e / c72f410 & 6c182f0):
    • docs/reference/orcad-operations.md and docs/reference/headless-linux-server.md have been updated to qualify daemon survival by scope isolation rather than claiming permanent limitation.
    • config/scripts/headless-serve-shutdown-workflow.test.mjs passes.

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

  1. [CRITICAL] Missing .scope suffix in StartTransientUnit D-Bus call (daemon-cgroup-scope.ts:225)

    • Failure Mechanism: Systemd's Manager.StartTransientUnit D-Bus API strictly requires full unit names including suffix. Passing bare orca-daemon-<nonce> causes systemd to reject the call with Unit name orca-daemon-... is not valid: missing a suffix or treat it as a .service where the PIDs property is illegal. The migration fails deterministically on every real systemd deployment.
    • Hollow Test: daemon-cgroup-scope.test.ts passed only because it mocked the execution and hardcoded the broken, suffix-less string into its assertion.
  2. [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, prepareDaemonReplacement immediately returns preserveDaemon(). This bypasses isDaemonStaleForCurrentBundle, getDaemonLaunchIdentity, getMacDaemonSystemResolverHealth, and getMacDaemonTccAttributionHealth. 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.
  3. [MAJOR] cgroupPathFromProc grabs the first controller line on multi-controller/cgroup v1 hosts (daemon-cgroup-scope.ts:160)

    • Failure Mechanism: if (fields.length < 3 && !line.startsWith('0::')) continue evaluates 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 returning null.

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 .scope suffix, 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),

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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(':')

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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
 }

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Important

The new 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 — readLegacyDaemonScopeProcesses reads the adopted daemon's /proc/<pid>/cgroup, and when it names an app-orca-*.scope, captures every PID in that scope's cgroup.procs; buildLegacyScopeMigrationCommand builds a busctl --user call … StartTransientUnit invocation and migrateLegacyDaemonScope runs it (5 s timeout, fail-closed on any error).
  • Wired migration into adoption — prepareDaemonReplacement attempts it on a healthy daemon and returns preserveDaemon() on success; launchNonce is threaded from createOutOfProcessLauncher.
  • Taught self-detection to recognize legacy scopes — detectOwnCgroupScopeUnit now also returns an app-orca-*.scope name.
  • Added coverage — legacy recognition, complete PID-set capture, exact command construction, and the fail-closed path (the file passes 24/24).

ℹ️ Nitpicks

  • buildLegacyScopeMigrationCommand omits CollectMode, while the fresh-launch path passes --collect. CollectMode defaults to inactive, so a migrated scope that ends failed is not collected and lingers until systemctl reset-failed/reboot — worth mirroring --collect given the scope leak in #19831.
  • After a migration, the daemon's pid record still holds the cgroupUnit it detected at startup (the legacy scope) and nothing rewrites it, so health.terminalDaemon.cgroupUnit would 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.

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

Comment thread src/main/daemon/daemon-cgroup-scope.ts Resolved

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

✅ No new issues found.

Reviewed changes

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 — daemonScopeUnitName now returns orca-daemon-<nonce>.scope, so the migration's StartTransientUnit name resolves a valid unit type (the previous bare name was rejected by systemd), and the fresh systemd-run --unit= path carries the same suffixed name. Test expectations updated in lockstep; pnpm test daemon-cgroup-scope.test.ts passes 24/24.
  • Hardened /proc/<pid>/cgroup parsing — cgroupPathFromProc now collects every parseable line and prefers the cgroup v2 unified line, then the name=systemd controller, 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.md Upgrade section now states that live processes survive only when the daemon is in an orca-daemon-*.scope (unscoped fallback still destructive; census only when cgroupUnit is null/unverifiable), the factory unit gained KillMode=mixed, and the shutdown-workflow gate assertions were updated in lockstep (config/scripts/headless-serve-shutdown-workflow.test.mjs passes 12/12).

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

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.

[Bug]: systemd KillMode=mixed/control-group SIGKILLs the terminal daemon and every live PTY on a combined-unit restart, with zero reattach

3 participants