Repository navigation
fix(daemon): make pid-record publish atomic via claim-then-link - #16924
brennanb2025 wants to merge 4 commits into
Conversation
A crash, power loss, or forced kill mid-write left a torn, unparseable daemon-vN.pid at the canonical path. For a retired protocol version nothing ever heals that record (stale-kill only reclaims the current version's), so the corrupt file became a permanent veto on pruning that version. Publish now writes a per-pid/per-uuid claim, fsyncs it, and hard-links it into place: readers see a complete record or none, and EEXIST ownership conflicts are preserved (rename would silently replace). Filesystems that refuse hard links degrade to the previous exclusive direct write. Claims are cleaned on every in-process failure path; crash-orphaned claims are reaped at the launch funnel, gated on the owner pid being provably dead (ESRCH), never on age.
|
Pushed and verified via |
|
No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info⚙️ Run configurationConfiguration used: Repository UI Review profile: CHILL Plan: Pro Plus Run ID: 📒 Files selected for processing (1)
Included review availability: Your plan provides up to 10 included reviews per hour; 1 remains after this review. 📝 WalkthroughWalkthroughThe daemon PID publisher now writes records to unique scratch claims, flushes them, and atomically links them into place. It preserves existing records and falls back to exclusive direct writes when hard links are unavailable. Artifact restoration uses exclusive hard links with copy fallback. A reaper removes claims from proven-dead publishers before daemon launch. Tests cover atomicity, durability, cleanup, conflicts, metadata, ownership, restoration, and Windows execution. Merge Risk: 🟠 High · up to The PR improves atomic PID-record publication but still changes daemon startup cleanup in a way that can remove another process’s publish claim or unlink an existing pathname after a claim-creation failure. That creates a concrete risk of deleting another daemon’s in-flight or replacement record, so merge should be blocked until ownership and cleanup behavior are corrected. 🚥 Pre-merge checks | ✅ 3 | ❌ 2❌ Failed checks (2 warnings)
✅ Passed checks (3 passed)
Full details: Description checkExplanation The description explains the problem, implementation, platform considerations, and test evidence in detail. However, it omits several required template sections, including an explicit What Changed section, a Fixes # issue link, Visual Proof or N/A, Testing, AI Disclosure, Review, Agent skill upstream boundary, Notes, and the Checklist. Resolution Add the missing required sections. Include the issue reference in the required Fixes # format, state N/A with a reason for Visual Proof if applicable, document testing platforms and commands, complete the applicable checkboxes, and provide the required AI Disclosure, Review, Agent skill boundary, and Notes content. Full details: Docstring CoverageExplanation Docstring coverage is 33.33% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 9 functions across 8 files. (1 skipped: 1 unsupported.)
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: Pro Plus
Run ID: deb6c2e4-a6cd-4c25-858c-c823da0962b7
📒 Files selected for processing (8)
.github/workflows/pr.ymlconfig/scripts/pr-code-change-scope.mjssrc/main/daemon/daemon-pid-publish-atomicity.test.tssrc/main/daemon/daemon-pid-publish-claim-reap.test.tssrc/main/daemon/daemon-pid-publish-claim-reap.tssrc/main/daemon/daemon-pid-publish-disk-contract.test.tssrc/main/daemon/daemon-spawner.test.tssrc/main/daemon/daemon-spawner.ts
Included review availability: Your plan provides up to 10 included reviews per hour; 0 remain after this review.
Independent adversarial review — head
|
| Reverted hunk | Author claimed red | My re-run |
|---|---|---|
| claim+link publish → main's direct write | 2 | 2 (torn record; fsync-before-visible) |
| fsync of the claim | 1 | 1 |
claim cleanup (finally unlink) |
8 | 8 (5 atomicity + 3 disk-contract) |
| no-hardlink degraded fallback | 2 | 2 |
| launch-funnel reap call | 1 | 1 |
| reaper's proven-dead fence | 1 | 1 |
Every hunk is load-bearing. Full daemon suite on head: 149 files / 1691 tests green locally, matching the PR claim.
3. The EEXIST claim (the load-bearing design decision) — CONFIRMED, link is justified
All three claimed call sites exist and genuinely depend on publish failing EEXIST against an existing record:
replaceDaemonPidFile(daemon-spawner.ts:223-260): claims the old record away by rename, then relies on the publish being exclusive — if a competitor published in the window, publish must throw so replace restores and returnsfalse. With rename-publication the competitor's freshly published record would be silently clobbered and replace would misreport success. The comment at :229-234 explicitly reasons about EEXIST as the ownership-conflict signal.daemon-stale-kill.ts:170-173: "Leaving it intact keeps the exclusive PID claim held, so a duplicate cannot take the endpoint" — leaving the record in place is only a fence because publish fails EEXIST; rename-publication would make this fencing dead code. The :182-187 unparseable-record reclaim exists for the same reason.DaemonEndpointLifecycle.publish(daemon-endpoint-lifecycle.ts:73-84) viapublishEndpointOwnership(daemon-entry.ts:277): a duplicate daemon must throw and refuse to serve; the error path deliberately skipsunlinkOwnedDaemonPidFilewhenpublishedOwnershipis false, i.e. it assumes a failed publish did NOT touch the rightful owner's record. Rename would break that assumption.
Rename replaces the destination on every platform Node supports (POSIX rename, libuv MoveFileEx with replace on Windows), so it really would erase the signal. The author did not overstate this. Bonus property I verified: the degraded fallback preserves the contract too, because the wx direct write also fails EEXIST — so even a filesystem that misclassifies link conflicts cannot lose the ownership signal.
4. Reaper attack
ESRCH-only: confirmed as implemented. claimOwnerIsProvenDead returns true only on error.code === 'ESRCH'; EPERM → not reaped. The module contains no stat, no mtime, no clock read — there is no age or heuristic path, and the only call site is DaemonSpawner.ensureRunning (after the early-return and throttle, so it runs only on real launches). PUBLISH_CLAIM_PATTERN cannot match records, tokens, .swap-/.hold- claims, or .corrupt quarantine files. The pin test locks the generator↔reaper name shape and keeps .publish- outside the released age-based sweeper pattern, and runtimeDir is userData/daemon (daemon-launch-paths.ts:9-13), so no OS tmp-cleaner applies.
PID recycled onto an unrelated live process: kill(pid, 0) succeeds, claim not reaped that launch — but this is not a permanent leak. The probe re-runs at every subsequent ensureRunning; the claim is reaped at the first launch when that pid is dead/unassigned. Worst case (pid pinned by a long-lived system process across every launch) the leak is one ~100-byte inert file per crashed publish, invisible to all readers (collectPinnedDaemonVersions scans ^daemon-v\d+\.pid$ only, so a claim can never veto pruning). Bounded, safe direction, self-healing.
Two racing publishers: claim names are per-pid/per-uuid so claims never collide; linkSync is the kernel arbiter; the loser gets EEXIST and its finally unlinks only its own claim. Correct.
Alive-but-wedged owner: claim retained (correct — never delete a live publisher's scratch); one file per wedged process, reaped at the first launch after it dies.
No-hardlink filesystems: claims are ordinary files — reapable everywhere; the publish itself degrades (see §6).
One inaccuracy (P2-a below): the comment in daemon-pid-publish-claim-reap.ts:15-20 says deleting a live publisher's claim "would fail that publish". Actually linkSync would throw ENOENT, which the non-EEXIST catch treats as a degrade signal, and the publish succeeds via the exclusive direct write (full bytes rewritten from memory, just non-atomically). The fence is still right; the stated consequence is wrong.
5. Fsync durability — data-only fsync, no directory fsync, and that is sufficient here
What the code does: fsyncFileSync(claimPath) (open + fsyncSync, r+ on Windows for FlushFileBuffers) — the claim file's data. It does not fsync the directory after linkSync, and bestEffortFsyncDirectorySync (which exists in secure-file.ts) is not used.
Why that is not the classic durability gap: the dangerous inversion — canonical name durable while the bytes are not — is impossible, because the data is made durable before the canonical name is ever created. The only power-loss outcome the missing directory fsync allows is publish-reported-success followed by the link entry being lost — which readers see as "no record", and after a power loss the daemon is dead anyway, so "no record" is the correct post-reboot state. No torn record is reachable through the link path. (The degraded direct-write path has no fsync at all — that is explicitly today's shipped behavior, unchanged.) Residual, not a finding: on macOS fsync does not force the drive cache (F_FULLFSYNC would); this matches the repo-wide durability idiom in writeSecureFile, and both names-and-bytes ride the same cache, so the failure mode requires drive-internal reordering.
6. Cross-platform
- Windows/NTFS: verified from the CI log that
package (windows)on this PR (runs-onwindows-2022) executeddaemon-pid-publish-disk-contract.test.ts— 4 tests passed, including EEXIST-not-EPERM while another process holds the record open. Both wiring lists (pr.yml+pr-code-change-scope.mjsWINDOWS_PACKAGE_TESTS) got the file, and editing them force-ran all jobs on this PR. - Degrade path on Windows: the
wxdirect write is byte-for-byte the pre-PR shipped path, EEXIST semantics intact. - ReFS / network mounts / overlay volumes: where
CreateHardLink/linkis unsupported or refused, any non-EEXIST error degrades to the previous stable behavior — the torn-write window returns on those volumes but nothing regresses versus previous stable, and the ownership contract survives (the fallback's own EEXIST). Pre-existing gap retained by design, not a regression. - Minor:
daemon-pid-publish-claim-reap.test.tsis not in the Windows package list, soprocess.kill(pid, 0)→ ESRCH semantics for the reaper are untested on Windows CI. Node maps a missing pid to ESRCH on Windows and the failure direction (EPERM/alive → don't reap) is the safe one, so this is hygiene, not risk (P2-c).
7. #16908 quarantine reachability — nothing goes dead
#16908 is still open (sibling, unmerged). Its quarantineCorruptDaemonPidRecord is reached from collectPinnedDaemonVersions whenever any on-disk daemon-vN.pid fails to parse. After this PR that remains reachable from at least four real sources: (1) torn records already in the field from old builds, (2) old builds sharing the runtime dir during mixed-version periods or rollback (they still publish non-atomically), (3) this PR's own no-hardlink degrade path, and (4) restoreClaimedDaemonArtifact's non-atomic copyFileSync restore, which can still leave a partial canonical record on crash. No recovery code in #16908 becomes dead. Cross-interference checked both ways: .corrupt files never match the reap pattern; .publish- claims never match #16908's record scan.
8. Performance (by hand — the perf skill is disable-model-invocation for this review, so it was not invoked)
Publish adds one file create + one fsync + one link + one unlink, once per daemon start — not a hot path; fsync is the only material cost (sub-ms to low-ms) and it buys the durability ordering. The reap adds one readdirSync of a ~dozen-entry dir plus one regex per entry per actual launch (the ensureRunning early-return and crash-loop throttle both precede it), and kill(pid, 0) probes only for matching claims — normally zero. No timers, no listeners, no unbounded structures; claim files are ~100 bytes with the bounded lifecycle described in §4. Windows CI cost: +33ms.
Findings
No P0. No P1. (No release-blocking candidates, so the counsel-validation loop is not triggered.)
- P2-a —
daemon-pid-publish-claim-reap.ts:15-20: comment says deleting a live publisher's claim "would fail that publish"; it would actually degrade to a successful non-atomic direct write (linkSync ENOENT lands in the non-EEXIST catch). Fix the comment (or narrow the degrade to unsupported-link errno codes) in a follow-up. - P2-b — the no-hardlink degrade fires silently (
daemon-spawner.ts:187-195). On volumes that refuse hard links, the atomicity guarantee silently reverts to the old torn-write behavior with no log line, so the field population on that path is unobservable. Oneconsole.warnwould make the capability degrade visible. - P2-c — reaper's ESRCH gate untested on Windows CI (see §6).
Residual risk (not findings): macOS fsync-vs-F_FULLFSYNC drive-cache reordering; rollback to an old build leaves any crash-orphaned .publish- claim invisible to old builds' cleanup (inert, ~100 bytes, reclaimed on the next new-build launch); pid-recycled claims persist while the pid stays occupied (bounded, self-healing).
Superseding bar
This is the shape I would write from scratch. The alternative families — kernel-lock-based ownership, or rename-publication serialized under a lock — change crash-recovery and network-filesystem semantics well beyond this fix's scope, and plain rename-publication is affirmatively wrong here (§3). Claim + fsync + exclusive link + errno-preserving degrade + ESRCH-fenced reap at the single launch funnel is the minimal design that keeps all three ownership contracts while closing the torn-write source. The three P2s above are the only deltas, all follow-up material.
Verdict
Merge-ready. Every headline claim in the PR description was independently reproduced: failing-first red on pristine main (2 tests, exact messages), 6/6 ablation hunks red in isolation with the exact claimed counts, all three EEXIST call sites real and rename-incompatible, reaper provably ESRCH-only with no age path, fsync ordering sufficient without a directory fsync for this contract, Windows NTFS contract verified from the CI log, and #16908's recovery remains fully reachable. The three P2s are non-blocking follow-ups.
|
Independent P2-closure pass (dispatched worker): the three review P2s from comment 5447786752 are closed in follow-up PR #16979, head
Link-vs-rename design untouched. #16979 needs manual retarget onto main after this PR merges. |
Review — findings, including one P1Reviewed at First, a correction to the PR bodyThe description says the base used a bare Can two daemons still race to delete each other's pid record?No. I enumerated every deletion site and none can remove another daemon's record: the publish P1 — the PR does not deliver its stated reader contract
Measured with four real OS processes hammering So the harm this PR's own comment names — "a torn record that, for a retired protocol version, nothing ever heals … permanently vetoing prune of that version" — is still reachable on this branch. It closes the window for one publisher and leaves the sibling open. A fix for this is being prepared as a commit on top of this head; it will not rebase the branch, since #16979 is stacked here. The declined CodeRabbit thread — right conclusion, wrong evidenceRe-derived from the code, claim by claim. CodeRabbit's proposed changes were correctly rejected: claim names really are invocation-unique ( But three of the four supporting claims do not hold up, and the thread should be reopened with a corrected record:
Also: the Windows sharing-violation test at Composition with #16900They compose; neither deletes the other's record. Zero file overlap. Verified on a composed tree (main + #16924 + #16900) with a deterministic interleaving test against the real Follow-ups, not fixed here
Verdict: patch, not supersede. The idiom is right, the Windows real-filesystem contract test is above the bar, and superseding would force #16979 to be rewritten. Not verified: no execution on Windows — the Windows reasoning is from libuv semantics only. |
…g copy publishDaemonPidFile is not the only writer of the canonical record. restoreClaimedDaemonArtifact republishes it with copyFileSync, which creates the entry and only then streams into it, so a concurrent reader can catch the record half-written — exactly the torn record the atomic publish exists to prevent, and the one nothing heals for a retired protocol version. It is reached from replaceDaemonPidFile when a publish loses the race and from every content-gated unlink, i.e. the contended and stale-kill paths. Publish the restore by linkSync instead. link is exclusive, so a restore still never overwrites a newer canonical replacement; that invariant is preserved rather than traded for atomicity. A non-EEXIST link failure degrades to the existing exclusive copy so volumes without hard links (exFAT, network mounts) keep a restorable record. Measured with four contending processes and a reader doing what killStaleDaemon does: torn reads 1366/1121/594 before, 0/0/0 after.
P1 fixed — head
|
CI note on
|
|
Note GitHub couldn't provide a complete incremental comparison for this pull request, so CodeRabbit is performing a full review instead. This review may take a little longer. |
There was a problem hiding this comment.
Actionable comments posted: 3
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro Plus
Run ID: 2bf26cf3-a460-4245-8470-d55aee1285af
📒 Files selected for processing (9)
.github/workflows/pr.ymlconfig/scripts/pr-code-change-scope.mjssrc/main/daemon/daemon-artifact-restore-atomicity.test.tssrc/main/daemon/daemon-pid-publish-atomicity.test.tssrc/main/daemon/daemon-pid-publish-claim-reap.test.tssrc/main/daemon/daemon-pid-publish-claim-reap.tssrc/main/daemon/daemon-pid-publish-disk-contract.test.tssrc/main/daemon/daemon-spawner.test.tssrc/main/daemon/daemon-spawner.ts
🚧 Files skipped from review as they are similar to previous changes (4)
- src/main/daemon/daemon-pid-publish-disk-contract.test.ts
- config/scripts/pr-code-change-scope.mjs
- src/main/daemon/daemon-pid-publish-atomicity.test.ts
- .github/workflows/pr.yml
Included review availability: Your plan provides up to 10 included reviews per hour; 3 remain after this review.
Attribution of the red shard — not caused by this PRUpdated the branch onto current
Evidence it was never attributable to this diff:
Root cause is a main-owned fragile test, not a product bug. Remaining red:
|
| test | reachability | today's tally |
|---|---|---|
src/main/windows/windows-host-job.win32.test.ts |
imports only node builtins + vitest — reaches no src/ code |
failed on 3 different branches (this one, coercion-daemon-inspect-r2, identity-slice1a); passed in 4 other runs |
src/main/browser/browser-route-dns-prefetch.electron.test.ts |
4-file import closure, no daemon code | 1 occurrence in 7 runs sampled; no cross-branch corroboration yet |
windows-host-job asserts teardown after a fixed sleep(3_000) with no deadline poll, so it is a race by construction; duration is ~7.1 s whether it passes or fails, so a timeout bump would not be the right fix either.
Not verified
No Windows host was available to me, so the Windows leg was not validated locally — the table above is from CI logs only. I made no code change; all gates here are CI's.
The directory's ownership rules ban sweepers absolutely ("No actor removes a
name it did not create"), scoped in prose to the socket path but read by every
agent working anywhere in src/main/daemon. This PR adds a sweeper without
amending them, so review keeps re-raising "remove the reaper" — correctly, from
the doc as written.
Scope the traps to every canonical name, and record the exception with the two
properties it actually rests on: publish scratch is never an actor's only copy,
and it is deleted only on an ESRCH-proven-dead owner. Sweeping the bind name or
.swap-/.hold- claims stays banned, since those can be an only copy.
ELI5
When Orca's terminal daemon starts, it writes a small note (
daemon-vN.pid) saying "I'm the daemon, here's my process id." Before this PR, it wrote that note directly into its final location, character by character. If the computer lost power or the process was killed halfway through, a half-written note was left behind — and Orca can't read half a note.Now the daemon writes the complete note on a scratch card first, makes sure it's fully on disk, and then slides it into place in one indivisible move. Anyone who looks either sees the whole note or no note — never half of one.
Why a torn note is not a minor glitch
daemon-stale-kill.tsheals unreadable records only for the current protocol version. Once a protocol version retires, nothing ever reads, rewrites, or deletes itsdaemon-vN.pidagain — so a record torn years ago becomes a permanent veto that silently disables pruning of that superseded daemon version, leaking roughly 260MB per version, forever. #16908 adds after-the-fact recovery (quarantine) for records that are already corrupt in the field; this PR removes the way new ones get created. Both are needed: this PR deliberately does not touch #16908's quarantine/recovery logic, and none of its recovery paths become unreachable — old builds' torn records still exist in the field, and the degraded no-hardlink fallback here (below) intentionally retains today's behavior.User-facing before/after
When would a user hit this? Their machine loses power, kernel panics, or force-kills the daemon (task manager, OOM,
kill -9) in the few milliseconds the daemon is writing its pid record at startup. Rare per-start, but every Orca install starts a daemon on every launch, and one unlucky interruption is permanent.daemon-vN.pidleft at the canonical pathHow
publishDaemonPidFilenow: writes the full record to a per-pid/per-uuid claim path (daemon-vN.pid.publish-<pid>-<uuid>, mode 0o600, exclusive) → fsyncs it (so power loss can't make the name durable without the bytes) → hard-links it to the canonical path → unlinks the claim.Design points reviewers will care about:
EEXISTwhen a record already exists (replaceDaemonPidFile's conflict detection, stale-kill's "leaving it in place fails the next daemon's exclusive publish", endpoint-ownership's duplicate fencing). Rename silently replaces the destination and would erase that contract. Link is atomic and exclusive on macOS, Linux, and Windows/NTFS.EEXIST, which callers already treat as an ownership conflict, even while another process holds the record open. A new real-filesystem test (daemon-pid-publish-disk-contract.test.ts) pins exactly that and is wired into thepackage (windows)CI job so it runs on a real NTFS runner (that's the reason for the smallpr.yml+pr-code-change-scope.mjsadditions).DaemonSpawner.ensureRunning) — gated on the owner pid probing ESRCH (provably dead), never on age, and matching any protocol version so retired-version scratch can't accumulate. Publish scratch is safe to reap because its content was never canonical; the reaper deliberately never touches.swap-/.hold-claims, which can hold the only copy of a live record.daemon-pid-identity.ts,daemon-bundle-staleness.ts,daemon-stale-kill.ts,daemon-init.ts#pidRecordMatchesEndpoint): all parse-or-null and fail open; with atomic publish none can observe partial content anymore. The pre-existing ENOENT window inreplaceDaemonPidFile(claim-away → republish) is unchanged and reads as "no record", which every reader already treats safely.Failing-first proof
The torn-write test was written and run against unmodified
origin/main(f96dfd5) before the fix:Ablation (each production hunk reverted in isolation → suite red)
finallyunlink)Plus: full
src/main/daemon/suite green (149 files, 1691 tests),pnpm tcclean, changed-code quality gate clean, and the released-sweeper pin test now also covers the new.publish-namespace.