fix(shared): Windows saves no longer fail while a scanner holds the file #21062
main fromrefs/pull/21062/head·merged by juliusmarminge View on GitHub
One run each on this PC, with a separate PowerShell process holding the target open.
Problem#
On Windows, a save through writeFileStringAtomically (server settings, keybindings, runtime state, provider caches, t3 theme) fails with EPERM if another process has the target open without delete sharing at that moment, which antivirus and indexers can do. The helper writes a temp file and renames it over the target, and Windows refuses that rename while the target is held. It renamed once, so a save landing in that window failed.
main, target held 400 ms: save FAILED after 28 ms, EPERM, old contents kept
fix, target held 400 ms: save succeeded after 518 ms
Change#
On Windows, when the rename fails with EPERM, EACCES or EBUSY, the write retries every 100 ms, up to 20 times (about 2 s). Other errors, and every error on other platforms, still fail on the first try.
Retrying old contents is only safe if nobody else saved in the meantime. Before the first attempt the write records the target's file ID, size and mtime, and before each retry it checks them again. If they changed, it stops and fails with the original error, as main does today. Without this, a t3 theme clear waiting out a lock wrote its stale contents over a settings save that landed right after the lock cleared. That was reproduced in review.
This is best effort, not a compare-and-swap. A save can still land between the last check and the rename, and the check only sees changes that alter the file ID, size or mtime (T3's own atomic writers always change the ID). In 300 samples here the check-to-rename gap was 0.38 ms median and 5.3 ms worst, but a descheduled process can make it longer.
The same error codes also mean permanent denials. A read-only target (mode with no write bit) fails at once. An ACL denial looks the same as a held file, so it now reports after about 2 s instead of right away. I kept the budget at 2 s because settings and keybinding saves hold their write lock while they wait.
#16998 already had this error-code check inside relayClient.ts. The relay client now imports it from atomicWrite.ts and keeps its own 10 s budget, so its behavior is unchanged.
Scope and approval#
Replaces #16574 by @yaacovcorcos, who found and fixed this. That branch no longer applies because the helper moved to packages/shared/src/atomicWrite.ts. This ports it and adds the changed-target check and the read-only fast path. There's no tracking issue.
Not covered: the desktop app's own settings writers (DesktopAppSettings.ts, DesktopClientSettings.ts, DesktopConnectionCatalogStore.ts) have their own single rename and don't use this helper.
Verification#
On this Windows 11 PC, with a separate PowerShell process holding the file open with FileShare.Read. The timings are samples from a loaded machine, not bounds.
fix, held 1500 ms: succeeded after 1629 ms
fix, held 5000 ms: FAILED after 2048 ms, EPERM, old contents kept
fix, read-only, no holder: FAILED after 11 ms, EPERM, old contents kept
The real t3 theme clear CLI with a scratch base dir, settings starting as {"defaultTheme":"midnight","enableProviderUpdateChecks":true}:
- main, lock only:
ThemeSettingsWriteError ... EPERM, exit 1. - fix, lock only: "Environment theme cleared", exit 0.
- fix, lock, then another process saves
enableProviderUpdateChecks:falseright after release: the CLI fails withEPERM, exit 1, and the file keeps the newer save. The first version of this branch, without the check, exited 0 and wrotetrueback over it.
vp test run src/atomicWrite.test.ts in packages/shared wraps the real file system, injects EBUSY/EPERM from rename, and steps TestClock:
| test | main | without the target check | this PR |
|---|---|---|---|
| waits out a Windows lock, then replaces the target | fails | passes | passes |
| gives up on a lock that doesn't clear, keeps the old contents | fails | passes | passes |
| doesn't replace a newer save that landed while the lock was held | passes | fails | passes |
| fails at once on a read-only Windows target | passes | fails | passes |
The relay client's Windows lock tests pass. Typecheck for packages/shared and lint on the touched files are clean. Three tests in these files fail on a Windows host on main too, unchanged here; the Linux CI run for this revision is pending. Not checked: macOS and Linux runtime (the write returns before the new code there), and a live Defender or indexer scan.
🤖 Generated with Claude Code (Claude Opus 5.5)
- 1
github-actions[bot](GitHub profile, opens in a new tab) added labelsvouch:trusted
github-actions[bot](GitHub profile, opens in a new tab) added labelssize:M
Approvability#
Verdict: Approved at
b3b183cMacroscope's review found this PR approvable — This is a bounded Windows save reliability fix with unchanged non-Windows behavior, explicit retry limits, and targeted coverage for lock and concurrent-save scenarios. The remaining relay-client change is a behavior-preserving helper reuse.
You can add or adjust custom eligibility rules. [Learn more](https://docs.macroscope.com/approvability#example-custom-eligibility-rules).No actionable comments were generated in the recent review. 🎉
ℹ️ Recent review info
-
⚙️ Run configuration
-
- Configuration used: Path: .coderabbit.config.ts
- Review profile: CHILL
- Plan: Advanced
- Run ID:
0a2dd754-ec94-4095-87b0-f9099f19f8ec
📥 Commits
-
Reviewing files that changed from the base of the PR and between 16918b57d6754d6f145e9b6367c825aa31a740da and b3b183ca221d4bf089e34d66f031acaed79984e4.
📒 Files selected for processing: 3
-
packages/shared/src/atomicWrite.test.tspackages/shared/src/atomicWrite.tspackages/shared/src/relayClient.ts
Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 6 remain after this review.
-
📝 Walkthrough
-
Atomic writes now retry selected Windows rename-lock errors when the target remains unchanged and writable. Relay activation uses the shared predicate to identify those errors.
Changes: Windows rename retries
Layer / File(s) Summary Guarded atomic-write retries
packages/shared/src/atomicWrite.ts,packages/shared/src/atomicWrite.test.tsWindows atomic writes retry EBUSY,EPERM, andEACCESup to 20 times with 100 ms delays when the target remains unchanged and is not read-only. Tests cover successful retries, persistent failures, concurrent writes, and read-only targets.Relay activation retry predicate
packages/shared/src/relayClient.tsRelay activation uses isWindowsRenameLockinstead of a local check for the three error codes.Priority: ➖ Normal
Estimated code review effort: 3 (Moderate) | ~20 minutes
Change: Bug fix
Suggested reviewers:
yordis,scottn-pv
Merge Risk: ⚪ Minimal · up to
b3b18-
No actionable merge-blocking risk is established. The Windows file-identity edge case remains unverified, but it does not currently establish a reason to delay merging.
Security architecture risk: 🔵 Low · up to
b3b18-
Retries are bounded and preserve existing access restrictions. The concurrency guard detects many intervening saves, but it cannot guarantee that a simultaneous save will never be overwritten. No new privilege or access path was identified.
Retained concerns
- Low · reliability · inferred: A delayed retry can replace a newer settings snapshot if another process saves between the retry's target-version check and rename. The base would have stopped after the initial lock error, although it already permitted concurrent overwrites during its initial rename. Per-process serialization and the version guard reduce exposure but do not establish cross-process ownership. This is a bounded persistence-consistency concern, not a verified security exploit.
Security review details
-
Security Blast Radius
- inferred — Effective exposure remains the existing caller-selected local persistence targets. Retries reuse the same resolved target and staged contents; they add no path-selection input or privilege escalation. The residual ownership risk concerns competing writers to the same file, rather than demonstrated cross-tenant or cross-service access.
Security Findings and Attack Paths
- inferred — A competing writer can cause stale replacement only if its update escapes the metadata comparison or lands after that comparison and before rename. The inspected evidence establishes this concurrency limitation, but not an attacker-controlled authorization bypass or a verified rollback of security policy.
Trust Boundaries and Controls
- observed — Each attempt still invokes filesystem rename under existing process authority. The error classifier only decides retry eligibility; it does not bypass operating-system denials. Caller semaphores serialize their own updates but do not constitute a shared cross-process lock.
Resilience and Maintainability Implications
- observed — The configured retry delays total about two seconds, limiting additional lock holding for settings saves; filesystem latency can extend elapsed time. Cleanup remains best effort and does not turn an already committed replacement into a reported cleanup failure.
Pre-merge checks:
4-
Check name Status Explanation Title check The title is concise, specific, and accurately describes the primary Windows save reliability fix. Description check The description covers the problem, implementation, scope and approval context, verification results, limitations, and agent attribution. It provides clear reproduction details and identifies checks t… Linked Issues check Check skipped because no linked issues were found for this pull request. Out of Scope Changes check Check skipped because no linked issues were found for this pull request. Full details: Description check
-
Explanation
The description covers the problem, implementation, scope and approval context, verification results, limitations, and agent attribution. It provides clear reproduction details and identifies checks that were not performed.
-
✨ Finishing Touches
-
🧪 Generate unit tests (beta)
-
- Create a new PR
-
- Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts
-
juliusmarminge merged this9494dba
juliusmarminge closed this
Sign in to join this conversation.
macroscopeapp[bot](GitHub profile, opens in a new tab) approved these changes