Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

fix: retry Windows file locks so a read racing atomicWrite stops returning the caller's default (#4095)

[._.]/ Adam Eivyc7f98af76d29
diff --git a/server/lib/fileUtils.js b/server/lib/fileUtils.js
index c4c3fdd8f0..b40445cbcd 100644
--- a/server/lib/fileUtils.js
+++ b/server/lib/fileUtils.js
@@ -21,6 +21,24 @@ import { createFileWriteQueue } from './fileWriteQueue.js';
export const execFileAsync = promisify(execFile);
const IS_WIN = process.platform === 'win32';
+// Call-time platform probe. `IS_WIN` above is a module-load snapshot (fine for
+// the path-shape helper at the bottom of this file); the Windows retry paths
+// below read the platform on every call so a POSIX host never carries a stale
+// decision and so the retry behavior is exercisable in tests.
+const isWindows = () => process.platform === 'win32';
+
+// Windows-only retry knobs (#4095). A destination lock from a concurrent reader
+// or an AV scan clears in milliseconds, so a handful of short retries is enough
+// to avoid both the writer's destination-missing backup swap and the reader's
+// phantom "nothing here yet".
+const WIN_RETRY_ATTEMPTS = 5;
+const WIN_RETRY_DELAY_MS = 10;
+// rename(2) failures that mean "the destination is momentarily locked", not
+// "this rename can never work".
+const WIN_RENAME_LOCK_CODES = ['EPERM', 'EACCES', 'EEXIST'];
+// read failures with the same transient meaning on the reader side.
+const WIN_READ_LOCK_CODES = ['EPERM', 'EACCES', 'EBUSY'];
+
// Cache __dirname calculation for services importing this module
const __lib_filename = fileURLToPath(import.meta.url);
const __lib_dirname = dirname(__lib_filename);
@@ -259,9 +277,23 @@ export async function atomicWrite(filePath, data) {
// overwrite), but still fails with EPERM/EACCES if the destination is locked (AV scan,
// concurrent reader). Fall back to a backup-swap so the original file is never lost.
const replace = async () => {
- const err = await rename(tmp, filePath).then(() => null, (e) => e);
+ let err = await rename(tmp, filePath).then(() => null, (e) => e);
+ // Retry the ATOMIC rename before resorting to the backup swap (#4095). The
+ // swap below renames the destination away and back, so for that instant the
+ // destination DOES NOT EXIST — a concurrent read lands on ENOENT and reads
+ // it as a trustworthy "nothing here yet", silently handing the caller its
+ // default instead of the file's real contents. A transient lock clears in
+ // milliseconds, so retrying keeps almost every write on the atomic path and
+ // never opens that window.
+ if (isWindows()) {
+ for (let attempt = 1; err && attempt < WIN_RETRY_ATTEMPTS && WIN_RENAME_LOCK_CODES.includes(err.code); attempt += 1) {
+ await sleep(WIN_RETRY_DELAY_MS);
+ err = await rename(tmp, filePath).then(() => null, (e) => e);
+ if (!err) console.log(`⚠️ atomicWrite rename succeeded after ${attempt} retry(s): ${basename(filePath)}`);
+ }
+ }
if (!err) return;
- if (process.platform === 'win32' && ['EPERM', 'EACCES', 'EEXIST'].includes(err.code)) {
+ if (isWindows() && WIN_RENAME_LOCK_CODES.includes(err.code)) {
const bak = `${filePath}.${process.pid}.${Date.now()}.${randomUUID()}.bak`;
const hadExisting = await rename(filePath, bak).then(() => true, (e) => {
if (e.code === 'ENOENT') return false;
@@ -483,6 +515,60 @@ export async function readFileTail(path, maxBytes) {
// in-band marker could legitimately BE the parsed value.
const PARSE_FAILED = Symbol('json-parse-failed');
+/**
+ * True when a `<filePath>.*.tmp` or `<filePath>.*.bak` sibling is on disk — the
+ * signature of an `atomicWrite` temp write or backup swap that is still in
+ * flight for THIS file. Non-throwing: an unreadable parent directory just means
+ * "no evidence of a swap".
+ *
+ * Only consulted on win32, and only after a read already failed with ENOENT, so
+ * the directory listing never lands on a POSIX read or on a successful read.
+ *
+ * @param {string} filePath
+ * @returns {Promise<boolean>}
+ */
+async function hasSwapSibling(filePath) {
+ const entries = await readdir(dirname(filePath)).catch(() => null);
+ if (!entries) return false;
+ const prefix = `${basename(filePath)}.`;
+ return entries.some((name) => name.startsWith(prefix) && (name.endsWith('.tmp') || name.endsWith('.bak')));
+}
+
+/**
+ * `readFile(filePath, 'utf-8')` with the Windows-only retries that keep a read
+ * racing `atomicWrite` from being mistaken for an empty/absent file (#4095).
+ *
+ * On POSIX this is a straight delegate — zero extra syscalls, zero delay.
+ *
+ * On win32 two transient failures are retried with a short backoff:
+ * - EPERM/EACCES/EBUSY — the destination is momentarily locked (AV scan, the
+ * writer's own open handle).
+ * - ENOENT, but ONLY when `hasSwapSibling` shows a swap is in flight. A file
+ * that was simply never written stays a zero-cost, silent "nothing here
+ * yet": one failed read, no retry, no sleep.
+ *
+ * Rejects with the last error once the attempts are exhausted, so the caller's
+ * existing errno handling is unchanged.
+ *
+ * @param {string} filePath
+ * @returns {Promise<string>}
+ */
+async function readTextWithSwapRetry(filePath) {
+ if (!isWindows()) return readFile(filePath, 'utf-8');
+ for (let attempt = 0; ; attempt += 1) {
+ const outcome = await readFile(filePath, 'utf-8').then((content) => ({ content }), (err) => ({ err }));
+ if (!outcome.err) {
+ if (attempt > 0) console.log(`⚠️ read succeeded after ${attempt} retry(s) — write swap in flight: ${basename(filePath)}`);
+ return outcome.content;
+ }
+ const last = attempt >= WIN_RETRY_ATTEMPTS - 1;
+ const retriable = WIN_READ_LOCK_CODES.includes(outcome.err.code)
+ || (outcome.err.code === 'ENOENT' && !last && await hasSwapSibling(filePath));
+ if (last || !retriable) throw outcome.err;
+ await sleep(WIN_RETRY_DELAY_MS);
+ }
+}
+
/**
* Read a JSON file, reporting whether the read is TRUSTWORTHY rather than
* collapsing every failure into the default (the `readJSONFile` behavior below).
@@ -519,9 +605,11 @@ const PARSE_FAILED = Symbol('json-parse-failed');
export async function readJSONFileStrict(filePath, defaultValue = null, { allowArray = true, logError = true } = {}) {
let content;
try {
- content = await readFile(filePath, 'utf-8');
+ content = await readTextWithSwapRetry(filePath);
} catch (err) {
// ENOENT = file doesn't exist → a trustworthy "nothing here yet", silently.
+ // On win32 an ENOENT that was really an `atomicWrite` swap window has
+ // already been retried above, so reaching here means genuinely absent.
if (err.code === 'ENOENT') {
return { ok: true, value: defaultValue };
}
diff --git a/server/lib/fileUtils.test.js b/server/lib/fileUtils.test.js
index 8bed5eac79..d9d7dda108 100644
--- a/server/lib/fileUtils.test.js
+++ b/server/lib/fileUtils.test.js
@@ -1,4 +1,4 @@
-import { describe, it, expect, vi, beforeEach, afterEach, afterAll } from 'vitest';
+import { describe, it, expect, vi, beforeAll, beforeEach, afterEach, afterAll } from 'vitest';
import { readFile, writeFile, rm, mkdir } from 'fs/promises';
import { mkdtempSync, rmSync, writeFileSync, readFileSync, readdirSync } from 'fs';
import { join } from 'path';
@@ -11,12 +11,17 @@ import * as fsPromises from 'fs/promises';
// no-op for root, which is how the container CI runs). Both default to delegating
// to the real implementation (so every other test in this file is unaffected);
// individual tests override with `mockRejectedValueOnce`.
+// `rename` and `readdir` are wrapped for the same reason (#4095): the Windows
+// swap-window retries key off transient EPERM/EACCES/EBUSY/ENOENT errnos that
+// cannot be provoked on a POSIX test host.
vi.mock('fs/promises', async (importOriginal) => {
const actual = await importOriginal();
return {
...actual,
mkdir: vi.fn((...args) => actual.mkdir(...args)),
readFile: vi.fn((...args) => actual.readFile(...args)),
+ rename: vi.fn((...args) => actual.rename(...args)),
+ readdir: vi.fn((...args) => actual.readdir(...args)),
};
});
import {
@@ -1261,6 +1266,156 @@ describe('fileUtils', () => {
});
});
+// =============================================================================
+// Windows swap-window retries (#4095)
+//
+// On win32 `atomicWrite`'s fallback backup swap renames the destination away and
+// back, so for an instant the file DOES NOT EXIST. A read landing in that window
+// used to get ENOENT and report it as a trustworthy "nothing here yet", handing
+// the caller its default instead of the real contents. These tests pin both
+// halves of the fix and that POSIX still pays nothing for it.
+// =============================================================================
+
+describe('Windows swap-window retries (#4095)', () => {
+ // Matches WIN_RETRY_ATTEMPTS in fileUtils.js.
+ const RETRY_ATTEMPTS = 5;
+ const lockError = (code) => Object.assign(new Error(`${code}: simulated windows lock`), { code });
+
+ let tmpRoot;
+ let realFs;
+ let restorePlatform = null;
+
+ const fakePlatform = (value) => {
+ const original = Object.getOwnPropertyDescriptor(process, 'platform');
+ Object.defineProperty(process, 'platform', { value, configurable: true });
+ restorePlatform = () => Object.defineProperty(process, 'platform', original);
+ };
+
+ beforeAll(async () => {
+ realFs = await vi.importActual('fs/promises');
+ });
+
+ beforeEach(() => {
+ tmpRoot = mkdtempSync(join(tmpdir(), 'fileutils-winswap-'));
+ // Earlier describes in this file exercise the same fs mocks — start from a
+ // clean call log so the call-count assertions below mean what they say.
+ fsPromises.readFile.mockClear();
+ fsPromises.rename.mockClear();
+ fsPromises.readdir.mockClear();
+ });
+
+ afterEach(() => {
+ if (restorePlatform) restorePlatform();
+ restorePlatform = null;
+ // Drop any unconsumed `*Once` queues AND re-establish the delegating
+ // implementations the rest of this file relies on.
+ fsPromises.readFile.mockReset();
+ fsPromises.rename.mockReset();
+ fsPromises.readdir.mockReset();
+ fsPromises.readFile.mockImplementation((...args) => realFs.readFile(...args));
+ fsPromises.rename.mockImplementation((...args) => realFs.rename(...args));
+ fsPromises.readdir.mockImplementation((...args) => realFs.readdir(...args));
+ rmSync(tmpRoot, { recursive: true, force: true });
+ });
+
+ describe('atomicWrite', () => {
+ it('retries the atomic rename on a transient lock instead of opening the destination-missing window', async () => {
+ const target = join(tmpRoot, 'state.json');
+ writeFileSync(target, JSON.stringify({ v: 1 }));
+ fakePlatform('win32');
+ fsPromises.rename.mockRejectedValueOnce(lockError('EPERM'));
+
+ await atomicWrite(target, { v: 2 });
+
+ expect(JSON.parse(readFileSync(target, 'utf8'))).toEqual({ v: 2 });
+ // The backup swap is identified by a rename whose SOURCE is the
+ // destination itself (`rename(filePath, bak)`). The retry path must never
+ // move the destination aside — that is the window this fix closes.
+ const movedDestinationAside = fsPromises.rename.mock.calls.some(([from]) => from === target);
+ expect(movedDestinationAside).toBe(false);
+ expect(fsPromises.rename).toHaveBeenCalledTimes(2);
+ });
+
+ it('still falls back to the backup swap when every retry is refused', async () => {
+ const target = join(tmpRoot, 'stubborn.json');
+ writeFileSync(target, JSON.stringify({ v: 1 }));
+ fakePlatform('win32');
+ for (let i = 0; i < RETRY_ATTEMPTS; i += 1) fsPromises.rename.mockRejectedValueOnce(lockError('EPERM'));
+
+ await atomicWrite(target, { v: 2 });
+
+ expect(JSON.parse(readFileSync(target, 'utf8'))).toEqual({ v: 2 });
+ const movedDestinationAside = fsPromises.rename.mock.calls.some(([from]) => from === target);
+ expect(movedDestinationAside).toBe(true);
+ // …and the swap cleaned up after itself.
+ expect(readdirSync(tmpRoot).filter((n) => n.endsWith('.bak') || n.endsWith('.tmp'))).toEqual([]);
+ });
+
+ it('does not retry off win32 — a rename failure still surfaces immediately', async () => {
+ const target = join(tmpRoot, 'posix.json');
+ writeFileSync(target, JSON.stringify({ v: 1 }));
+ fsPromises.rename.mockRejectedValueOnce(lockError('EPERM'));
+
+ await expect(atomicWrite(target, { v: 2 })).rejects.toThrow(/EPERM/);
+
+ expect(fsPromises.rename).toHaveBeenCalledTimes(1);
+ // The original file is untouched and no temp debris is left behind.
+ expect(JSON.parse(readFileSync(target, 'utf8'))).toEqual({ v: 1 });
+ expect(readdirSync(tmpRoot)).toEqual(['posix.json']);
+ });
+ });
+
+ describe('readJSONFileStrict', () => {
+ it('retries a locked read on win32 and returns the real contents as trustworthy', async () => {
+ const target = join(tmpRoot, 'locked.json');
+ writeFileSync(target, JSON.stringify({ real: true }));
+ fakePlatform('win32');
+ fsPromises.readFile.mockRejectedValueOnce(lockError('EBUSY'));
+
+ expect(await readJSONFileStrict(target, { fallback: true })).toEqual({ ok: true, value: { real: true } });
+ expect(fsPromises.readFile).toHaveBeenCalledTimes(2);
+ });
+
+ it('retries an ENOENT on win32 when a swap sibling shows a write is in flight', async () => {
+ const target = join(tmpRoot, 'swapping.json');
+ writeFileSync(target, JSON.stringify({ real: true }));
+ // The debris `atomicWrite` leaves visible while a swap is mid-flight.
+ writeFileSync(`${target}.1234.5678.bak`, '{"real":true}');
+ fakePlatform('win32');
+ fsPromises.readFile.mockRejectedValueOnce(lockError('ENOENT'));
+
+ expect(await readJSONFileStrict(target, { fallback: true })).toEqual({ ok: true, value: { real: true } });
+ expect(fsPromises.readdir).toHaveBeenCalled();
+ });
+
+ it('does not retry a plain missing file on win32 — no sibling, no second read', async () => {
+ const missing = join(tmpRoot, 'never-written.json');
+ fakePlatform('win32');
+
+ expect(await readJSONFileStrict(missing, { fallback: true })).toEqual({ ok: true, value: { fallback: true } });
+ expect(fsPromises.readFile).toHaveBeenCalledTimes(1);
+ });
+
+ it('costs a plain missing file nothing off win32 — one read, no directory scan', async () => {
+ const missing = join(tmpRoot, 'never-written.json');
+
+ expect(await readJSONFileStrict(missing, { fallback: true })).toEqual({ ok: true, value: { fallback: true } });
+ expect(fsPromises.readFile).toHaveBeenCalledTimes(1);
+ expect(fsPromises.readdir).not.toHaveBeenCalled();
+ });
+
+ it('does not retry a locked read off win32 — the read stays untrustworthy', async () => {
+ const target = join(tmpRoot, 'posix-locked.json');
+ writeFileSync(target, JSON.stringify({ real: true }));
+ fsPromises.readFile.mockRejectedValueOnce(lockError('EBUSY'));
+
+ expect(await readJSONFileStrict(target, { fallback: true }, { logError: false }))
+ .toEqual({ ok: false, value: { fallback: true } });
+ expect(fsPromises.readFile).toHaveBeenCalledTimes(1);
+ });
+ });
+});
+
// =============================================================================
// createCachedStore — cached JSON store with serialized writes (#2539)
// =============================================================================