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: serialize maintenance recovery with stage publication (#8850)

[._.]/ Adam Eivya3be762cac8f
diff --git a/docs/STORAGE.md b/docs/STORAGE.md
index e6605ae229..e27f2fb181 100644
--- a/docs/STORAGE.md
+++ b/docs/STORAGE.md
@@ -117,7 +117,7 @@ recorded endpoints, and the running pool before cutover.
Coordinator ownership and cancellation share one exclusive durable initial claim. Once owned, an operation advances only through `accepted → quiescing → exporting → importing → committing → verifying → verified`; each transition requires the same operation, current ownership token, and expected previous stage. Immutable stage publications tolerate a retry of the same transition. Every stage (including `verified`) retains the admission fence. Stage names record coordinator progress; they do not independently prove quiescence, transfer, or healthy target startup. Verification-only server startup can read the recorded target through its actual pool at the `verifying` or `verified` stage; its bounded result is transient, creates no new store, and never advances the journal or reopens admission.
-The journal also supplies an **internal ownership-recovery foundation**, not a callable transfer workflow. `reserveCoordinatorWorker(id, token)` reserves a one-use `worker-<token>/` directory bound to that operation and owner. A future coordinator launches its worker through `spawnDetached` with this directory and `cleanup: false`. `recoverCoordinator(id, previousToken, recoveryToken)` accepts only the recorded operation and current token, at `accepted`, `quiescing`, `exporting`, or `importing`, after the detached supervisor has published a complete numeric `exit` receipt. The caller durably records its unique recovery token before attempting recovery. An immutable successor publication chooses exactly one winner across competing recoveries and revokes the old token; retrying that same recorded request returns its published token after a crash between publication and acknowledgement. A different claimant cannot recover or reuse the winner's token. Each successor reserves a new worker directory; old logs and completion evidence remain intact. Recovery preserves the source, target, operation ID, and stage. It does not treat an interrupted import as source success or advance to committing.
+The journal also supplies an **internal ownership-recovery foundation**, not a callable transfer workflow. `reserveCoordinatorWorker(id, token)` atomically publishes a complete, one-use `worker-<token>/` directory bound to that operation and owner. A crash while preparing its binding leaves only an unpublished temporary directory, so the same owner can retry reservation. A future coordinator launches its worker through `spawnDetached` with this directory and `cleanup: false`. `recoverCoordinator(id, previousToken, recoveryToken)` accepts only the recorded operation and current token, at `accepted`, `quiescing`, `exporting`, or `importing`, after the detached supervisor has published a complete numeric `exit` receipt. The caller durably records its unique recovery token before attempting recovery. An immutable successor publication chooses exactly one winner across competing recoveries and revokes the old token; retrying that same recorded request returns its published token after a crash between publication and acknowledgement. A different claimant cannot recover or reuse the winner's token. A shared per-owner/per-stage decision publication serializes ownership handoff with stage transitions. Recovery completes an already-decided forward stage before choosing its successor; a predecessor that lost the decision cannot publish a new stage. Each successor reserves a new worker directory; old logs and completion evidence remain intact. Recovery preserves the source, target, operation ID, and stage. It does not treat an interrupted import as source success or advance to committing.
There is deliberately no PID-death, elapsed-time, or force recovery. A launch interrupted before its supervisor records an exit stays fenced, even if its PID appears dead. A worker exit does **not** prove its descendants stopped: before any export or import, the future execution coordinator must inventory and stop/drain PM2 server and CoS processes, admitted spawns, and owned detached writers, refusing unknown state. It must retain the complete source dump and re-establish quiescence before retrying the same target transaction. Those execution and transfer steps remain tracked by #8850; verified target restart, saved-mode commit, and admission release remain #8851.
diff --git a/server/lib/databaseMaintenanceJournal.js b/server/lib/databaseMaintenanceJournal.js
index 753f528313..de28777e48 100644
--- a/server/lib/databaseMaintenanceJournal.js
+++ b/server/lib/databaseMaintenanceJournal.js
@@ -1,4 +1,4 @@
-import { existsSync, lstatSync, mkdirSync, linkSync, unlinkSync, openSync, closeSync, fsyncSync, readFileSync, renameSync, writeFileSync } from 'node:fs';
+import { existsSync, lstatSync, mkdirSync, linkSync, unlinkSync, openSync, closeSync, fsyncSync, readFileSync, renameSync, rmSync, writeFileSync } from 'node:fs';
import { join } from 'node:path';
import { randomUUID } from 'node:crypto';
import { z } from 'zod';
@@ -29,6 +29,13 @@ const coordinatorSchema = z.object({
token: z.string().uuid(),
}).strict();
const successorSchema = coordinatorSchema.extend({ previousToken: z.string().uuid() });
+const decisionSchema = coordinatorSchema.extend({
+ stage: z.enum(stages),
+ action: z.discriminatedUnion('kind', [
+ z.object({ kind: z.literal('transition'), nextStage: z.enum(stages) }).strict(),
+ z.object({ kind: z.literal('recovery'), recoveryToken: z.string().uuid() }).strict(),
+ ]),
+});
const normalizedHost = host => ['localhost', '127.0.0.1', '::1', '[::1]'].includes(host.toLowerCase())
? 'loopback' : host.toLowerCase();
@@ -190,10 +197,21 @@ export function createDatabaseMaintenanceJournal(dataDir = PATHS.data) {
assertNotRealDataWrite(activeDir, 'database maintenance worker reservation');
const owner = assertCoordinator(id, token);
const directory = workerDirectory(token);
- mkdirSync(directory, { mode: 0o700 });
- syncDirectory(activeDir);
- writeDurableExclusive(join(directory, 'owner.json'), owner);
- syncDirectory(directory);
+ try { lstatSync(directory); throw databaseMaintenanceError(); } catch (err) {
+ if (err.code !== 'ENOENT') throw err;
+ }
+ const pending = join(activeDir, 'worker-pending-' + randomUUID());
+ mkdirSync(pending, { mode: 0o700 });
+ try {
+ writeDurableExclusive(join(pending, 'owner.json'), owner);
+ syncDirectory(pending);
+ // The complete, nonempty reservation is published at once. Another
+ // launch cannot replace it (rename refuses a nonempty destination).
+ renameSync(pending, directory);
+ syncDirectory(activeDir);
+ } finally {
+ rmSync(pending, { recursive: true, force: true });
+ }
return directory;
};
@@ -223,6 +241,29 @@ export function createDatabaseMaintenanceJournal(dataDir = PATHS.data) {
return { state: 'exited', exitCode };
};
+ // A durable CAS for EACH outgoing (owner, stage) state. Transition and
+ // recovery compete on the SAME file, so a predecessor paused after checking
+ // its token cannot publish a new stage after losing ownership. Interrupted
+ // stage decisions can be completed identically before attempting recovery.
+ const decide = (id, token, stage, action) => {
+ const value = decisionSchema.parse({ id, token, stage, action });
+ const destination = join(activeDir, 'decision-' + stage + '-' + token + '.json');
+ const pending = join(activeDir, 'decision-' + randomUUID() + '.pending');
+ writeDurableExclusive(pending, value);
+ try {
+ linkSync(pending, destination);
+ } catch (err) {
+ if (err.code !== 'EEXIST') throw err;
+ } finally {
+ unlinkSync(pending);
+ }
+ syncDirectory(activeDir);
+ if (!lstatSync(destination).isFile()) throw databaseMaintenanceError();
+ const winner = decisionSchema.parse(JSON.parse(readFileSync(destination, 'utf8')));
+ if (winner.id !== id || winner.token !== token || winner.stage !== stage) throw databaseMaintenanceError();
+ return winner.action;
+ };
+
// This transfers journal ownership only, NEVER database authority. Before
// export/import a successor must re-establish writer/child quiescence: the
// worker's exit says nothing about descendants it might have left behind.
@@ -244,9 +285,19 @@ export function createDatabaseMaintenanceJournal(dataDir = PATHS.data) {
return recoveryToken;
}
assertCoordinator(id, previousToken);
- const current = read();
- if (!['accepted', 'quiescing', 'exporting', 'importing'].includes(current.stage)
- || coordinatorStatus(id).state !== 'exited') throw databaseMaintenanceError();
+ if (coordinatorStatus(id).state !== 'exited') throw databaseMaintenanceError();
+ // Only four transfer stages can advance here; each interrupted transition
+ // completion moves strictly forward, never reverses an import to success.
+ while (true) {
+ const current = read();
+ if (!['accepted', 'quiescing', 'exporting', 'importing'].includes(current.stage)) throw databaseMaintenanceError();
+ const decision = decide(id, previousToken, current.stage, { kind: 'recovery', recoveryToken });
+ if (decision.kind === 'recovery') {
+ if (decision.recoveryToken !== recoveryToken) throw databaseMaintenanceError();
+ break;
+ }
+ if (read().stage === current.stage) transition(id, previousToken, current.stage, decision.nextStage);
+ }
const directory = workerDirectory(previousToken);
const fd = openSync(join(directory, 'exit'), 'r+');
try { fsyncSync(fd); } finally { closeSync(fd); }
@@ -283,6 +334,8 @@ export function createDatabaseMaintenanceJournal(dataDir = PATHS.data) {
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 decision = decide(id, token, expectedStage, { kind: 'transition', nextStage });
+ if (decision.kind !== 'transition' || decision.nextStage !== nextStage) throw databaseMaintenanceError();
const next = journalSchema.parse({ ...current, stage: nextStage });
const pending = join(activeDir, 'publication-' + randomUUID() + '.pending');
writeDurableExclusive(pending, next);
diff --git a/server/lib/databaseMaintenanceRecovery.test.js b/server/lib/databaseMaintenanceRecovery.test.js
index 7c03e3648c..a6ad35f829 100644
--- a/server/lib/databaseMaintenanceRecovery.test.js
+++ b/server/lib/databaseMaintenanceRecovery.test.js
@@ -1,6 +1,6 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { randomUUID } from 'node:crypto';
-import { spawn } from 'node:child_process';
+import { spawn, spawnSync } from 'node:child_process';
import { mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
@@ -159,6 +159,64 @@ describe('same-operation coordinator recovery', () => {
expect(() => journal.assertAdmission()).toThrow();
});
+ it.each(['before-decision', 'before-stage-publication'])('serializes recovery against a paused predecessor (%s)', async barrier => {
+ const operation = journal.begin({ source, target });
+ const token = journal.acquireCoordinator(operation.id);
+ const directory = journal.reserveCoordinatorWorker(operation.id, token);
+ writeFileSync(join(directory, 'exit'), '0');
+ const ready = join(root, 'transition-ready');
+ const release = join(root, 'transition-release');
+ const method = barrier === 'before-decision' ? 'openSync' : 'linkSync';
+ const pathIndex = barrier === 'before-decision' ? 0 : 1;
+ const match = barrier === 'before-decision' ? "path.includes('decision-') && path.endsWith('.pending')" : "path.endsWith('published-quiescing.json')";
+ const code = `import fs from 'node:fs';
+ import {syncBuiltinESMExports} from 'node:module';
+ const original=fs[${JSON.stringify(method)}];
+ let paused=false;
+ fs[${JSON.stringify(method)}]=(...args)=>{
+ const path=String(args[${pathIndex}]);
+ if(!paused && (${match})) {
+ paused=true; fs.writeFileSync(${JSON.stringify(ready)},'ready');
+ while(!fs.existsSync(${JSON.stringify(release)})) Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,10);
+ }
+ return original(...args);
+ };
+ syncBuiltinESMExports();
+ const {createDatabaseMaintenanceJournal}=await import(${JSON.stringify(moduleUrl)});
+ try {createDatabaseMaintenanceJournal(${JSON.stringify(data)}).transition(${JSON.stringify(operation.id)},${JSON.stringify(token)},'accepted','quiescing');}
+ catch {process.exitCode=1;}`;
+ const handle = spawn(process.execPath, ['--input-type=module', '-e', code], { stdio: 'ignore' });
+ const child = { handle, finished: false };
+ child.done = new Promise(resolve => handle.once('close', status => { child.finished = true; resolve(status); }));
+ children.push(child);
+ await vi.waitFor(() => expect(readFileSync(ready, 'utf8')).toBe('ready'), { timeout: 20_000 });
+ const next = journal.recoverCoordinator(operation.id, token, randomUUID());
+ writeFileSync(release, '');
+ expect(await child.done).toBe(barrier === 'before-decision' ? 1 : 0);
+ expect(journal.read()).toEqual({ ...operation, stage: barrier === 'before-decision' ? 'accepted' : 'quiescing' });
+ expect(() => journal.transition(operation.id, token, 'quiescing', 'exporting')).toThrow();
+ expect(journal.reserveCoordinatorWorker(operation.id, next)).not.toBe(directory);
+ expect(() => journal.assertAdmission()).toThrow();
+ });
+
+ it('keeps a crashed unpublished worker reservation retryable by the same owner', () => {
+ const operation = journal.begin({ source, target });
+ const token = journal.acquireCoordinator(operation.id);
+ const code = `import fs from 'node:fs';
+ import {syncBuiltinESMExports} from 'node:module';
+ const original=fs.renameSync;
+ fs.renameSync=(from,to)=>{if(String(to).endsWith(${JSON.stringify('worker-' + token)})) process.exit(7); return original(from,to);};
+ syncBuiltinESMExports();
+ const {createDatabaseMaintenanceJournal}=await import(${JSON.stringify(moduleUrl)});
+ createDatabaseMaintenanceJournal(${JSON.stringify(data)}).reserveCoordinatorWorker(${JSON.stringify(operation.id)},${JSON.stringify(token)});`;
+ expect(spawnSync(process.execPath, ['--input-type=module', '-e', code], { timeout: 10_000 }).status).toBe(7);
+ expect(journal.coordinatorStatus(operation.id)).toEqual({ state: 'unregistered' });
+ journal.reserveCoordinatorWorker(operation.id, token);
+ expect(journal.coordinatorStatus(operation.id)).toEqual({ state: 'awaiting-exit' });
+ expect(() => journal.reserveCoordinatorWorker(operation.id, token)).toThrow();
+ expect(() => journal.recoverCoordinator(operation.id, token, randomUUID())).toThrow();
+ });
+
it('rejects a reused ancestor token without publishing an ownership cycle', () => {
const operation = journal.begin({ source, target });
const initial = journal.acquireCoordinator(operation.id);