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: tolerate a torn migration-lock owner file (#12301)

[._.]/ Adam Eivy89a836875e70
diff --git a/scripts/run-migrations.js b/scripts/run-migrations.js
index 8cad1346fb..cb66e33264 100644
--- a/scripts/run-migrations.js
+++ b/scripts/run-migrations.js
@@ -1,5 +1,5 @@
#!/usr/bin/env node
-import { readFile, mkdir, rm, stat, writeFile } from 'fs/promises';
+import { readFile, mkdir, rm, stat, writeFile, rename } from 'fs/promises';
import { join, dirname } from 'path';
import { pathToFileURL } from 'url';
import { isWorktreeRoot } from '../server/lib/dataRoot.js';
@@ -64,7 +64,11 @@ const pidAlive = (pid) => {
};
const readLockOwner = (lockDir) => readFile(join(lockDir, LOCK_OWNER_FILE), 'utf-8')
- .then((raw) => JSON.parse(raw), () => null)
+ .then((raw) => {
+ // A reader can land between the holder's mkdir and a complete owner write;
+ // an unparseable file means "owner unknown", same as a missing one.
+ try { return JSON.parse(raw); } catch { return null; }
+ }, () => null)
.then((owner) => (owner && typeof owner === 'object' ? owner : null));
/**
@@ -100,7 +104,10 @@ async function acquireMigrationLock(lockDir, { waitMs = LOCK_WAIT_MS, pollMs = L
throw err;
});
if (taken) {
- await writeFile(join(lockDir, LOCK_OWNER_FILE), JSON.stringify({ pid: process.pid, startedAt: Date.now() }));
+ // temp + rename so a concurrent runner sees no owner file or a whole one.
+ const ownerPath = join(lockDir, LOCK_OWNER_FILE);
+ await writeFile(`${ownerPath}.tmp`, JSON.stringify({ pid: process.pid, startedAt: Date.now() }));
+ await rename(`${ownerPath}.tmp`, ownerPath);
return () => rm(lockDir, { recursive: true, force: true });
}
const stale = await lockStaleReason(lockDir);
diff --git a/scripts/run-migrations.test.js b/scripts/run-migrations.test.js
index 89bd327d16..03f980ea25 100644
--- a/scripts/run-migrations.test.js
+++ b/scripts/run-migrations.test.js
@@ -443,6 +443,17 @@ export default {
expect(appliedCount()).toBe(1);
});
+ it('waits on a lock whose owner file is empty (torn read) instead of throwing', async () => {
+ mkdirSync(lockDir);
+ writeFileSync(join(lockDir, 'owner.json'), '');
+ setTimeout(() => rmSync(lockDir, { recursive: true, force: true }), 40);
+
+ const ran = await runMigrations({ rootDir, migrationsDir, lockWaitMs: 2000, lockPollMs: 10 });
+
+ expect(ran).toBeTruthy();
+ expect(appliedCount()).toBeGreaterThan(0);
+ });
+
it('gives up after the bounded wait while a live holder keeps the lock', async () => {
mkdirSync(lockDir);
writeFileSync(join(lockDir, 'owner.json'), JSON.stringify({ pid: process.pid, startedAt: Date.now() }));