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 recoverable database stage publications (#8816)

[._.]/ Adam Eivy0ada74c71d08
diff --git a/docs/BACKUP.md b/docs/BACKUP.md
index a5978093bf..66b30184fe 100644
--- a/docs/BACKUP.md
+++ b/docs/BACKUP.md
@@ -257,3 +257,5 @@ node scripts/database-maintenance.mjs cancel <operation-id>
Cancellation supports only the initial accepted stage, preserves the journal in the machine-local cancelled archive, and never switches mode or reverses direction. Restart managed processes through the existing PM2 ecosystem workflow after cancellation if their normal boot was refused. CLI configuration follows the ecosystem's environment precedence; run from the same configured operator environment. Changed source configuration, a different operation ID, an unknown stage/version, and a competing operation are refused.
An incomplete publication or interrupted cancellation remains fenced. Do not remove the active directory, steal its cancellation claim, or guess a backend from `.env`: retain the journal for recovery. This first boundary deliberately supplies no transfer-stage resume/rollback command; the detached coordinator and verified restart protocol are tracked in #8810, and Settings recovery feedback in #8811. Normal startup and migration must not be re-enabled by treating this preparatory operation as a completed cutover.
+
+Coordinator stage publication uses immutable, atomically linked records. A same-operation retry with the existing owner token can confirm its last transition after a lost response; abandoned temporary files do not advance the stage, and a delayed retry cannot overwrite later progress. Interrupted claims from the older publication protocol still fail closed. This does not permit replacing a coordinator, reopening admission, or retrying SQL import: those require the offline recovery protocol.
diff --git a/server/lib/databaseMaintenanceJournal.js b/server/lib/databaseMaintenanceJournal.js
index 04c9467070..5221acb26e 100644
--- a/server/lib/databaseMaintenanceJournal.js
+++ b/server/lib/databaseMaintenanceJournal.js
@@ -1,4 +1,4 @@
-import { existsSync, lstatSync, mkdirSync, openSync, closeSync, fsyncSync, readFileSync, renameSync, writeFileSync } from 'node:fs';
+import { existsSync, lstatSync, mkdirSync, linkSync, unlinkSync, openSync, closeSync, fsyncSync, readFileSync, renameSync, writeFileSync } from 'node:fs';
import { join } from 'node:path';
import { randomUUID } from 'node:crypto';
import { z } from 'zod';
@@ -83,7 +83,21 @@ export function createDatabaseMaintenanceJournal(dataDir = PATHS.data) {
if (!lstatSync(activeDir).isDirectory() || !lstatSync(recordPath).isFile()) {
throw databaseMaintenanceError();
}
- return journalSchema.parse(JSON.parse(readFileSync(recordPath, 'utf8')));
+ let current = journalSchema.parse(JSON.parse(readFileSync(recordPath, 'utf8')));
+ // Immutable publications cannot be overwritten by a delayed older writer.
+ // Legacy journals keep their recorded stage as the history's starting point.
+ for (const stage of stages.slice(stages.indexOf(current.stage) + 1)) {
+ const stagePath = join(activeDir, 'published-' + stage + '.json');
+ try { lstatSync(stagePath); } catch (err) {
+ if (err.code === 'ENOENT') break;
+ throw err;
+ }
+ if (!lstatSync(stagePath).isFile()) throw databaseMaintenanceError();
+ const next = journalSchema.parse(JSON.parse(readFileSync(stagePath, 'utf8')));
+ if (JSON.stringify(next) !== JSON.stringify({ ...current, stage })) throw databaseMaintenanceError();
+ current = next;
+ }
+ return current;
} catch {
throw databaseMaintenanceError();
}
@@ -129,20 +143,36 @@ export function createDatabaseMaintenanceJournal(dataDir = PATHS.data) {
const transition = (id, token, expectedStage, nextStage) => {
assertNotRealDataWrite(activeDir, 'database maintenance transition');
const current = read();
- if (!current || current.id !== id || current.stage !== expectedStage
+ if (!current || current.id !== id || !stages.includes(expectedStage)
|| stages.indexOf(nextStage) !== stages.indexOf(expectedStage) + 1) throw databaseMaintenanceError();
const ownerPath = join(activeDir, 'cancel-' + id + '.claim');
if (!lstatSync(ownerPath).isFile()) throw databaseMaintenanceError();
const owner = JSON.parse(readFileSync(ownerPath, 'utf8'));
if (typeof token !== 'string' || owner.id !== id || owner.token !== token) throw databaseMaintenanceError();
- // Exclusive per-stage publication also serializes two calls by the owner.
- // A crash before rename leaves a pending file and fails closed on retry.
- writeDurableExclusive(join(activeDir, 'stage-' + expectedStage + '.claim'), { id });
- const pending = join(activeDir, 'stage-' + expectedStage + '.pending');
+ // An acknowledged publication may have crashed before returning to its
+ // caller. Only that exact owned transition is idempotent, never a reversal.
+ if (current.stage === nextStage) {
+ syncDirectory(activeDir);
+ return current;
+ }
+ if (current.stage !== expectedStage) throw databaseMaintenanceError();
+ // Do not reinterpret interrupted writes from the old publication protocol.
+ if (existsSync(join(activeDir, 'stage-' + expectedStage + '.claim'))) throw databaseMaintenanceError();
const next = journalSchema.parse({ ...current, stage: nextStage });
+ const pending = join(activeDir, 'publication-' + randomUUID() + '.pending');
writeDurableExclusive(pending, next);
- renameSync(pending, recordPath);
+ try {
+ // link is an atomic, no-replace publication of already-fsynced bytes.
+ // A competing owner-token retry may win; both describe the same transition.
+ linkSync(pending, join(activeDir, 'published-' + nextStage + '.json'));
+ } catch (err) {
+ if (err.code !== 'EEXIST') throw err;
+ } finally {
+ unlinkSync(pending);
+ }
syncDirectory(activeDir);
+ const published = read();
+ if (!published || published.id !== id || stages.indexOf(published.stage) < stages.indexOf(nextStage)) throw databaseMaintenanceError();
return next;
};
diff --git a/server/lib/databaseMaintenanceJournal.test.js b/server/lib/databaseMaintenanceJournal.test.js
index 82fb2aaa43..ebc7e4c443 100644
--- a/server/lib/databaseMaintenanceJournal.test.js
+++ b/server/lib/databaseMaintenanceJournal.test.js
@@ -66,7 +66,7 @@ describe('persistent database maintenance boundary', () => {
j.transition(${JSON.stringify(operation.id)}, ${JSON.stringify(token)}, ${JSON.stringify(stage)}, ${JSON.stringify(next)});`);
expect(result.status, result.stderr).toBe(0);
expect(journal.read()).toEqual({ ...operation, stage: next });
- expect(() => journal.transition(operation.id, token, stage, next)).toThrow();
+ expect(journal.transition(operation.id, token, stage, next)).toEqual({ ...operation, stage: next });
expect(() => journal.assertAdmission()).toThrow();
stage = next;
}
@@ -86,11 +86,31 @@ describe('persistent database maintenance boundary', () => {
const child = spawn(process.execPath, ['--input-type=module', '-e', code], { stdio: 'ignore' });
child.once('close', code => resolve(code));
});
- expect((await Promise.all([run(), run()])).sort()).toEqual([0, 1]);
+ expect((await Promise.all([run(), run()])).sort()).toEqual([0, 0]);
expect(journal.read()).toEqual({ ...operation, stage: 'quiescing' });
expect(() => journal.assertAdmission()).toThrow();
});
+ it('recovers unpublished temporary bytes and acknowledged publications without regressing later stages', () => {
+ const operation = journal.begin({ source, target });
+ const token = journal.acquireCoordinator(operation.id);
+ const active = join(data, 'database-maintenance');
+ // A process killed while preparing its unique file leaves no visible stage.
+ writeFileSync(join(active, 'publication-interrupted.pending'), '{');
+ expect(journal.read()).toEqual(operation);
+ journal.transition(operation.id, token, 'accepted', 'quiescing');
+ // A restarted caller with the same durable ownership can confirm the write.
+ expect(journal.transition(operation.id, token, 'accepted', 'quiescing').stage).toBe('quiescing');
+ journal.transition(operation.id, token, 'quiescing', 'exporting');
+ expect(() => journal.transition(operation.id, token, 'accepted', 'quiescing')).toThrow();
+ expect(journal.read().stage).toBe('exporting');
+ expect(() => journal.assertAdmission()).toThrow();
+ const publication = join(active, 'published-quiescing.json');
+ writeFileSync(publication, JSON.stringify({ ...operation, stage: 'quiescing', target: source }));
+ expect(() => journal.read()).toThrow();
+ expect(journal.isFenced()).toBe(true);
+ });
+
it('preserves the fence and prior stage after interrupted stage publication', () => {
const operation = journal.begin({ source, target });
const token = journal.acquireCoordinator(operation.id);