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(migrations): remove a killed runner's orphaned ledger temp file

Adam Eivybf80813fe43b
diff --git a/scripts/run-migrations.js b/scripts/run-migrations.js
index cb66e33264..19e20e5780 100644
--- a/scripts/run-migrations.js
+++ b/scripts/run-migrations.js
@@ -1,6 +1,6 @@
#!/usr/bin/env node
-import { readFile, mkdir, rm, stat, writeFile, rename } from 'fs/promises';
-import { join, dirname } from 'path';
+import { readFile, readdir, mkdir, rm, stat, writeFile, rename } from 'fs/promises';
+import { basename, join, dirname } from 'path';
import { pathToFileURL } from 'url';
import { isWorktreeRoot } from '../server/lib/dataRoot.js';
import { isDirectlyInvoked } from './lib/directInvocation.js';
@@ -168,6 +168,14 @@ export async function runMigrations({
}
async function runPendingMigrations({ rootDir, migrationsDir, appliedFile }) {
+ // A runner killed between writing the ledger's temp file and renaming it
+ // leaves `migrations.applied.json.tmp-<pid>` behind, and no later run (a new
+ // pid) would ever reuse it. Under the lock no other runner can own one.
+ const tmpPrefix = `${basename(appliedFile)}.tmp-`;
+ for (const name of await readdir(dirname(appliedFile))) {
+ if (name.startsWith(tmpPrefix)) await rm(join(dirname(appliedFile), name), { force: true });
+ }
+
// Load applied migrations list (repairing a corrupt file aside — see
// readAppliedList).
const applied = await readAppliedList(appliedFile, { repair: true });
diff --git a/scripts/run-migrations.test.js b/scripts/run-migrations.test.js
index 03f980ea25..02e62de4b1 100644
--- a/scripts/run-migrations.test.js
+++ b/scripts/run-migrations.test.js
@@ -470,12 +470,16 @@ export default {
mkdirSync(lockDir);
// Above every platform's pid ceiling, so the liveness probe reports ESRCH.
writeFileSync(join(lockDir, 'owner.json'), JSON.stringify({ pid: 2147483646, startedAt: Date.now() }));
+ // The dead holder was killed mid ledger write: its temp file never renamed.
+ const orphanTmp = `${appliedFile}.tmp-2147483646`;
+ writeFileSync(orphanTmp, '["000-earlier.js"');
const ran = await runMigrations({ rootDir, migrationsDir, lockWaitMs: 60, lockPollMs: 10 });
expect(ran).toBe(1);
expect(warnSpy).toHaveBeenCalledWith(expect.stringContaining('no longer running'));
expect(existsSync(lockDir)).toBe(false);
+ expect(existsSync(orphanTmp)).toBe(false);
});
it('reclaims a lock held past the stale timeout even when its pid is unknown', async () => {