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: preserve the original file when Windows atomic replacement stays locked (#9556)

Adam Eivy011ddbe8a4da
diff --git a/docs/TROUBLESHOOTING.md b/docs/TROUBLESHOOTING.md
index 24b6913b6d..627e8b7f2f 100644
--- a/docs/TROUBLESHOOTING.md
+++ b/docs/TROUBLESHOOTING.md
@@ -856,3 +856,19 @@ a test, and update macOS + `mflux`/`mlx`.
2. **Browser console**: F12 → Console for frontend errors
3. **Server logs**: Look for emoji prefixes (❌ errors, ⚠️ warnings)
4. **GitHub Issues**: Report bugs at https://github.com/atomantic/PortOS/issues
+
+## Recovering a store with an orphaned `.bak` file
+
+**Symptom**: a read reports a store as unreadable with "is missing but a `<name>.*.bak` backup sibling exists — recovery required", or a Windows write fails with "stayed locked … the existing file was left untouched".
+
+**Cause**: Windows can keep a file locked (antivirus scan, open handle) so the atomic replace is refused. Current versions retry briefly, then fail the write and leave the original file untouched. Older versions instead moved the file to `<name>.<pid>.<ts>.<uuid>.bak` and could lose the canonical copy if installing the new file also failed. PortOS never picks a backup automatically, because it cannot tell which copy is correct.
+
+**Solution**:
+
+1. Stop PortOS (and anything else that writes the data directory) so nothing recreates the canonical file.
+2. Keep every copy — do not delete any `.bak` or `.tmp` sibling yet.
+3. Inspect the `.bak` files (newest timestamp first) and decide which holds the right state.
+4. Copy the chosen one to the canonical filename (e.g. `settings.json`), leaving the other copies in place.
+5. Restart PortOS, confirm the data is intact, then remove the leftover backups.
+
+For a failed write, wait for the lock to clear (pause the antivirus scan on the data directory) and repeat the action; no recovery is needed.
diff --git a/server/lib/fileCore.js b/server/lib/fileCore.js
index 14cb8b4ddc..190130a55a 100644
--- a/server/lib/fileCore.js
+++ b/server/lib/fileCore.js
@@ -32,14 +32,10 @@ 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
+// to avoid both a failed write and the reader's
// 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'];
@@ -258,36 +254,16 @@ export async function atomicWrite(filePath, data) {
};
// 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.
+ // concurrent reader). Retry the atomic rename a bounded number of times; if the lock
+ // persists, FAIL the write (#9556). The previous fallback moved the destination to a `.bak`
+ // sibling and installed the temp file — if that install also failed, the only canonical
+ // copy was left orphaned at the backup path while readers saw a trustworthy "absent" store.
+ // Rejecting leaves the original bytes untouched at filePath.
const replace = async () => {
- // 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.
- const firstRename = await renameWithWindowsRetries(tmp, filePath);
- const err = firstRename.err;
+ const { err } = await renameWithWindowsRetries(tmp, filePath);
if (!err) return;
if (isWindows() && WIN_RENAME_LOCK_CODES.includes(err.code)) {
- const bak = `${filePath}.${process.pid}.${Date.now()}.${randomUUID()}.bak`;
- // 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 renameWithWindowsRetries(bak, filePath);
- throw renameErr;
- }
- if (hadExisting) await unlink(bak).catch(() => {});
- return;
+ err.message = `${err.message} — ${basename(filePath)} stayed locked after ${WIN_RETRY_ATTEMPTS} attempts; the existing file was left untouched, so retry the write once the lock (AV scan, open handle) clears`;
}
throw err;
};
diff --git a/server/lib/fileUtils.test.js b/server/lib/fileUtils.test.js
index ead138b68d..73afbc2a79 100644
--- a/server/lib/fileUtils.test.js
+++ b/server/lib/fileUtils.test.js
@@ -1415,7 +1415,6 @@ 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;
@@ -1473,64 +1472,22 @@ describe('Windows swap-window retries (#4095)', () => {
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 () => {
+ it('preserves the original bytes and removes only the temp file when every retry stays locked (#9556)', 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('retries a transient lock while moving the existing destination to backup', async () => {
- const target = join(tmpRoot, 'transient-backup-lock.json');
- 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'));
-
- await atomicWrite(target, { v: 2 });
-
- expect(JSON.parse(readFileSync(target, 'utf8'))).toEqual({ v: 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([]);
- });
-
- it('preserves the existing destination when the backup move stays locked', async () => {
- const target = join(tmpRoot, 'persistent-backup-lock.json');
- 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 < BACKUP_RETRY_ATTEMPTS; i += 1) fsPromises.rename.mockRejectedValueOnce(lockError('EBUSY'));
+ fsPromises.rename.mockRejectedValue(lockError('EPERM'));
- await expect(atomicWrite(target, { v: 2 })).rejects.toMatchObject({ code: 'EBUSY' });
+ await expect(atomicWrite(target, { v: 2 })).rejects.toMatchObject({
+ code: 'EPERM',
+ message: expect.stringContaining('existing file was left untouched'),
+ });
+ // The destination is never moved aside — no backup swap exists any more.
+ expect(fsPromises.rename.mock.calls.some(([from]) => from === target)).toBe(false);
+ expect(fsPromises.rename).toHaveBeenCalledTimes(RETRY_ATTEMPTS);
expect(JSON.parse(readFileSync(target, 'utf8'))).toEqual({ v: 1 });
- expect(fsPromises.rename).toHaveBeenCalledTimes(RETRY_ATTEMPTS + BACKUP_RETRY_ATTEMPTS);
- expect(readdirSync(tmpRoot)).toEqual(['persistent-backup-lock.json']);
+ expect(readdirSync(tmpRoot)).toEqual(['stubborn.json']);
});
it('does not retry off win32 — a rename failure still surfaces immediately', async () => {
@@ -1598,6 +1555,16 @@ describe('Windows swap-window retries (#4095)', () => {
expect(fsPromises.readFile).toHaveBeenCalledTimes(1);
});
+ it('reports a missing file with a legacy .bak sibling as recovery-required, never empty (#9556)', async () => {
+ const target = join(tmpRoot, 'orphaned.json');
+ writeFileSync(`${target}.1234.5678.bak`, '{"secret":"original"}');
+ fakePlatform('win32');
+
+ expect(await readJSONFileStrict(target, { fallback: true }, { logError: false }))
+ .toEqual({ ok: false, value: { fallback: true } });
+ expect(await tryReadFileStrict(target)).toEqual({ ok: false, value: null });
+ });
+
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');
diff --git a/server/lib/jsonIo.js b/server/lib/jsonIo.js
index 472c004fb7..9eb04e2a79 100644
--- a/server/lib/jsonIo.js
+++ b/server/lib/jsonIo.js
@@ -231,6 +231,18 @@ async function hasSwapSibling(filePath) {
});
}
+/**
+ * Error for a missing canonical file that has a legacy `.bak` sibling: the only
+ * copy of the data may live at the backup path. Deliberately NOT ENOENT, so both
+ * strict readers report it as unreadable/recovery-required instead of absent.
+ * Carries no file contents; the guide is docs/TROUBLESHOOTING.md.
+ */
+function orphanedBackupError(filePath, cause) {
+ const err = new Error(`${basename(filePath)} is missing but a ${basename(filePath)}.*.bak backup sibling exists — recovery required; stop writers and restore it manually (see docs/TROUBLESHOOTING.md "Recovering a store with an orphaned .bak file")`, { cause });
+ err.code = 'EBACKUP_ORPHANED';
+ return err;
+}
+
/**
* `readFile(filePath, encoding)` with the Windows-only retries that keep a read
* racing `atomicWrite` from being mistaken for an empty/absent file (#4095).
@@ -261,6 +273,9 @@ async function readWithSwapRetry(filePath, encoding = 'utf-8') {
return outcome.content;
}
const last = attempt >= WIN_RETRY_ATTEMPTS - 1;
+ // Retries exhausted on a vanished file that still has a `.bak` sibling: a legacy
+ // backup swap lost its canonical copy (#9556). Never report this as absent.
+ if (last && outcome.err.code === 'ENOENT' && await hasSwapSibling(filePath)) throw orphanedBackupError(filePath, outcome.err);
const retriable = WIN_READ_LOCK_CODES.includes(outcome.err.code)
|| (outcome.err.code === 'ENOENT' && !last && await hasSwapSibling(filePath));
if (last || !retriable) throw outcome.err;