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: extend Windows backup rename recovery window

[._.]/ Adam Eivy08c11bb1f48b
diff --git a/server/lib/aiToolkit/internal/atomicWrite.js b/server/lib/aiToolkit/internal/atomicWrite.js
index 31bc780755..e145928b36 100644
--- a/server/lib/aiToolkit/internal/atomicWrite.js
+++ b/server/lib/aiToolkit/internal/atomicWrite.js
@@ -22,15 +22,20 @@ import { dirname } from 'path';
const WIN_RETRY_ATTEMPTS = 5;
const WIN_RETRY_DELAY_MS = 10;
+const WIN_BACKUP_RETRY_ATTEMPTS = 20;
+const WIN_BACKUP_RETRY_DELAY_MS = 25;
const WIN_RENAME_LOCK_CODES = ['EPERM', 'EACCES', 'EEXIST', 'EBUSY'];
const isWindows = () => process.platform === 'win32';
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
-async function renameWithWindowsRetries(from, to) {
+async function renameWithWindowsRetries(from, to, {
+ attempts = WIN_RETRY_ATTEMPTS,
+ delayMs = WIN_RETRY_DELAY_MS,
+} = {}) {
let err = await rename(from, to).then(() => null, (e) => e);
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);
+ for (let attempt = 1; err && attempt < attempts && WIN_RENAME_LOCK_CODES.includes(err.code); attempt += 1) {
+ await sleep(delayMs);
err = await rename(from, to).then(() => null, (e) => e);
}
}
@@ -53,7 +58,10 @@ export async function atomicWrite(filePath, data) {
if (!err) return;
if (isWindows() && WIN_RENAME_LOCK_CODES.includes(err.code)) {
const bak = `${filePath}.${process.pid}.${Date.now()}.${randomUUID()}.bak`;
- const backupError = await renameWithWindowsRetries(filePath, bak);
+ const backupError = await renameWithWindowsRetries(filePath, bak, {
+ attempts: WIN_BACKUP_RETRY_ATTEMPTS,
+ delayMs: WIN_BACKUP_RETRY_DELAY_MS,
+ });
if (backupError && backupError.code !== 'ENOENT') throw backupError;
const hadExisting = !backupError;
const renameErr = await renameWithWindowsRetries(tmp, filePath);
diff --git a/server/lib/aiToolkit/internal/atomicWrite.test.js b/server/lib/aiToolkit/internal/atomicWrite.test.js
index fa216527fe..90d1fe651f 100644
--- a/server/lib/aiToolkit/internal/atomicWrite.test.js
+++ b/server/lib/aiToolkit/internal/atomicWrite.test.js
@@ -17,6 +17,7 @@ import { atomicWrite } from './atomicWrite.js';
const realFsPromises = await vi.importActual('fs/promises');
const RETRY_ATTEMPTS = 5;
+const BACKUP_RETRY_ATTEMPTS = 20;
const lockError = (code) => Object.assign(new Error(`${code}: simulated windows lock`), { code });
let tmpRoot;
@@ -42,12 +43,12 @@ describe('AI Toolkit atomicWrite Windows backup retries', () => {
const target = join(tmpRoot, 'transient.json');
writeFileSync(target, '{"v":1}');
for (let i = 0; i < RETRY_ATTEMPTS; i += 1) fsPromises.rename.mockRejectedValueOnce(lockError('EPERM'));
- fsPromises.rename.mockRejectedValueOnce(lockError('EBUSY'));
+ for (let i = 0; i < RETRY_ATTEMPTS; i += 1) fsPromises.rename.mockRejectedValueOnce(lockError('EBUSY'));
await atomicWrite(target, { v: 2 });
expect(readFileSync(target, 'utf8')).toBe('{\n "v": 2\n}');
- expect(fsPromises.rename.mock.calls.filter(([from]) => from === target)).toHaveLength(2);
+ expect(fsPromises.rename.mock.calls.filter(([from]) => from === target)).toHaveLength(RETRY_ATTEMPTS + 1);
expect(readdirSync(tmpRoot).filter((name) => name.endsWith('.bak') || name.endsWith('.tmp'))).toEqual([]);
});
@@ -55,12 +56,12 @@ describe('AI Toolkit atomicWrite Windows backup retries', () => {
const target = join(tmpRoot, 'persistent.json');
writeFileSync(target, '{"v":1}');
for (let i = 0; i < RETRY_ATTEMPTS; i += 1) fsPromises.rename.mockRejectedValueOnce(lockError('EPERM'));
- for (let i = 0; i < RETRY_ATTEMPTS; i += 1) fsPromises.rename.mockRejectedValueOnce(lockError('EBUSY'));
+ for (let i = 0; i < BACKUP_RETRY_ATTEMPTS; i += 1) fsPromises.rename.mockRejectedValueOnce(lockError('EBUSY'));
await expect(atomicWrite(target, { v: 2 })).rejects.toMatchObject({ code: 'EBUSY' });
expect(readFileSync(target, 'utf8')).toBe('{"v":1}');
- expect(fsPromises.rename).toHaveBeenCalledTimes(RETRY_ATTEMPTS * 2);
+ expect(fsPromises.rename).toHaveBeenCalledTimes(RETRY_ATTEMPTS + BACKUP_RETRY_ATTEMPTS);
expect(readdirSync(tmpRoot)).toEqual(['persistent.json']);
});
});
diff --git a/server/lib/fileCore.js b/server/lib/fileCore.js
index 8b74bac9b8..bc76ebe3ed 100644
--- a/server/lib/fileCore.js
+++ b/server/lib/fileCore.js
@@ -36,6 +36,10 @@ const isWindows = () => process.platform === 'win32';
// phantom "nothing here yet".
const WIN_RETRY_ATTEMPTS = 5;
const WIN_RETRY_DELAY_MS = 10;
+// The backup move follows a failed atomic replace, where a reader or AV scan
+// can keep the existing destination locked longer than the first retry window.
+const WIN_BACKUP_RETRY_ATTEMPTS = 20;
+const WIN_BACKUP_RETRY_DELAY_MS = 25;
// rename(2) failures that mean "the destination is momentarily locked", not
// "this rename can never work".
const WIN_RENAME_LOCK_CODES = ['EPERM', 'EACCES', 'EEXIST', 'EBUSY'];
@@ -221,22 +225,26 @@ export async function atomicWrite(filePath, data) {
if (existingMode !== null) {
await chmod(tmp, existingMode).catch(() => {});
}
+ const renameWithWindowsRetries = async (from, to, {
+ attempts = WIN_RETRY_ATTEMPTS,
+ delayMs = WIN_RETRY_DELAY_MS,
+ } = {}) => {
+ let err = await rename(from, to).then(() => null, (e) => e);
+ let retries = 0;
+ if (isWindows()) {
+ for (let attempt = 1; err && attempt < attempts && WIN_RENAME_LOCK_CODES.includes(err.code); attempt += 1) {
+ await sleep(delayMs);
+ retries += 1;
+ err = await rename(from, to).then(() => null, (e) => e);
+ if (!err) console.log(`⚠️ atomicWrite rename succeeded after ${retries} retry(s): ${basename(filePath)}`);
+ }
+ }
+ return { err, retries };
+ };
// Node's fs.rename uses MoveFileExW with MOVEFILE_REPLACE_EXISTING on Windows (atomic
// overwrite), but still fails with EPERM/EACCES/EBUSY 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 renameWithRetries = async (from, to) => {
- let err = await rename(from, to).then(() => null, (e) => e);
- 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(from, to).then(() => null, (e) => e);
- if (!err) console.log(`⚠️ atomicWrite rename succeeded after ${attempt} retry(s): ${basename(filePath)}`);
- }
- }
- return err;
- };
-
// 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
@@ -244,16 +252,23 @@ export async function atomicWrite(filePath, data) {
// 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.
- const err = await renameWithRetries(tmp, filePath);
+ const firstRename = await renameWithWindowsRetries(tmp, filePath);
+ const err = firstRename.err;
if (!err) return;
if (isWindows() && WIN_RENAME_LOCK_CODES.includes(err.code)) {
const bak = `${filePath}.${process.pid}.${Date.now()}.${randomUUID()}.bak`;
- const backupErr = await renameWithRetries(filePath, bak);
- const hadExisting = backupErr?.code !== 'ENOENT';
- if (hadExisting && backupErr) throw backupErr;
- const renameErr = await rename(tmp, filePath).then(() => null, (e) => e);
+ // A transient Windows lock can also reject the move to the backup. Retry
+ // that move before giving up; until it succeeds, the original stays at
+ // filePath and is safe to read.
+ const backupRename = await renameWithWindowsRetries(filePath, bak, {
+ attempts: WIN_BACKUP_RETRY_ATTEMPTS,
+ delayMs: WIN_BACKUP_RETRY_DELAY_MS,
+ });
+ if (backupRename.err && backupRename.err.code !== 'ENOENT') throw backupRename.err;
+ const hadExisting = !backupRename.err;
+ const renameErr = (await renameWithWindowsRetries(tmp, filePath)).err;
if (renameErr) {
- if (hadExisting) await rename(bak, filePath).catch(() => {});
+ if (hadExisting) await renameWithWindowsRetries(bak, filePath);
throw renameErr;
}
if (hadExisting) await unlink(bak).catch(() => {});
diff --git a/server/lib/fileUtils.test.js b/server/lib/fileUtils.test.js
index f39baa2a83..ead138b68d 100644
--- a/server/lib/fileUtils.test.js
+++ b/server/lib/fileUtils.test.js
@@ -1415,6 +1415,7 @@ describe('fileUtils', () => {
describe('Windows swap-window retries (#4095)', () => {
// Matches WIN_RETRY_ATTEMPTS in fileCore.js.
const RETRY_ATTEMPTS = 5;
+ const BACKUP_RETRY_ATTEMPTS = 20;
const lockError = (code) => Object.assign(new Error(`${code}: simulated windows lock`), { code });
let tmpRoot;
@@ -1509,12 +1510,12 @@ describe('Windows swap-window retries (#4095)', () => {
writeFileSync(target, JSON.stringify({ v: 1 }));
fakePlatform('win32');
for (let i = 0; i < RETRY_ATTEMPTS; i += 1) fsPromises.rename.mockRejectedValueOnce(lockError('EPERM'));
- fsPromises.rename.mockRejectedValueOnce(lockError('EBUSY'));
+ for (let i = 0; i < RETRY_ATTEMPTS; i += 1) fsPromises.rename.mockRejectedValueOnce(lockError('EBUSY'));
await atomicWrite(target, { v: 2 });
expect(JSON.parse(readFileSync(target, 'utf8'))).toEqual({ v: 2 });
- expect(fsPromises.rename.mock.calls.filter(([from]) => from === target)).toHaveLength(2);
+ expect(fsPromises.rename.mock.calls.filter(([from]) => from === target)).toHaveLength(RETRY_ATTEMPTS + 1);
expect(readdirSync(tmpRoot).filter((n) => n.endsWith('.bak') || n.endsWith('.tmp'))).toEqual([]);
});
@@ -1523,12 +1524,12 @@ describe('Windows swap-window retries (#4095)', () => {
writeFileSync(target, JSON.stringify({ v: 1 }));
fakePlatform('win32');
for (let i = 0; i < RETRY_ATTEMPTS; i += 1) fsPromises.rename.mockRejectedValueOnce(lockError('EPERM'));
- for (let i = 0; i < RETRY_ATTEMPTS; i += 1) fsPromises.rename.mockRejectedValueOnce(lockError('EBUSY'));
+ for (let i = 0; i < BACKUP_RETRY_ATTEMPTS; i += 1) fsPromises.rename.mockRejectedValueOnce(lockError('EBUSY'));
await expect(atomicWrite(target, { v: 2 })).rejects.toMatchObject({ code: 'EBUSY' });
expect(JSON.parse(readFileSync(target, 'utf8'))).toEqual({ v: 1 });
- expect(fsPromises.rename).toHaveBeenCalledTimes(RETRY_ATTEMPTS * 2);
+ expect(fsPromises.rename).toHaveBeenCalledTimes(RETRY_ATTEMPTS + BACKUP_RETRY_ATTEMPTS);
expect(readdirSync(tmpRoot)).toEqual(['persistent-backup-lock.json']);
});