Skip to content

fix(runtime): reclaim temp files orphaned by interrupted mobile store writes - #24049

Merged
nwparker merged 4 commits into
stablyai:mainfrom
LDH1103:fix/reclaim-orphaned-secure-write-temps
Oct 3, 2026
Merged

nwparker merged 4 commits into
stablyai:mainfrom
LDH1103:fix/reclaim-orphaned-secure-write-temps

Conversation

@LDH1103

@LDH1103 LDH1103 commented Sep 30, 2026 •

Copy link
Copy Markdown
Contributor

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.*.tmp and mobile-notification-dismissals.json.*.tmp could remain in the desktop user-data directory indefinitely. Each store constructor now starts the existing removeStaleDurableWriteTempFiles sweep 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 (d2bd1a77978072034c5b300ef57efb7c29a79edb and 83e4e9e56046648444f4dcd72caf8920128fe3be) 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:

  • Before startup cleanup: a two-day-old matching foreign-process temp remains after opening each store.
  • After startup cleanup: that file is removed; own-process temps, fresh foreign temps, another store's temps, similar filenames, wrong suffixes, and the final store file remain byte-for-byte intact.

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.ts failed both original constructor cases with AssertionError: expected true to be false because 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=1 and isolated fixtures. Local checks passed:

  • pnpm tc:node
  • pnpm exec oxfmt --check on the three changed files
  • pnpm exec oxlint on the three changed files
  • pnpm 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 and verify both passed. Unit shard 2 ran all four new regression cases successfully on Ubuntu 24.04 ARM64, with ORCA_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.

  • I manually tested these changes locally
  • Automated tests added/updated, or explained why not below

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

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

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

  • This PR is small and focused
  • I explained what changed and why (ELI5, the user-facing before/after, the mechanism, and why over the alternatives)
  • 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) — scoped local gates and full CI checks above passed

… 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.
@greptile-apps

greptile-apps Bot commented Sep 30, 2026 •

Copy link
Copy Markdown

RetriggerConfidence Score: 5/5

[Medium risk] Adds cleanup for orphaned temporary files in mobile stores.

The PR appears safe to merge; no outstanding finding or new issue was identified.

Summary

The PR adds asynchronous cleanup of day-old temporary writes when the device registry and mobile notification dismissal store open.

  • The latest change replaces fixed test PIDs with values guaranteed to differ from the test process’s PID.

Reviews (2) · Last reviewed commit: "test(runtime): derive orphan-temp fixtur..."

@coderabbitai

coderabbitai Bot commented Sep 30, 2026 •

Copy link
Copy Markdown
Contributor

Review in Change Stack →

Navigate logical layers of code changes, visualize relationships, and explore their blast radius.

📝 Walkthrough

Walkthrough

DeviceRegistry 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 83e4e

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 Summary

Architecture risk: 🔵 Low · up to 83e4e

The change affects 1 system.

Changed systems: src

Architecture concerns
No architecture-level concerns identified.

Review details

Systems and components

  • observed — src (service) was modified; 3 changed files map to changed impact.

Before / after behavior

  • observed — Modified behavior in src/main/runtime/device-registry.ts: Adds the durable-write temp-file cleanup import.
  • observed — Modified behavior in src/main/runtime/device-registry.ts: Defines the stale-temp cleanup age as 24 hours.
  • observed — Modified behavior in src/main/runtime/device-registry.ts: The constructor now starts stale durable-write temp-file cleanup for the registry path with the 24-hour minimum age before loading the registry.
  • observed — Modified behavior in src/main/runtime/mobile-notification-dismissal-store.ts: Imports the stale durable-write temporary-file cleanup helper.
🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check. Docstring coverage is scoped to functions touched by this diff. Analyzed 0 functions across 3…
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.
Title check ✅ Passed The title clearly and concisely describes the main change: reclaiming temporary files left by interrupted mobile store writes.
Description check ✅ Passed The description is complete and directly addresses the required sections. It explains the user impact, implementation, rationale, issue context, testing, AI use, review status, compatibility considera…

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.

@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 — one small test-robustness suggestion inline.

Reviewed changes

  • Reclaim orphaned secure-write temps on construct — DeviceRegistry and MobileNotificationDismissalStore now fire-and-forget removeStaleDurableWriteTempFiles(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.ts asserts a two-day-old <file>.<pid>.<ts>.<hex>.tmp is 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.

Pullfrog  | Fix all ➔ | Fix 👍s ➔ | View workflow run | Using 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.

@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

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 use process.pid + 1 / process.pid + 2 instead of hardcoded 4242/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.

Pullfrog  | View workflow run | Using DeepSeek Flash (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.

Caution

Some comments are outside the diff and can’t be posted inline due to GitHub limitations.

⚠️ Outside diff range comments (1)

🟡 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 win

Protect temporary files owned by live processes.

removeStaleDurableWriteTempFiles skips only this process's PID. A POSIX process can pause during writeSecureFile before renameSync for more than 24 hours. The cleanup can then remove its temporary path, and the resumed write fails with ENOENT. 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

📥 Commits

Reviewing files that changed from the base of the PR and between d2bd1a7 and 83e4e9e.

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

@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

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.backup name, 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 pending spies removeStaleDurableWriteTempFiles with 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 to afterEach so the module spy cannot leak between parameterized cases.
  • Merge — main merged 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.

Pullfrog  | View workflow run | Using deepseek-v4.1-flash (free via Pullfrog for OSS) | 𝕏

@nwparker

nwparker commented Oct 3, 2026

Copy link
Copy Markdown
Contributor

Final merge review at 2837d281f6a626688f0004c3405d91ccab4805c6: the complete changed source matches the independently reviewed commit, and the documented required repository checks pass: detect changes and check repository guards, verify.

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.

@nwparker
nwparker merged commit 6565a3f into stablyai:main Oct 3, 2026
34 checks passed
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.

2 participants