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): only sweep ledger temp files whose writer has exited

Adam Eivy74aa673768fc
diff --git a/scripts/run-migrations.js b/scripts/run-migrations.js
index 19e20e5780..61032002ef 100644
--- a/scripts/run-migrations.js
+++ b/scripts/run-migrations.js
@@ -170,10 +170,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.
+ // pid) would ever reuse it. Remove only a dead writer's file: a lock reclaimed
+ // by age can still have a live holder mid-write.
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 });
+ if (!name.startsWith(tmpPrefix)) continue;
+ const pid = Number(name.slice(tmpPrefix.length));
+ if (!Number.isInteger(pid) || pid <= 0 || pid === process.pid || pidAlive(pid)) continue;
+ await rm(join(dirname(appliedFile), name), { force: true });
}
// Load applied migrations list (repairing a corrupt file aside — see
diff --git a/scripts/run-migrations.test.js b/scripts/run-migrations.test.js
index 02e62de4b1..593cc44815 100644
--- a/scripts/run-migrations.test.js
+++ b/scripts/run-migrations.test.js
@@ -473,6 +473,9 @@ export default {
// The dead holder was killed mid ledger write: its temp file never renamed.
const orphanTmp = `${appliedFile}.tmp-2147483646`;
writeFileSync(orphanTmp, '["000-earlier.js"');
+ // A live process's temp file may be mid-write (a lock reclaimed by age).
+ const liveTmp = `${appliedFile}.tmp-${process.ppid}`;
+ writeFileSync(liveTmp, '["000-earlier.js"]');
const ran = await runMigrations({ rootDir, migrationsDir, lockWaitMs: 60, lockPollMs: 10 });
@@ -480,6 +483,7 @@ export default {
expect(warnSpy).toHaveBeenCalledWith(expect.stringContaining('no longer running'));
expect(existsSync(lockDir)).toBe(false);
expect(existsSync(orphanTmp)).toBe(false);
+ expect(existsSync(liveTmp)).toBe(true);
});
it('reclaims a lock held past the stale timeout even when its pid is unknown', async () => {