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
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
fix: retry transient Windows rename locks
[._.]/ Adam Eivy57a17d377d60
diff --git a/server/lib/fileCore.js b/server/lib/fileCore.jsindex b8960f93be..8b74bac9b8 100644--- a/server/lib/fileCore.js+++ b/server/lib/fileCore.js@@ -38,7 +38,7 @@ 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'];+const WIN_RENAME_LOCK_CODES = ['EPERM', 'EACCES', 'EEXIST', 'EBUSY'];// read failures with the same transient meaning on the reader side.const WIN_READ_LOCK_CODES = ['EPERM', 'EACCES', 'EBUSY'];const FILE_WATCH_FALLBACK_POLL_MS = 5000;@@ -222,10 +222,21 @@ export async function atomicWrite(filePath, data) {await chmod(tmp, existingMode).catch(() => {});}// Node's fs.rename uses MoveFileExW with MOVEFILE_REPLACE_EXISTING on Windows (atomic- // overwrite), but still fails with EPERM/EACCES if the destination is locked (AV scan,+ // 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 () => {- let err = await rename(tmp, filePath).then(() => null, (e) => e);+ 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@@ -233,20 +244,13 @@ 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.- 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)}`);- }- }+ const err = await renameWithRetries(tmp, filePath);if (!err) return;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;- throw e;- });+ 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);if (renameErr) {if (hadExisting) await rename(bak, filePath).catch(() => {});diff --git a/server/lib/fileUtils.test.js b/server/lib/fileUtils.test.jsindex 8c64b85d32..786a681ddb 100644--- a/server/lib/fileUtils.test.js+++ b/server/lib/fileUtils.test.js@@ -1459,6 +1459,36 @@ describe('Windows swap-window retries (#4095)', () => {expect(fsPromises.rename).toHaveBeenCalledTimes(2);});+ it('retries a transient EBUSY lock on the atomic rename', async () => {+ const target = join(tmpRoot, 'busy.json');+ writeFileSync(target, JSON.stringify({ v: 1 }));+ fakePlatform('win32');+ fsPromises.rename.mockRejectedValueOnce(lockError('EBUSY'));++ await atomicWrite(target, { v: 2 });++ expect(JSON.parse(readFileSync(target, 'utf8'))).toEqual({ v: 2 });+ expect(fsPromises.rename).toHaveBeenCalledTimes(2);+ expect(fsPromises.rename.mock.calls.some(([from]) => from === target)).toBe(false);+ });++ it('retries moving a locked destination into the backup slot', async () => {+ const target = join(tmpRoot, 'busy-backup.json');+ 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'));++ await atomicWrite(target, { v: 2 });++ expect(JSON.parse(readFileSync(target, 'utf8'))).toEqual({ v: 2 });+ const moves = fsPromises.rename.mock.calls.filter(([from]) => from === target);+ expect(moves).toHaveLength(2);+ expect(moves[0][1]).toMatch(/\.bak$/);+ expect(moves[1][1]).toBe(moves[0][1]);+ expect(readdirSync(tmpRoot).filter((n) => n.endsWith('.bak') || n.endsWith('.tmp'))).toEqual([]);+ });+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 }));diff --git a/server/lib/imageThumbnail.test.js b/server/lib/imageThumbnail.test.jsindex c130e84eed..d8e5483aa0 100644--- a/server/lib/imageThumbnail.test.js+++ b/server/lib/imageThumbnail.test.js@@ -13,7 +13,7 @@ vi.mock('sharp', async (original) => {const { default: sharp } = await import('sharp');const { ensureImageThumbnail } = await import('./imageThumbnail.js');-afterAll(() => rmSync(tempRoot, { recursive: true, force: true }));+afterAll(() => rmSync(tempRoot, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 }));beforeEach(() => { sharpCalls.count = 0; });async function source(name) {diff --git a/server/routes/brainCollectionPagination.test.js b/server/routes/brainCollectionPagination.test.jsindex 34c15593b4..cf74ede09f 100644--- a/server/routes/brainCollectionPagination.test.js+++ b/server/routes/brainCollectionPagination.test.js@@ -97,7 +97,7 @@ describe('Brain collection pagination (synthetic thousands-record fixtures)', ()});afterAll(() => {- if (tempRoot) rmSync(tempRoot, { recursive: true, force: true });+ if (tempRoot) rmSync(tempRoot, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 });});describe('Inbox pagination & bounds', () => {diff --git a/server/services/assetMounts.test.js b/server/services/assetMounts.test.jsindex e668ace4cb..9637db92ef 100644--- a/server/services/assetMounts.test.js+++ b/server/services/assetMounts.test.js@@ -28,7 +28,7 @@ const tempRoot = createTempDataRoot('portos-asset-mounts-');vi.mock('../lib/fileUtils.js', async (importOriginal) => (makePathsProxy(await importOriginal(), { dataRoot: tempRoot })));-afterAll(() => rmSync(tempRoot, { recursive: true, force: true }));+afterAll(() => rmSync(tempRoot, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 }));// Dynamic, not a static import: the `vi.mock` factory above closes over// `tempRoot`, and a static import would be hoisted above that binding.