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
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
fix: make coordinator recovery acknowledgement retry-safe (#8850)
[._.]/ Adam Eivy71fd23aa536d
diff --git a/docs/STORAGE.md b/docs/STORAGE.mdindex 7adfc2d068..e6605ae229 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)` 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. An immutable successor publication chooses exactly one winner across competing recoveries and revokes the old 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)` 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.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.jsindex 78e3171734..8069db44c1 100644--- a/server/lib/databaseMaintenanceJournal.js+++ b/server/lib/databaseMaintenanceJournal.js@@ -227,8 +227,22 @@ export function createDatabaseMaintenanceJournal(dataDir = PATHS.data) {// export/import a successor must re-establish writer/child quiescence: the// worker's exit says nothing about descendants it might have left behind.// No PID probe, clock, reverse operation, or source-success inference occurs.- const recoverCoordinator = (id, previousToken) => {+ const recoverCoordinator = (id, previousToken, recoveryToken) => {assertNotRealDataWrite(activeDir, 'database maintenance coordinator recovery');+ coordinatorSchema.parse({ id, token: recoveryToken });+ coordinatorSchema.parse({ id, token: previousToken });+ if (recoveryToken === previousToken) throw databaseMaintenanceError();+ const owner = readCoordinator(id);+ // The caller persists its recovery token before attempting publication.+ // A crash after link/fsync but before returning must be retryable by that+ // same claimant; another claimant must never learn or reuse its token.+ if (owner?.token === recoveryToken) {+ const published = successorSchema.parse(JSON.parse(readFileSync(+ join(activeDir, 'coordinator-after-' + previousToken + '.json'), 'utf8')));+ if (published.id !== id || published.previousToken !== previousToken || published.token !== recoveryToken) throw databaseMaintenanceError();+ syncDirectory(activeDir);+ return recoveryToken;+ }assertCoordinator(id, previousToken);const current = read();if (!['accepted', 'quiescing', 'exporting', 'importing'].includes(current.stage)@@ -237,13 +251,15 @@ export function createDatabaseMaintenanceJournal(dataDir = PATHS.data) {const fd = openSync(join(directory, 'exit'), 'r+');try { fsyncSync(fd); } finally { closeSync(fd); }syncDirectory(directory);- const next = { id, token: randomUUID(), previousToken };- const pending = join(activeDir, 'coordinator-' + next.token + '.pending');+ const next = { id, token: recoveryToken, previousToken };+ const pending = join(activeDir, 'coordinator-' + randomUUID() + '.pending');writeDurableExclusive(pending, next);try {- // EEXIST is a LOST recovery race, unlike an idempotent stage publication:- // the winner owns a different token and this caller must not execute.+ // EEXIST is a lost race unless this is the SAME recorded recovery+ // request. Different claimants must never receive the winning token.linkSync(pending, join(activeDir, 'coordinator-after-' + previousToken + '.json'));+ } catch (err) {+ if (err.code !== 'EEXIST' || readCoordinator(id)?.token !== recoveryToken) throw err;} finally {unlinkSync(pending);}diff --git a/server/lib/databaseMaintenanceRecovery.test.js b/server/lib/databaseMaintenanceRecovery.test.jsindex f826e62974..6b13b0035a 100644--- a/server/lib/databaseMaintenanceRecovery.test.js+++ b/server/lib/databaseMaintenanceRecovery.test.js@@ -1,4 +1,5 @@import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import { randomUUID } from 'node:crypto';import { spawn } from 'node:child_process';import { mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';import { tmpdir } from 'node:os';@@ -60,9 +61,10 @@ async function launchWorker(operation, token, stage = 'importing') {return { ...child, controlDir };}-function recoveryProcess(operation, token) {+function recoveryProcess(operation, token, recoveryToken = randomUUID(), crashAfterPublication = false) {const code = `import {createDatabaseMaintenanceJournal} from ${JSON.stringify(moduleUrl)};- try {console.log(createDatabaseMaintenanceJournal(${JSON.stringify(data)}).recoverCoordinator(${JSON.stringify(operation.id)},${JSON.stringify(token)}));}+ try {const token = createDatabaseMaintenanceJournal(${JSON.stringify(data)}).recoverCoordinator(${JSON.stringify(operation.id)},${JSON.stringify(token)},${JSON.stringify(recoveryToken)});+ if (${crashAfterPublication}) process.exit(7); console.log(token);}catch {process.exitCode=1;}`;return new Promise((resolve, reject) => {const child = spawn(process.execPath, ['--input-type=module', '-e', code], { stdio: ['ignore', 'pipe', 'pipe'] });@@ -81,7 +83,7 @@ describe('same-operation coordinator recovery', () => {// A paused import is not a recoverable dead owner, however old its PID or// timestamps appear. Only the supervisor's completed exit receipt counts.expect(journal.coordinatorStatus(operation.id)).toEqual({ state: 'awaiting-exit' });- expect(() => journal.recoverCoordinator(operation.id, token)).toThrow();+ expect(() => journal.recoverCoordinator(operation.id, token, randomUUID())).toThrow();expect(() => journal.reserveCoordinatorWorker(operation.id, token)).toThrow();expect(() => journal.assertAdmission()).toThrow();writeFileSync(join(worker.controlDir, 'finish'), '');@@ -95,7 +97,7 @@ describe('same-operation coordinator recovery', () => {expect(journal.read()).toEqual({ ...operation, stage: 'importing' });expect(journal.coordinatorStatus(operation.id)).toEqual({ state: 'unregistered' });expect(() => journal.transition(operation.id, token, 'importing', 'committing')).toThrow();- expect(() => journal.recoverCoordinator(operation.id, token)).toThrow();+ expect(() => journal.recoverCoordinator(operation.id, token, randomUUID())).toThrow();expect(() => journal.begin({ source: to, target: from })).toThrow();expect(() => journal.cancel(operation.id, from)).toThrow();expect(() => journal.assertAdmission()).toThrow();@@ -106,7 +108,7 @@ describe('same-operation coordinator recovery', () => {// No worker was launched into the new reservation; recovery cannot invent// success from a missing/dead PID, even on repeated attempts.writeFileSync(join(nextDirectory, 'pid'), '2147483647');- expect(() => journal.recoverCoordinator(operation.id, successor)).toThrow();+ expect(() => journal.recoverCoordinator(operation.id, successor, randomUUID())).toThrow();}, 40_000);it('recovers a killed worker only after its supervisor acknowledges exit', async () => {@@ -115,24 +117,44 @@ describe('same-operation coordinator recovery', () => {const worker = await launchWorker(operation, token, 'exporting');worker.handle.kill('SIGKILL');await worker.done;- const next = journal.recoverCoordinator(operation.id, token);+ const next = journal.recoverCoordinator(operation.id, token, randomUUID());expect(next).not.toBe(token);expect(journal.read()).toEqual({ ...operation, stage: 'exporting' });expect(() => journal.assertAdmission()).toThrow();}, 40_000);+ it('recovers a published ownership handoff after its caller crashes before receiving the result', async () => {+ const operation = journal.begin({ source, target });+ const token = journal.acquireCoordinator(operation.id);+ const worker = await launchWorker(operation, token, 'exporting');+ writeFileSync(join(worker.controlDir, 'finish'), '');+ await worker.done;+ // This request identity is recorded BEFORE launching the recovery process.+ const recoveryToken = randomUUID();+ writeFileSync(join(root, 'recovery-request.json'), JSON.stringify({ id: operation.id, previousToken: token, recoveryToken }));+ expect(await recoveryProcess(operation, token, recoveryToken, true)).toEqual({ status: 7, token: '' });+ const request = JSON.parse(readFileSync(join(root, 'recovery-request.json'), 'utf8'));+ const retry = await recoveryProcess(operation, request.previousToken, request.recoveryToken);+ expect(retry).toEqual({ status: 0, token: recoveryToken });+ expect((await recoveryProcess(operation, token)).status).toBe(1);+ expect(journal.read()).toEqual({ ...operation, stage: 'exporting' });+ journal.reserveCoordinatorWorker(operation.id, retry.token);+ expect(() => journal.reserveCoordinatorWorker(operation.id, retry.token)).toThrow();+ expect(() => journal.assertAdmission()).toThrow();+ }, 40_000);+it('refuses absent, partial, foreign, or damaged completion evidence and preserves the fence', () => {const operation = journal.begin({ source, target });const token = journal.acquireCoordinator(operation.id);- expect(() => journal.recoverCoordinator(operation.id, token)).toThrow();+ expect(() => journal.recoverCoordinator(operation.id, token, randomUUID())).toThrow();const controlDir = journal.reserveCoordinatorWorker(operation.id, token);for (const value of ['', 'success', '0 trailing', '99999999999', '1\n0']) {writeFileSync(join(controlDir, 'exit'), value);- expect(() => journal.recoverCoordinator(operation.id, token)).toThrow();+ expect(() => journal.recoverCoordinator(operation.id, token, randomUUID())).toThrow();}writeFileSync(join(controlDir, 'exit'), '0\n');writeFileSync(join(controlDir, 'owner.json'), JSON.stringify({ id: operation.id, token: '00000000-0000-4000-8000-000000000000' }));- expect(() => journal.recoverCoordinator(operation.id, token)).toThrow();+ expect(() => journal.recoverCoordinator(operation.id, token, randomUUID())).toThrow();expect(journal.read()).toEqual(operation);expect(() => journal.assertAdmission()).toThrow();});@@ -147,7 +169,7 @@ describe('same-operation coordinator recovery', () => {journal.transition(operation.id, token, current, next);current = next;}- expect(() => journal.recoverCoordinator(operation.id, token)).toThrow();+ expect(() => journal.recoverCoordinator(operation.id, token, randomUUID())).toThrow();expect(journal.read().stage).toBe('committing');expect(() => journal.assertAdmission()).toThrow();});