Skip to content

fix(daemon): make pid-record publish atomic via claim-then-link - #16924

Open
brennanb2025 wants to merge 4 commits into
mainfrom
brennanb2025/daemon-pid-atomic-publish-r1
Open

brennanb2025 wants to merge 4 commits into
mainfrom
brennanb2025/daemon-pid-atomic-publish-r1

Conversation

@brennanb2025

@brennanb2025 brennanb2025 commented Aug 28, 2026 •

Copy link
Copy Markdown
Contributor
Files Added Deleted Net
Test 5 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​480 $\color{#cf222e}{\Huge{\mathbf{−}}}$​1 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​479
Prod 5 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​165 $\color{#cf222e}{\Huge{\mathbf{−}}}$​18 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​147

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.ts heals unreadable records only for the current protocol version. Once a protocol version retires, nothing ever reads, rewrites, or deletes its daemon-vN.pid again — 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.

Before After
Crash/power loss mid-publish Torn daemon-vN.pid left at the canonical path Canonical path holds a complete record or nothing
That version later retires Corrupt record permanently vetoes pruning → ~260MB leaked per superseded version, forever Nothing to veto; pruning proceeds
Concurrent reader during publish Could observe a partially-written record Sees the old state or the complete new record
Second daemon racing to publish Fails with EEXIST (ownership conflict) Unchanged — hard-link publication is atomic and exclusive

How

publishDaemonPidFile now: 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:

  • Why link, not rename: three call sites depend on publish failing with EEXIST when 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.
  • Windows is load-bearing: renaming onto a record held open by another process (AV, indexer, a reader) fails with EPERM/EACCES on Windows — exactly the daemon case. Link-to-a-nonexistent-name never renames onto anything; when the destination exists the failure is 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 the package (windows) CI job so it runs on a real NTFS runner (that's the reason for the small pr.yml + pr-code-change-scope.mjs additions).
  • Degraded fallback: filesystems that refuse hard links get the previous exclusive direct write — identical to today's shipped behavior, so no topology loses a working daemon in exchange for atomicity.
  • Claim cleanup: the claim is unlinked on every in-process path (success, EEXIST, mid-write failure). Claims orphaned by a crash are reaped at the daemon launch funnel (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.
  • Mode/ownership: 0o600 is applied at claim creation and carried by the link (same inode). Windows keeps today's semantics (mode is a no-op there, ACLs inherit from the runtime dir — unchanged).
  • Readers audited for partial-read windows (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 in replaceDaemonPidFile (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:

FAIL  daemon-pid-publish-atomicity.test.ts
  × never leaves a torn record at the canonical path when the publisher dies mid-write
    AssertionError: expected null not to be null   ← reader parsed the torn record to null
  × flushes the record to disk before it becomes visible at the canonical path
    AssertionError: expected -1 to be greater than or equal to 0   ← no fsync existed

Ablation (each production hunk reverted in isolation → suite red)

Reverted hunk Red tests
claim+link publish → direct write (main's body) 2 (torn record; fsync-before-visible)
fsync of the claim 1
claim cleanup (finally unlink) 8
no-hardlink degraded fallback 2
launch-funnel reap call 1
reaper's proven-dead fence 1

Plus: full src/main/daemon/ suite green (149 files, 1691 tests), pnpm tc clean, changed-code quality gate clean, and the released-sweeper pin test now also covers the new .publish- namespace.

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.
@brennanb2025

Copy link
Copy Markdown
Contributor Author

Pushed and verified via git ls-remote: branch head is exactly e0b44cdd6f421681f71a15b9636cd5606b219fd6 (single commit off origin/main f96dfd5). Failing-first proof, Windows-semantics test wiring, and the ablation table are in the PR description.

@coderabbitai

coderabbitai Bot commented Aug 28, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 73cbce1c-a9fc-48f7-b7c5-5ad9e33238c0

📥 Commits

Reviewing files that changed from the base of the PR and between bada62d and 3e46ca9.

📒 Files selected for processing (1)
  • src/main/daemon/AGENTS.md

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


📝 Walkthrough

Walkthrough

The 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 3e46c

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)

Check name Status Explanation Resolution
Description check ⚠️ Warning 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 sec… 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 …
Docstring Coverage ⚠️ Warning 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… Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (3 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly identifies the main change: atomic daemon PID-record publication using a claim-then-link workflow.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Full details: Description check

Explanation

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 Coverage

Explanation

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

  • Fix all pre-merge checks with AI

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: Pro Plus

Run ID: deb6c2e4-a6cd-4c25-858c-c823da0962b7

📥 Commits

Reviewing files that changed from the base of the PR and between ebe6b55 and e0b44cd.

📒 Files selected for processing (8)
  • .github/workflows/pr.yml
  • config/scripts/pr-code-change-scope.mjs
  • src/main/daemon/daemon-pid-publish-atomicity.test.ts
  • src/main/daemon/daemon-pid-publish-claim-reap.test.ts
  • src/main/daemon/daemon-pid-publish-claim-reap.ts
  • src/main/daemon/daemon-pid-publish-disk-contract.test.ts
  • src/main/daemon/daemon-spawner.test.ts
  • src/main/daemon/daemon-spawner.ts

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

@brennanb2025

Copy link
Copy Markdown
Contributor Author

Independent adversarial review — head e0b44cdd6f421681f71a15b9636cd5606b219fd6

Sole reviewer; nothing below is taken from the PR description — every claim was re-run or re-derived from this SHA. Verdict at the end.

1. Failing-first re-run (pristine main)

Reproduced. Checked out base f96dfd5810, dropped only daemon-pid-publish-atomicity.test.ts on top: 2 failed / 5 passed, with exactly the claimed assertions — expected null not to be null (reader parsed the torn record to null) and expected -1 to be greater than or equal to 0 (no fsync event existed).

2. Ablation matrix re-run (each production hunk reverted in isolation, all 37 new+spawner tests)

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:

  1. 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 returns false. 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.
  2. 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.
  3. DaemonEndpointLifecycle.publish (daemon-endpoint-lifecycle.ts:73-84) via publishEndpointOwnership (daemon-entry.ts:277): a duplicate daemon must throw and refuse to serve; the error path deliberately skips unlinkOwnedDaemonPidFile when publishedOwnership is 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-on windows-2022) executed daemon-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.mjs WINDOWS_PACKAGE_TESTS) got the file, and editing them force-ran all jobs on this PR.
  • Degrade path on Windows: the wx direct write is byte-for-byte the pre-PR shipped path, EEXIST semantics intact.
  • ReFS / network mounts / overlay volumes: where CreateHardLink/link is 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.ts is not in the Windows package list, so process.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. One console.warn would 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.

@brennanb2025

Copy link
Copy Markdown
Contributor Author

Independent P2-closure pass (dispatched worker): the three review P2s from comment 5447786752 are closed in follow-up PR #16979, head f6e57229fa7ff57e71e0669a7e9d1acad9f7907e (verified via git ls-remote), stacked on this PR's branch at e0b44cdd6f421681f71a15b9636cd5606b219fd6.

  • P2a: reap comment corrected — deleting a live claim degrades that publish to the non-atomic exclusive write (it does not fail it).
  • P2b: no-hardlink degrade now warns with the errno; warn pinned failing-first in daemon-pid-publish-atomicity.test.ts (atomic path asserts no warn).
  • P2c: daemon-pid-publish-claim-reap.test.ts (real fs + real processes: keeps live-owner claim, reaps dead-owner claim) wired into the package (windows) job via BOTH pr.yml and WINDOWS_PACKAGE_TESTS in config/scripts/pr-code-change-scope.mjs; those edits are GLOBAL_FORCE so fix(daemon): close #16924 review P2s — degrade warn, reap comment, Windows claim-reap CI #16979's CI executes it on windows-2022.

Link-vs-rename design untouched. #16979 needs manual retarget onto main after this PR merges.

@brennanb2025

Copy link
Copy Markdown
Contributor Author

Review — findings, including one P1

Reviewed at e0b44cdd6f, rebased onto current origin/main (94e7586665) before judging anything. The rebase is clean: merge-tree exit 0, main touched src/main/daemon/ only with a formatting commit (c4b39295c1) since the merge base, and the merged pr.yml / pr-code-change-scope.mjs preserve both this PR's added test-list entry and main's NATIVE_CACHE_FILES restructure. On the rebased tree: tsc exit 0, oxlint clean, src/main/daemon/ 1691 passed / 3 skipped.

First, a correction to the PR body

The description says the base used a bare writeFileSync. It did not — it was writeFileSync(pidPath, serializeDaemonPidFile(pidFile), { mode: 0o600, flag: 'wx' }), and wx is O_CREAT|O_EXCL. Mutual exclusion between two daemons already worked. The defects this PR actually fixes are the torn-read window and the missing fsync. "Two daemons could clobber each other's record" is not accurate and should come out of the body before merge, because it changes how a reviewer weighs the risk.

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 finally unlinks only its own invocation-unique .publish-<pid>-<uuid> name; claimAndUnlinkOwnedFile claims the canonical entry with an atomic renameSync before inspecting it, so a replacement installed afterwards sits at the canonical path and cannot be unlinked; and restoreClaimedDaemonArtifact restores exclusively, so it cannot overwrite a newer record. A .publish- claim that has already been linked is a second hard link to the same inode, so deleting it cannot destroy the canonical name — a genuinely good property of choosing link over rename.

P1 — the PR does not deliver its stated reader contract

publishDaemonPidFile is not the only publisher of the canonical name. restoreClaimedDaemonArtifact republishes it with copyFileSync(source, target, COPYFILE_EXCL) — a create-then-copy that is observable half-written — and it is reached from replaceDaemonPidFile (publish lost the race) and from claimAndUnlinkOwnedFile (stale-kill / shutdown), i.e. exactly the contended paths.

Measured with four real OS processes hammering replaceDaemonPidFile on one runtime dir plus an observer doing what killStaleDaemon does. torn = canonical record present and unparseable:

PR tree:                          torn: 1366 / 1121 / 594   (three 4s runs)
same rig, restore uses linkSync:  torn: 0

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 evidence

Re-derived from the code, claim by claim. CodeRabbit's proposed changes were correctly rejected: claim names really are invocation-unique (${pidPath}.publish-${process.pid}-${randomUUID()}), so the finally can only ever unlink this call's own scratch; the EEXIST in question is on the canonical linkSync, not on claim creation, which is what CodeRabbit misread; and removing the reaper would let crashed publishers' claims accumulate forever. "Track successful claim creation" would change nothing observable.

But three of the four supporting claims do not hold up, and the thread should be reopened with a corrected record:

  • "Test-pinned" — no, for three of the named properties. Replacing randomUUID() with a constant: 37/37 still pass. Treating any kill error as death (not just ESRCH): 37/37 still pass. Dropping the own-pid exclusion: 37/37 still pass — that last one is dead code anyway, since process.kill(process.pid, 0) always succeeds, so the test named "…or by this process" passes for a different reason than its name implies.
  • "The reaper is ESRCH-fenced, so a proven-dead owner cannot be mid-publish" — the fence does have a probe→rmSync TOCTOU window. What actually makes it safe is the uuid in claim 1, not the fence. Severity is bounded: if a live claim is deleted, linkSync fails ENOENT (not EEXIST) and the degrade branch still publishes.
  • "Runs on windows-2022 in CI" — not for this PR. Only daemon-pid-publish-disk-contract.test.ts is wired into the Windows job here. daemon-pid-publish-claim-reap.test.ts, the file the decline cites as its evidence, is added to Windows by fix(daemon): close #16924 review P2s — degrade warn, reap comment, Windows claim-reap CI #16979 — which is stacked behind this PR.

Also: the Windows sharing-violation test at daemon-pid-publish-disk-contract.test.ts:78 uses openSync(pidPath, 'r'), but libuv's Windows fs__open always requests FILE_SHARE_DELETE, so it cannot reproduce the AV/indexer holder its comment cites. It is still a valid link-EEXIST contract test; it is not the sharing-violation test it claims to be.

Composition with #16900

They 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 reclaimLegacyDaemonOwnershipFiles and the real replaceDaemonPidFile, plus an ablation control — deleting #16900's if (currentRecordText !== provenRecordText) return correctly turns the key case red, so the gate is not vacuously passing. #16924's widened absent-window lands in #16900's catch { return }, which preserves. The reaper's anchored daemon-v\d+\.pid\.publish- pattern never matches a legacy canonical name.

Follow-ups, not fixed here

  • Absent-record window widened ~170x per replace (fsync now sits inside the rename interval): ~7 → ~1180 absent reads per successful replace. Every third-party reader lands in the "no record" branch far more often. Both handle it in the safe direction, so no correctness break — but it should be a conscious decision.
  • Swap-claim leak rate is ~3–5x worse, and the reaper deliberately excludes .swap-/.hold- names, so nothing ever reclaims them. publish-claims-leaked was 0 in every non-crash run. Absolute volume is tiny in production, but it suggests the reaper was scoped to the claim family that does not actually leak.
  • Mixed-version: neither an old (wx) nor a new (link) build clobbers the other — publishThrew: 0 across a four-process mixed run, so no migration is needed. But old builds still write non-atomically and there is no healing path for a torn record of a retired protocol version.
  • mode: 0o600 is a no-op on Windows, so the record publishes under inherited directory ACLs; secure-file.ts has applySecurePathRestriction for this. Pre-existing, not a regression.
  • Consider bestEffortFsyncDirectorySync (already in src/shared/secure-file.ts, beside the fsyncFileSync this PR imports) after the link, or state that omitting it is deliberate — losing the name is the safe direction, losing the bytes is not.

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.
@brennanb2025

Copy link
Copy Markdown
Contributor Author

P1 fixed — head c7eb8e3f06

restoreClaimedDaemonArtifact now publishes the restored record by hard link, degrading to the exclusive copy only when the filesystem refuses hard links. The replacement-preserving invariant is preserved rather than traded away: linkSync is exclusive exactly as COPYFILE_EXCL was, so a restore still cannot overwrite a newer canonical replacement — it simply no longer creates the entry and then streams into it, which was the observable torn window.

I verified this independently rather than taking the fix on trust:

fixed tree   — daemon-artifact-restore-atomicity.test.ts   7 passed (7)

ablated (only daemon-spawner.ts reverted to e0b44cdd6f):
  × never leaves a torn canonical record when the publisher dies part-way
      AssertionError: expected null not to be null
  × does not retry through the copy when the link already proved a replacement exists
      AssertionError: expected "vi.fn()" to not be called at all, but actually been called 1 times
   Tests  2 failed | 5 passed (7)

full src/main/daemon/ on the fixed tree   150 passed | 2 skipped (152)
                                          1698 passed | 3 skipped (1701)

1698 vs 1691 before — exactly the seven added tests, no regression. The five that stay green under ablation are the degrade and replacement-preserving cases, which existed before and are declared as preservation tests.

Each branch is pinned separately rather than as a bundle: torn-record, parseable-restore, never-overwrite-a-newer-replacement, no-copy-retry-after-EEXIST, replacement-that-then-vanished, hard-link-unsupported degrade, and degraded-path semantics.

Still open before merge

  1. Pin the uuid gate. Replacing randomUUID() with a constant currently leaves 37/37 green, yet the uuid is the entire fence on the reaper's probe→rmSync TOCTOU.
  2. Pin ESRCH-vs-EPERM. Treating any kill error as death also leaves 37/37 green, so nothing stops a future edit from reaping a live claim owned by another user.
  3. Resolve the own-pid branch. process.kill(process.pid, 0) always succeeds, so the exclusion is dead code and the test named "…or by this process" passes for a different reason than its name implies — delete the branch or make the assertion real.
  4. Correct the CodeRabbit thread record. Its closing appeal to windows-2022 coverage does not hold for this PR: only daemon-pid-publish-disk-contract.test.ts is wired into the Windows job here; daemon-pid-publish-claim-reap.test.ts is added by fix(daemon): close #16924 review P2s — degrade warn, reap comment, Windows claim-reap CI #16979, which is stacked behind this one.
  5. Fix the disk-contract comment at daemon-pid-publish-disk-contract.test.ts:78 — openSync(pidPath, 'r') cannot reproduce the AV/indexer holder it cites, because libuv always opens with FILE_SHARE_DELETE. The test is a valid link-EEXIST contract; it is not the sharing-violation contract it claims to be.

Worth a conscious decision, not fixes: the absent-record window is ~170x wider per replace, and the .swap- claim leak rate is 3–5x worse while the new reaper deliberately excludes that family — publish-claims-leaked was 0 in every non-crash run, which suggests the reaper targets the claim family that does not actually leak.

Not verified: nothing was executed on Windows; all Windows reasoning is from libuv/Win32 semantics. No exotic-filesystem run. Power-loss durability is untested — the fsync test asserts syscall order via a mock.

@brennanb2025

Copy link
Copy Markdown
Contributor Author

CI note on c7eb8e3f06 — one red shard, not attributable to this PR, but not a known flake either

PR Checks is failing: test / tests node 24 6/8, and verify only as the aggregate. One test out of the shard:

src/main/updater.startup-scheduling.test.ts
  > reschedules the next automatic check 24 hours after finding an available update
AssertionError: expected "vi.fn()" to be called 1 times, but got 2 times

Being precise about its status, because the tempting summary is wrong in both directions:

  • It is not pre-existing on this branch. PR Checks on the previous head e0b44cdd6f was a success, and shard 6/8 there was green. This is the first failure observed here, so it should not be waved through as "the usual flake."
  • It is also not attributable to the change. This PR touches only src/main/daemon/; the updater test neither imports nor is imported by anything in it. It passes locally in isolation (10/10), and still passes when run together with the main-process test files that newly joined shard 6/8 (60/60).

The likely mechanism is shard re-partitioning rather than anything in the diff. Diffing the shard's file list between the green and red runs, membership moved by 20 files (847 → 857; 5 out, 15 in) — partly because the new test file shifts the global partition, and partly because main advanced between the two merge refs. That makes a co-location- or order-sensitive fake-timer assertion the most plausible cause, but I could not reproduce it locally, so I am reporting it as unproven rather than asserting it.

Recommended resolution: gh pr update-branch, then a fresh run. Note that gh run rerun cannot settle this — it re-runs against the original attempt's merge base, so it would pin the same stale merge ref rather than picking up main. An update-branch also satisfies the separate readiness finding that this branch's CI last ran against a merge base 45 commits behind.

I have deliberately not run update-branch myself: it moves the branch head, and #16979 is stacked on this branch, so the merge ordering is yours to decide. The stack is currently intact — git merge-tree --write-tree c7eb8e3f06 f6e57229fa exits 0 and #16979 reports MERGEABLE.

@coderabbitai

coderabbitai Bot commented Aug 28, 2026

Copy link
Copy Markdown
Contributor

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.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 3


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 2bf26cf3-a460-4245-8470-d55aee1285af

📥 Commits

Reviewing files that changed from the base of the PR and between 94e7586 and bada62d.

📒 Files selected for processing (9)
  • .github/workflows/pr.yml
  • config/scripts/pr-code-change-scope.mjs
  • src/main/daemon/daemon-artifact-restore-atomicity.test.ts
  • src/main/daemon/daemon-pid-publish-atomicity.test.ts
  • src/main/daemon/daemon-pid-publish-claim-reap.test.ts
  • src/main/daemon/daemon-pid-publish-claim-reap.ts
  • src/main/daemon/daemon-pid-publish-disk-contract.test.ts
  • src/main/daemon/daemon-spawner.test.ts
  • src/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.

Comment thread src/main/daemon/daemon-spawner.ts Resolved
Comment thread src/main/daemon/daemon-spawner.ts Resolved
@brennanb2025

Copy link
Copy Markdown
Contributor Author

Attribution of the red shard — not caused by this PR

Updated the branch onto current main (was 45 commits behind). New head bada62de95; the PR's own 7 files are blob-identical to c7eb8e3f06, so the hard-link publish fix is unchanged.

test / tests node 24 6/8 is now green. The previous red was src/main/updater.startup-scheduling.test.ts:243 — "reschedules the next automatic check 24 hours after finding an available update", expected "vi.fn()" to be called 1 times, but got 2 times. verify was only the aggregate gate mirroring test, not an independent failure.

Evidence it was never attributable to this diff:

  1. The failing test cannot execute any code this PR changes. It does vi.mock('./ipc/pty', factory), which severs the only path from updater.ts into src/main/daemon/. Verified with a Vite transform probe that appends a load-marker to daemon-spawner.ts: running daemon-spawner.test.ts (positive control) writes the marker; running updater.startup-scheduling.test.ts does not. The module is never evaluated.
  2. Shard composition is unchanged. Reimplementing vitest 4.1.5's BaseSequencer.shard (sha1-of-path, sorted, sliced), shard 6/8 membership is byte-identical between origin/main and this PR's merge tree — 865 files each, empty diff. The model reproduces CI exactly: 863 of the computed files appear in the job log, matching CI's reported 863. None of the 4 added test files land in shard 6 (they go to 3, 3, 8, 1).
  3. The same assertion failed on another branch. Run 33176931539 (pid-publish-p2-closures-r1, head 9b4e9bf17b) failed the identical test at the identical line with the identical message, in a shard of a different size (853 files). That head does not contain c7eb8e3f06.
  4. Same shard, same code, red → green. This run re-tested the identical 865-file shard-6 composition with the same production diff and passed.

Root cause is a main-owned fragile test, not a product bug. vi.waitFor under fake timers advances fake time in 50 ms steps, and UPDATE_CHECK_SILENT_SETTLE_DELAY_MS is exactly 1_000 (src/main/updater.ts:118). When the poll count varies under load, the silent-settle timer can fire while the attempt is still active and re-arm a 1-hour retry (updater.ts:553) instead of the 24-hour path (updater.ts:558); that retry then fires inside the test's 23h59m advance. The test's own next assertion was already softened for exactly this reason — line 243 was left exact. I am flagging this rather than patching it: it belongs to main, not to this PR, and I could not reproduce it locally (75 runs green: 25 solo, 48 under 8-way contention, 2 full --shard=6/8), so I cannot prove a fix.

Remaining red: package (windows) — also not this PR

Two failures, neither of which imports anything this PR touches:

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.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant