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([issue-10127]): preserve execution ownership and revocation through restore

[._.]/ Adam Eivy77760cc005c8
diff --git a/server/services/backup.js b/server/services/backup.js
index d6c5cef9f5..9e705da048 100644
--- a/server/services/backup.js
+++ b/server/services/backup.js
@@ -1337,6 +1337,7 @@ const RESTORE_PRESERVED_FILES = Object.freeze([
const caseInsensitiveGlob = (name) => name.replace(/[a-z]/gi, ch => `[${ch.toLowerCase()}${ch.toUpperCase()}]`);
const RESTORE_PRESERVED_RSYNC_EXCLUDES = RESTORE_PRESERVED_FILES.map(name => `--exclude=/${caseInsensitiveGlob(name)}`);
const isRestorePreservedPath = (relativePath) => {
+ if (typeof relativePath !== 'string') return false;
const normalized = relativePath.toLowerCase();
return RESTORE_PRESERVED_FILES.some(path => normalized === path || normalized.startsWith(`${path}/`));
};
@@ -1786,6 +1787,13 @@ async function replayAdmittedDump({ tableCount, sizeBytes, snapshotId, dump, res
error: 'The restore recovery journal could not be written. Restore was refused without changing data.',
};
}
+ try {
+ const { preparePeerExecutionRestore } = await import('./peerExecutionRestore.js');
+ await preparePeerExecutionRestore(record.id);
+ } catch (err) {
+ console.error(`❌ restore: execution consumption capture failed: ${err.message}`);
+ return pendingRecoveryResult('restore_execution_reconciliation', record);
+ }
const { host: pgHost, port, database: pgDb, user: pgUser } = POOL_CONFIG;
const pgPort = String(port);
@@ -1850,7 +1858,7 @@ async function replayAdmittedDump({ tableCount, sizeBytes, snapshotId, dump, res
// fenced instead of reopening writes or replaying again.
const settled = await settleReplayOutcome(record);
if (settled.outcome === 'rolled_back') return replay;
- if (settled.outcome === 'uncertain') return pendingRecoveryResult('restore_commit_unknown', record);
+ if (settled.outcome === 'uncertain') return pendingRecoveryResult(settled.reason ?? 'restore_commit_unknown', record);
record = settled.record;
}
diff --git a/server/services/backup.test.js b/server/services/backup.test.js
index ee07e920a6..4a40cd7e76 100644
--- a/server/services/backup.test.js
+++ b/server/services/backup.test.js
@@ -73,6 +73,11 @@ vi.mock('../lib/databaseMaintenanceJournal.js', () => ({
vi.mock('../scripts/run-db-migrations.js', () => ({
runDbMigrations: vi.fn().mockResolvedValue(0),
}));
+const executionRestore = vi.hoisted(() => ({ prepare: vi.fn(), finish: vi.fn() }));
+vi.mock('./peerExecutionRestore.js', () => ({
+ preparePeerExecutionRestore: executionRestore.prepare,
+ finishPeerExecutionRestore: executionRestore.finish,
+}));
// Passthrough seam: the snapshot-cut failure tests wrap acquisition to shorten the
// drain timeout or fail release. Left unset, runBackup uses the real boundary.
const snapshotCutSeam = vi.hoisted(() => ({ wrap: null }));
@@ -1245,6 +1250,8 @@ describe('restorePostgres', () => {
vi.unstubAllEnvs();
rmSync(RECOVERY_JOURNAL(), { force: true });
query.mockReset().mockImplementation(restoreDbAnswer());
+ executionRestore.prepare.mockReset().mockResolvedValue(undefined);
+ executionRestore.finish.mockReset().mockResolvedValue(undefined);
checkHealth.mockResolvedValue({ connected: true });
getServerMajorVersion.mockResolvedValue(16);
({ restorePostgres } = await import('./backup.js'));
@@ -1507,6 +1514,40 @@ describe('restorePostgres', () => {
expect(atSpawn.env.PGAPPNAME).toBe(`portos-restore-${atSpawn.journal.id}`);
// Success releases admission.
expect(readRecoveryJournal()).toBeNull();
+ expect(executionRestore.prepare).toHaveBeenCalledWith(atSpawn.journal.id);
+ expect(executionRestore.prepare.mock.invocationCallOrder[0]).toBeLessThan(spawn.mock.invocationCallOrder[0]);
+ expect(executionRestore.finish).toHaveBeenCalledWith(atSpawn.journal.id);
+ });
+
+ it('never spawns replay when execution recovery capture fails, then recovers the proven unchanged database', async () => {
+ executionRestore.prepare.mockRejectedValueOnce(new Error('fixture capture unavailable'));
+ const result = await restorePostgres('/dest', 'snap-1', { dryRun: false });
+ expect(result).toMatchObject({ status: 'failed', reason: 'restore_execution_reconciliation' });
+ expect(spawn).not.toHaveBeenCalled();
+ const current = readRecoveryJournal();
+ expect(await resumeDatabaseRestore(current.id)).toMatchObject({ status: 'ok', outcome: 'rolled_back' });
+ expect(executionRestore.finish).toHaveBeenCalledWith(current.id, { rolledBack: true });
+ expect(readRecoveryJournal()).toBeNull();
+ });
+
+ it('keeps committed restore fenced through execution reconciliation failure and retries without replay', async () => {
+ executionRestore.finish.mockRejectedValueOnce(new Error('fixture execution evidence unavailable'));
+ const result = await runRestore();
+ expect(result).toMatchObject({ status: 'failed', reason: 'restore_execution_reconciliation' });
+ const current = readRecoveryJournal();
+ const replayCount = spawn.mock.calls.length;
+ expect(await resumeDatabaseRestore(current.id)).toMatchObject({ status: 'ok', outcome: 'repaired' });
+ expect(spawn).toHaveBeenCalledTimes(replayCount);
+ expect(readRecoveryJournal()).toBeNull();
+ });
+
+ it('retains the generic fence when rollback execution reconciliation fails', async () => {
+ executionRestore.finish.mockRejectedValueOnce(new Error('fixture rollback evidence unavailable'));
+ const result = await runRestore({ exitCode: 1 });
+ expect(result).toMatchObject({ status: 'failed', reason: 'restore_execution_reconciliation' });
+ const current = readRecoveryJournal();
+ expect(await resumeDatabaseRestore(current.id)).toMatchObject({ status: 'ok', outcome: 'rolled_back' });
+ expect(readRecoveryJournal()).toBeNull();
});
it.each([
diff --git a/server/services/backupRestoreRecovery.js b/server/services/backupRestoreRecovery.js
index 1325d978eb..e8bf2cd9b0 100644
--- a/server/services/backupRestoreRecovery.js
+++ b/server/services/backupRestoreRecovery.js
@@ -31,6 +31,7 @@ const SESSION_SETTLE_MS = 200;
const MESSAGES = {
restore_commit_unknown: 'The restore could not confirm whether the database dump was committed. Ordinary database work stays paused and the dump will NOT be replayed; retry recovery from Settings > Backup once PostgreSQL is reachable.',
restore_schema_reconciliation: 'The database dump was applied, but schema recovery is incomplete. It was not rolled back and will not be replayed. Ordinary database work stays paused: retry recovery from Settings > Backup, or restart PortOS to retry automatically. If it keeps failing, check the server logs.',
+ restore_execution_reconciliation: 'Execution request consumption and unresolved ownership are awaiting reconciliation. Database work stays paused; the dump will not be replayed. Recovery retries automatically at startup and can also be retried from Settings > Backup.',
restore_sync_resync: 'The database dump was applied, but peer sync could not be reset yet. It will not be replayed. Ordinary database work stays paused: retry recovery from Settings > Backup, or restart PortOS to retry automatically.',
restore_recovery_release: 'The database dump was applied and repaired, but the recovery journal could not be cleared. Ordinary database work stays paused: retry recovery from Settings > Backup.',
restore_recovery_pending: 'A previous database restore is awaiting recovery. Finish it from Settings > Backup before starting another restore.',
@@ -168,6 +169,14 @@ export async function repairCommittedRestore(record) {
console.error(`❌ DB restore ${record.id}: schema reconciliation failed: ${reconciliationError.message}`);
return pendingRecoveryResult('restore_schema_reconciliation', record);
}
+ const executionError = await (async () => {
+ const { finishPeerExecutionRestore } = await import('./peerExecutionRestore.js');
+ await finishPeerExecutionRestore(record.id);
+ })().then(() => null, error => error);
+ if (executionError) {
+ console.error(`❌ DB restore ${record.id}: execution reconciliation failed: ${executionError.message}`);
+ return pendingRecoveryResult('restore_execution_reconciliation', record);
+ }
const resync = await resyncFederationAfterRestore(record.feedPositions).then(
(syncCursorsRewound) => ({ syncCursorsRewound }),
(err) => ({ err }),
@@ -195,6 +204,13 @@ export async function repairCommittedRestore(record) {
export async function settleReplayOutcome(record) {
const outcome = await inspectReplayOutcome(record);
if (outcome === 'rolled_back') {
+ try {
+ const { finishPeerExecutionRestore } = await import('./peerExecutionRestore.js');
+ await finishPeerExecutionRestore(record.id, { rolledBack: true });
+ } catch (err) {
+ console.error(`❌ DB restore ${record.id}: rollback execution reconciliation failed: ${err.message}`);
+ return { outcome: 'uncertain', record, reason: 'restore_execution_reconciliation' };
+ }
databaseRestoreRecovery.release(record.id);
console.log(`💾 DB restore ${record.id}: replay rolled back; database admission reopened without changes`);
return { outcome, record };
@@ -226,7 +242,7 @@ export async function resumeDatabaseRestore(id) {
if (current.stage === 'replaying') {
const settled = await settleReplayOutcome(current);
if (settled.outcome === 'rolled_back') return { status: 'ok', outcome: 'rolled_back' };
- if (settled.outcome === 'uncertain') return pendingRecoveryResult('restore_commit_unknown', current);
+ if (settled.outcome === 'uncertain') return pendingRecoveryResult(settled.reason ?? 'restore_commit_unknown', current);
current = settled.record;
}
const repaired = await repairCommittedRestore(current);
diff --git a/server/services/peerExecutionLedger.db.test.js b/server/services/peerExecutionLedger.db.test.js
index 20b14c512a..6cee9a8859 100644
--- a/server/services/peerExecutionLedger.db.test.js
+++ b/server/services/peerExecutionLedger.db.test.js
@@ -58,11 +58,11 @@ describe.skipIf(!runDb)('receiver-local permanent execution consumption', () =>
it('retains consumed identity independently of action, renewal, sender and generation floors', async () => {
const saved = await ledger.consume(input);
await ledger.advanceGenerationFloor({ hostInstanceId: input.hostInstanceId, peerInstanceId: input.peerInstanceId,
- action: input.intent.action, generation: 4 });
+ action: input.intent.action, generation: 4, executionEpoch: input.executionEpoch });
expect(await ledger.consume(input)).toMatchObject({ isNew: false, operation: saved.operation });
await expect(ledger.consume({ ...input, requestId: randomUUID() })).rejects.toMatchObject({ code: 'PEER_EXECUTION_GENERATION_STALE' });
expect(await ledger.advanceGenerationFloor({ hostInstanceId: input.hostInstanceId, peerInstanceId: input.peerInstanceId,
- action: input.intent.action, generation: 2 })).toBe(4);
+ action: input.intent.action, generation: 2, executionEpoch: input.executionEpoch })).toBe(4);
expect((await ledger.consume({ ...input, peerInstanceId: randomUUID() })).isNew).toBe(true);
});
it('has one-way compare-and-set states and cannot turn timeout/uncertainty into a second launch', async () => {
@@ -113,7 +113,7 @@ describe.skipIf(!runDb)('receiver-local permanent execution consumption', () =>
const draining = await ledger.transition(owner.operationId, 1, 'draining');
const started = await ledger.transition(owner.operationId, draining.revision, 'in-flight', { claim: claim() });
await ledger.advanceGenerationFloor({ hostInstanceId: input.hostInstanceId, peerInstanceId: input.peerInstanceId,
- action: input.intent.action, generation: 7 });
+ action: input.intent.action, generation: 7, executionEpoch: input.executionEpoch });
const id = randomUUID();
const pending = await ledger.prepareRestore(id);
await query('DELETE FROM peer_execution_operations');
@@ -127,7 +127,7 @@ describe.skipIf(!runDb)('receiver-local permanent execution consumption', () =>
await expect(restarted.consume(input)).rejects.toMatchObject({ code: 'PEER_EXECUTION_AUTHORITY_UNAVAILABLE' });
const completed = await restarted.reconcileRestore(id);
expect(await restarted.reconcileRestore(id)).toEqual(completed);
- expect((await restarted.read(first.operationId)).state).toBe('failed');
+ expect((await restarted.read(first.operationId)).state).toBe('uncertain');
expect(await restarted.read(owner.operationId)).toMatchObject({ state: 'uncertain', claim: started.claim });
await expect(restarted.consume(input)).rejects.toMatchObject({ code: 'PEER_EXECUTION_AUTHORITY_UNAVAILABLE' });
await expect(restarted.consume({ ...input, executionEpoch: completed.epoch }))
@@ -163,6 +163,26 @@ describe.skipIf(!runDb)('receiver-local permanent execution consumption', () =>
expect(await ledger.read(saved.operationId)).toBeNull();
expect(ledger.authority.read().phase).toBe('reconciling');
});
+ it('refuses a generation-floor write during capture/reconciliation instead of acknowledging revocation that restore can erase', async () => {
+ await ledger.consume(input);
+ const id = randomUUID();
+ const pending = await ledger.prepareRestore(id);
+ const floor = { hostInstanceId: input.hostInstanceId, peerInstanceId: input.peerInstanceId,
+ action: input.intent.action, generation: 7 };
+ for (const executionEpoch of [input.executionEpoch, pending.epoch]) {
+ await expect(ledger.advanceGenerationFloor({ ...floor, executionEpoch }))
+ .rejects.toMatchObject({ code: 'PEER_EXECUTION_AUTHORITY_UNAVAILABLE' });
+ }
+ await query('DELETE FROM peer_execution_operations');
+ await query('DELETE FROM peer_execution_generation_floors');
+ const completed = await ledger.reconcileRestore(id);
+ expect(await ledger.advanceGenerationFloor({ ...floor, executionEpoch: completed.epoch })).toBe(7);
+ const nextRestore = randomUUID(); await ledger.prepareRestore(nextRestore);
+ await query('DELETE FROM peer_execution_generation_floors');
+ await ledger.reconcileRestore(nextRestore);
+ const { rows: [row] } = await query('SELECT generation FROM peer_execution_generation_floors');
+ expect(Number(row.generation)).toBe(7);
+ });
it('retains the recovery fence when the database commit outcome is unknown, then reconciles the same facts', async () => {
const saved = (await ledger.consume(input)).operation;
const id = randomUUID(); await ledger.prepareRestore(id);
@@ -178,6 +198,47 @@ describe.skipIf(!runDb)('receiver-local permanent execution consumption', () =>
await expect(ambiguous.reconcileRestore(id)).rejects.toThrow(/acknowledgement/);
expect(ledger.authority.read().phase).toBe('reconciling');
await ledger.reconcileRestore(id);
- expect((await ledger.read(saved.operationId)).state).toBe('failed');
+ expect((await ledger.read(saved.operationId)).state).toBe('uncertain');
+ });
+ it('preserves a journal start across DB rollback and restore even when the captured DB claim is absent', async () => {
+ const { createMaintenanceAdmission } = await import('../lib/maintenanceAdmission.js');
+ const owner = createMaintenanceAdmission(directory);
+ const hold = owner.begin({ reason: 'Fixture restore crash gap', owner: 'Fixture operator' }).hold;
+ const saved = (await ledger.consume(input)).operation;
+ const draining = await ledger.transition(saved.operationId, 1, 'draining');
+ const { executionEpoch: _epoch, ...bound } = input;
+ const reserved = owner.claimReady({ id: hold.id, revision: hold.revision,
+ operation: { operationId: saved.operationId, ...bound } }, owner.observeIdle());
+ const started = owner.transitionExclusive({ id: reserved.id, revision: reserved.revision, fingerprint: reserved.fingerprint },
+ 'in-flight', owner.observeIdle());
+ const expected = { id: started.id, revision: started.revision, fingerprint: started.fingerprint };
+ const rollback = createPeerExecutionLedger({ dataDir: directory, db: { query, withTransaction: fn => withTransaction(async client => {
+ await fn(client); throw new Error('fixture rollback after journal start');
+ }) } });
+ await expect(rollback.transition(saved.operationId, draining.revision, 'in-flight', { claim: expected })).rejects.toThrow(/rollback/);
+ expect(await ledger.read(saved.operationId)).toMatchObject({ state: 'draining', claim: null });
+ const id = randomUUID(); await ledger.prepareRestore(id);
+ await query('DELETE FROM peer_execution_operations');
+ await ledger.reconcileRestore(id);
+ expect(await ledger.read(saved.operationId)).toMatchObject({ state: 'uncertain', claim: expected, receipt: null });
+ expect(owner.getExclusive()).toEqual(started);
+ expect(() => owner.resume(hold)).toThrow();
+ });
+ it('preserves stronger same-owner evidence and refuses a conflicting restored owner', async () => {
+ const saved = (await ledger.consume(input)).operation;
+ const draining = await ledger.transition(saved.operationId, 1, 'draining');
+ const original = claim();
+ await ledger.transition(saved.operationId, draining.revision, 'in-flight', { claim: original });
+ const id = randomUUID(); await ledger.prepareRestore(id);
+ const stronger = { ...original, revision: original.revision + 3 };
+ await query('UPDATE peer_execution_operations SET claim = $2::jsonb WHERE operation_id = $1', [saved.operationId, JSON.stringify(stronger)]);
+ await ledger.reconcileRestore(id);
+ expect((await ledger.read(saved.operationId)).claim).toEqual(stronger);
+ const next = randomUUID(); await ledger.prepareRestore(next);
+ const conflict = { ...stronger, id: randomUUID() };
+ await query('UPDATE peer_execution_operations SET claim = $2::jsonb WHERE operation_id = $1', [saved.operationId, JSON.stringify(conflict)]);
+ await expect(ledger.reconcileRestore(next)).rejects.toThrow(/Conflicting execution owner/);
+ expect((await ledger.read(saved.operationId)).claim).toEqual(conflict);
+ expect(ledger.authority.read().phase).toBe('reconciling');
});
});
diff --git a/server/services/peerExecutionLedger.js b/server/services/peerExecutionLedger.js
index 62b6a37c12..3a14a5cbd6 100644
--- a/server/services/peerExecutionLedger.js
+++ b/server/services/peerExecutionLedger.js
@@ -105,13 +105,16 @@ export function createPeerExecutionLedger({ db, dataDir, authority = createPeerE
return row ? fromRow(row) : null;
};
const advanceGenerationFloor = raw => {
- const input = floorSchema.parse(raw);
+ const input = floorSchema.extend({ executionEpoch: uuid }).parse(raw);
+ authority.requireReady(input.executionEpoch);
return locked(async client => {
+ authority.requireReady(input.executionEpoch);
const { rows: [row] } = await client.query(`INSERT INTO peer_execution_generation_floors
(host_instance_id, peer_instance_id, action, generation) VALUES ($1, $2, $3, $4)
ON CONFLICT (host_instance_id, peer_instance_id, action) DO UPDATE
SET generation = GREATEST(peer_execution_generation_floors.generation, EXCLUDED.generation) RETURNING generation`,
[input.hostInstanceId, input.peerInstanceId, input.action, input.generation]);
+ authority.requireReady(input.executionEpoch);
return Number(row.generation);
});
};
@@ -222,6 +225,21 @@ export function createPeerExecutionLedger({ db, dataDir, authority = createPeerE
const proof = await visitFacts();
if (proof.digest !== record.recovery.digest || proof.count !== record.recovery.count)
throw executionAuthorityError('Execution recovery evidence is missing or conflicting.');
+ const { createMaintenanceAdmission } = await import('../lib/maintenanceAdmission.js');
+ const coordinator = createMaintenanceAdmission(dataDir);
+ const journal = coordinator.getExclusive();
+ const journalIdentity = journal && { id: journal.id, revision: journal.revision, fingerprint: journal.fingerprint };
+ const journalOperation = row => ({ operationId: row.operationId, requestId: row.binding.requestId,
+ peerInstanceId: row.binding.peerInstanceId, hostInstanceId: row.binding.hostInstanceId,
+ grantId: row.binding.grantId, grantGeneration: row.binding.grantGeneration, scope: row.binding.scope,
+ pairBinding: row.binding.pairBinding, intent: row.binding.intent, receiverVersion: row.binding.receiverVersion,
+ evidenceDigest: row.binding.evidenceDigest });
+ const mergeClaims = claims => {
+ const present = claims.filter(Boolean);
+ if (present.some(claim => claim.id !== present[0].id || claim.fingerprint !== present[0].fingerprint))
+ throw executionAuthorityError('Conflicting execution owner evidence cannot be discarded.');
+ return present.reduce((newest, claim) => !newest || claim.revision > newest.revision ? claim : newest, null);
+ };
await locked(async client => {
const replayed = await visitFacts(async fact => {
if (fact.kind === 'floor') {
@@ -240,20 +258,24 @@ export function createPeerExecutionLedger({ db, dataDir, authority = createPeerE
throw executionAuthorityError('Restored execution consumption conflicts with non-rewound evidence.');
if (rows.some(row => terminal(row.state) && terminal(saved.state) && JSON.stringify(receiptSchema.parse(row.receipt)) !== JSON.stringify(saved.receipt)))
throw executionAuthorityError('Restored terminal evidence conflicts with non-rewound evidence.');
- if (rows.some(row => terminal(row.state) && !terminal(saved.state)
- && (row.receipt.code !== 'EXECUTION_AUTHORITY_RESTORED' || row.receipt.executionEpoch !== record.epoch)))
+ if (rows.some(row => terminal(row.state) && !terminal(saved.state)))
throw executionAuthorityError('Restored completion contradicts non-rewound unresolved ownership.');
- const started = saved.claim || ['in-flight', 'awaiting-reconnect', 'uncertain'].includes(saved.state);
- const state = terminal(saved.state) ? saved.state : started ? 'uncertain' : 'failed';
- const receipt = terminal(saved.state) ? saved.receipt : state === 'failed'
- ? { outcome: 'failed', code: 'EXECUTION_AUTHORITY_RESTORED', evidenceDigest: null, executionEpoch: record.epoch } : null;
+ if (journal?.operation.operationId === saved.operationId
+ && JSON.stringify(journal.operation) !== JSON.stringify(journalOperation(saved)))
+ throw executionAuthorityError('Preserved journal ownership conflicts with permanent request consumption.');
+ const owner = mergeClaims([saved.claim, ...rows.map(row => fromRow(row).claim),
+ journal?.operation.operationId === saved.operationId ? journalIdentity : null]);
+ // Missing DB claim is not proof of no launch: journal-start/DB-rollback
+ // can leave queued/draining storage behind an already-started owner.
+ const state = terminal(saved.state) ? saved.state : 'uncertain';
+ const receipt = terminal(saved.state) ? saved.receipt : null;
await client.query(`INSERT INTO peer_execution_operations
(operation_id, host_instance_id, peer_instance_id, request_id, fingerprint, binding, execution_epoch, state, revision, claim, receipt)
VALUES ($1,$2,$3,$4,$5,$6::jsonb,$7,$8,$9,$10::jsonb,$11::jsonb)
ON CONFLICT (operation_id) DO UPDATE SET state = EXCLUDED.state,
revision = GREATEST(peer_execution_operations.revision, EXCLUDED.revision), claim = EXCLUDED.claim, receipt = EXCLUDED.receipt, updated_at = NOW()`,
[saved.operationId, saved.binding.hostInstanceId, saved.binding.peerInstanceId, saved.binding.requestId, saved.fingerprint,
- JSON.stringify(saved.binding), saved.binding.executionEpoch, state, saved.revision + 1, JSON.stringify(saved.claim), JSON.stringify(receipt)]);
+ JSON.stringify(saved.binding), saved.binding.executionEpoch, state, saved.revision + 1, JSON.stringify(owner), JSON.stringify(receipt)]);
});
if (replayed.digest !== proof.digest || replayed.count !== proof.count)
throw executionAuthorityError('Execution recovery evidence changed during reconciliation.');
@@ -261,6 +283,14 @@ export function createPeerExecutionLedger({ db, dataDir, authority = createPeerE
// capture. They also cannot become launchable just because generic restore ended.
await client.query(`UPDATE peer_execution_operations SET state = 'uncertain', revision = revision + 1,
receipt = NULL, updated_at = NOW() WHERE state IN ('queued', 'draining', 'in-flight', 'awaiting-reconnect')`);
+ if (journal) {
+ const { rows: [owner] } = await client.query('SELECT * FROM peer_execution_operations WHERE operation_id = $1', [journal.operation.operationId]);
+ if (!owner || JSON.stringify(journal.operation) !== JSON.stringify(journalOperation(fromRow(owner))))
+ throw executionAuthorityError('Preserved journal ownership has no matching permanent consumption.');
+ }
+ const latest = coordinator.getExclusive();
+ if (JSON.stringify(latest) !== JSON.stringify(journal))
+ throw executionAuthorityError('Preserved journal ownership changed during reconciliation.');
const current = authority.read();
if (current?.epoch !== record.epoch || current.recovery?.id !== id)
throw executionAuthorityError('The execution recovery owner changed during reconciliation.');
diff --git a/server/services/peerExecutionRestore.js b/server/services/peerExecutionRestore.js
new file mode 100644
index 0000000000..e78818f087
--- /dev/null
+++ b/server/services/peerExecutionRestore.js
@@ -0,0 +1,33 @@
+/** Restore hooks only. Does not create a grant or connect an execution adapter. */
+import { createPeerExecutionLedger } from './peerExecutionLedger.js';
+import { executionAuthorityError } from '../lib/peerExecutionAuthority.js';
+
+async function receiverLedger({ repairSchema = false } = {}) {
+ // Restore-only subtree: ordinary backup reads pay no Postgres/ledger imports.
+ const [db, { PATHS }] = await Promise.all([import('../lib/db.js'), import('../lib/paths.js')]);
+ if (repairSchema) await db.ensureSchema({ force: true });
+ return createPeerExecutionLedger({ db, dataDir: PATHS.data });
+}
+
+export async function preparePeerExecutionRestore(id) {
+ const ledger = await receiverLedger();
+ await ledger.initialize();
+ return ledger.prepareRestore(id);
+}
+
+export async function finishPeerExecutionRestore(id, { rolledBack = false } = {}) {
+ const ledger = await receiverLedger({ 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; no identity is lost.
+ if (!before) 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.');
+ // Generic recovery proved no replay session can commit and no receipt exists.
+ // Capture the unchanged DB; never recapture a committed/unknown rewind.
+ await ledger.prepareRestore(id);
+ }
+ return ledger.reconcileRestore(id);
+}