Repository navigation
fix(runtime): reclaim temp files orphaned by interrupted mobile store writes - #24049
Conversation
… writes The mobile dismissal store and device registry write through writeSecureJsonFile, which stages a `<file>.<pid>.<ts>.<hex>.tmp` beside the target and renames it after the ACL is applied. When the process dies or is killed between those steps (for example while icacls hangs, stablyai#20497), the temp is never removed and accumulates in userData. Sweep temps older than a day, skipping this process's own, when each store opens, reusing removeStaleDurableWriteTempFiles like the other stores that already reclaim their orphaned writes.
|
|
Navigate logical layers of code changes, visualize relationships, and explore their blast radius. 📝 WalkthroughWalkthroughDeviceRegistry and MobileNotificationDismissalStore now start cleanup of stale durable-write temporary files during construction, using a minimum age of 24 hours. A parameterized test checks that opening either store removes an old matching file and retains a recent matching file. Priority: ⬇️ Low Merge Risk: 🔵 Low · up to A live store write paused for over 24 hours can fail when startup cleanup removes its temporary file. This rare, localized risk is low, but protecting live writers is advisable before merging. Architecture SummaryArchitecture risk: 🔵 Low · up to The change affects 1 system. Changed systems: Architecture concerns Review detailsSystems and components
Before / after behavior
🚥 Pre-merge checks | ✅ 5✅ Passed checks (5 passed)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
There was a problem hiding this comment.
ℹ️ No critical issues — one small test-robustness suggestion inline.
Reviewed changes
- Reclaim orphaned secure-write temps on construct —
DeviceRegistryandMobileNotificationDismissalStorenow fire-and-forgetremoveStaleDurableWriteTempFiles(path, { minimumAgeMs: 24h })in their constructors, matching the sweep the stats, sidecar, usage-cache, and profile stores already run. - New coverage —
mobile-store-orphaned-temp-cleanup.test.tsasserts a two-day-old<file>.<pid>.<ts>.<hex>.tmpis removed on open while a fresh temp is kept, for both stores.
I verified the matcher lines up: writeSecureFile stages <targetPath>.<pid>.<timestamp>.<hex>.tmp (src/shared/secure-file.ts:135), which satisfies removeStaleDurableWriteTempFiles's prefix (basename + '.'), .tmp suffix, and own-pid skip (src/main/durable-file-write.ts:178), and both stores write through writeSecureJsonFile. The new test passes and pnpm tc:node plus the surrounding dismissal/pairing/push suites are green.
DeepSeek Flash (free via Pullfrog for OSS) | 𝕏
A hardcoded PID could collide with the test worker's own PID, which the sweep deliberately skips, making the test time out.
There was a problem hiding this comment.
✅ No new issues found.
Reviewed changes
The only change since the prior pullfrog review (d2bd1a7) is in the new test, addressing the one earlier inline suggestion.
- Test fixture PIDs derived from
process.pid— the simulated other-process temps now useprocess.pid + 1/process.pid + 2instead of hardcoded4242/4343, removing the possible (if unlikely) collision where the runner's own pid made the sweep treat the "orphan" as an own-process temp and time the test out. The matcher and age policy are otherwise unchanged.
DeepSeek Flash (free via Pullfrog for OSS) | 𝕏
There was a problem hiding this comment.
Caution
Some comments are outside the diff and can’t be posted inline due to GitHub limitations.
🟡 Minor · Protect temporary files owned by live processes. · device-registry.ts:76-78
src/main/runtime/device-registry.ts:76-78
🩺 Stability & Availability | 🟡 Minor | ⚡ Quick winProtect temporary files owned by live processes.
removeStaleDurableWriteTempFilesskips only this process's PID. A POSIX process can pause duringwriteSecureFilebeforerenameSyncfor more than 24 hours. The cleanup can then remove its temporary path, and the resumed write fails withENOENT. Add an owner-PID liveness check in this shared helper so both stores receive the protection.Suggested fix
+function isProcessAlive(pid: number): boolean { + try { + process.kill(pid, 0) + return true + } catch (error) { + return (error as NodeJS.ErrnoException).code === 'EPERM' + } +} + /** * Sweep temp files orphaned by a death between write and rename — for multi-MB payloads they would * otherwise accumulate forever. Callers can require a minimum age to spare another live instance's @@ if (options.minimumAgeMs) { const info = await stat(path).catch(() => null) if (!info || Date.now() - info.mtimeMs < options.minimumAgeMs) { return } } + const ownerPid = /^(\d+)\./.exec(name.slice(prefix.length))?.[1] + if (ownerPid && isProcessAlive(Number(ownerPid))) { + return + } await rm(path, { force: true }).catch(() => {})
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Advanced
Run ID: ba22775f-cd80-44bd-986f-3701b412f74c
📒 Files selected for processing (1)
src/main/runtime/mobile-store-orphaned-temp-cleanup.test.ts
Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 8 remain after this review.
There was a problem hiding this comment.
✅ No new issues found.
Reviewed changes
The production stores are byte-identical since the prior pullfrog review (83e4e9e); the delta is the merge of main plus test-only hardening in mobile-store-orphaned-temp-cleanup.test.ts.
- Coverage for preserved files — the reclaim test now writes an own-pid temp, the other store's temp, a
-backup-suffixed name, and a.tmp.backupname, ages them two days, and asserts they survive byte-for-byte ('[]') while the >24h foreign orphan is removed. - New pending-cleanup test —
%s loads while startup cleanup is still pendingspiesremoveStaleDurableWriteTempFileswith an unresolved promise and verifies the constructor returns a usable store (listDevices()/reconcile([])both[]), proving loading is not blocked by the fire-and-forget sweep. - Spy cleanup —
vi.restoreAllMocks()added toafterEachso the module spy cannot leak between parameterized cases. - Merge —
mainmerged into the branch; the three PR files are unchanged by it.
I ran ORCA_BACKGROUND_LAUNCH=1 pnpm test src/main/runtime/mobile-store-orphaned-temp-cleanup.test.ts this run: 4 tests passed. The prior inline suggestion (derive simulated PIDs from process.pid) is addressed and its thread is resolved.
deepseek-v4.1-flash (free via Pullfrog for OSS) | 𝕏
|
Final merge review at Reuse the existing stale temporary-file cleanup policy when each mobile store opens. Merge risk and retained limits: Low–moderate: a foreign writer paused over 24 hours can lose its temporary file and fail its resumed rename. Contributor authors and existing co-author credit will be preserved explicitly in the squash commit. |

ELI5
A crash while saving mobile pairing or dismissed-alert data can leave a temporary copy behind. Orca now removes those copies once they are at least a day old when the corresponding store next opens.
What Changed
Before,
orca-devices.json.*.tmpandmobile-notification-dismissals.json.*.tmpcould remain in the desktop user-data directory indefinitely. Each store constructor now starts the existingremoveStaleDurableWriteTempFilessweep with a 24-hour minimum age, before continuing to load the store.The sweep checks only that store filename followed by
.and ending in.tmp, uses the file's modification time, skips this process's temporary files at every age, and keeps younger files from other processes. It runs asynchronously and ignores filesystem cleanup errors. Pairing data, dismissal data, permissions, and file formats are unchanged.Why
Reuse the same cleanup policy already used by the sidecar, stats, usage-cache, and profile stores. This avoids a second sweep implementation or changing every secure-file writer for two stores with demonstrated leftover files.
This retains both original LDH1103 commits (
d2bd1a77978072034c5b300ef57efb7c29a79edband83e4e9e56046648444f4dcd72caf8920128fe3be) and adds maintainer validation and safety coverage. Compared with LDH1103's #24029: that PR changes dismissal writes to run asynchronously; this one adds startup cleanup. The constructor and temp-file naming remain compatible by source inspection; the two PRs were not executed together.Linked Issue
Related to #20497: interrupted writes explain the leftovers. This PR addresses local leftover files only; it does not fix the broader hang or remote execution and must not close that issue.
Visual Proof
N/A: no rendered UI change. Filesystem snapshots from disposable directories provide the internal cleanup before/after evidence instead:
These are uploaded attachments, absent from the PR diff. No real user-data path, running app, setting, or credential was changed.
Testing
Independently reproduced before any production edit on main
efbf651c7bb2eec778daf1844f8228e70809ec9f:ORCA_BACKGROUND_LAUNCH=1 pnpm test src/main/runtime/mobile-store-orphaned-temp-cleanup.test.tsfailed both original constructor cases withAssertionError: expected true to be falsebecause the stale file still existed.After the fix, the regression passes and additionally checks the retained-file cases above, modification time rather than filename timestamp, and usable store loading while cleanup is pending. Scoped pairing, dismissal read-failure, runtime-metadata, device-revocation, push, durable-file, and secure-file suites: 28 files / 208 tests passed.
Local platform: macOS arm64, Node 24.20.0. Every test/proof run used
ORCA_BACKGROUND_LAUNCH=1and isolated fixtures. Local checks passed:pnpm tc:nodepnpm exec oxfmt --checkon the three changed filespnpm exec oxlinton the three changed filespnpm run check:code-quality:changed -- efbf651c7bb2eec778daf1844f8228e70809ec9f(zero findings)CI is green at published head
2837d281f6a626688f0004c3405d91ccab4805c6: PR Checks passed static analysis, typechecking, five full Node 24 unit shards, relay integration, and Linux/Windows packaging. The required repository guard andverifyboth passed. Unit shard 2 ran all four new regression cases successfully on Ubuntu 24.04 ARM64, withORCA_BACKGROUND_LAUNCH=1. Linux packaging ran on Ubuntu 24.04; Windows packaging ran on Windows Server 2022.Headless persistence CI passed 930 tests in 90 files on Ubuntu 22.04, with 31 tests/two files skipped, plus the Node 18 smoke handoff. That suite excludes the new mobile-store regression. Mobile Checks and PR test LoC also passed.
Native Windows regression tests were not rerun by the maintainer; Windows CI packaging is build coverage. The original contributor reported Windows 11 validation, which is not claimed as a maintainer rerun. No combined execution with #24029, manual rendered UI test, or real user-data mutation.
AI Disclosure
Original contributor disclosure retained: LDH1103 used Claude Code (Claude Opus 5.5) for log analysis, implementation, and tests, and reviewed the submission.
Codex assisted the maintainer reproduction, supplemental tests, filesystem proof, and verification; a separate Orca agent reviewed the published commit independently.
Review
Independent Orca review is clean for head
2837d281f6a626688f0004c3405d91ccab4805c6, with zero actionable findings. The reviewer independently passed 73 tests in seven files plus six probes covering nonempty loading and public writes during pending cleanup, errors in listing/stat/deletion, and the paused-foreign-writer limit below.Pullfrog reviewed this same commit and found no new issues; no unresolved inline review threads remain. The production stores, shared cleanup helper, and secure writer are byte-identical to the contributor version. Optional fresh CodeRabbit coverage is missing under shared quota; its older review is not presented as a new review of the supplemental tests.
Merge risk: low, limited to removing matching temporary files older than a day. The existing sweep deliberately protects this process and recent foreign writes; it does not check whether an older foreign PID is alive. CodeRabbit's concern about a foreign writer paused for more than 24 hours is valid: its old temp may be removed and its resumed rename can fail. This PR keeps the shared age policy rather than expanding process-liveness semantics across every caller, and does not promise protection for that case.
Negative user-facing trade-off: a foreign Orca process paused mid-write for more than 24 hours can lose its staged file when another process opens the store; resuming that write can then fail. Applying the shared sweep to these two stores introduces that rare risk. The 24-hour mtime threshold preserves recent foreign writes, and this process's temps are exempt at every age. Startup adds one asynchronous directory listing per store and metadata checks only for matching foreign temps, with no new blocking cleanup work.
Agent skill upstream boundary
docs/reference/agent-skill-sharing-upstream-boundary.mdand copies or mechanically translates no upstream skill-installer source, tests, fixtures, registry entries, path tables, comments, or documentation.Notes
Uses existing Node filesystem/path code across macOS, Linux, and Windows. Both stores use the desktop's local user-data directory, independent of git worktrees or folder workspaces. No SSH execution, paired-runtime payload, agent status, git command, provider behavior, UI, or on-disk format changes.
Checklist
N/Awith reasonpnpm lint,pnpm typecheck,pnpm test, andpnpm buildpass (or CI will cover; local preferred) — scoped local gates and full CI checks above passed