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: retire never-accepted peer requests during status recovery

[._.]/ Adam Eivy5f9246a52452
diff --git a/client/src/components/instances/PeerAdministrationPanel.jsx b/client/src/components/instances/PeerAdministrationPanel.jsx
index b13ef66b4c..baee11d881 100644
--- a/client/src/components/instances/PeerAdministrationPanel.jsx
+++ b/client/src/components/instances/PeerAdministrationPanel.jsx
@@ -136,17 +136,21 @@ function ExecutionControls({ peer, setup, onSetup }) {
const saved = safeReadJsonStorage(storageKey);
return typeof saved?.requestId === 'string' ? saved : null;
});
+ const requestRef = useRef(request);
const [busy, setBusy] = useState(false);
const busyRef = useRef(false);
const [error, setError] = useState('');
const mounted = useMounted();
const unresolved = request && !['succeeded', 'failed'].includes(request.state);
const remember = (value, requireDurable = false) => {
- safeWriteJsonStorage(storageKey, value);
- if (requireDurable && safeReadStorage(storageKey) !== JSON.stringify(value)) {
+ const original = value.preflight ?? (requestRef.current?.requestId === value.requestId ? requestRef.current.preflight : null);
+ const next = original ? { ...value, preflight: original } : value;
+ safeWriteJsonStorage(storageKey, next);
+ if (requireDurable && safeReadStorage(storageKey) !== JSON.stringify(next)) {
throw new Error('Execution was not submitted because this browser could not save its recovery record. Enable persistent browser storage and prepare the action again.');
}
- if (mounted.current) setRequest(value);
+ requestRef.current = next;
+ if (mounted.current) setRequest(next);
};
const run = async work => {
if (busyRef.current) return;
@@ -174,15 +178,24 @@ function ExecutionControls({ peer, setup, onSetup }) {
});
const dispatch = () => run(async () => {
// Verify persistent storage BEFORE launch so recovery survives reloads and tab closure.
- const pending = { requestId: preflight.payload.requestId, state: 'uncertain' };
+ const pending = { requestId: preflight.payload.requestId, state: 'uncertain', preflight };
remember(pending, true);
const envelope = preflight;
setPreflight(null);
- const value = await dispatchPeerExecution({ peerId: peer.id, preflight: envelope }, { silent: true });
+ const value = await dispatchPeerExecution({ peerId: peer.id, preflight: envelope }, { silent: true }).catch(err => {
+ // Only our sender can prove that no dispatch was attempted. Remote
+ // refusals, unrelated errors and lost responses remain uncertain.
+ if (err.code === 'PEER_EXECUTION_NOT_SENT' && err.context?.requestId === pending.requestId) {
+ remember({ requestId: pending.requestId, state: 'failed', code: err.code });
+ }
+ throw err;
+ });
remember(value);
});
const checkStatus = () => run(async () => {
- const value = await getPeerExecutionStatus({ peerId: peer.id, requestId: request.requestId }, { silent: true });
+ const value = await getPeerExecutionStatus({ peerId: peer.id, requestId: request.requestId,
+ ...(request.preflight ? { preflight: request.preflight } : {}),
+ }, { silent: true });
if (!Number.isSafeInteger(request.revision) || value.revision >= request.revision) remember(value);
});
diff --git a/client/src/components/instances/PeerAdministrationPanel.test.jsx b/client/src/components/instances/PeerAdministrationPanel.test.jsx
index 159dddf196..36df62327b 100644
--- a/client/src/components/instances/PeerAdministrationPanel.test.jsx
+++ b/client/src/components/instances/PeerAdministrationPanel.test.jsx
@@ -123,6 +123,7 @@ describe('separate peer execution controls', () => {
expect(dispatchPeerExecution).not.toHaveBeenCalled();
fireEvent.click(screen.getByRole('button', { name: 'Submit execution' }));
await screen.findByText('Execution status: draining');
+ expect(storage.safeReadJsonStorage(`peer-execution:${setup.hostInstanceId}:${peer.id}:${setup.peerInstanceId}`).preflight).toEqual(preview);
expect(dispatchPeerExecution).toHaveBeenCalledWith({ peerId: peer.id, preflight: preview }, { silent: true });
});
@@ -140,6 +141,23 @@ describe('separate peer execution controls', () => {
expect(screen.queryByText('Execution status: uncertain')).toBeNull();
});
+ it.each([
+ ['PEER_EXECUTION_NOT_SENT', envelope.payload.requestId, 'failed'],
+ ['PEER_EXECUTION_NOT_SENT', 'unrelated-request', 'uncertain'],
+ ['PEER_ADMIN_REMOTE_REFUSED', envelope.payload.requestId, 'uncertain'],
+ ])('recovers only correlated local non-dispatch proof: %s / %s', async (code, requestId, state) => {
+ previewPeerExecution.mockResolvedValue(envelope);
+ dispatchPeerExecution.mockRejectedValue(Object.assign(new Error('Dispatch did not complete'), { code, context: { requestId } }));
+ await open();
+ fireEvent.click(screen.getByRole('button', { name: 'Prepare PortOS restart execution' }));
+ fireEvent.click(await screen.findByRole('button', { name: 'Submit execution' }));
+ await screen.findByText('Dispatch did not complete');
+ expect(screen.getByText(`Execution status: ${state}`)).toBeTruthy();
+ expect(screen.getByRole('button', { name: 'Prepare PortOS restart execution' }).disabled).toBe(state === 'uncertain');
+ expect(dispatchPeerExecution).toHaveBeenCalledTimes(1);
+ expect(storage.safeReadJsonStorage(`peer-execution:${setup.hostInstanceId}:${peer.id}:${setup.peerInstanceId}`).preflight).toEqual(envelope);
+ });
+
it('retains an uncertain launch across tab closure and recovers with status without a second dispatch', async () => {
previewPeerExecution.mockResolvedValue(envelope);
dispatchPeerExecution.mockRejectedValue(new Error('Response timed out'));
@@ -161,7 +179,8 @@ describe('separate peer execution controls', () => {
await screen.findByText('Execution status: succeeded');
expect(dispatchPeerExecution).toHaveBeenCalledTimes(1);
expect(dispatchPeerExecution).toHaveBeenCalledWith({ peerId: peer.id, preflight: envelope }, { silent: true });
- expect(getPeerExecutionStatus).toHaveBeenCalledWith({ peerId: peer.id, requestId: envelope.payload.requestId }, { silent: true });
+ expect(getPeerExecutionStatus).toHaveBeenCalledWith({ peerId: peer.id, requestId: envelope.payload.requestId, preflight: envelope }, { silent: true });
+ expect(storage.safeReadJsonStorage(`peer-execution:${setup.hostInstanceId}:${peer.id}:${setup.peerInstanceId}`).preflight).toEqual(envelope);
});
});
diff --git a/docs/features/peer-administration.md b/docs/features/peer-administration.md
index 4d613b17f4..11caac761b 100644
--- a/docs/features/peer-administration.md
+++ b/docs/features/peer-administration.md
@@ -39,11 +39,13 @@ catalog execution grant. Installation verifies the streamed byte count and hash
before publication and never replaces an existing destination file.
On the sending host, prepare the desired action, inspect its exact signed
-preflight, then request execution. The sender stores the request identity before
+preflight, then request execution. The sender stores the request identity and signed preview before
sending and refuses dispatch if that recovery record cannot be read back.
An uncertain response retains the request and offers **Check status**; it never
starts another attempt automatically. The receiving host owns the durable ledger;
-browser storage is a convenience for finding its receipt.
+browser storage retains the evidence needed to recover its receipt. A proven local
+pre-send rejection permits a fresh preview. A timeout or unsigned remote refusal
+never does.
## Authority and drain
@@ -100,6 +102,16 @@ launch; explicit status reads can reconcile exact completion evidence arriving
after boot. Terminal database persistence, journal settlement and hold release
are independently recoverable, including crashes between those boundaries.
+Status requests can include the original signed preview. When the receiver has
+never consumed that request, it verifies the signature and both instance identities,
+then atomically records a permanent failed receipt under the same database lock
+as dispatch. That receipt proves no launch occurred and prevents any delayed
+dispatch or reused preflight from starting it later. Already accepted requests
+retain their original state. This recovery works after receiver restart, grant
+revocation and epoch rotation while the original pair credential remains valid;
+it never restores authority from the preview. A request without verifiable
+original evidence remains unresolved instead of treating a bare 404 as proof.
+
Updates and restarts write per-operation launch evidence before starting their
detached adapter. Reconciliation requires its exact successful exit receipt and
matching target evidence: restarted fixed process identities, or the expected
diff --git a/server/lib/peerAdminValidation.js b/server/lib/peerAdminValidation.js
index 49a793fb61..bc32f4423b 100644
--- a/server/lib/peerAdminValidation.js
+++ b/server/lib/peerAdminValidation.js
@@ -56,10 +56,10 @@ export const peerExecutionPreflightPayloadSchema = peerExecutionDispatchSchema.e
scope: z.literal(PEER_EXECUTION_SCOPE), senderInstanceId: uuid, targetInstanceId: uuid,
expiresAt: z.number().int().positive().safe(),
}).strict();
-export const peerExecutionRemoteDispatchSchema = peerAdminPeerSchema.extend({
- preflight: z.object({ payload: peerExecutionPreflightPayloadSchema, signature: z.string().regex(/^[a-f0-9]{64}$/) }).strict(),
-}).strict();
-export const peerExecutionRemoteStatusSchema = peerAdminPeerSchema.extend({ requestId: uuid }).strict();
+const executionPreflightEnvelope = z.object({ payload: peerExecutionPreflightPayloadSchema, signature: z.string().regex(/^[a-f0-9]{64}$/) }).strict();
+export const peerExecutionRemoteDispatchSchema = peerAdminPeerSchema.extend({ preflight: executionPreflightEnvelope }).strict();
+export const peerExecutionStatusSchema = z.object({ requestId: uuid, preflight: executionPreflightEnvelope.optional() }).strict();
+export const peerExecutionRemoteStatusSchema = peerExecutionStatusSchema.extend({ peerId }).strict();
export const peerExecutionReceiptPayloadSchema = z.object({
protocolVersion: z.literal(1), scope: z.literal(PEER_EXECUTION_SCOPE), requestId: uuid,
diff --git a/server/routes/peerAdministration.js b/server/routes/peerAdministration.js
index ff34c3e2fd..a5d78d3e7f 100644
--- a/server/routes/peerAdministration.js
+++ b/server/routes/peerAdministration.js
@@ -2,7 +2,7 @@ import { Router } from 'express';
import { asyncHandler } from '../lib/errorHandler.js';
import { validateRequest } from '../lib/validation.js';
import {
- peerAdminPreflightSchema, peerAdminPlanSchema, peerAdminReceiptSchema, peerExecutionPreflightSchema, peerExecutionDispatchSchema,
+ peerAdminPreflightSchema, peerAdminPlanSchema, peerAdminReceiptSchema, peerExecutionPreflightSchema, peerExecutionDispatchSchema, peerExecutionStatusSchema,
} from '../lib/peerAdminValidation.js';
import {
createPeerAdminPreflight,
@@ -39,7 +39,7 @@ router.post('/execution/dispatch', asyncHandler(async (req, res) => {
res.status(202).json(await (await peerExecutionRuntime()).dispatch(req, input));
}));
router.post('/execution/status', asyncHandler(async (req, res) => {
- const input = validateRequest(peerAdminReceiptSchema, req.body);
+ const input = validateRequest(peerExecutionStatusSchema, req.body);
const { peerExecutionRuntime } = await import('../services/peerExecutionRuntime.js');
res.json(await (await peerExecutionRuntime()).status(req, input));
}));
diff --git a/server/services/peerAdminConsumer.js b/server/services/peerAdminConsumer.js
index d800a2b140..075c40651f 100644
--- a/server/services/peerAdminConsumer.js
+++ b/server/services/peerAdminConsumer.js
@@ -131,8 +131,15 @@ function verifiedExecutionReceipt(peer, self, envelope, requestId) {
/** Exactly one dispatch attempt; a lost response is recovered through status. */
export async function dispatchPeerExecution({ peerId, preflight }) {
- const { peer, self } = await peerAdminIdentity(peerId);
- const payload = verifiedExecutionPreflight(peer, self, preflight, preflight?.payload?.requestId);
+ // Only this local block can assert that dispatch was never attempted.
+ const { peer, self, payload } = await (async () => {
+ const { peer, self } = await peerAdminIdentity(peerId);
+ return { peer, self, payload: verifiedExecutionPreflight(peer, self, preflight, preflight?.payload?.requestId) };
+ })().catch(() => {
+ throw new ServerError('Execution was not sent because its preview or paired identity is no longer valid. Prepare a fresh preview.', {
+ status: 409, code: 'PEER_EXECUTION_NOT_SENT', context: { requestId: preflight?.payload?.requestId },
+ });
+ });
const { requestId, grantId, grantGeneration, intent, evidenceDigest, executionEpoch, version } = payload;
const envelope = await exchange(peer, 'executionDispatch', {
protocolVersion: 1, requestId, grantId, grantGeneration, intent, evidenceDigest, executionEpoch, version,
@@ -141,9 +148,9 @@ export async function dispatchPeerExecution({ peerId, preflight }) {
return verifiedExecutionReceipt(peer, self, envelope, requestId);
}
-export async function getPeerExecutionStatus({ peerId, requestId }) {
+export async function getPeerExecutionStatus({ peerId, requestId, preflight }) {
const { peer, self } = await peerAdminIdentity(peerId);
- const envelope = await exchange(peer, 'executionStatus', { requestId }, AbortSignal.timeout(10_000)).catch(executionUnavailable);
+ const envelope = await exchange(peer, 'executionStatus', { requestId, ...(preflight && { preflight }) }, AbortSignal.timeout(10_000)).catch(executionUnavailable);
await unchangedPair(peerId, peer, self);
return verifiedExecutionReceipt(peer, self, envelope, requestId);
}
diff --git a/server/services/peerAdminConsumer.test.js b/server/services/peerAdminConsumer.test.js
index fdd4ac6d7c..5153b742ca 100644
--- a/server/services/peerAdminConsumer.test.js
+++ b/server/services/peerAdminConsumer.test.js
@@ -49,13 +49,18 @@ describe('peer execution sender boundary', () => {
expect(credential.peerAuthAccepted).toBe(true);
});
- it('rejects a forged or expired preview before making a dispatch request', async () => {
+ it('proves only local preview rejection was never sent, binding the result to its request', async () => {
const preflight = signed(snapshot(randomUUID()));
preflight.payload.intent = { action: 'portos.update' };
- await expect(dispatchPeerExecution({ peerId: peer.id, preflight })).rejects.toMatchObject({ code: 'PEER_EXECUTION_UNVERIFIED_RESPONSE' });
- await expect(dispatchPeerExecution({ peerId: peer.id, preflight: signed({ ...snapshot(randomUUID()), expiresAt: Date.now() - 1 }) }))
- .rejects.toMatchObject({ code: 'PEER_EXECUTION_UNVERIFIED_RESPONSE' });
+ await expect(dispatchPeerExecution({ peerId: peer.id, preflight })).rejects.toMatchObject({ code: 'PEER_EXECUTION_NOT_SENT', context: { requestId: preflight.payload.requestId } });
+ const expired = signed({ ...snapshot(randomUUID()), expiresAt: Date.now() - 1 });
+ await expect(dispatchPeerExecution({ peerId: peer.id, preflight: expired }))
+ .rejects.toMatchObject({ code: 'PEER_EXECUTION_NOT_SENT', context: { requestId: expired.payload.requestId } });
expect(peerFetch).not.toHaveBeenCalled();
+ peerFetch.mockResolvedValueOnce({ ok: false });
+ await expect(dispatchPeerExecution({ peerId: peer.id, preflight: signed(snapshot(randomUUID())) }))
+ .rejects.toMatchObject({ code: 'PEER_ADMIN_REMOTE_REFUSED' });
+ expect(peerFetch).toHaveBeenCalledOnce();
});
it('rejects signed responses with another intent or a pair changed while preparing', async () => {
@@ -74,8 +79,9 @@ describe('peer execution sender boundary', () => {
expect(peerFetch).toHaveBeenCalledTimes(1);
const completed = { ...receipt(preflight.payload.requestId), state: 'succeeded', revision: 4 };
readPeerBody.mockResolvedValueOnce(signed(completed, 'execution-receipt'));
- await expect(getPeerExecutionStatus({ peerId: peer.id, requestId: preflight.payload.requestId })).resolves.toEqual(completed);
+ await expect(getPeerExecutionStatus({ peerId: peer.id, requestId: preflight.payload.requestId, preflight })).resolves.toEqual(completed);
expect(peerFetch.mock.calls[1][0]).toMatch(/execution\/status$/);
+ expect(JSON.parse(peerFetch.mock.calls[1][1].body)).toEqual({ requestId: preflight.payload.requestId, preflight });
});
it('rejects a valid signature for an unrelated receipt or incorrect signature purpose', async () => {
diff --git a/server/services/peerExecution.js b/server/services/peerExecution.js
index c62924b2cb..e4168797ac 100644
--- a/server/services/peerExecution.js
+++ b/server/services/peerExecution.js
@@ -3,7 +3,8 @@ import { createHash } from 'node:crypto';
import { canonicalStringify } from '../lib/objects.js';
import { createMutex } from '../lib/asyncMutex.js';
import { peerExecutionError } from './peerExecutionGrants.js';
-import { peerAdminPairBinding, signPeerAdmin } from './peerAdministration.js';
+import { peerExecutionPreflightPayloadSchema } from '../lib/peerAdminValidation.js';
+import { peerAdminPairBinding, signPeerAdmin, verifyPeerAdminSignature } from './peerAdministration.js';
const hash = value => createHash('sha256').update(canonicalStringify(value)).digest('hex');
const claimRef = claim => ({ id: claim.id, revision: claim.revision, fingerprint: claim.fingerprint });
@@ -208,9 +209,22 @@ export function createPeerExecutionReceiver({ ledger, grants, coordinator, adapt
await finish(operation, { state: 'failed', code: 'PEER_EXECUTION_INTERRUPTED_BEFORE_LAUNCH' }, null);
}
};
- const status = (req, { requestId }) => locked(async () => {
+ const status = (req, { requestId, preflight: envelope }) => locked(async () => {
const pair = await caller(req);
let operation = await findRequest(pair, requestId);
+ if (!operation && envelope) {
+ const payload = envelope.payload;
+ if (!peerExecutionPreflightPayloadSchema.safeParse(payload).success
+ || !verifyPeerAdminSignature(pair.peer, 'execution-preflight', payload, envelope.signature)
+ || payload.requestId !== requestId || payload.senderInstanceId !== pair.peer.instanceId
+ || payload.targetInstanceId !== pair.self.instanceId)
+ fail('PEER_EXECUTION_RECOVERY_UNVERIFIED', 'The original request preview could not be verified.');
+ operation = await ledger.retireUnconsumed({ hostInstanceId: pair.self.instanceId, peerInstanceId: pair.peer.instanceId,
+ requestId, grantId: payload.grantId, grantGeneration: payload.grantGeneration, scope: 'execution-v1',
+ pairBinding: peerAdminPairBinding(pair.peer, pair.self), intent: payload.intent, receiverVersion: payload.version,
+ evidenceDigest: payload.evidenceDigest, executionEpoch: payload.executionEpoch });
+ preflights.delete(`${pair.peer.instanceId}:${requestId}`);
+ }
if (!operation) throw peerExecutionError('PEER_EXECUTION_NOT_FOUND', 'Execution request not found.', 404);
// A deliberate receipt read may observe completion written after server boot.
// It never dispatches work, retries a launch, or cancels live local work.
diff --git a/server/services/peerExecution.test.js b/server/services/peerExecution.test.js
index 20a202c637..073f3d9c2e 100644
--- a/server/services/peerExecution.test.js
+++ b/server/services/peerExecution.test.js
@@ -29,6 +29,12 @@ beforeEach(async () => {
const operation = { operationId: randomUUID(), binding, fingerprint: hash(binding), revision: 1, state: 'queued', claim: null, receipt: null };
operations.set(operation.operationId, operation); return { operation, isNew: true };
},
+ retireUnconsumed: async binding => {
+ const { operation, isNew } = await ledger.consume(binding);
+ if (!isNew) return operation;
+ const retired = { ...operation, state: 'failed', receipt: { outcome: 'failed', code: 'PEER_EXECUTION_NOT_ACCEPTED', evidenceDigest: null, executionEpoch: epoch } };
+ operations.set(retired.operationId, retired); return retired;
+ },
read: async id => operations.get(id),
readRequest: async ({ hostInstanceId, peerInstanceId, requestId }) => [...operations.values()].find(row => row.binding.requestId === requestId
&& row.binding.hostInstanceId === hostInstanceId && row.binding.peerInstanceId === peerInstanceId) ?? null,
@@ -87,6 +93,37 @@ describe('receiver execution public workflow with fixture-only side effects', ()
expect((await restarted.status('paired', input)).payload.state).toBe('succeeded');
expect(adapters.run).toHaveBeenCalledTimes(1);
});
+ it('retires an unconsumed signed request after restart and revocation, preventing every delayed dispatch', async () => {
+ await grant();
+ const requestId = randomUUID();
+ const envelope = await receiver.preflight('paired', { protocolVersion: 1, requestId, intent });
+ const { scope: _scope, senderInstanceId: _sender, targetInstanceId: _target, expiresAt: _expiry, ...dispatch } = envelope.payload;
+ await grant({ allowExecution: false });
+ const restarted = makeReceiver();
+ await expect(restarted.status('paired', { requestId })).rejects.toMatchObject({ code: 'PEER_EXECUTION_NOT_FOUND' });
+ await expect(restarted.status('paired', { requestId, preflight: { ...envelope, signature: 'a'.repeat(64) } })).rejects.toMatchObject({ code: 'PEER_EXECUTION_RECOVERY_UNVERIFIED' });
+ expect(operations.size).toBe(0);
+ const retired = await restarted.status('paired', { requestId, preflight: envelope });
+ expect(retired.payload).toMatchObject({ state: 'failed', code: 'PEER_EXECUTION_NOT_ACCEPTED' });
+ expect((await receiver.dispatch('paired', dispatch)).payload).toEqual(retired.payload);
+ await expect(restarted.preflight('paired', { protocolVersion: 1, requestId, intent })).rejects.toMatchObject({ code: 'PEER_EXECUTION_CONSUMED' });
+ await makeReceiver().recover();
+ expect((await restarted.status('paired', { requestId })).payload).toEqual(retired.payload);
+ expect(adapters.run).not.toHaveBeenCalled();
+ expect(coordinator.status().state).toBe('normal');
+ });
+ it('returns the existing accepted operation when recovery races an admitted dispatch', async () => {
+ const active = coordinator.admit('render', 'Fixture render');
+ await grant();
+ const requestId = randomUUID();
+ const preflight = await receiver.preflight('paired', { protocolVersion: 1, requestId, intent });
+ const { scope: _scope, senderInstanceId: _sender, targetInstanceId: _target, expiresAt: _expiry, ...input } = preflight.payload;
+ await receiver.dispatch('paired', input);
+ const response = await receiver.status('paired', { requestId, preflight });
+ expect(['queued', 'draining']).toContain(response.payload.state);
+ await active.finish(); await receiver.drain(); await idle();
+ expect(adapters.run).toHaveBeenCalledOnce();
+ });
it('lets admitted work settle naturally and rechecks revocation before dispatch', async () => {
const active = coordinator.admit('provider', 'Fixture provider');
await grant(); const input = await prepare(); await receiver.dispatch('paired', input);
diff --git a/server/services/peerExecutionLedger.db.test.js b/server/services/peerExecutionLedger.db.test.js
index 54156ebd27..001202c89a 100644
--- a/server/services/peerExecutionLedger.db.test.js
+++ b/server/services/peerExecutionLedger.db.test.js
@@ -65,6 +65,31 @@ describe.skipIf(!runDb)('receiver-local permanent execution consumption', () =>
expect(coordinator.status().state).toBe('normal');
expect(await ledger.generationFloor({ hostInstanceId: input.hostInstanceId, peerInstanceId: input.peerInstanceId, action: input.intent.action })).toBe(1);
});
+ it('permanently retires unconsumed requests without authorizing work and serializes against delayed consume', async () => {
+ const retired = await ledger.retireUnconsumed(input);
+ expect(retired).toMatchObject({ state: 'failed', revision: 1, claim: null, receipt: { code: 'PEER_EXECUTION_NOT_ACCEPTED' } });
+ expect((await ledger.consume(input)).operation).toEqual(retired);
+ expect((await ledger.consume(input)).isNew).toBe(false);
+ const restarted = createPeerExecutionLedger({ db, dataDir: directory });
+ expect(await restarted.readRequest(input)).toEqual(retired);
+ const other = { ...input, requestId: randomUUID() };
+ const [accepted, observed] = await Promise.all([ledger.consume(other), restarted.retireUnconsumed(other)]);
+ expect(observed.operationId).toBe(accepted.operation.operationId);
+ expect(observed.state).toBe(accepted.operation.state);
+ expect((await ledger.list()).length).toBe(2);
+ const stale = { ...input, requestId: randomUUID() };
+ ledger.authority.invalidate();
+ const denied = await restarted.retireUnconsumed(stale);
+ expect(denied.receipt.executionEpoch).toBe(ledger.authority.read().epoch);
+ expect(denied.binding.executionEpoch).toBe(stale.executionEpoch);
+ const recoveryId = randomUUID();
+ await ledger.prepareRestore(recoveryId);
+ await query('DELETE FROM peer_execution_operations');
+ await query('DELETE FROM peer_execution_generation_floors');
+ await ledger.reconcileRestore(recoveryId);
+ expect((await restarted.readRequest(input)).state).toBe('failed');
+ expect((await restarted.readRequest(stale)).receipt.code).toBe('PEER_EXECUTION_NOT_ACCEPTED');
+ });
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');
diff --git a/server/services/peerExecutionLedger.js b/server/services/peerExecutionLedger.js
index 05acf02dd8..20cafea6c0 100644
--- a/server/services/peerExecutionLedger.js
+++ b/server/services/peerExecutionLedger.js
@@ -99,6 +99,25 @@ export function createPeerExecutionLedger({ db, dataDir, authority = createPeerE
return { operation: fromRow(row), isNew: true };
});
};
+ // A status recovery may retire a signed request that never reached consume.
+ // Use the same DB lock as consume: either the launch owns the row already,
+ // or this permanent terminal tombstone wins and every delayed launch loses.
+ const retireUnconsumed = async raw => {
+ const binding = peerExecutionBindingSchema.parse(raw);
+ return locked(async client => {
+ const epoch = authority.read()?.epoch;
+ authority.requireReady(epoch);
+ const previous = await find(client, binding);
+ if (previous) return previous;
+ const receipt = { outcome: 'failed', code: 'PEER_EXECUTION_NOT_ACCEPTED', evidenceDigest: null, executionEpoch: epoch };
+ const { rows: [row] } = await client.query(`INSERT INTO peer_execution_operations
+ (operation_id, host_instance_id, peer_instance_id, request_id, fingerprint, binding, execution_epoch, state, receipt)
+ VALUES ($1, $2, $3, $4, $5, $6::jsonb, $7, 'failed', $8::jsonb) RETURNING *`,
+ [makeId(), binding.hostInstanceId, binding.peerInstanceId, binding.requestId, fingerprint(binding), JSON.stringify(binding), binding.executionEpoch, JSON.stringify(receipt)]);
+ authority.requireReady(epoch);
+ return fromRow(row);
+ });
+ };
const readRequest = async ({ hostInstanceId, peerInstanceId, requestId }) => {
uuid.parse(hostInstanceId); uuid.parse(peerInstanceId); uuid.parse(requestId);
return find(db, { hostInstanceId, peerInstanceId, requestId });
@@ -327,5 +346,5 @@ export function createPeerExecutionLedger({ db, dataDir, authority = createPeerE
if (current?.phase === 'ready' && current.settledRecoveryId === id) return current;
return authority.completeRestore(id);
};
- return { initialize, consume, read, readRequest, generationFloor, list, listActive, transition, advanceGenerationFloor, prepareRestore, adoptEmptyRestore, reconcileRestore, authority };
+ return { initialize, consume, retireUnconsumed, read, readRequest, generationFloor, list, listActive, transition, advanceGenerationFloor, prepareRestore, adoptEmptyRestore, reconcileRestore, authority };
}