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 legacy empty restore adoption resumable [issue-10127]
[._.]/ Adam Eivy77db5444bc5b
diff --git a/docs/STORAGE.md b/docs/STORAGE.mdindex 87cc1a9a64..88063d81ca 100644--- a/docs/STORAGE.md+++ b/docs/STORAGE.md@@ -809,6 +809,12 @@ evidence, streamed in bounded records/pages rather than a writable parallel storUnknown DB commit outcomes retain the fence and retry the same evidence. Conflicts,missing capture and interrupted publication fail closed. Nonterminal records remainuncertain; missing DB claim evidence never proves that the journal owner did not start.+Legacy post-replay adoption publishes a fenced exact-ID empty-adoption record+directly, never a transient ready epoch. Its first publication has an atomic intent+link. Only that matching intent/record plus both tables proved empty under the+shared PostgreSQL writer lock can resume adoption or repair its interrupted file+publication. This bounded exception cannot recover or recapture ordinary rewinds,+replace missing permanent facts, or steal another restore's ownership by age/PID.Filesystem restore preserves both execution files and the whole`workflow-maintenance/` subtree, case-insensitively, including absent or damageddiff --git a/docs/features/peer-administration.md b/docs/features/peer-administration.mdindex e88a8947c5..2044c83812 100644--- a/docs/features/peer-administration.md+++ b/docs/features/peer-administration.md@@ -198,6 +198,13 @@ records remain uncertain. Stronger same-owner claim evidence survives, conflictiowners refuse reconciliation, and the preserved journal must match and remainstable. Restore never releases a coordinator claim or interrupts active work.+Legacy committed restores that predate this ledger may adopt only a positively+empty pair of ledger tables. Adoption persists the exact recovery ID directly in+a fenced capture state, with an atomic same-ID intent covering first publication.+Database-lock waits, capture failures and interrupted publication resume only that+empty-adoption owner after another empty-table proof. Ordinary committed rewinds+never recapture an empty database. Downstream repair retries reuse the settled ID.+Filesystem restore preserves the epoch/recovery files and maintenance-ownersubtree, including scoped and mixed-case requests. It does not yet invalidateexecution authority for filesystem-only identity/configuration restores.diff --git a/server/lib/peerExecutionAuthority.js b/server/lib/peerExecutionAuthority.jsindex a9352e50f6..9a9967759d 100644--- a/server/lib/peerExecutionAuthority.js+++ b/server/lib/peerExecutionAuthority.js@@ -10,6 +10,7 @@ const recordSchema = z.object({version: z.literal(1), epoch: uuid, revision: z.number().int().positive().safe(),phase: z.enum(['ready', 'capturing', 'reconciling']),settledRecoveryId: uuid.nullable(),+ emptyAdoptionId: uuid.nullable(),recovery: z.object({ id: uuid, digest: z.string().regex(/^[a-f0-9]{64}$/).nullable(),count: z.number().int().nonnegative().safe().nullable() }).strict().nullable(),}).strict().refine(value => (value.phase === 'ready') === (value.recovery === null))@@ -31,19 +32,24 @@ export function createPeerExecutionAuthority(dataDir, { io = fs, assertWrite = aconst fd = io.openSync(dataDir, 'r');try { io.fsyncSync(fd); } finally { io.closeSync(fd); }};- const read = ({ inside = false } = {}) => {- if (damaged || (!inside && exists(lock))) throw executionAuthorityError('Execution authority needs reconciliation.');+ const read = ({ inside = false, recovery = false } = {}) => {+ if ((!recovery && damaged) || (!inside && exists(lock))) throw executionAuthorityError('Execution authority needs reconciliation.');if (!exists(path)) return null;try {if (!io.lstatSync(path).isFile()) throw new Error('not a regular file');return recordSchema.parse(JSON.parse(io.readFileSync(path, 'utf8')));} catch { throw executionAuthorityError('Execution authority is unreadable; it cannot be reset.'); }};- const transaction = change => {+ const transaction = (change, { emptyAdoptionId = null } = {}) => {assertWrite(path, 'peer execution authority');if (damaged) throw executionAuthorityError('Execution authority publication was interrupted.');io.mkdirSync(dataDir, { recursive: true, mode: 0o700 });- try { io.mkdirSync(lock, { mode: 0o700 }); }+ // The first legacy adoption has no earlier record. An atomic intent link+ // makes even a crash before its first JSON publication recoverable by ID.+ try {+ if (emptyAdoptionId) io.symlinkSync(`empty-adoption:${emptyAdoptionId}`, lock);+ else io.mkdirSync(lock, { mode: 0o700 });+ }catch { throw executionAuthorityError('Execution authority is being changed or needs recovery.'); }let publishing = false;try {@@ -63,7 +69,10 @@ export function createPeerExecutionAuthority(dataDir, { io = fs, assertWrite = a} finally {// Never steal an interrupted publication by age or PID.if (!damaged) {- try { io.rmdirSync(lock); syncDirectory(); } catch { damaged = true; }+ try {+ if (emptyAdoptionId) io.unlinkSync(lock); else io.rmdirSync(lock);+ syncDirectory();+ } catch { damaged = true; }}}};@@ -74,7 +83,7 @@ export function createPeerExecutionAuthority(dataDir, { io = fs, assertWrite = areturn current;};const initialize = () => transaction(current => current ?? {- version: 1, epoch: makeId(), revision: 1, phase: 'ready', recovery: null, settledRecoveryId: null,+ version: 1, epoch: makeId(), revision: 1, phase: 'ready', recovery: null, settledRecoveryId: null, emptyAdoptionId: null,});const beginRestore = id => {uuid.parse(id);@@ -82,10 +91,41 @@ export function createPeerExecutionAuthority(dataDir, { io = fs, assertWrite = aif (!current) throw executionAuthorityError('Initialize the empty ledger before restoring execution records.');if (current.recovery?.id === id) return current;if (current.phase !== 'ready') throw executionAuthorityError('Another execution recovery is pending.');- return { ...current, epoch: makeId(), revision: current.revision + 1, phase: 'capturing',+ return { ...current, emptyAdoptionId: null, epoch: makeId(), revision: current.revision + 1, phase: 'capturing',recovery: { id, digest: null, count: null } };});};+ // Internal restore primitive: caller MUST hold the ledger writer transaction+ // lock and have positively proved BOTH tables empty. No age/PID lock stealing.+ const recoverEmptyAdoption = id => {+ uuid.parse(id);+ const current = read({ inside: true, recovery: true });+ const locked = exists(lock);+ const intent = locked && io.lstatSync(lock).isSymbolicLink() && io.readlinkSync(lock) === `empty-adoption:${id}`;+ if (current?.emptyAdoptionId !== id && !(intent && !current)) {+ if (locked || damaged) throw executionAuthorityError('Interrupted authority has no matching empty-adoption proof.');+ return current;+ }+ assertWrite(path, 'peer execution empty restore recovery');+ if (locked) {+ if (io.lstatSync(lock).isSymbolicLink()) {+ if (!intent) throw executionAuthorityError('The empty-adoption owner changed.');+ io.unlinkSync(lock);+ } else io.rmdirSync(lock); // Refuses unexpected contents.+ syncDirectory();+ }+ damaged = false;+ return current;+ };+ const beginEmptyAdoption = id => {+ uuid.parse(id);+ return transaction(current => {+ if (current?.emptyAdoptionId === id) return current;+ if (current) throw executionAuthorityError('Existing authority cannot be replaced by legacy empty adoption.');+ return { version: 1, epoch: makeId(), revision: 1, phase: 'capturing',+ recovery: { id, digest: null, count: null }, settledRecoveryId: null, emptyAdoptionId: id };+ }, { emptyAdoptionId: id });+ };const recordSnapshot = (id, digest, count) => transaction(current => {if (current?.recovery?.id !== id || current.phase !== 'capturing')throw executionAuthorityError('The execution recovery owner changed.');@@ -96,5 +136,6 @@ export function createPeerExecutionAuthority(dataDir, { io = fs, assertWrite = athrow executionAuthorityError('The execution recovery owner changed.');return { ...current, revision: current.revision + 1, phase: 'ready', recovery: null, settledRecoveryId: id };});- return { read, requireReady, initialize, beginRestore, recordSnapshot, completeRestore, recoveryPath, assertWrite };+ return { read, requireReady, initialize, beginRestore, beginEmptyAdoption, recoverEmptyAdoption,+ recordSnapshot, completeRestore, recoveryPath, assertWrite };}diff --git a/server/services/peerExecutionLedger.db.test.js b/server/services/peerExecutionLedger.db.test.jsindex b5d331383f..d827eb74b5 100644--- a/server/services/peerExecutionLedger.db.test.js+++ b/server/services/peerExecutionLedger.db.test.js@@ -7,6 +7,7 @@ import { join } from 'node:path';import { checkHealth, close, ensureSchema, query, withTransaction } from '../lib/db.js';import { requireDbOrSkip } from '../lib/dbTestGate.js';import { createPeerExecutionLedger } from './peerExecutionLedger.js';+import { createPeerExecutionAuthority } from '../lib/peerExecutionAuthority.js';const health = await checkHealth().catch(() => ({ connected: false }));if (health.connected) await ensureSchema();@@ -37,16 +38,71 @@ afterEach(async () => {afterAll(async () => { if (health.connected) await close(); });describe.skipIf(!runDb)('receiver-local permanent execution consumption', () => {+ it.each(['acquisition', 'capture-query', 'begin-publication', 'snapshot-publication', 'completion-publication', 'directory-sync'])+ ('resumes only the same legacy empty-adoption owner after %s failure and process reconstruction', async boundary => {+ const { _createPeerExecutionRestore } = await import('./peerExecutionRestore.js');+ fs.unlinkSync(join(directory, 'peer-execution-authority.json'));+ const id = randomUUID();+ let publications = 0, failed = false;+ const io = { ...fs,+ renameSync: (...args) => {+ publications++;+ const target = { 'begin-publication': 1, 'snapshot-publication': 2, 'completion-publication': 3 }[boundary];+ if (!failed && publications === target) { failed = true; throw new Error('fixture publication failure'); }+ return fs.renameSync(...args);+ },+ fsyncSync: fd => {+ if (boundary === 'directory-sync' && !failed && fs.fstatSync(fd).isDirectory()) {+ failed = true; throw new Error('fixture directory-sync failure');+ }+ return fs.fsyncSync(fd);+ },+ };+ const faultDb = { query, withTransaction: fn => {+ if (boundary === 'acquisition' && !failed) { failed = true; return Promise.reject(new Error('fixture acquisition failure')); }+ return withTransaction(client => fn({ query: (sql, params) => {+ if (boundary === 'capture-query' && !failed && sql.startsWith('SELECT * FROM peer_execution_operations')) {+ failed = true; throw new Error('fixture capture-query failure');+ }+ return client.query(sql, params);+ } }));+ } };+ const faulty = createPeerExecutionLedger({ db: faultDb, dataDir: directory,+ authority: createPeerExecutionAuthority(directory, { io }) });+ const hooks = _createPeerExecutionRestore({ receiver: async () => faulty });+ await expect(hooks.finishPeerExecutionRestore(id)).rejects.toThrow(/fixture/);+ expect(failed).toBe(true);+ // A different generic restore cannot adopt or steal this ownership.+ const restarted = createPeerExecutionLedger({ db, dataDir: directory });+ const retry = _createPeerExecutionRestore({ receiver: async () => restarted });+ if (boundary !== 'acquisition') await expect(retry.finishPeerExecutionRestore(randomUUID())).rejects.toThrow();+ const completed = await retry.finishPeerExecutionRestore(id);+ expect(completed).toMatchObject({ phase: 'ready', settledRecoveryId: id, emptyAdoptionId: id });+ expect(await retry.finishPeerExecutionRestore(id)).toEqual(completed);+ expect(await restarted.list()).toEqual([]);+ });+ it('never recaptures a normal committed rewind even if both rewound tables are empty', async () => {+ const { _createPeerExecutionRestore } = await import('./peerExecutionRestore.js');+ const saved = (await ledger.consume(input)).operation;+ const id = randomUUID();+ ledger.authority.beginRestore(id);+ await query('DELETE FROM peer_execution_operations');+ await query('DELETE FROM peer_execution_generation_floors');+ const hooks = _createPeerExecutionRestore({ receiver: async () => ledger });+ await expect(hooks.finishPeerExecutionRestore(id)).rejects.toThrow(/committed restore/);+ expect(ledger.authority.read()).toMatchObject({ phase: 'capturing', emptyAdoptionId: null });+ expect(await ledger.read(saved.operationId)).toBeNull();+ });it('durably settles legacy empty committed-restore compatibility before downstream retries', async () => {- const { createPeerExecutionRestore } = await import('./peerExecutionRestore.js');- const hooks = createPeerExecutionRestore({ receiver: async () => ledger });+ const { _createPeerExecutionRestore } = await import('./peerExecutionRestore.js');+ const hooks = _createPeerExecutionRestore({ receiver: async () => ledger });fs.unlinkSync(join(directory, 'peer-execution-authority.json'));const id = randomUUID();const first = await hooks.finishPeerExecutionRestore(id);expect(first).toMatchObject({ phase: 'ready', settledRecoveryId: id });// Federation resync/generic-journal release can fail after this hook returns.await expect(Promise.reject(new Error('fixture downstream release failure'))).rejects.toThrow(/downstream/);- const restarted = createPeerExecutionRestore({ receiver: async () => createPeerExecutionLedger({ db, dataDir: directory }) });+ const restarted = _createPeerExecutionRestore({ receiver: async () => createPeerExecutionLedger({ db, dataDir: directory }) });expect(await restarted.finishPeerExecutionRestore(id)).toEqual(first);});it('serializes duplicate first requests, retaining one operation through process reconstruction', async () => {diff --git a/server/services/peerExecutionLedger.js b/server/services/peerExecutionLedger.jsindex 5948f9beeb..6d46f0731e 100644--- a/server/services/peerExecutionLedger.js+++ b/server/services/peerExecutionLedger.js@@ -155,8 +155,7 @@ export function createPeerExecutionLedger({ db, dataDir, authority = createPeerEWHERE ($1::uuid IS NULL OR operation_id > $1) ORDER BY operation_id LIMIT $2`, [after, limit]);return rows.map(fromRow);};- const prepareRestore = id => locked(async client => {- const started = authority.beginRestore(id); // Invalidates old evidence BEFORE any rewind.+ const captureRestore = async (client, id, started) => {if (started.phase !== 'capturing') return started; // Never recapture a rewound database on retry.const pending = `${authority.recoveryPath}.${makeId()}.pending`;authority.assertWrite(pending, 'peer execution restore evidence');@@ -197,6 +196,20 @@ export function createPeerExecutionLedger({ db, dataDir, authority = createPeerEtry { fs.fsyncSync(directory); } finally { fs.closeSync(directory); }}return authority.recordSnapshot(id, hash.digest('hex'), count);+ };+ const prepareRestore = id => locked(client => captureRestore(client, id, authority.beginRestore(id)));+ const adoptEmptyRestore = id => locked(async client => {+ uuid.parse(id);+ // Before any file publication/recovery, prove this receiver never had facts+ // in the restored schema. A normal capture can NEVER take this retry path.+ const { rows: [row] } = await client.query('SELECT EXISTS(SELECT 1 FROM peer_execution_operations) OR EXISTS(SELECT 1 FROM peer_execution_generation_floors) AS occupied');+ let current;+ if (!row.occupied) current = authority.recoverEmptyAdoption(id);+ else current = authority.read();+ if (current?.phase === 'ready' && current.settledRecoveryId === id) return current;+ if (current && current.emptyAdoptionId !== id) return current;+ if (row.occupied) throw executionAuthorityError('Legacy empty adoption has unexpected permanent execution facts.');+ return captureRestore(client, id, authority.beginEmptyAdoption(id));});// Stream twice: authenticate ALL recovery bytes before applying any rows.const visitFacts = async visit => {@@ -299,5 +312,5 @@ export function createPeerExecutionLedger({ db, dataDir, authority = createPeerEif (current?.phase === 'ready' && current.settledRecoveryId === id) return current;return authority.completeRestore(id);};- return { initialize, consume, read, list, transition, advanceGenerationFloor, prepareRestore, reconcileRestore, authority };+ return { initialize, consume, read, list, transition, advanceGenerationFloor, prepareRestore, adoptEmptyRestore, reconcileRestore, authority };}diff --git a/server/services/peerExecutionRestore.js b/server/services/peerExecutionRestore.jsindex 397dd1ebd0..e5647b0de2 100644--- a/server/services/peerExecutionRestore.js+++ b/server/services/peerExecutionRestore.js@@ -9,7 +9,7 @@ async function receiverLedger({ repairSchema = false } = {}) {return createPeerExecutionLedger({ db, dataDir: PATHS.data });}-export function createPeerExecutionRestore({ receiver = receiverLedger } = {}) {+export function _createPeerExecutionRestore({ receiver = receiverLedger } = {}) {const preparePeerExecutionRestore = async id => {const ledger = await receiver();await ledger.initialize();@@ -17,15 +17,10 @@ export function createPeerExecutionRestore({ receiver = receiverLedger } = {}) {};const finishPeerExecutionRestore = async (id, { rolledBack = false } = {}) => {const ledger = await receiver({ repairSchema: rolledBack });- const before = ledger.authority.read();- const current = await ledger.initialize();- // A generic restore started by a version predating the ledger has no capture.- // initialize only permits this when BOTH new tables are empty. Durably settle- // that empty baseline so downstream repair/release retries remain idempotent.- if (!before) {- await ledger.prepareRestore(id);- return ledger.reconcileRestore(id);- }+ // No transient ready epoch: legacy compatibility publishes its exact ID+ // directly as capturing under the shared PG lock, and resumes only that mode.+ const current = await ledger.adoptEmptyRestore(id);+ if (current.phase === 'ready' && current.settledRecoveryId === id) return current;if (rolledBack && current.phase === 'ready') return current;if (current.phase === 'capturing') {if (!rolledBack) throw executionAuthorityError('A committed restore lacks completed non-rewound execution capture.');@@ -38,6 +33,6 @@ export function createPeerExecutionRestore({ receiver = receiverLedger } = {}) {return { preparePeerExecutionRestore, finishPeerExecutionRestore };}-const restoreHooks = createPeerExecutionRestore();+const restoreHooks = _createPeerExecutionRestore();export const preparePeerExecutionRestore = restoreHooks.preparePeerExecutionRestore;export const finishPeerExecutionRestore = restoreHooks.finishPeerExecutionRestore;