From 4cd9a7357c6faaec274c01461d8c1a452ba8cce4 Mon Sep 17 00:00:00 2001 From: Andrew Peris Date: Tue, 10 Nov 2026 10:16:01 -0500 Subject: [PATCH 01/33] Implement O09 result-link inspection (runner.js) --- src/offline-orchestration-prototype/runner.js | 234 +++++++++++++++--- 1 file changed, 197 insertions(+), 37 deletions(-) diff --git a/src/offline-orchestration-prototype/runner.js b/src/offline-orchestration-prototype/runner.js index 82a45f7..eed6f71 100644 --- a/src/offline-orchestration-prototype/runner.js +++ b/src/offline-orchestration-prototype/runner.js @@ -46,6 +46,25 @@ const EXPECTED_EXECUTION_SCOPE = Object.freeze({ revision: 1, identity_sha256: EXPECTED_PRODUCTION_SHA256 }); +const RECOVERY_EVENT_TYPES = new Set([ + 'admitted', 'authorization-blocked', 'budget-exhausted', 'cancelled-before-dispatch', + 'closed-without-retry', 'contract-mapping-blocked', 'dispatch-started', 'job-closed', + 'persisting', 'prepared', 'provider-outcome', 'result-prepared', 'resume-window', 'terminal' +]); +const RECOVERY_DIAGNOSTIC_STATES = Object.freeze({ + 'not-found': Object.freeze({ stage: 'lookup', code: 'RECORD_NOT_FOUND' }), + 'reconciliation-required': Object.freeze({ stage: 'integrity', code: 'RECONCILIATION_REQUIRED' }), + terminal: Object.freeze({ stage: 'terminal', code: 'TERMINAL_RESULT_VERIFIED' }), + 'resume-candidate': Object.freeze({ stage: 'resume', code: 'RESUME_CANDIDATE' }), + 'resume-window-empty': Object.freeze({ stage: 'resume', code: 'RESUME_WINDOW_EMPTY' }), + 'retry-delay-not-elapsed': Object.freeze({ stage: 'resume', code: 'RETRY_DELAY_NOT_ELAPSED' }), + 'resume-not-eligible': Object.freeze({ stage: 'resume', code: 'RESUME_NOT_ELIGIBLE' }), + 'deadline-unverifiable': Object.freeze({ stage: 'time', code: 'DEADLINE_UNVERIFIABLE' }), + 'budget-exhausted': Object.freeze({ stage: 'limits', code: 'BUDGET_EXHAUSTED' }), + 'contract-mapping-blocked': Object.freeze({ stage: 'mapping', code: 'CONTRACT_MAPPING_BLOCKED' }), + 'execution-unresolved': Object.freeze({ stage: 'execution', code: 'EXECUTION_UNRESOLVED' }), + 'read-only-inspection-required': Object.freeze({ stage: 'inspection', code: 'INSPECTION_REQUIRED' }) +}); const defaultRuntime = Object.freeze({ now: () => Math.floor(performance.now()), @@ -70,6 +89,21 @@ function freezeDeep(value, seen = new WeakSet()) { return Object.freeze(value); } +function recoveryDiagnostic(status) { + const safeStatus = Object.prototype.hasOwnProperty.call(RECOVERY_DIAGNOSTIC_STATES, status) + ? status : 'reconciliation-required'; + const { stage, code } = RECOVERY_DIAGNOSTIC_STATES[safeStatus]; + return freezeDeep({ + status: safeStatus, + stage, + code, + read_only: true, + no_writes: true, + no_provider_calls: true, + authority_check_required: safeStatus === 'resume-candidate' + }); +} + function digest(bytes) { return `sha256:${createHash('sha256').update(bytes).digest('hex')}`; } @@ -2000,17 +2034,21 @@ function createRunner({ runtime = defaultRuntime, store = new InMemoryPrototypeS function inspectRecoveryCore(jobId, { beforeProtectedRead, onCandidate } = {}) { if (typeof jobId !== 'string' || !jobId) throw new OfflineOrchestrationError('INVALID_JOB_ID'); + const reconciliationRequired = () => recoveryDiagnostic('reconciliation-required'); let entries; try { entries = store.readEvents(jobId); } catch { - return freezeDeep({ kind: 'recovery-inspection', status: 'reconciliation-required', job_id: jobId, read_only: true }); + return reconciliationRequired(); } if (entries === UNKNOWN_STORE_STATE || !Array.isArray(entries)) { - return freezeDeep({ kind: 'recovery-inspection', status: 'reconciliation-required', job_id: jobId, read_only: true }); + return reconciliationRequired(); } - if (entries.length === 0) return freezeDeep({ kind: 'recovery-inspection', status: 'not-found', job_id: jobId, read_only: true }); - const admitted = entries.find(item => item.type === 'admitted'); - if (!admitted || entries.filter(item => item.type === 'admitted').length !== 1) { - return freezeDeep({ kind: 'recovery-inspection', status: 'reconciliation-required', job_id: jobId, read_only: true }); + if (entries.length === 0) return recoveryDiagnostic('not-found'); + const admittedEvents = entries.filter(item => item?.type === 'admitted'); + const admitted = admittedEvents[0]; + if (!admitted || admittedEvents.length !== 1 + || entries.some(item => !item || typeof item !== 'object' || Array.isArray(item) + || item.job_id !== jobId || typeof item.type !== 'string' || !RECOVERY_EVENT_TYPES.has(item.type))) { + return reconciliationRequired(); } const verifiedBlobs = new Map(); const readVerifiedBlob = (key, expectedSize, expectedSha) => { @@ -2028,65 +2066,187 @@ function createRunner({ runtime = defaultRuntime, store = new InMemoryPrototypeS const verifyBlob = (key, expectedSize, expectedSha) => readVerifiedBlob(key, expectedSize, expectedSha) !== false; if (!verifyBlob(admitted.input_key, admitted.input_byte_size, admitted.input_sha256) || !verifyBlob(admitted.prompt_key, admitted.prompt_byte_size, admitted.prompt_sha256)) { - return freezeDeep({ kind: 'recovery-inspection', status: 'reconciliation-required', job_id: jobId, read_only: true }); + return reconciliationRequired(); } for (const item of entries) { if (item.type === 'provider-outcome' && !verifyBlob(item.payload_key, item.byte_size, item.sha256)) { - return freezeDeep({ kind: 'recovery-inspection', status: 'reconciliation-required', job_id: jobId, read_only: true }); + return reconciliationRequired(); } if (item.type === 'persisting' || item.type === 'terminal') { const resultBytes = readVerifiedBlob(`result:${item.result_id}`, item.result_byte_size, item.result_sha256); - if (resultBytes === false) { - return freezeDeep({ kind: 'recovery-inspection', status: 'reconciliation-required', job_id: jobId, read_only: true }); - } + if (resultBytes === false) return reconciliationRequired(); let result; try { result = JSON.parse(resultBytes.toString('utf8')); } catch { - return freezeDeep({ kind: 'recovery-inspection', status: 'reconciliation-required', job_id: jobId, read_only: true }); + return reconciliationRequired(); } - for (const output of result.outputs ?? []) { + if (!result || typeof result !== 'object' || Array.isArray(result) || !Array.isArray(result.outputs)) { + return reconciliationRequired(); + } + for (const output of result.outputs) { + if (!output || typeof output !== 'object' || Array.isArray(output)) return reconciliationRequired(); const artifact = output.artifact; - if (!artifact || !verifyBlob(`artifact:${artifact.artifact_uri}`, artifact.byte_size, artifact.sha256)) { - return freezeDeep({ kind: 'recovery-inspection', status: 'reconciliation-required', job_id: jobId, read_only: true }); + if (!artifact || typeof artifact !== 'object' || Array.isArray(artifact) + || !verifyBlob(`artifact:${artifact.artifact_uri}`, artifact.byte_size, artifact.sha256)) { + return reconciliationRequired(); } } } } - const last = entries.at(-1); - const terminal = entries.some(item => item.type === 'job-closed'); + + const resultPrepared = entries.filter(item => item.type === 'result-prepared'); + const persisting = entries.filter(item => item.type === 'persisting'); + const terminals = entries.filter(item => item.type === 'terminal'); + if (resultPrepared.length !== persisting.length || resultPrepared.length !== terminals.length) { + return reconciliationRequired(); + } + if (resultPrepared.length > 0) { + const productionBytes = verifiedBlobs.get(admitted.input_key); + let production; + try { + production = readProduction(productionBytes.toString('utf8')); + if (!productionBytes.equals(Buffer.from(production.canonical, 'utf8')) + || canonicalJson(admitted.production) !== canonicalJson(production.reference)) { + return reconciliationRequired(); + } + } catch { + return reconciliationRequired(); + } + + const seenAttempts = new Set(); + const seenExecutions = new Set(); + const seenResults = new Set(); + let priorChain; + const matching = (type, attemptId) => entries.filter(item => item.type === type && item.attempt_id === attemptId); + const isResourceId = value => typeof value === 'string' && value.startsWith('urn:uuid:') + && UUID.test(value.slice('urn:uuid:'.length)); + const isExecutionId = value => typeof value === 'string' && value.startsWith('exec-offline-') + && UUID.test(value.slice('exec-offline-'.length)); + const isDigest = value => typeof value === 'string' && /^sha256:[0-9a-f]{64}$/.test(value); + for (const preparedResult of resultPrepared) { + const { attempt_id: attemptId, execution_id: executionId, result_id: resultId, + result_byte_size: byteSize, result_sha256: sha256, status } = preparedResult; + if (!isResourceId(attemptId) || !isExecutionId(executionId) || !isResourceId(resultId) + || !Number.isSafeInteger(byteSize) || byteSize < 0 || !isDigest(sha256) + || !['complete', 'failed'].includes(status) + || seenAttempts.size >= OFFLINE_ORCHESTRATION_LIMITS.maxAttemptsPerJob + || seenAttempts.has(attemptId) || seenExecutions.has(executionId) || seenResults.has(resultId)) { + return reconciliationRequired(); + } + seenAttempts.add(attemptId); + seenExecutions.add(executionId); + seenResults.add(resultId); + + const preparedAttempts = matching('prepared', attemptId); + const dispatches = matching('dispatch-started', attemptId); + const outcomes = matching('provider-outcome', attemptId); + const persistingMatches = matching('persisting', attemptId); + const terminalMatches = matching('terminal', attemptId); + if (preparedAttempts.length !== 1 || dispatches.length !== 1 || outcomes.length !== 1 + || persistingMatches.length !== 1 || terminalMatches.length !== 1) return reconciliationRequired(); + const [prepared] = preparedAttempts; + const [dispatch] = dispatches; + const [outcome] = outcomes; + const [persistingRecord] = persistingMatches; + const [terminal] = terminalMatches; + const ordered = [prepared, dispatch, outcome, preparedResult, persistingRecord, terminal] + .map(item => entries.indexOf(item)); + if (ordered.some((index, position) => index < 0 + || (position > 0 && index <= ordered[position - 1]))) return reconciliationRequired(); + + if (prepared.execution_id !== executionId || dispatch.execution_id !== executionId + || outcome.execution_id !== executionId || persistingRecord.execution_id !== executionId + || terminal.execution_id !== executionId || persistingRecord.result_id !== resultId + || terminal.result_id !== resultId || persistingRecord.result_byte_size !== byteSize + || terminal.result_byte_size !== byteSize || persistingRecord.result_sha256 !== sha256 + || terminal.result_sha256 !== sha256 || persistingRecord.attempt_id !== attemptId + || terminal.attempt_id !== attemptId || preparedResult.job_id !== jobId + || outcome.payload_key !== `provider-outcome:${executionId}` || !isDigest(outcome.sha256) + || !Number.isSafeInteger(outcome.byte_size) || outcome.byte_size < 0 + || !Number.isSafeInteger(dispatch.call_number) || dispatch.call_number < 1 + || canonicalJson(prepared.production) !== canonicalJson(admitted.production)) { + return reconciliationRequired(); + } + + const outcomeBytes = verifiedBlobs.get(outcome.payload_key); + const resultBytes = verifiedBlobs.get(`result:${resultId}`); + if (!Buffer.isBuffer(outcomeBytes) || !Buffer.isBuffer(resultBytes)) return reconciliationRequired(); + let providerResult; + let result; + try { + const outcomeSource = outcomeBytes.toString('utf8'); + const resultSource = resultBytes.toString('utf8'); + providerResult = JSON.parse(outcomeSource); + result = JSON.parse(resultSource); + if (!outcomeBytes.equals(Buffer.from(canonicalJson(providerResult), 'utf8')) + || !resultBytes.equals(Buffer.from(canonicalJson(result), 'utf8'))) return reconciliationRequired(); + } catch { + return reconciliationRequired(); + } + if (!providerResult || typeof providerResult !== 'object' || Array.isArray(providerResult) + || !result || typeof result !== 'object' || Array.isArray(result) + || !admitted.production || typeof admitted.production !== 'object' || Array.isArray(admitted.production) + || !prepared.production || typeof prepared.production !== 'object' || Array.isArray(prepared.production)) { + return reconciliationRequired(); + } + if ((!priorChain && prepared.retry_of_attempt_id !== null) + || (priorChain && (prepared.retry_of_attempt_id !== priorChain.attemptId + || priorChain.result.status !== 'failed' || priorChain.result.outputs.length !== 0 + || !eligibleRateLimit(priorChain.providerResult)))) return reconciliationRequired(); + let resultValidation; + try { + resultValidation = result.spec_version === '1.1.0' + ? validateComicBuildResultCandidate(canonicalJson(result), production.canonical) + : result.spec_version === '1.0.0' ? validateComicManifest(canonicalJson(result)) : { valid: false }; + if (!validateExecutionDocument(providerResult).valid + || providerResult.execution_id !== executionId || providerResult.status !== outcome.status + || result.result_id !== resultId || result.attempt_id !== attemptId || result.status !== status + || canonicalJson(prepared.production) !== canonicalJson(admitted.production) + || canonicalJson(result.production) !== canonicalJson(admitted.production) + || !resultValidation.valid) return reconciliationRequired(); + if (result.status === 'complete') { + if (providerResult.status !== 'succeeded' || typeof providerResult.output?.content !== 'string' + || result.outputs.length !== 1) return reconciliationRequired(); + const outputBytes = Buffer.from(providerResult.output.content, 'utf8'); + const artifact = result.outputs[0].artifact; + const storedArtifact = verifiedBlobs.get(`artifact:${artifact.artifact_uri}`); + if (!Buffer.isBuffer(storedArtifact) || !storedArtifact.equals(outputBytes) + || artifact.byte_size !== outputBytes.byteLength || artifact.sha256 !== digest(outputBytes)) { + return reconciliationRequired(); + } + } else if (result.outputs.length !== 0) return reconciliationRequired(); + } catch { + return reconciliationRequired(); + } + priorChain = { attemptId, providerResult, result }; + } + } + + const closedEvents = entries.filter(item => item.type === 'job-closed'); + if (closedEvents.length > 1 || (closedEvents.length === 1 && entries.at(-1) !== closedEvents[0])) { + return reconciliationRequired(); + } + const terminal = closedEvents.length === 1; const blocked = entries.some(item => item.type === 'contract-mapping-blocked'); const dispatched = entries.some(item => item.type === 'dispatch-started'); const outcomeRecorded = entries.some(item => item.type === 'provider-outcome'); const budgetExhausted = entries.some(item => item.type === 'budget-exhausted'); - if (terminal) { - return freezeDeep({ kind: 'recovery-inspection', status: 'terminal', last_lifecycle_event: last.type, - job_id: jobId, read_only: true, writes_performed: 0, provider_calls_performed: 0 }); - } + if (terminal) return recoveryDiagnostic('terminal'); + const resumeClassification = classifyResumeCandidate(jobId, entries, admitted, verifiedBlobs); if (resumeClassification) { if (resumeClassification.candidate) onCandidate?.(resumeClassification.candidate); - return freezeDeep({ kind: 'recovery-inspection', status: resumeClassification.status, - ...(resumeClassification.status === 'resume-candidate' ? { authority_check_required: true } : {}), - last_lifecycle_event: last.type, job_id: jobId, read_only: true, - writes_performed: 0, provider_calls_performed: 0 }); + return recoveryDiagnostic(resumeClassification.status); } const clock = safeClock(runtime); const deadlineUnverifiable = !clock || clock.epochId !== admitted.clock_epoch_id || !Number.isSafeInteger(admitted.deadline_monotonic_ms); const deadlineExpired = !deadlineUnverifiable && clock.now >= admitted.deadline_monotonic_ms; - return freezeDeep({ kind: 'recovery-inspection', - status: blocked ? 'contract-mapping-blocked' - : deadlineUnverifiable ? 'deadline-unverifiable' - : budgetExhausted || deadlineExpired ? 'budget-exhausted' - : dispatched && !outcomeRecorded ? 'execution-unresolved' : 'read-only-inspection-required', - last_lifecycle_event: last.type, - job_id: jobId, - read_only: true, - writes_performed: 0, - provider_calls_performed: 0 - }); + return recoveryDiagnostic(blocked ? 'contract-mapping-blocked' + : deadlineUnverifiable ? 'deadline-unverifiable' + : budgetExhausted || deadlineExpired ? 'budget-exhausted' + : dispatched && !outcomeRecorded ? 'execution-unresolved' : 'read-only-inspection-required'); } - function inspectRecovery(jobId) { return inspectRecoveryCore(jobId); } From 2b3f4c1ec3224b66cf955bbf2bfbd3b421268594 Mon Sep 17 00:00:00 2001 From: Andrew Peris Date: Tue, 10 Nov 2026 10:16:06 -0500 Subject: [PATCH 02/33] Implement O09 result-link inspection (runner.test.js) --- tests/offline-orchestration-prototype/runner.test.js | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/tests/offline-orchestration-prototype/runner.test.js b/tests/offline-orchestration-prototype/runner.test.js index eceb870..52d2fb6 100644 --- a/tests/offline-orchestration-prototype/runner.test.js +++ b/tests/offline-orchestration-prototype/runner.test.js @@ -1645,8 +1645,8 @@ test('deadline expiry does not hide a committed terminal result during read-only const inspection = value.inspectRecovery(result.job_id); assert.equal(inspection.status, 'terminal'); assert.equal(inspection.read_only, true); - assert.equal(inspection.writes_performed, 0); - assert.equal(inspection.provider_calls_performed, 0); + assert.equal(inspection.no_writes, true); + assert.equal(inspection.no_provider_calls, true); }); test('read-only recovery requires every terminal artifact to be readable and match its result', async () => { @@ -1763,6 +1763,7 @@ test('explicit candidate enables one delayed caller-authorized retry with immuta assert.equal(events.filter(e => e.type === 'dispatch-started').length, 2); assert.equal(events.filter(e => e.type === 'prepared')[1].retry_of_attempt_id, first.attempt_id); assert.equal(events.at(-1).type, 'job-closed'); + assert.equal(h.value.inspectRecovery(first.job_id).status, 'terminal'); await assert.rejects(() => h.value.retry({ authorizeRetry: true }), e => e.code === 'RETRY_NOT_AVAILABLE'); }); From d3d572a1a63fe12f89cbc8f972eca8b7370dcdea Mon Sep 17 00:00:00 2001 From: Andrew Peris Date: Tue, 10 Nov 2026 10:16:14 -0500 Subject: [PATCH 03/33] Implement O09 result-link inspection (resume-candidate.test.js) --- .../resume-candidate.test.js | 47 +++++++++++++++++-- 1 file changed, 42 insertions(+), 5 deletions(-) diff --git a/tests/offline-orchestration-prototype/resume-candidate.test.js b/tests/offline-orchestration-prototype/resume-candidate.test.js index 5f756aa..6a181ad 100644 --- a/tests/offline-orchestration-prototype/resume-candidate.test.js +++ b/tests/offline-orchestration-prototype/resume-candidate.test.js @@ -144,11 +144,48 @@ test('reopened local store reports a read-only candidate at the inclusive retry }); const inspected = restarted.inspectRecovery(seeded.jobId); - assert.equal(inspected.status, 'resume-candidate'); - assert.equal(inspected.authority_check_required, true); - assert.equal(inspected.read_only, true); - assert.equal(inspected.writes_performed, 0); - assert.equal(inspected.provider_calls_performed, 0); + assert.deepEqual(inspected, { + status: 'resume-candidate', + stage: 'resume', + code: 'RESUME_CANDIDATE', + read_only: true, + no_writes: true, + no_provider_calls: true, + authority_check_required: true + }); + + const result = seeded.result.result; + const events = reopened.readEvents(seeded.jobId); + const resultPrepared = events.filter(item => item.type === 'result-prepared'); + const persisting = events.filter(item => item.type === 'persisting'); + const terminal = events.filter(item => item.type === 'terminal'); + assert.equal(resultPrepared.length, 1); + assert.equal(persisting.length, 1); + assert.equal(terminal.length, 1); + for (const link of [resultPrepared[0], persisting[0], terminal[0]]) { + assert.equal(link.attempt_id, seeded.result.attempt_id); + assert.equal(link.execution_id, seeded.result.execution_id); + assert.equal(link.result_id, result.result_id); + assert.equal(link.result_byte_size, Buffer.byteLength(canonicalJson(result))); + assert.equal(link.result_sha256, `sha256:${createHash('sha256').update(canonicalJson(result)).digest('hex')}`); + } + assert.equal(resultPrepared[0].status, 'failed'); + const resultBytes = reopened.readImmutable(`result:${result.result_id}`); + assert.ok(Buffer.isBuffer(resultBytes)); + assert.equal(resultBytes.toString('utf8'), canonicalJson(result)); + assert.deepEqual(result.outputs, []); + const outcome = events.find(item => item.type === 'provider-outcome'); + assert.equal(outcome.attempt_id, seeded.result.attempt_id); + assert.equal(outcome.execution_id, seeded.result.execution_id); + assert.equal(outcome.status, 'failed'); + assert.equal(outcome.payload_key, `provider-outcome:${seeded.result.execution_id}`); + const resumeWindow = events.find(item => item.type === 'resume-window'); + assert.equal(resumeWindow.terminal_result_id, result.result_id); + const diagnostic = JSON.stringify(inspected); + for (const value of [seeded.jobId, seeded.result.attempt_id, seeded.result.execution_id, + result.result_id, outcome.payload_key, resultPrepared[0].result_sha256]) { + assert.equal(diagnostic.includes(value), false); + } assert.equal(reopened.eventCount, beforeEvents); assert.equal(reopened.blobCount, beforeBlobs); assert.equal(resumeClaimCalls(), 0); From 71737161f2b6c0a1e2e65d7ce9157442805310bd Mon Sep 17 00:00:00 2001 From: Andrew Peris Date: Tue, 10 Nov 2026 10:16:21 -0500 Subject: [PATCH 04/33] Implement O09 result-link inspection (local-file-store.test.js) --- .../local-file-store.test.js | 105 ++++++++++++++++-- 1 file changed, 98 insertions(+), 7 deletions(-) diff --git a/tests/offline-orchestration-prototype/local-file-store.test.js b/tests/offline-orchestration-prototype/local-file-store.test.js index feb9c90..36fb9f1 100644 --- a/tests/offline-orchestration-prototype/local-file-store.test.js +++ b/tests/offline-orchestration-prototype/local-file-store.test.js @@ -1,14 +1,14 @@ import assert from 'node:assert/strict'; import { - appendFileSync, closeSync, fsyncSync, lstatSync, mkdirSync, mkdtempSync, + appendFileSync, closeSync, fsyncSync, lstatSync, mkdirSync, mkdtempSync, readFileSync, openSync, rmSync, statSync, symlinkSync, writeFileSync } from 'node:fs'; import { tmpdir } from 'node:os'; import { join } from 'node:path'; import test from 'node:test'; import { readFile } from 'node:fs/promises'; -import { randomUUID } from 'node:crypto'; -import { MockTextAdapter } from '../../src/prompt-sdk/index.js'; +import { createHash, randomUUID } from 'node:crypto'; +import { canonicalJson, MockTextAdapter } from '../../src/prompt-sdk/index.js'; import { createSyntheticExecutionAuthorityVerifier, SYNTHETIC_EXECUTION_PURPOSE @@ -21,6 +21,7 @@ import { const fixture = JSON.parse(await readFile(new URL('../fixtures/comic-manifest-v1.json', import.meta.url), 'utf8')); const productionSource = JSON.stringify(fixture.production); +const sha256 = bytes => `sha256:${createHash('sha256').update(bytes).digest('hex')}`; function temporaryDirectory() { return mkdtempSync(join(tmpdir(), 'dss-o08-local-store-')); @@ -229,12 +230,102 @@ test('runner can inspect a committed synthetic result from a reopened local stor const beforeEvents = reopened.eventCount; const beforeBlobs = reopened.blobCount; const inspection = restarted.inspectRecovery(completed.job_id); - assert.equal(inspection.status, 'terminal'); - assert.equal(inspection.read_only, true); - assert.equal(inspection.writes_performed, 0); - assert.equal(inspection.provider_calls_performed, 0); + assert.deepEqual(inspection, { + status: 'terminal', + stage: 'terminal', + code: 'TERMINAL_RESULT_VERIFIED', + read_only: true, + no_writes: true, + no_provider_calls: true, + authority_check_required: false + }); + const events = reopened.readEvents(completed.job_id); + const resultPrepared = events.filter(item => item.type === 'result-prepared'); + const persisting = events.filter(item => item.type === 'persisting'); + const terminal = events.filter(item => item.type === 'terminal'); + assert.equal(resultPrepared.length, 1); + assert.equal(persisting.length, 1); + assert.equal(terminal.length, 1); + const expected = completed.result; + const resultBytes = reopened.readImmutable(`result:${expected.result_id}`); + assert.ok(Buffer.isBuffer(resultBytes)); + assert.equal(resultBytes.toString('utf8'), canonicalJson(expected)); + for (const link of [resultPrepared[0], persisting[0], terminal[0]]) { + assert.equal(link.attempt_id, completed.attempt_id); + assert.equal(link.execution_id, completed.execution_id); + assert.equal(link.result_id, expected.result_id); + assert.equal(link.result_byte_size, resultBytes.byteLength); + assert.equal(link.result_sha256, sha256(resultBytes)); + } + assert.equal(resultPrepared[0].status, expected.status); + const outcome = events.find(item => item.type === 'provider-outcome'); + assert.equal(outcome.attempt_id, completed.attempt_id); + assert.equal(outcome.execution_id, completed.execution_id); + assert.equal(outcome.status, 'succeeded'); + assert.equal(outcome.payload_key, `provider-outcome:${completed.execution_id}`); + const outcomeBytes = reopened.readImmutable(outcome.payload_key); + assert.ok(Buffer.isBuffer(outcomeBytes)); + assert.equal(outcomeBytes.byteLength, outcome.byte_size); + assert.equal(sha256(outcomeBytes), outcome.sha256); + for (const output of expected.outputs) { + const artifact = output.artifact; + const artifactBytes = reopened.readImmutable(`artifact:${artifact.artifact_uri}`); + assert.ok(Buffer.isBuffer(artifactBytes)); + assert.equal(artifactBytes.byteLength, artifact.byte_size); + assert.equal(sha256(artifactBytes), artifact.sha256); + } assert.equal(reopened.eventCount, beforeEvents); assert.equal(reopened.blobCount, beforeBlobs); assert.equal(restartedCalls, 0); await assert.rejects(() => restarted.submit({ productionSource }), error => error.code === 'JOB_STORE_LIFETIME_LIMIT'); }); + +test('read-only recovery rejects duplicate result links after reopening and keeps diagnostics value-free', async t => { + const root = temporaryDirectory(); + t.after(() => rmSync(root, { recursive: true, force: true })); + const store = new LocalFilePrototypeStore(root); + let calls = 0; + const first = prototype(store, ({ phase }) => { + if (phase === 'dispatch-confirmed') calls++; + }); + const completed = await first.submit({ productionSource }); + const eventPath = join(root, 'events', `${Buffer.from(completed.job_id).toString('base64url')}.jsonl`); + const entries = readFileSync(eventPath, 'utf8').trimEnd().split('\n').map(line => JSON.parse(line)); + const terminalIndex = entries.findIndex(item => item.type === 'terminal'); + assert.ok(terminalIndex >= 0); + const duplicate = structuredClone(entries[terminalIndex]); + duplicate.private_content = 'PRIVATE-CONTENT-SENTINEL'; + duplicate.exception_text = 'EXCEPTION-TEXT-SENTINEL'; + duplicate.path = root; + duplicate.fingerprint = 'FINGERPRINT-SENTINEL'; + duplicate.secret_digest = 'sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa'; + entries.splice(terminalIndex + 1, 0, duplicate); + writeFileSync(eventPath, `${entries.map(item => canonicalJson(item)).join('\n')}\n`); + + let restartedCalls = 0; + const reopened = new LocalFilePrototypeStore(root); + const restarted = prototype(reopened, () => { restartedCalls++; }); + const beforeEvents = structuredClone(reopened.readEvents(completed.job_id)); + const beforeBlobs = reopened.blobCount; + const inspection = restarted.inspectRecovery(completed.job_id); + assert.deepEqual(inspection, { + status: 'reconciliation-required', + stage: 'integrity', + code: 'RECONCILIATION_REQUIRED', + read_only: true, + no_writes: true, + no_provider_calls: true, + authority_check_required: false + }); + const diagnostic = JSON.stringify(inspection); + for (const value of [completed.job_id, completed.attempt_id, completed.execution_id, + completed.result.result_id, root, completed.result.outputs[0].artifact.artifact_uri, + completed.result.outputs[0].artifact.sha256, 'PRIVATE-CONTENT-SENTINEL', + 'EXCEPTION-TEXT-SENTINEL', 'FINGERPRINT-SENTINEL', 'secret_digest']) { + assert.equal(diagnostic.includes(value), false); + } + assert.deepEqual(reopened.readEvents(completed.job_id), beforeEvents); + assert.equal(reopened.blobCount, beforeBlobs); + assert.equal(restartedCalls, 0); + assert.equal(calls, 1); +}); \ No newline at end of file From 5ad0668e173b23a0804a43876d2b8793f8a8489e Mon Sep 17 00:00:00 2001 From: Andrew Peris Date: Tue, 10 Nov 2026 10:16:28 -0500 Subject: [PATCH 05/33] Implement O09 result-link inspection (offline-orchestration-prototype.md) --- docs/offline-orchestration-prototype.md | 31 +++++++++++++++++++++++-- 1 file changed, 29 insertions(+), 2 deletions(-) diff --git a/docs/offline-orchestration-prototype.md b/docs/offline-orchestration-prototype.md index 8422e06..20fd2b8 100644 --- a/docs/offline-orchestration-prototype.md +++ b/docs/offline-orchestration-prototype.md @@ -355,5 +355,32 @@ O07 receive bounded prerequisite passes only for the synthetic path described in the [durable-resume decision packet](o08-durable-resume-decision-packet.md); their Studio issues remain open and no broader production readiness is implied. O08 receives a scoped pass for its accepted synthetic, no-context, -local-filesystem behavior, while issue #109 remains open and O09 remains -separately gated. +local-filesystem behavior, while issue #109 remains open. The bounded O09 +result-link inspection slice and its remaining limits are recorded below; this +does not close Studio issue #110 or claim broader acceptance. +## O09 result-link inspection slice (2026-11-10) + +The opt-in local-file-store inspection now validates the canonical result +lifecycle links for each result-bearing attempt before classifying recovery. +For each attempt, the unique `prepared`, `dispatch-started`, `provider-outcome`, +`result-prepared`, `persisting`, and `terminal` events must agree on job, +attempt, execution, result ID, result status, byte size, and digest where +recorded, and occur in order. The provider outcome payload and canonical result +bytes must match their lifecycle references; the result must link to the +admitted synthetic production, and every output artifact URI, byte size, and +digest must resolve to matching local bytes. Missing, duplicate, malformed, or +contradictory links fail closed as `reconciliation-required`. Inspection +performs no writes or provider calls. + +The public `inspectRecovery()` projection contains only fixed status, stage, +and code values with boolean fields. It never returns job, attempt, execution, +result, or artifact identifiers; lifecycle event names; local paths; hashes; +protected content; exception text; or fingerprints. Result, outcome, and +artifact bytes remain in the caller-owned private local store. + +Coverage is limited to the pinned synthetic no-context local path, including +successful and no-output rate-limit results, reopened-store inspection, and a +canonical event-log duplicate-link corruption case. This does not authenticate +same-account edits to the local store, establish power-loss durability or +support for other filesystems, add providers or infrastructure, use production +data, or close Studio issue #110. From bcc616037186173aecc252e1fc8cbc2ca98ee02e Mon Sep 17 00:00:00 2001 From: Andrew Peris Date: Tue, 10 Nov 2026 10:17:18 -0500 Subject: [PATCH 06/33] Fix O09 documentation section spacing --- docs/offline-orchestration-prototype.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/offline-orchestration-prototype.md b/docs/offline-orchestration-prototype.md index 20fd2b8..fb479f1 100644 --- a/docs/offline-orchestration-prototype.md +++ b/docs/offline-orchestration-prototype.md @@ -358,6 +358,7 @@ O08 receives a scoped pass for its accepted synthetic, no-context, local-filesystem behavior, while issue #109 remains open. The bounded O09 result-link inspection slice and its remaining limits are recorded below; this does not close Studio issue #110 or claim broader acceptance. + ## O09 result-link inspection slice (2026-11-10) The opt-in local-file-store inspection now validates the canonical result From e88d6635ff4eebcb192f95cd30f23e71b508d903 Mon Sep 17 00:00:00 2001 From: Andrew Peris Date: Tue, 10 Nov 2026 10:44:28 -0500 Subject: [PATCH 07/33] fix: reconcile complete O09 result chains --- src/offline-orchestration-prototype/runner.js | 156 ++++++++++++++++-- 1 file changed, 145 insertions(+), 11 deletions(-) diff --git a/src/offline-orchestration-prototype/runner.js b/src/offline-orchestration-prototype/runner.js index eed6f71..8546da3 100644 --- a/src/offline-orchestration-prototype/runner.js +++ b/src/offline-orchestration-prototype/runner.js @@ -63,7 +63,8 @@ const RECOVERY_DIAGNOSTIC_STATES = Object.freeze({ 'budget-exhausted': Object.freeze({ stage: 'limits', code: 'BUDGET_EXHAUSTED' }), 'contract-mapping-blocked': Object.freeze({ stage: 'mapping', code: 'CONTRACT_MAPPING_BLOCKED' }), 'execution-unresolved': Object.freeze({ stage: 'execution', code: 'EXECUTION_UNRESOLVED' }), - 'read-only-inspection-required': Object.freeze({ stage: 'inspection', code: 'INSPECTION_REQUIRED' }) + 'read-only-inspection-required': Object.freeze({ stage: 'inspection', code: 'INSPECTION_REQUIRED' }), + 'closed-without-result': Object.freeze({ stage: 'terminal', code: 'JOB_CLOSED_WITHOUT_RESULT' }) }); const defaultRuntime = Object.freeze({ @@ -2103,6 +2104,9 @@ function createRunner({ runtime = defaultRuntime, store = new InMemoryPrototypeS if (resultPrepared.length > 0) { const productionBytes = verifiedBlobs.get(admitted.input_key); let production; + if (!admitted.production || typeof admitted.production !== 'object' || Array.isArray(admitted.production)) { + return reconciliationRequired(); + } try { production = readProduction(productionBytes.toString('utf8')); if (!productionBytes.equals(Buffer.from(production.canonical, 'utf8')) @@ -2149,6 +2153,31 @@ function createRunner({ runtime = defaultRuntime, store = new InMemoryPrototypeS const [outcome] = outcomes; const [persistingRecord] = persistingMatches; const [terminal] = terminalMatches; + if (priorChain) { + const priorWindows = matching('resume-window', priorChain.attemptId); + if (priorWindows.length !== 1) return reconciliationRequired(); + const priorWindow = priorWindows[0]; + const timeRecord = admitted.resume_time; + const windowKeys = ['authority_id', 'context_enabled', 'deadline_at_ms', 'domain_id', 'epoch_id', 'started_at_ms']; + const validTimeRecord = timeRecord && typeof timeRecord === 'object' && !Array.isArray(timeRecord) + && Object.keys(timeRecord).sort().join('|') === windowKeys.join('|') + && timeRecord.authority_id === SYNTHETIC_RESUME_TIME_AUTHORITY_ID && typeof timeRecord.domain_id === 'string' + && typeof timeRecord.epoch_id === 'string' && timeRecord.context_enabled === false + && Number.isSafeInteger(timeRecord.started_at_ms) && Number.isSafeInteger(timeRecord.deadline_at_ms) + && timeRecord.deadline_at_ms === checkedAdd(timeRecord.started_at_ms, OFFLINE_ORCHESTRATION_LIMITS.jobBudgetMs); + const priorWindowIndex = entries.indexOf(priorWindow); + if (!validTimeRecord || priorWindow.attempt_id !== priorChain.attemptId + || priorWindow.execution_id !== priorChain.executionId + || priorWindow.terminal_result_id !== priorChain.resultId + || !Number.isSafeInteger(priorWindow.checked_at_ms) + || priorWindow.checked_at_ms < timeRecord.started_at_ms + || priorWindow.checked_at_ms >= timeRecord.deadline_at_ms + || priorWindow.retry_not_before_at_ms !== checkedAdd(priorWindow.checked_at_ms, + priorChain.providerResult.error.retry_after_ms) + || priorWindow.deadline_at_ms !== timeRecord.deadline_at_ms + || priorWindowIndex <= priorChain.terminalIndex + || entries.indexOf(prepared) <= priorWindowIndex) return reconciliationRequired(); + } else if (prepared.retry_of_attempt_id !== null) return reconciliationRequired(); const ordered = [prepared, dispatch, outcome, preparedResult, persistingRecord, terminal] .map(item => entries.indexOf(item)); if (ordered.some((index, position) => index < 0 @@ -2164,6 +2193,8 @@ function createRunner({ runtime = defaultRuntime, store = new InMemoryPrototypeS || outcome.payload_key !== `provider-outcome:${executionId}` || !isDigest(outcome.sha256) || !Number.isSafeInteger(outcome.byte_size) || outcome.byte_size < 0 || !Number.isSafeInteger(dispatch.call_number) || dispatch.call_number < 1 + || !admitted.production || typeof admitted.production !== 'object' || Array.isArray(admitted.production) + || !prepared.production || typeof prepared.production !== 'object' || Array.isArray(prepared.production) || canonicalJson(prepared.production) !== canonicalJson(admitted.production)) { return reconciliationRequired(); } @@ -2184,9 +2215,7 @@ function createRunner({ runtime = defaultRuntime, store = new InMemoryPrototypeS return reconciliationRequired(); } if (!providerResult || typeof providerResult !== 'object' || Array.isArray(providerResult) - || !result || typeof result !== 'object' || Array.isArray(result) - || !admitted.production || typeof admitted.production !== 'object' || Array.isArray(admitted.production) - || !prepared.production || typeof prepared.production !== 'object' || Array.isArray(prepared.production)) { + || !result || typeof result !== 'object' || Array.isArray(result)) { return reconciliationRequired(); } if ((!priorChain && prepared.retry_of_attempt_id !== null) @@ -2195,18 +2224,28 @@ function createRunner({ runtime = defaultRuntime, store = new InMemoryPrototypeS || !eligibleRateLimit(priorChain.providerResult)))) return reconciliationRequired(); let resultValidation; try { + const resultSource = canonicalJson(result); resultValidation = result.spec_version === '1.1.0' - ? validateComicBuildResultCandidate(canonicalJson(result), production.canonical) - : result.spec_version === '1.0.0' ? validateComicManifest(canonicalJson(result)) : { valid: false }; + ? validateComicBuildResultCandidate(resultSource, production.canonical) + : result.spec_version === '1.0.0' ? validateComicManifest(resultSource) : { valid: false }; + const compatibility = result.spec_version === '1.1.0' ? resultValidation + : result.spec_version === '1.0.0' + ? validateComicOutputCompatibility(production.canonical, resultSource) : { valid: false }; if (!validateExecutionDocument(providerResult).valid || providerResult.execution_id !== executionId || providerResult.status !== outcome.status || result.result_id !== resultId || result.attempt_id !== attemptId || result.status !== status || canonicalJson(prepared.production) !== canonicalJson(admitted.production) || canonicalJson(result.production) !== canonicalJson(admitted.production) - || !resultValidation.valid) return reconciliationRequired(); + || !resultValidation.valid || !compatibility.valid) return reconciliationRequired(); + if (result.spec_version === '1.1.0' + && (admitted.no_output_result_version !== '1.1.0' || result.status !== 'failed' + || providerResult.status !== 'failed' || !eligibleRateLimit(providerResult) + || result.outputs.length !== 0)) return reconciliationRequired(); if (result.status === 'complete') { - if (providerResult.status !== 'succeeded' || typeof providerResult.output?.content !== 'string' - || result.outputs.length !== 1) return reconciliationRequired(); + if (result.spec_version !== '1.0.0' || providerResult.status !== 'succeeded' + || typeof providerResult.output?.content !== 'string' || result.outputs.length !== 1) { + return reconciliationRequired(); + } const outputBytes = Buffer.from(providerResult.output.content, 'utf8'); const artifact = result.outputs[0].artifact; const storedArtifact = verifiedBlobs.get(`artifact:${artifact.artifact_uri}`); @@ -2218,7 +2257,100 @@ function createRunner({ runtime = defaultRuntime, store = new InMemoryPrototypeS } catch { return reconciliationRequired(); } - priorChain = { attemptId, providerResult, result }; + const ownWindows = matching('resume-window', attemptId); + if (ownWindows.length > 1) return reconciliationRequired(); + let resumeWindowIndex; + if (ownWindows.length === 1) { + const resumeWindow = ownWindows[0]; + const timeRecord = admitted.resume_time; + const timeKeys = 'authority_id|context_enabled|deadline_at_ms|domain_id|epoch_id|started_at_ms'; + if (!timeRecord || Object.keys(timeRecord).sort().join('|') !== timeKeys + || timeRecord.authority_id !== SYNTHETIC_RESUME_TIME_AUTHORITY_ID + || typeof timeRecord.domain_id !== 'string' || typeof timeRecord.epoch_id !== 'string' + || timeRecord.context_enabled !== false + || !Number.isSafeInteger(timeRecord.started_at_ms) + || !Number.isSafeInteger(timeRecord.deadline_at_ms) + || resumeWindow.attempt_id !== attemptId || resumeWindow.execution_id !== executionId + || resumeWindow.terminal_result_id !== resultId + || result.status !== 'failed' || result.outputs.length !== 0 + || !eligibleRateLimit(providerResult) + || !Number.isSafeInteger(resumeWindow.checked_at_ms) + || resumeWindow.checked_at_ms < timeRecord.started_at_ms + || resumeWindow.checked_at_ms >= timeRecord.deadline_at_ms + || resumeWindow.retry_not_before_at_ms !== checkedAdd(resumeWindow.checked_at_ms, + providerResult.error.retry_after_ms) + || resumeWindow.deadline_at_ms !== timeRecord.deadline_at_ms + || entries.indexOf(resumeWindow) <= entries.indexOf(terminal)) return reconciliationRequired(); + resumeWindowIndex = entries.indexOf(resumeWindow); + } + priorChain = { attemptId, executionId, resultId, terminalIndex: entries.indexOf(terminal), + resumeWindowIndex, providerResult, result }; + } + + // All result-bearing attempt records must belong to a verified chain. The + // only allowed trailing attempt is an explicitly stopped retry with no result. + const resultAttemptEventTypes = new Set(['prepared', 'dispatch-started', 'provider-outcome', + 'result-prepared', 'persisting', 'terminal', 'resume-window', + 'contract-mapping-blocked', 'budget-exhausted', 'cancelled-before-dispatch']); + const orphanIds = new Set(entries.filter(item => resultAttemptEventTypes.has(item.type) + && item.attempt_id !== undefined && !seenAttempts.has(item.attempt_id)) + .map(item => item.attempt_id)); + if (orphanIds.size > 0) { + if (orphanIds.size !== 1 || !priorChain || priorChain.resumeWindowIndex === undefined) { + return reconciliationRequired(); + } + const [orphanId] = orphanIds; + const orphanEvents = entries.filter(item => resultAttemptEventTypes.has(item.type) + && item.attempt_id === orphanId); + const ofType = type => orphanEvents.filter(item => item.type === type); + const orphanPrepared = ofType('prepared'); + const orphanDispatches = ofType('dispatch-started'); + const orphanOutcomes = ofType('provider-outcome'); + const orphanStops = orphanEvents.filter(item => ['contract-mapping-blocked', + 'budget-exhausted', 'cancelled-before-dispatch'].includes(item.type)); + const orphanResults = orphanEvents.filter(item => ['result-prepared', 'persisting', + 'terminal', 'resume-window'].includes(item.type)); + const stopCounts = new Map(); + for (const item of orphanStops) stopCounts.set(item.type, (stopCounts.get(item.type) ?? 0) + 1); + if (orphanPrepared.length !== 1 || orphanDispatches.length > 1 || orphanOutcomes.length > 1 + || orphanStops.length < 1 || [...stopCounts.values()].some(count => count > 1) || orphanResults.length !== 0 + || orphanPrepared[0].retry_of_attempt_id !== priorChain.attemptId + || !isResourceId(orphanId) || !isExecutionId(orphanPrepared[0].execution_id) + || entries.indexOf(orphanPrepared[0]) <= priorChain.resumeWindowIndex) { + return reconciliationRequired(); + } + const orphanExecutionId = orphanPrepared[0].execution_id; + const orphanDispatch = orphanDispatches[0]; + const orphanOutcome = orphanOutcomes[0]; + if ((orphanDispatch && (orphanDispatch.execution_id !== orphanExecutionId + || orphanDispatch.call_number !== 1 + || entries.indexOf(orphanDispatch) <= entries.indexOf(orphanPrepared[0]))) + || (orphanOutcome && (!orphanDispatch || orphanOutcome.execution_id !== orphanExecutionId + || orphanOutcome.payload_key !== `provider-outcome:${orphanExecutionId}` + || !isDigest(orphanOutcome.sha256) || !Number.isSafeInteger(orphanOutcome.byte_size) + || entries.indexOf(orphanOutcome) <= entries.indexOf(orphanDispatch)))) { + return reconciliationRequired(); + } + if (orphanOutcome) { + const orphanOutcomeBytes = verifiedBlobs.get(orphanOutcome.payload_key); + let orphanProviderResult; + try { orphanProviderResult = JSON.parse(orphanOutcomeBytes.toString('utf8')); } catch { + return reconciliationRequired(); + } + if (!orphanProviderResult || !validateExecutionDocument(orphanProviderResult).valid + || orphanProviderResult.execution_id !== orphanExecutionId + || orphanProviderResult.status !== orphanOutcome.status) return reconciliationRequired(); + } + const lastAttemptIndex = entries.indexOf(orphanOutcome ?? orphanDispatch ?? orphanPrepared[0]); + const stopIndices = orphanStops.map(item => entries.indexOf(item)); + const closedEvents = entries.filter(item => item.type === 'job-closed'); + if (orphanStops.some(item => item.execution_id !== undefined + && item.execution_id !== orphanExecutionId) + || stopIndices.some(index => index <= lastAttemptIndex) + || (closedEvents.length === 1 && (entries.at(-1) !== closedEvents[0] + || entries.indexOf(closedEvents[0]) <= Math.max(...stopIndices))) + || (closedEvents.length === 0 && (orphanStops.length !== 1 + || orphanStops[0].type !== 'contract-mapping-blocked'))) return reconciliationRequired(); } } @@ -2231,7 +2363,9 @@ function createRunner({ runtime = defaultRuntime, store = new InMemoryPrototypeS const dispatched = entries.some(item => item.type === 'dispatch-started'); const outcomeRecorded = entries.some(item => item.type === 'provider-outcome'); const budgetExhausted = entries.some(item => item.type === 'budget-exhausted'); - if (terminal) return recoveryDiagnostic('terminal'); + if (terminal) return recoveryDiagnostic(resultPrepared.length > 0 ? 'terminal' + : blocked ? 'contract-mapping-blocked' + : budgetExhausted ? 'budget-exhausted' : 'closed-without-result'); const resumeClassification = classifyResumeCandidate(jobId, entries, admitted, verifiedBlobs); if (resumeClassification) { From 2513d3c03531977148b8a793e7b06f03fa3f3574 Mon Sep 17 00:00:00 2001 From: Andrew Peris Date: Tue, 10 Nov 2026 10:44:49 -0500 Subject: [PATCH 08/33] test: cover O09 local result corruption --- .../local-file-store.test.js | 187 +++++++++++++++++- 1 file changed, 186 insertions(+), 1 deletion(-) diff --git a/tests/offline-orchestration-prototype/local-file-store.test.js b/tests/offline-orchestration-prototype/local-file-store.test.js index 36fb9f1..87c736b 100644 --- a/tests/offline-orchestration-prototype/local-file-store.test.js +++ b/tests/offline-orchestration-prototype/local-file-store.test.js @@ -328,4 +328,189 @@ test('read-only recovery rejects duplicate result links after reopening and keep assert.equal(reopened.blobCount, beforeBlobs); assert.equal(restartedCalls, 0); assert.equal(calls, 1); -}); \ No newline at end of file +}); + + +function localEventPath(root, jobId) { + return join(root, 'events', `${Buffer.from(jobId).toString('base64url')}.jsonl`); +} + +function localBlobPath(root, key) { + return join(root, 'blobs', `${Buffer.from(key).toString('base64url')}.blob`); +} + +function writeLocalEventLog(root, jobId, entries) { + writeFileSync(localEventPath(root, jobId), `${entries.map(item => canonicalJson(item)).join('\\n')}\\n`); +} + +function writeLocalBlob(root, key, bytes) { + writeFileSync(localBlobPath(root, key), bytes); +} + +function assertSafeReconciliation(inspection, values) { + assert.deepEqual(inspection, { + status: 'reconciliation-required', + stage: 'integrity', + code: 'RECONCILIATION_REQUIRED', + read_only: true, + no_writes: true, + no_provider_calls: true, + authority_check_required: false + }); + const publicValue = JSON.stringify(inspection); + for (const value of values) assert.equal(publicValue.includes(value), false); +} + +test('reopened inspection rejects orphan attempt lifecycle records without exposing their values', async t => { + for (const orphanType of ['prepared', 'dispatch-started', 'provider-outcome']) { + await t.test(orphanType, async t => { + const root = temporaryDirectory(); + t.after(() => rmSync(root, { recursive: true, force: true })); + const store = new LocalFilePrototypeStore(root); + let calls = 0; + const completed = await prototype(store, () => { calls++; }).submit({ productionSource }); + const entries = store.readEvents(completed.job_id); + const source = entries.find(item => item.type === orphanType); + assert.ok(source); + const orphan = structuredClone(source); + orphan.attempt_id = 'urn:uuid:30000000-0000-4000-8000-000000000003'; + orphan.private_content = 'ORPHAN-PRIVATE-CONTENT-SENTINEL'; + orphan.exception_text = 'ORPHAN-EXCEPTION-SENTINEL'; + orphan.fingerprint = 'ORPHAN-FINGERPRINT-SENTINEL'; + const closeIndex = entries.findIndex(item => item.type === 'job-closed'); + assert.ok(closeIndex >= 0); + entries.splice(closeIndex, 0, orphan); + writeLocalEventLog(root, completed.job_id, entries); + + const reopened = new LocalFilePrototypeStore(root); + let restartedCalls = 0; + const restarted = prototype(reopened, () => { restartedCalls++; }); + const beforeEvents = structuredClone(reopened.readEvents(completed.job_id)); + const beforeBlobs = reopened.blobCount; + const inspection = restarted.inspectRecovery(completed.job_id); + assertSafeReconciliation(inspection, [ + root, completed.job_id, completed.attempt_id, completed.execution_id, + completed.result.result_id, completed.result.outputs[0].artifact.artifact_uri, + completed.result.outputs[0].artifact.sha256, 'ORPHAN-PRIVATE-CONTENT-SENTINEL', + 'ORPHAN-EXCEPTION-SENTINEL', 'ORPHAN-FINGERPRINT-SENTINEL' + ]); + assert.deepEqual(reopened.readEvents(completed.job_id), beforeEvents); + assert.equal(reopened.blobCount, beforeBlobs); + assert.equal(restartedCalls, 0); + assert.equal(calls, 1); + }); + } +}); + +test('reopened inspection reconciles a malformed prepared production before canonicalization', async t => { + const root = temporaryDirectory(); + t.after(() => rmSync(root, { recursive: true, force: true })); + const store = new LocalFilePrototypeStore(root); + let calls = 0; + const completed = await prototype(store, () => { calls++; }).submit({ productionSource }); + const entries = store.readEvents(completed.job_id); + const prepared = entries.find(item => item.type === 'prepared'); + assert.ok(prepared); + delete prepared.production; + prepared.private_content = 'MALFORMED-PRIVATE-CONTENT-SENTINEL'; + prepared.exception_text = 'MALFORMED-EXCEPTION-SENTINEL'; + writeLocalEventLog(root, completed.job_id, entries); + + const reopened = new LocalFilePrototypeStore(root); + let restartedCalls = 0; + const restarted = prototype(reopened, () => { restartedCalls++; }); + const beforeEvents = structuredClone(reopened.readEvents(completed.job_id)); + const beforeBlobs = reopened.blobCount; + assertSafeReconciliation(restarted.inspectRecovery(completed.job_id), [ + root, completed.job_id, completed.attempt_id, completed.execution_id, + completed.result.result_id, 'MALFORMED-PRIVATE-CONTENT-SENTINEL', + 'MALFORMED-EXCEPTION-SENTINEL' + ]); + assert.deepEqual(reopened.readEvents(completed.job_id), beforeEvents); + assert.equal(reopened.blobCount, beforeBlobs); + assert.equal(restartedCalls, 0); + assert.equal(calls, 1); +}); + +test('reopened inspection rejects a 1.1.0 no-output result paired with a success outcome', async t => { + const root = temporaryDirectory(); + const successRoot = temporaryDirectory(); + t.after(() => rmSync(root, { recursive: true, force: true })); + t.after(() => rmSync(successRoot, { recursive: true, force: true })); + const failedStore = new LocalFilePrototypeStore(root); + let calls = 0; + const failed = await prototype(failedStore, () => { calls++; }).submit({ + productionSource, + noOutputResultVersion: '1.1.0', + mockOutcome: { kind: 'rate-limit', retry_after_ms: 10 } + }); + assert.equal(failed.result.spec_version, '1.1.0'); + const successStore = new LocalFilePrototypeStore(successRoot); + const successful = await prototype(successStore).submit({ productionSource }); + const successOutcomeEvent = successStore.readEvents(successful.job_id).find(item => item.type === 'provider-outcome'); + const successOutcome = JSON.parse(successStore.readImmutable(successOutcomeEvent.payload_key).toString('utf8')); + successOutcome.execution_id = failed.execution_id; + if (Object.hasOwn(successOutcome, 'idempotency_key')) successOutcome.idempotency_key = `idem-${failed.execution_id}`; + const bytes = Buffer.from(canonicalJson(successOutcome), 'utf8'); + const entries = failedStore.readEvents(failed.job_id); + const outcome = entries.find(item => item.type === 'provider-outcome'); + outcome.status = 'succeeded'; + outcome.byte_size = bytes.byteLength; + outcome.sha256 = sha256(bytes); + outcome.private_content = 'OUTCOME-PRIVATE-CONTENT-SENTINEL'; + writeLocalBlob(root, outcome.payload_key, bytes); + writeLocalEventLog(root, failed.job_id, entries); + + const reopened = new LocalFilePrototypeStore(root); + let restartedCalls = 0; + const restarted = prototype(reopened, () => { restartedCalls++; }); + const beforeEvents = structuredClone(reopened.readEvents(failed.job_id)); + const beforeBlobs = reopened.blobCount; + assertSafeReconciliation(restarted.inspectRecovery(failed.job_id), [ + root, failed.job_id, failed.attempt_id, failed.execution_id, failed.result.result_id, + failed.result.outputs.length === 0 ? 'NO-ARTIFACT' : failed.result.outputs[0].artifact.artifact_uri, + 'OUTCOME-PRIVATE-CONTENT-SENTINEL' + ]); + assert.deepEqual(reopened.readEvents(failed.job_id), beforeEvents); + assert.equal(reopened.blobCount, beforeBlobs); + assert.equal(restartedCalls, 0); + assert.equal(calls, 1); +}); + +test('reopened v1.0 result inspection checks production-output compatibility after linked digest updates', async t => { + const root = temporaryDirectory(); + t.after(() => rmSync(root, { recursive: true, force: true })); + const store = new LocalFilePrototypeStore(root); + let calls = 0; + const completed = await prototype(store, () => { calls++; }).submit({ productionSource }); + const resultKey = `result:${completed.result.result_id}`; + const result = JSON.parse(store.readImmutable(resultKey).toString('utf8')); + assert.equal(result.spec_version, '1.0.0'); + result.outputs[0].rendition_id = 'tampered-rendition'; + result.private_content = 'COMPATIBILITY-PRIVATE-CONTENT-SENTINEL'; + const bytes = Buffer.from(canonicalJson(result), 'utf8'); + const entries = store.readEvents(completed.job_id); + for (const item of entries) { + if (['result-prepared', 'persisting', 'terminal'].includes(item.type)) { + item.result_byte_size = bytes.byteLength; + item.result_sha256 = sha256(bytes); + } + } + writeLocalBlob(root, resultKey, bytes); + writeLocalEventLog(root, completed.job_id, entries); + + const reopened = new LocalFilePrototypeStore(root); + let restartedCalls = 0; + const restarted = prototype(reopened, () => { restartedCalls++; }); + const beforeEvents = structuredClone(reopened.readEvents(completed.job_id)); + const beforeBlobs = reopened.blobCount; + assertSafeReconciliation(restarted.inspectRecovery(completed.job_id), [ + root, completed.job_id, completed.attempt_id, completed.execution_id, completed.result.result_id, + completed.result.outputs[0].artifact.artifact_uri, completed.result.outputs[0].artifact.sha256, + 'COMPATIBILITY-PRIVATE-CONTENT-SENTINEL' + ]); + assert.deepEqual(reopened.readEvents(completed.job_id), beforeEvents); + assert.equal(reopened.blobCount, beforeBlobs); + assert.equal(restartedCalls, 0); + assert.equal(calls, 1); +}); From 2219e6b6c02e0c8b7856477a9b411c2c29686169 Mon Sep 17 00:00:00 2001 From: Andrew Peris Date: Tue, 10 Nov 2026 10:45:54 -0500 Subject: [PATCH 09/33] test: cover O09 retry-chain corruption --- .../resume-candidate.test.js | 122 ++++++++++++++++++ 1 file changed, 122 insertions(+) diff --git a/tests/offline-orchestration-prototype/resume-candidate.test.js b/tests/offline-orchestration-prototype/resume-candidate.test.js index 6a181ad..7ea0d42 100644 --- a/tests/offline-orchestration-prototype/resume-candidate.test.js +++ b/tests/offline-orchestration-prototype/resume-candidate.test.js @@ -887,3 +887,125 @@ test('uncertain new provider-outcome write is not replayed after restart', async assert.equal(repeat.status, 'resume-not-eligible'); assert.equal(providerCalls, 1); }); + + +function writeResumeEventLog(root, jobId, entries) { + const eventPath = join(root, 'events', `${Buffer.from(jobId).toString('base64url')}.jsonl`); + writeFileSync(eventPath, `${entries.map(item => canonicalJson(item)).join('\\n')}\\n`); +} + +function assertResumeReconciliation(inspection, values) { + assert.deepEqual(inspection, { + status: 'reconciliation-required', + stage: 'integrity', + code: 'RECONCILIATION_REQUIRED', + read_only: true, + no_writes: true, + no_provider_calls: true, + authority_check_required: false + }); + const value = JSON.stringify(inspection); + for (const item of values) assert.equal(value.includes(item), false); +} + +async function completeSeededRetry(seeded, onMockCall = () => {}) { + seeded.runtime.advance(10); + const reopened = new LocalFilePrototypeStore(seeded.root); + const runner = createRunner(reopened, { + timeAuthority: resumeAuthority({ now: () => seeded.window.retry_not_before_at_ms }), + onMockCall + }); + const result = await runner.resume({ jobId: seeded.jobId, authorizeResume: true }); + assert.equal(result.kind, 'terminal'); + assert.equal(result.retry_eligible, false); + return { reopened, runner, result }; +} + +test('completed retry inspection rejects a second prepared/dispatch before the first terminal', async t => { + const seeded = await seedRetryEligible(t, 10); + let resumedCalls = 0; + const completed = await completeSeededRetry(seeded, ({ phase }) => { + if (phase === 'dispatch-confirmed') resumedCalls++; + }); + assert.equal(completed.runner.inspectRecovery(seeded.jobId).status, 'terminal'); + const entries = completed.reopened.readEvents(seeded.jobId); + const prepared = entries.filter(item => item.type === 'prepared'); + const dispatches = entries.filter(item => item.type === 'dispatch-started'); + const firstTerminal = entries.find(item => item.type === 'terminal' && item.attempt_id === prepared[0].attempt_id); + assert.equal(prepared.length, 2); + assert.equal(dispatches.length, 2); + assert.ok(firstTerminal); + const moved = new Set([prepared[1], dispatches[1]]); + const interleaved = entries.filter(item => !moved.has(item)); + const terminalIndex = interleaved.indexOf(firstTerminal); + interleaved.splice(terminalIndex, 0, prepared[1], dispatches[1]); + writeResumeEventLog(seeded.root, seeded.jobId, interleaved); + + const reopened = new LocalFilePrototypeStore(seeded.root); + let inspectionCalls = 0; + const probe = createRunner(reopened, { onMockCall: () => { inspectionCalls++; } }); + const beforeEvents = structuredClone(reopened.readEvents(seeded.jobId)); + const beforeBlobs = reopened.blobCount; + const finalTerminal = entries.find(item => item.type === 'terminal' && item.attempt_id === prepared[1].attempt_id); + assertResumeReconciliation(probe.inspectRecovery(seeded.jobId), [ + seeded.root, seeded.jobId, prepared[0].attempt_id, prepared[1].attempt_id, + prepared[0].execution_id, prepared[1].execution_id, + firstTerminal.result_id, finalTerminal.result_id, + 'PRIVATE-RESULT-SENTINEL' + ]); + assert.deepEqual(reopened.readEvents(seeded.jobId), beforeEvents); + assert.equal(reopened.blobCount, beforeBlobs); + assert.equal(inspectionCalls, 0); + assert.equal(seeded.providerCalls(), 1); + assert.equal(resumedCalls, 1); +}); + +test('completed retry inspection rejects mismatched and duplicate resume-window links', async t => { + for (const corruption of ['mismatched-result-link', 'duplicate-window']) { + await t.test(corruption, async t => { + const seeded = await seedRetryEligible(t, 10); + let resumedCalls = 0; + const completed = await completeSeededRetry(seeded, ({ phase }) => { + if (phase === 'dispatch-confirmed') resumedCalls++; + }); + const entries = completed.reopened.readEvents(seeded.jobId); + const firstPrepared = entries.find(item => item.type === 'prepared'); + const firstWindow = entries.find(item => item.type === 'resume-window'); + const secondPrepared = entries.find(item => item.type === 'prepared' + && item.attempt_id !== firstPrepared.attempt_id); + const secondTerminal = entries.find(item => item.type === 'terminal' + && item.attempt_id === secondPrepared.attempt_id); + assert.ok(firstWindow); + assert.ok(secondTerminal); + if (corruption === 'mismatched-result-link') { + firstWindow.terminal_result_id = secondTerminal.result_id; + firstWindow.private_content = 'WINDOW-PRIVATE-CONTENT-SENTINEL'; + } else { + const duplicate = structuredClone(firstWindow); + duplicate.private_content = 'WINDOW-PRIVATE-CONTENT-SENTINEL'; + duplicate.exception_text = 'WINDOW-EXCEPTION-SENTINEL'; + const nextIndex = entries.indexOf(secondPrepared); + entries.splice(nextIndex, 0, duplicate); + } + writeResumeEventLog(seeded.root, seeded.jobId, entries); + + const reopened = new LocalFilePrototypeStore(seeded.root); + let inspectionCalls = 0; + const probe = createRunner(reopened, { onMockCall: () => { inspectionCalls++; } }); + const beforeEvents = structuredClone(reopened.readEvents(seeded.jobId)); + const beforeBlobs = reopened.blobCount; + assertResumeReconciliation(probe.inspectRecovery(seeded.jobId), [ + seeded.root, seeded.jobId, firstPrepared.attempt_id, secondPrepared.attempt_id, + firstPrepared.execution_id, secondPrepared.execution_id, + firstWindow.terminal_result_id, secondTerminal.result_id, + seeded.result.result.result_id, 'WINDOW-PRIVATE-CONTENT-SENTINEL', + 'WINDOW-EXCEPTION-SENTINEL' + ]); + assert.deepEqual(reopened.readEvents(seeded.jobId), beforeEvents); + assert.equal(reopened.blobCount, beforeBlobs); + assert.equal(inspectionCalls, 0); + assert.equal(seeded.providerCalls(), 1); + assert.equal(resumedCalls, 1); + }); + } +}); From f23476e34cbb6fbc865435d3841dab0a102d9d8d Mon Sep 17 00:00:00 2001 From: Andrew Peris Date: Tue, 10 Nov 2026 10:55:48 -0500 Subject: [PATCH 10/33] fix: fail closed on unlinked O09 records --- src/offline-orchestration-prototype/runner.js | 104 +++++++++++++++++- 1 file changed, 98 insertions(+), 6 deletions(-) diff --git a/src/offline-orchestration-prototype/runner.js b/src/offline-orchestration-prototype/runner.js index 8546da3..b3c1425 100644 --- a/src/offline-orchestration-prototype/runner.js +++ b/src/offline-orchestration-prototype/runner.js @@ -2101,6 +2101,7 @@ function createRunner({ runtime = defaultRuntime, store = new InMemoryPrototypeS if (resultPrepared.length !== persisting.length || resultPrepared.length !== terminals.length) { return reconciliationRequired(); } + let trailingNoResultAttempt = false; if (resultPrepared.length > 0) { const productionBytes = verifiedBlobs.get(admitted.input_key); let production; @@ -2241,6 +2242,13 @@ function createRunner({ runtime = defaultRuntime, store = new InMemoryPrototypeS && (admitted.no_output_result_version !== '1.1.0' || result.status !== 'failed' || providerResult.status !== 'failed' || !eligibleRateLimit(providerResult) || result.outputs.length !== 0)) return reconciliationRequired(); + if (result.spec_version === '1.0.0' && result.status === 'failed') { + const supportedFailure = providerResult.status === 'cancelled' + || (providerResult.status === 'failed' + && ['output-validation', 'rate-limit'].includes(providerResult.error?.category)) + || (providerResult.status === 'succeeded' && typeof providerResult.output?.content === 'string'); + if (!supportedFailure) return reconciliationRequired(); + } if (result.status === 'complete') { if (result.spec_version !== '1.0.0' || providerResult.status !== 'succeeded' || typeof providerResult.output?.content !== 'string' || result.outputs.length !== 1) { @@ -2292,9 +2300,13 @@ function createRunner({ runtime = defaultRuntime, store = new InMemoryPrototypeS const resultAttemptEventTypes = new Set(['prepared', 'dispatch-started', 'provider-outcome', 'result-prepared', 'persisting', 'terminal', 'resume-window', 'contract-mapping-blocked', 'budget-exhausted', 'cancelled-before-dispatch']); - const orphanIds = new Set(entries.filter(item => resultAttemptEventTypes.has(item.type) - && item.attempt_id !== undefined && !seenAttempts.has(item.attempt_id)) - .map(item => item.attempt_id)); + if (entries.some(item => resultAttemptEventTypes.has(item.type) && item.attempt_id === undefined)) { + return reconciliationRequired(); + } + const orphanAttemptRecords = entries.filter(item => item.attempt_id !== undefined + && !seenAttempts.has(item.attempt_id)); + if (orphanAttemptRecords.some(item => !resultAttemptEventTypes.has(item.type))) return reconciliationRequired(); + const orphanIds = new Set(orphanAttemptRecords.map(item => item.attempt_id)); if (orphanIds.size > 0) { if (orphanIds.size !== 1 || !priorChain || priorChain.resumeWindowIndex === undefined) { return reconciliationRequired(); @@ -2352,6 +2364,83 @@ function createRunner({ runtime = defaultRuntime, store = new InMemoryPrototypeS || (closedEvents.length === 0 && (orphanStops.length !== 1 || orphanStops[0].type !== 'contract-mapping-blocked'))) return reconciliationRequired(); } + trailingNoResultAttempt = orphanIds.size > 0; + } else { + // A job with no verified result chain can expose only a consistent, + // single-attempt early-stop or unresolved path. A close marker alone is + // never evidence that a result was persisted. + const noResultLifecycleTypes = new Set(['result-prepared', 'persisting', 'terminal', 'resume-window']); + if (entries.some(item => noResultLifecycleTypes.has(item.type))) return reconciliationRequired(); + const noResultAttemptTypes = new Set(['prepared', 'dispatch-started', 'provider-outcome', + 'contract-mapping-blocked', 'budget-exhausted', 'cancelled-before-dispatch']); + const noResultAttemptRecords = entries.filter(item => item.attempt_id !== undefined); + if (noResultAttemptRecords.some(item => !noResultAttemptTypes.has(item.type))) return reconciliationRequired(); + const attemptIds = new Set(noResultAttemptRecords.map(item => item.attempt_id)); + if (attemptIds.size > 1) return reconciliationRequired(); + const noResultStops = entries.filter(item => ['contract-mapping-blocked', + 'budget-exhausted', 'cancelled-before-dispatch'].includes(item.type)); + if (attemptIds.size === 1) { + const [attemptId] = attemptIds; + const attemptRecords = noResultAttemptRecords.filter(item => item.attempt_id === attemptId); + const preparedAttempts = attemptRecords.filter(item => item.type === 'prepared'); + const dispatches = attemptRecords.filter(item => item.type === 'dispatch-started'); + const outcomes = attemptRecords.filter(item => item.type === 'provider-outcome'); + const stops = attemptRecords.filter(item => ['contract-mapping-blocked', + 'budget-exhausted', 'cancelled-before-dispatch'].includes(item.type)); + const prepared = preparedAttempts[0]; + const resourceId = value => typeof value === 'string' && value.startsWith('urn:uuid:') + && UUID.test(value.slice('urn:uuid:'.length)); + const executionIdValid = value => typeof value === 'string' && value.startsWith('exec-offline-') + && UUID.test(value.slice('exec-offline-'.length)); + if (!resourceId(attemptId) || preparedAttempts.length !== 1 || dispatches.length > 1 + || outcomes.length > 1 || stops.length > 2 + || new Set(stops.map(item => item.type)).size !== stops.length + || !executionIdValid(prepared.execution_id) || prepared.retry_of_attempt_id !== null + || attemptRecords.some(item => item.execution_id !== undefined + && item.execution_id !== prepared.execution_id)) return reconciliationRequired(); + const dispatch = dispatches[0]; + const outcome = outcomes[0]; + if ((dispatch && (dispatch.call_number !== 1 + || entries.indexOf(dispatch) <= entries.indexOf(prepared))) + || (outcome && (!dispatch || outcome.payload_key !== `provider-outcome:${prepared.execution_id}` + || !Number.isSafeInteger(outcome.byte_size) || outcome.byte_size < 0 + || typeof outcome.sha256 !== 'string' || !/^sha256:[0-9a-f]{64}$/.test(outcome.sha256) + || entries.indexOf(outcome) <= entries.indexOf(dispatch)))) return reconciliationRequired(); + if (outcome) { + const outcomeBytes = verifiedBlobs.get(outcome.payload_key); + let providerResult; + try { providerResult = JSON.parse(outcomeBytes.toString('utf8')); } catch { + return reconciliationRequired(); + } + if (!providerResult || !validateExecutionDocument(providerResult).valid + || providerResult.execution_id !== prepared.execution_id + || providerResult.status !== outcome.status) return reconciliationRequired(); + } + const closedEventsForAttempt = entries.filter(item => item.type === 'job-closed'); + const lastAttemptIndex = entries.indexOf(outcome ?? dispatch ?? prepared); + const stopIndices = stops.map(item => entries.indexOf(item)); + if (stopIndices.some(index => index <= lastAttemptIndex) + || (closedEventsForAttempt.length === 1 && (entries.at(-1) !== closedEventsForAttempt[0] + || stopIndices.length === 0 || entries.indexOf(closedEventsForAttempt[0]) <= Math.max(...stopIndices))) + || (stops.some(item => item.type === 'cancelled-before-dispatch') && (dispatch || outcome)) + || (closedEventsForAttempt.length === 1 && !stops.some(item => + item.type === 'budget-exhausted' || item.type === 'cancelled-before-dispatch')) + || (closedEventsForAttempt.length === 0 && stops.some(item => item.type !== 'contract-mapping-blocked'))) { + return reconciliationRequired(); + } + } + if (entries.some(item => ['prepared', 'dispatch-started', 'provider-outcome', + 'contract-mapping-blocked'].includes(item.type) && item.attempt_id === undefined)) { + return reconciliationRequired(); + } + const closedEventsForJob = entries.filter(item => item.type === 'job-closed'); + const closingStops = noResultStops.filter(item => + item.type === 'budget-exhausted' || item.type === 'cancelled-before-dispatch'); + if (closedEventsForJob.length === 1 && (entries.at(-1) !== closedEventsForJob[0] + || closingStops.length === 0 + || entries.indexOf(closedEventsForJob[0]) <= Math.max(...closingStops.map(item => entries.indexOf(item))))) { + return reconciliationRequired(); + } } const closedEvents = entries.filter(item => item.type === 'job-closed'); @@ -2363,9 +2452,12 @@ function createRunner({ runtime = defaultRuntime, store = new InMemoryPrototypeS const dispatched = entries.some(item => item.type === 'dispatch-started'); const outcomeRecorded = entries.some(item => item.type === 'provider-outcome'); const budgetExhausted = entries.some(item => item.type === 'budget-exhausted'); - if (terminal) return recoveryDiagnostic(resultPrepared.length > 0 ? 'terminal' - : blocked ? 'contract-mapping-blocked' - : budgetExhausted ? 'budget-exhausted' : 'closed-without-result'); + if (terminal) return recoveryDiagnostic(trailingNoResultAttempt + ? blocked ? 'contract-mapping-blocked' + : budgetExhausted ? 'budget-exhausted' : 'closed-without-result' + : resultPrepared.length > 0 ? 'terminal' + : blocked ? 'contract-mapping-blocked' + : budgetExhausted ? 'budget-exhausted' : 'closed-without-result'); const resumeClassification = classifyResumeCandidate(jobId, entries, admitted, verifiedBlobs); if (resumeClassification) { From 3fa2c15219b4a2b45f97b9af28da1cbe9a5c2124 Mon Sep 17 00:00:00 2001 From: Andrew Peris Date: Tue, 10 Nov 2026 10:56:05 -0500 Subject: [PATCH 11/33] fix: write canonical O09 event fixtures --- tests/offline-orchestration-prototype/local-file-store.test.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/offline-orchestration-prototype/local-file-store.test.js b/tests/offline-orchestration-prototype/local-file-store.test.js index 87c736b..e967a82 100644 --- a/tests/offline-orchestration-prototype/local-file-store.test.js +++ b/tests/offline-orchestration-prototype/local-file-store.test.js @@ -340,7 +340,7 @@ function localBlobPath(root, key) { } function writeLocalEventLog(root, jobId, entries) { - writeFileSync(localEventPath(root, jobId), `${entries.map(item => canonicalJson(item)).join('\\n')}\\n`); + writeFileSync(localEventPath(root, jobId), `${entries.map(item => canonicalJson(item)).join('\n')}\n`); } function writeLocalBlob(root, key, bytes) { From d03a28e96daa42d285cf0ee9fe292bf2343e0a87 Mon Sep 17 00:00:00 2001 From: Andrew Peris Date: Tue, 10 Nov 2026 10:56:14 -0500 Subject: [PATCH 12/33] fix: write canonical O09 retry fixtures --- tests/offline-orchestration-prototype/resume-candidate.test.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/offline-orchestration-prototype/resume-candidate.test.js b/tests/offline-orchestration-prototype/resume-candidate.test.js index 7ea0d42..d5a7363 100644 --- a/tests/offline-orchestration-prototype/resume-candidate.test.js +++ b/tests/offline-orchestration-prototype/resume-candidate.test.js @@ -891,7 +891,7 @@ test('uncertain new provider-outcome write is not replayed after restart', async function writeResumeEventLog(root, jobId, entries) { const eventPath = join(root, 'events', `${Buffer.from(jobId).toString('base64url')}.jsonl`); - writeFileSync(eventPath, `${entries.map(item => canonicalJson(item)).join('\\n')}\\n`); + writeFileSync(eventPath, `${entries.map(item => canonicalJson(item)).join('\n')}\n`); } function assertResumeReconciliation(inspection, values) { From b1bcba584eefda7251777cd061b905e766e451a9 Mon Sep 17 00:00:00 2001 From: Andrew Peris Date: Tue, 10 Nov 2026 10:56:32 -0500 Subject: [PATCH 13/33] test: verify O09 closed-stop diagnostics --- .../runner.test.js | 72 ++++++++++++++++++- 1 file changed, 71 insertions(+), 1 deletion(-) diff --git a/tests/offline-orchestration-prototype/runner.test.js b/tests/offline-orchestration-prototype/runner.test.js index 52d2fb6..4464206 100644 --- a/tests/offline-orchestration-prototype/runner.test.js +++ b/tests/offline-orchestration-prototype/runner.test.js @@ -2232,7 +2232,15 @@ for (const outcome of ['output-validation', 'cancelled', 'mismatched-success']) if (outcome === 'mismatched-success') assert.equal(lastOutcome.output.content, 'Different synthetic output.'); assert.deepEqual(h.store.readImmutable(`result:${first.result.result_id}`), original); assert.equal(events.filter(e => e.type === 'terminal').length, 1); - assert.equal(h.value.inspectRecovery(first.job_id).status, 'terminal'); + assert.deepEqual(h.value.inspectRecovery(first.job_id), { + status: 'contract-mapping-blocked', + stage: 'mapping', + code: 'CONTRACT_MAPPING_BLOCKED', + read_only: true, + no_writes: true, + no_provider_calls: true, + authority_check_required: false + }); await assert.rejects(() => h.value.retry({ authorizeRetry: true }), e => e.code === 'RETRY_NOT_AVAILABLE'); await assert.rejects(() => h.value.submit({ productionSource }), e => e.code === 'JOB_STORE_LIFETIME_LIMIT'); }); @@ -2271,3 +2279,65 @@ test('a timed-out second attempt preserves uncertainty without closing or fabric assert.equal(events.filter(e => e.type === 'provider-outcome').length, 2); await assert.rejects(() => h.value.retry({ authorizeRetry: true }), e => e.code === 'RETRY_NOT_AVAILABLE'); }); + + +test('closed jobs without a result expose a fixed stop diagnostic and reject orphan attempt links', async () => { + const clock = createRuntime(); + let providerCalls = 0; + const h = runner({ + runtime: clock.runtime, + onMockCall({ phase }) { + if (phase === 'created') clock.set(10_000 + OFFLINE_ORCHESTRATION_LIMITS.jobBudgetMs); + if (phase === 'dispatch-confirmed') providerCalls++; + } + }); + const stopped = await h.value.submit({ productionSource }); + assert.equal(stopped.status, 'budget-exhausted'); + const validInspection = h.value.inspectRecovery(stopped.job_id); + assert.deepEqual(validInspection, { + status: 'closed-without-result', + stage: 'terminal', + code: 'JOB_CLOSED_WITHOUT_RESULT', + read_only: true, + no_writes: true, + no_provider_calls: true, + authority_check_required: false + }); + const originalReadEvents = h.store.readEvents.bind(h.store); + const events = originalReadEvents(stopped.job_id); + const prepared = events.find(item => item.type === 'prepared'); + assert.ok(prepared); + const orphanDispatch = { + ...structuredClone(prepared), + type: 'dispatch-started', + attempt_id: 'urn:uuid:30000000-0000-4000-8000-000000000003', + execution_id: 'exec-offline-30000000-0000-4000-8000-000000000003', + call_number: 1, + private_content: 'NO-RESULT-PRIVATE-CONTENT-SENTINEL', + exception_text: 'NO-RESULT-EXCEPTION-SENTINEL' + }; + const closeIndex = events.findIndex(item => item.type === 'job-closed'); + assert.ok(closeIndex >= 0); + events.splice(closeIndex, 0, orphanDispatch); + h.store.readEvents = jobId => jobId === stopped.job_id ? structuredClone(events) : originalReadEvents(jobId); + const beforeEventCount = h.store.eventCount; + const beforeBlobCount = h.store.blobCount; + const inspection = h.value.inspectRecovery(stopped.job_id); + assert.deepEqual(inspection, { + status: 'reconciliation-required', + stage: 'integrity', + code: 'RECONCILIATION_REQUIRED', + read_only: true, + no_writes: true, + no_provider_calls: true, + authority_check_required: false + }); + const publicValue = JSON.stringify(inspection); + for (const value of [stopped.job_id, prepared.attempt_id, prepared.execution_id, + 'NO-RESULT-PRIVATE-CONTENT-SENTINEL', 'NO-RESULT-EXCEPTION-SENTINEL']) { + assert.equal(publicValue.includes(value), false); + } + assert.equal(h.store.eventCount, beforeEventCount); + assert.equal(h.store.blobCount, beforeBlobCount); + assert.equal(providerCalls, 0); +}); From 38c490be635eb2abecb16e2f3da1252c570d2646 Mon Sep 17 00:00:00 2001 From: Andrew Peris Date: Tue, 10 Nov 2026 10:57:14 -0500 Subject: [PATCH 14/33] docs: clarify O09 reconciliation limits --- docs/offline-orchestration-prototype.md | 47 ++++++++++++++++--------- 1 file changed, 30 insertions(+), 17 deletions(-) diff --git a/docs/offline-orchestration-prototype.md b/docs/offline-orchestration-prototype.md index fb479f1..79ee9ad 100644 --- a/docs/offline-orchestration-prototype.md +++ b/docs/offline-orchestration-prototype.md @@ -361,27 +361,40 @@ does not close Studio issue #110 or claim broader acceptance. ## O09 result-link inspection slice (2026-11-10) -The opt-in local-file-store inspection now validates the canonical result -lifecycle links for each result-bearing attempt before classifying recovery. -For each attempt, the unique `prepared`, `dispatch-started`, `provider-outcome`, -`result-prepared`, `persisting`, and `terminal` events must agree on job, -attempt, execution, result ID, result status, byte size, and digest where -recorded, and occur in order. The provider outcome payload and canonical result -bytes must match their lifecycle references; the result must link to the -admitted synthetic production, and every output artifact URI, byte size, and -digest must resolve to matching local bytes. Missing, duplicate, malformed, or -contradictory links fail closed as `reconciliation-required`. Inspection +The opt-in local-file-store inspection validates the canonical result lifecycle +links for every result-bearing attempt before classifying recovery. Each chain +must contain one matching `prepared`, `dispatch-started`, `provider-outcome`, +`result-prepared`, `persisting`, and `terminal` event. Their job, attempt, +execution, result ID, status, byte size, and digest references must agree, and +the events must occur in order. A retry's prepared event must follow the prior +attempt's terminal and its unique resume-window; the window must refer to the +prior terminal result and match its recorded retry delay and deadline. Unmatched +or interleaved attempt records, missing or duplicate windows, and contradictory +links fail closed. + +The result and provider-outcome bytes are canonical and match their lifecycle +references. The result must link to the admitted synthetic production. Version +1.0.0 results also pass output compatibility checks against that production; +version 1.1.0 is accepted only for the pinned no-output eligible rate-limit +mapping. Every output artifact URI, byte size, and digest must resolve to the +matching local bytes. When no result chain exists, inspection validates the +single attempt's lifecycle and explicit stop markers before reporting a +closed-without-result state. A final resultless retry can follow a verified +chain only when its stop is explicit and consistently linked. Inspection performs no writes or provider calls. -The public `inspectRecovery()` projection contains only fixed status, stage, -and code values with boolean fields. It never returns job, attempt, execution, -result, or artifact identifiers; lifecycle event names; local paths; hashes; -protected content; exception text; or fingerprints. Result, outcome, and -artifact bytes remain in the caller-owned private local store. +The public `inspectRecovery()` projection contains only fixed allowlisted +status, stage, and code values with boolean fields. It never returns job, +attempt, execution, result, or artifact identifiers; lifecycle event names; +local paths; hashes; protected content; exception text; or fingerprints. +Result, outcome, and artifact bytes remain in the caller-owned private local +store. Coverage is limited to the pinned synthetic no-context local path, including -successful and no-output rate-limit results, reopened-store inspection, and a -canonical event-log duplicate-link corruption case. This does not authenticate +successful and no-output rate-limit results, reopened inspection, retry and +reopen, and corruption cases for orphan/interleaved attempts, malformed +production links, inconsistent result outcomes, resume-window links, and +schema-valid output compatibility tampering. This does not authenticate same-account edits to the local store, establish power-loss durability or support for other filesystems, add providers or infrastructure, use production data, or close Studio issue #110. From f03f4f23bfb92bbbd651da4be0dad257cd40928d Mon Sep 17 00:00:00 2001 From: Andrew Peris Date: Tue, 10 Nov 2026 10:58:48 -0500 Subject: [PATCH 15/33] test: cover malformed O09 production links --- .../local-file-store.test.js | 59 ++++++++++--------- 1 file changed, 32 insertions(+), 27 deletions(-) diff --git a/tests/offline-orchestration-prototype/local-file-store.test.js b/tests/offline-orchestration-prototype/local-file-store.test.js index e967a82..54c5326 100644 --- a/tests/offline-orchestration-prototype/local-file-store.test.js +++ b/tests/offline-orchestration-prototype/local-file-store.test.js @@ -402,34 +402,39 @@ test('reopened inspection rejects orphan attempt lifecycle records without expos } }); -test('reopened inspection reconciles a malformed prepared production before canonicalization', async t => { - const root = temporaryDirectory(); - t.after(() => rmSync(root, { recursive: true, force: true })); - const store = new LocalFilePrototypeStore(root); - let calls = 0; - const completed = await prototype(store, () => { calls++; }).submit({ productionSource }); - const entries = store.readEvents(completed.job_id); - const prepared = entries.find(item => item.type === 'prepared'); - assert.ok(prepared); - delete prepared.production; - prepared.private_content = 'MALFORMED-PRIVATE-CONTENT-SENTINEL'; - prepared.exception_text = 'MALFORMED-EXCEPTION-SENTINEL'; - writeLocalEventLog(root, completed.job_id, entries); +test('reopened inspection reconciles absent and non-object prepared production before canonicalization', async t => { + for (const corruption of ['absent', 'non-object']) { + await t.test(corruption, async t => { + const root = temporaryDirectory(); + t.after(() => rmSync(root, { recursive: true, force: true })); + const store = new LocalFilePrototypeStore(root); + let calls = 0; + const completed = await prototype(store, () => { calls++; }).submit({ productionSource }); + const entries = store.readEvents(completed.job_id); + const prepared = entries.find(item => item.type === 'prepared'); + assert.ok(prepared); + if (corruption === 'absent') delete prepared.production; + else prepared.production = 'MALFORMED-PRODUCTION-SENTINEL'; + prepared.private_content = 'MALFORMED-PRIVATE-CONTENT-SENTINEL'; + prepared.exception_text = 'MALFORMED-EXCEPTION-SENTINEL'; + writeLocalEventLog(root, completed.job_id, entries); - const reopened = new LocalFilePrototypeStore(root); - let restartedCalls = 0; - const restarted = prototype(reopened, () => { restartedCalls++; }); - const beforeEvents = structuredClone(reopened.readEvents(completed.job_id)); - const beforeBlobs = reopened.blobCount; - assertSafeReconciliation(restarted.inspectRecovery(completed.job_id), [ - root, completed.job_id, completed.attempt_id, completed.execution_id, - completed.result.result_id, 'MALFORMED-PRIVATE-CONTENT-SENTINEL', - 'MALFORMED-EXCEPTION-SENTINEL' - ]); - assert.deepEqual(reopened.readEvents(completed.job_id), beforeEvents); - assert.equal(reopened.blobCount, beforeBlobs); - assert.equal(restartedCalls, 0); - assert.equal(calls, 1); + const reopened = new LocalFilePrototypeStore(root); + let restartedCalls = 0; + const restarted = prototype(reopened, () => { restartedCalls++; }); + const beforeEvents = structuredClone(reopened.readEvents(completed.job_id)); + const beforeBlobs = reopened.blobCount; + assertSafeReconciliation(restarted.inspectRecovery(completed.job_id), [ + root, completed.job_id, completed.attempt_id, completed.execution_id, + completed.result.result_id, 'MALFORMED-PRODUCTION-SENTINEL', + 'MALFORMED-PRIVATE-CONTENT-SENTINEL', 'MALFORMED-EXCEPTION-SENTINEL' + ]); + assert.deepEqual(reopened.readEvents(completed.job_id), beforeEvents); + assert.equal(reopened.blobCount, beforeBlobs); + assert.equal(restartedCalls, 0); + assert.equal(calls, 1); + }); + } }); test('reopened inspection rejects a 1.1.0 no-output result paired with a success outcome', async t => { From 4b4ff781acd286a9556113cdc272b86776ed83b3 Mon Sep 17 00:00:00 2001 From: Andrew Peris Date: Tue, 10 Nov 2026 10:59:27 -0500 Subject: [PATCH 16/33] test: cover reopened no-result stop links --- .../local-file-store.test.js | 49 +++++++++++++++++++ 1 file changed, 49 insertions(+) diff --git a/tests/offline-orchestration-prototype/local-file-store.test.js b/tests/offline-orchestration-prototype/local-file-store.test.js index 54c5326..b3311b7 100644 --- a/tests/offline-orchestration-prototype/local-file-store.test.js +++ b/tests/offline-orchestration-prototype/local-file-store.test.js @@ -519,3 +519,52 @@ test('reopened v1.0 result inspection checks production-output compatibility aft assert.equal(restartedCalls, 0); assert.equal(calls, 1); }); + + +test('reopened no-result close requires its linked stop and rejects orphan dispatch records', async t => { + const root = temporaryDirectory(); + t.after(() => rmSync(root, { recursive: true, force: true })); + const store = new LocalFilePrototypeStore(root); + let calls = 0; + const controller = new AbortController(); + controller.abort(); + const stopped = await prototype(store, () => { calls++; }).submit({ + productionSource, + signal: controller.signal + }); + assert.equal(stopped.status, 'cancelled-before-dispatch'); + assert.equal(store.readEvents(stopped.job_id).some(item => item.type === 'terminal'), false); + const validInspection = prototype(store).inspectRecovery(stopped.job_id); + assert.equal(validInspection.status, 'closed-without-result'); + assert.equal(validInspection.code, 'JOB_CLOSED_WITHOUT_RESULT'); + const entries = store.readEvents(stopped.job_id); + const prepared = entries.find(item => item.type === 'prepared'); + assert.ok(prepared); + const orphanDispatch = { + ...structuredClone(prepared), + type: 'dispatch-started', + attempt_id: 'urn:uuid:30000000-0000-4000-8000-000000000003', + execution_id: 'exec-offline-30000000-0000-4000-8000-000000000003', + call_number: 1, + private_content: 'LOCAL-NO-RESULT-PRIVATE-SENTINEL', + exception_text: 'LOCAL-NO-RESULT-EXCEPTION-SENTINEL' + }; + const closeIndex = entries.findIndex(item => item.type === 'job-closed'); + assert.ok(closeIndex >= 0); + entries.splice(closeIndex, 0, orphanDispatch); + writeLocalEventLog(root, stopped.job_id, entries); + + const reopened = new LocalFilePrototypeStore(root); + let restartedCalls = 0; + const restarted = prototype(reopened, () => { restartedCalls++; }); + const beforeEvents = structuredClone(reopened.readEvents(stopped.job_id)); + const beforeBlobs = reopened.blobCount; + assertSafeReconciliation(restarted.inspectRecovery(stopped.job_id), [ + root, stopped.job_id, stopped.attempt_id, stopped.execution_id, + 'LOCAL-NO-RESULT-PRIVATE-SENTINEL', 'LOCAL-NO-RESULT-EXCEPTION-SENTINEL' + ]); + assert.deepEqual(reopened.readEvents(stopped.job_id), beforeEvents); + assert.equal(reopened.blobCount, beforeBlobs); + assert.equal(restartedCalls, 0); + assert.equal(calls, 0); +}); From 9fab76a8a8173bcc1172d511bb2b4e298f9f7a4e Mon Sep 17 00:00:00 2001 From: Andrew Peris Date: Tue, 10 Nov 2026 11:02:01 -0500 Subject: [PATCH 17/33] fix: verify closed stop and retry window links --- src/offline-orchestration-prototype/runner.js | 34 ++++++++++++++++++- 1 file changed, 33 insertions(+), 1 deletion(-) diff --git a/src/offline-orchestration-prototype/runner.js b/src/offline-orchestration-prototype/runner.js index b3c1425..5e938d4 100644 --- a/src/offline-orchestration-prototype/runner.js +++ b/src/offline-orchestration-prototype/runner.js @@ -2278,6 +2278,8 @@ function createRunner({ runtime = defaultRuntime, store = new InMemoryPrototypeS || timeRecord.context_enabled !== false || !Number.isSafeInteger(timeRecord.started_at_ms) || !Number.isSafeInteger(timeRecord.deadline_at_ms) + || timeRecord.deadline_at_ms !== checkedAdd(timeRecord.started_at_ms, + OFFLINE_ORCHESTRATION_LIMITS.jobBudgetMs) || resumeWindow.attempt_id !== attemptId || resumeWindow.execution_id !== executionId || resumeWindow.terminal_result_id !== resultId || result.status !== 'failed' || result.outputs.length !== 0 @@ -2303,6 +2305,10 @@ function createRunner({ runtime = defaultRuntime, store = new InMemoryPrototypeS if (entries.some(item => resultAttemptEventTypes.has(item.type) && item.attempt_id === undefined)) { return reconciliationRequired(); } + const allowedAttemptIdTypes = new Set([...resultAttemptEventTypes, 'closed-without-retry']); + if (entries.some(item => item.attempt_id !== undefined && !allowedAttemptIdTypes.has(item.type))) { + return reconciliationRequired(); + } const orphanAttemptRecords = entries.filter(item => item.attempt_id !== undefined && !seenAttempts.has(item.attempt_id)); if (orphanAttemptRecords.some(item => !resultAttemptEventTypes.has(item.type))) return reconciliationRequired(); @@ -2364,6 +2370,16 @@ function createRunner({ runtime = defaultRuntime, store = new InMemoryPrototypeS || (closedEvents.length === 0 && (orphanStops.length !== 1 || orphanStops[0].type !== 'contract-mapping-blocked'))) return reconciliationRequired(); } + const closedWithoutRetry = entries.filter(item => item.type === 'closed-without-retry'); + const jobClosedForRetry = entries.find(item => item.type === 'job-closed'); + if (closedWithoutRetry.length > 1 || (closedWithoutRetry.length === 1 + && (!priorChain || priorChain.resumeWindowIndex === undefined || !jobClosedForRetry + || closedWithoutRetry[0].attempt_id !== priorChain.attemptId + || closedWithoutRetry[0].result_id !== priorChain.resultId + || entries.indexOf(closedWithoutRetry[0]) <= priorChain.resumeWindowIndex + || (jobClosedForRetry && entries.indexOf(closedWithoutRetry[0]) >= entries.indexOf(jobClosedForRetry))))) { + return reconciliationRequired(); + } trailingNoResultAttempt = orphanIds.size > 0; } else { // A job with no verified result chain can expose only a consistent, @@ -2379,6 +2395,9 @@ function createRunner({ runtime = defaultRuntime, store = new InMemoryPrototypeS if (attemptIds.size > 1) return reconciliationRequired(); const noResultStops = entries.filter(item => ['contract-mapping-blocked', 'budget-exhausted', 'cancelled-before-dispatch'].includes(item.type)); + const noResultStopCounts = new Map(); + for (const item of noResultStops) noResultStopCounts.set(item.type, (noResultStopCounts.get(item.type) ?? 0) + 1); + if ([...noResultStopCounts.values()].some(count => count > 1)) return reconciliationRequired(); if (attemptIds.size === 1) { const [attemptId] = attemptIds; const attemptRecords = noResultAttemptRecords.filter(item => item.attempt_id === attemptId); @@ -2397,7 +2416,20 @@ function createRunner({ runtime = defaultRuntime, store = new InMemoryPrototypeS || new Set(stops.map(item => item.type)).size !== stops.length || !executionIdValid(prepared.execution_id) || prepared.retry_of_attempt_id !== null || attemptRecords.some(item => item.execution_id !== undefined - && item.execution_id !== prepared.execution_id)) return reconciliationRequired(); + && item.execution_id !== prepared.execution_id) + || !admitted.production || typeof admitted.production !== 'object' || Array.isArray(admitted.production) + || !prepared.production || typeof prepared.production !== 'object' || Array.isArray(prepared.production)) { + return reconciliationRequired(); + } + const productionBytes = verifiedBlobs.get(admitted.input_key); + try { + const production = readProduction(productionBytes.toString('utf8')); + if (!productionBytes.equals(Buffer.from(production.canonical, 'utf8')) + || canonicalJson(admitted.production) !== canonicalJson(production.reference) + || canonicalJson(prepared.production) !== canonicalJson(admitted.production)) { + return reconciliationRequired(); + } + } catch { return reconciliationRequired(); } const dispatch = dispatches[0]; const outcome = outcomes[0]; if ((dispatch && (dispatch.call_number !== 1 From b2a1f79aacae6bbab520694662937ba9449165fa Mon Sep 17 00:00:00 2001 From: Andrew Peris Date: Tue, 10 Nov 2026 11:06:59 -0500 Subject: [PATCH 18/33] fix: preserve canonical in-process retry chains --- src/offline-orchestration-prototype/runner.js | 60 +++++++++++-------- 1 file changed, 34 insertions(+), 26 deletions(-) diff --git a/src/offline-orchestration-prototype/runner.js b/src/offline-orchestration-prototype/runner.js index 5e938d4..a33770f 100644 --- a/src/offline-orchestration-prototype/runner.js +++ b/src/offline-orchestration-prototype/runner.js @@ -2156,28 +2156,34 @@ function createRunner({ runtime = defaultRuntime, store = new InMemoryPrototypeS const [terminal] = terminalMatches; if (priorChain) { const priorWindows = matching('resume-window', priorChain.attemptId); - if (priorWindows.length !== 1) return reconciliationRequired(); - const priorWindow = priorWindows[0]; - const timeRecord = admitted.resume_time; - const windowKeys = ['authority_id', 'context_enabled', 'deadline_at_ms', 'domain_id', 'epoch_id', 'started_at_ms']; - const validTimeRecord = timeRecord && typeof timeRecord === 'object' && !Array.isArray(timeRecord) - && Object.keys(timeRecord).sort().join('|') === windowKeys.join('|') - && timeRecord.authority_id === SYNTHETIC_RESUME_TIME_AUTHORITY_ID && typeof timeRecord.domain_id === 'string' - && typeof timeRecord.epoch_id === 'string' && timeRecord.context_enabled === false - && Number.isSafeInteger(timeRecord.started_at_ms) && Number.isSafeInteger(timeRecord.deadline_at_ms) - && timeRecord.deadline_at_ms === checkedAdd(timeRecord.started_at_ms, OFFLINE_ORCHESTRATION_LIMITS.jobBudgetMs); - const priorWindowIndex = entries.indexOf(priorWindow); - if (!validTimeRecord || priorWindow.attempt_id !== priorChain.attemptId - || priorWindow.execution_id !== priorChain.executionId - || priorWindow.terminal_result_id !== priorChain.resultId - || !Number.isSafeInteger(priorWindow.checked_at_ms) - || priorWindow.checked_at_ms < timeRecord.started_at_ms - || priorWindow.checked_at_ms >= timeRecord.deadline_at_ms - || priorWindow.retry_not_before_at_ms !== checkedAdd(priorWindow.checked_at_ms, - priorChain.providerResult.error.retry_after_ms) - || priorWindow.deadline_at_ms !== timeRecord.deadline_at_ms - || priorWindowIndex <= priorChain.terminalIndex - || entries.indexOf(prepared) <= priorWindowIndex) return reconciliationRequired(); + if (priorWindows.length > 1) return reconciliationRequired(); + if (admitted.resume_time !== undefined) { + if (priorWindows.length !== 1) return reconciliationRequired(); + const priorWindow = priorWindows[0]; + const timeRecord = admitted.resume_time; + const windowKeys = ['authority_id', 'context_enabled', 'deadline_at_ms', 'domain_id', 'epoch_id', 'started_at_ms']; + const validTimeRecord = timeRecord && typeof timeRecord === 'object' && !Array.isArray(timeRecord) + && Object.keys(timeRecord).sort().join('|') === windowKeys.join('|') + && timeRecord.authority_id === SYNTHETIC_RESUME_TIME_AUTHORITY_ID + && typeof timeRecord.domain_id === 'string' && typeof timeRecord.epoch_id === 'string' + && timeRecord.context_enabled === false + && Number.isSafeInteger(timeRecord.started_at_ms) && Number.isSafeInteger(timeRecord.deadline_at_ms) + && timeRecord.deadline_at_ms === checkedAdd(timeRecord.started_at_ms, OFFLINE_ORCHESTRATION_LIMITS.jobBudgetMs); + const priorWindowIndex = entries.indexOf(priorWindow); + if (!validTimeRecord || priorWindow.attempt_id !== priorChain.attemptId + || priorWindow.execution_id !== priorChain.executionId + || priorWindow.terminal_result_id !== priorChain.resultId + || !Number.isSafeInteger(priorWindow.checked_at_ms) + || priorWindow.checked_at_ms < timeRecord.started_at_ms + || priorWindow.checked_at_ms >= timeRecord.deadline_at_ms + || priorWindow.retry_not_before_at_ms !== checkedAdd(priorWindow.checked_at_ms, + priorChain.providerResult.error.retry_after_ms) + || priorWindow.deadline_at_ms !== timeRecord.deadline_at_ms + || priorWindowIndex <= priorChain.terminalIndex + || entries.indexOf(prepared) <= priorWindowIndex) return reconciliationRequired(); + } else if (priorWindows.length !== 0 || entries.indexOf(prepared) <= priorChain.terminalIndex) { + return reconciliationRequired(); + } } else if (prepared.retry_of_attempt_id !== null) return reconciliationRequired(); const ordered = [prepared, dispatch, outcome, preparedResult, persistingRecord, terminal] .map(item => entries.indexOf(item)); @@ -2314,7 +2320,8 @@ function createRunner({ runtime = defaultRuntime, store = new InMemoryPrototypeS if (orphanAttemptRecords.some(item => !resultAttemptEventTypes.has(item.type))) return reconciliationRequired(); const orphanIds = new Set(orphanAttemptRecords.map(item => item.attempt_id)); if (orphanIds.size > 0) { - if (orphanIds.size !== 1 || !priorChain || priorChain.resumeWindowIndex === undefined) { + if (orphanIds.size !== 1 || !priorChain + || (admitted.resume_time !== undefined && priorChain.resumeWindowIndex === undefined)) { return reconciliationRequired(); } const [orphanId] = orphanIds; @@ -2334,7 +2341,7 @@ function createRunner({ runtime = defaultRuntime, store = new InMemoryPrototypeS || orphanStops.length < 1 || [...stopCounts.values()].some(count => count > 1) || orphanResults.length !== 0 || orphanPrepared[0].retry_of_attempt_id !== priorChain.attemptId || !isResourceId(orphanId) || !isExecutionId(orphanPrepared[0].execution_id) - || entries.indexOf(orphanPrepared[0]) <= priorChain.resumeWindowIndex) { + || entries.indexOf(orphanPrepared[0]) <= (priorChain.resumeWindowIndex ?? priorChain.terminalIndex)) { return reconciliationRequired(); } const orphanExecutionId = orphanPrepared[0].execution_id; @@ -2373,10 +2380,11 @@ function createRunner({ runtime = defaultRuntime, store = new InMemoryPrototypeS const closedWithoutRetry = entries.filter(item => item.type === 'closed-without-retry'); const jobClosedForRetry = entries.find(item => item.type === 'job-closed'); if (closedWithoutRetry.length > 1 || (closedWithoutRetry.length === 1 - && (!priorChain || priorChain.resumeWindowIndex === undefined || !jobClosedForRetry + && (!priorChain || (admitted.resume_time !== undefined && priorChain.resumeWindowIndex === undefined) + || !jobClosedForRetry || closedWithoutRetry[0].attempt_id !== priorChain.attemptId || closedWithoutRetry[0].result_id !== priorChain.resultId - || entries.indexOf(closedWithoutRetry[0]) <= priorChain.resumeWindowIndex + || entries.indexOf(closedWithoutRetry[0]) <= (priorChain.resumeWindowIndex ?? priorChain.terminalIndex) || (jobClosedForRetry && entries.indexOf(closedWithoutRetry[0]) >= entries.indexOf(jobClosedForRetry))))) { return reconciliationRequired(); } From 268628cda999d8c447751760ecae750fb68a2b9c Mon Sep 17 00:00:00 2001 From: Andrew Peris Date: Tue, 10 Nov 2026 11:07:13 -0500 Subject: [PATCH 19/33] test: clone local recovery fixtures before mutation --- .../local-file-store.test.js | 29 +++++++++++-------- 1 file changed, 17 insertions(+), 12 deletions(-) diff --git a/tests/offline-orchestration-prototype/local-file-store.test.js b/tests/offline-orchestration-prototype/local-file-store.test.js index b3311b7..789d317 100644 --- a/tests/offline-orchestration-prototype/local-file-store.test.js +++ b/tests/offline-orchestration-prototype/local-file-store.test.js @@ -368,8 +368,8 @@ test('reopened inspection rejects orphan attempt lifecycle records without expos t.after(() => rmSync(root, { recursive: true, force: true })); const store = new LocalFilePrototypeStore(root); let calls = 0; - const completed = await prototype(store, () => { calls++; }).submit({ productionSource }); - const entries = store.readEvents(completed.job_id); + const completed = await prototype(store, ({ phase }) => { if (phase === 'dispatch-confirmed') calls++; }).submit({ productionSource }); + const entries = structuredClone(store.readEvents(completed.job_id)); const source = entries.find(item => item.type === orphanType); assert.ok(source); const orphan = structuredClone(source); @@ -409,8 +409,8 @@ test('reopened inspection reconciles absent and non-object prepared production b t.after(() => rmSync(root, { recursive: true, force: true })); const store = new LocalFilePrototypeStore(root); let calls = 0; - const completed = await prototype(store, () => { calls++; }).submit({ productionSource }); - const entries = store.readEvents(completed.job_id); + const completed = await prototype(store, ({ phase }) => { if (phase === 'dispatch-confirmed') calls++; }).submit({ productionSource }); + const entries = structuredClone(store.readEvents(completed.job_id)); const prepared = entries.find(item => item.type === 'prepared'); assert.ok(prepared); if (corruption === 'absent') delete prepared.production; @@ -444,7 +444,7 @@ test('reopened inspection rejects a 1.1.0 no-output result paired with a success t.after(() => rmSync(successRoot, { recursive: true, force: true })); const failedStore = new LocalFilePrototypeStore(root); let calls = 0; - const failed = await prototype(failedStore, () => { calls++; }).submit({ + const failed = await prototype(failedStore, ({ phase }) => { if (phase === 'dispatch-confirmed') calls++; }).submit({ productionSource, noOutputResultVersion: '1.1.0', mockOutcome: { kind: 'rate-limit', retry_after_ms: 10 } @@ -457,7 +457,7 @@ test('reopened inspection rejects a 1.1.0 no-output result paired with a success successOutcome.execution_id = failed.execution_id; if (Object.hasOwn(successOutcome, 'idempotency_key')) successOutcome.idempotency_key = `idem-${failed.execution_id}`; const bytes = Buffer.from(canonicalJson(successOutcome), 'utf8'); - const entries = failedStore.readEvents(failed.job_id); + const entries = structuredClone(failedStore.readEvents(failed.job_id)); const outcome = entries.find(item => item.type === 'provider-outcome'); outcome.status = 'succeeded'; outcome.byte_size = bytes.byteLength; @@ -487,14 +487,16 @@ test('reopened v1.0 result inspection checks production-output compatibility aft t.after(() => rmSync(root, { recursive: true, force: true })); const store = new LocalFilePrototypeStore(root); let calls = 0; - const completed = await prototype(store, () => { calls++; }).submit({ productionSource }); + const completed = await prototype(store, ({ phase }) => { if (phase === 'dispatch-confirmed') calls++; }).submit({ productionSource }); const resultKey = `result:${completed.result.result_id}`; const result = JSON.parse(store.readImmutable(resultKey).toString('utf8')); assert.equal(result.spec_version, '1.0.0'); result.outputs[0].rendition_id = 'tampered-rendition'; - result.private_content = 'COMPATIBILITY-PRIVATE-CONTENT-SENTINEL'; const bytes = Buffer.from(canonicalJson(result), 'utf8'); - const entries = store.readEvents(completed.job_id); + const entries = structuredClone(store.readEvents(completed.job_id)); + const terminal = entries.find(item => item.type === 'terminal'); + assert.ok(terminal); + terminal.private_content = 'COMPATIBILITY-PRIVATE-CONTENT-SENTINEL'; for (const item of entries) { if (['result-prepared', 'persisting', 'terminal'].includes(item.type)) { item.result_byte_size = bytes.byteLength; @@ -527,8 +529,11 @@ test('reopened no-result close requires its linked stop and rejects orphan dispa const store = new LocalFilePrototypeStore(root); let calls = 0; const controller = new AbortController(); - controller.abort(); - const stopped = await prototype(store, () => { calls++; }).submit({ + const value = prototype(store, ({ phase }) => { + if (phase === 'created') controller.abort(); + if (phase === 'dispatch-confirmed') calls++; + }); + const stopped = await value.submit({ productionSource, signal: controller.signal }); @@ -537,7 +542,7 @@ test('reopened no-result close requires its linked stop and rejects orphan dispa const validInspection = prototype(store).inspectRecovery(stopped.job_id); assert.equal(validInspection.status, 'closed-without-result'); assert.equal(validInspection.code, 'JOB_CLOSED_WITHOUT_RESULT'); - const entries = store.readEvents(stopped.job_id); + const entries = structuredClone(store.readEvents(stopped.job_id)); const prepared = entries.find(item => item.type === 'prepared'); assert.ok(prepared); const orphanDispatch = { From 94f65391157bf86a1aba8a787b03b2765d11f1c4 Mon Sep 17 00:00:00 2001 From: Andrew Peris Date: Tue, 10 Nov 2026 11:07:21 -0500 Subject: [PATCH 20/33] test: clone retry logs before corruption --- .../offline-orchestration-prototype/resume-candidate.test.js | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/tests/offline-orchestration-prototype/resume-candidate.test.js b/tests/offline-orchestration-prototype/resume-candidate.test.js index d5a7363..5db33cd 100644 --- a/tests/offline-orchestration-prototype/resume-candidate.test.js +++ b/tests/offline-orchestration-prototype/resume-candidate.test.js @@ -928,7 +928,7 @@ test('completed retry inspection rejects a second prepared/dispatch before the f if (phase === 'dispatch-confirmed') resumedCalls++; }); assert.equal(completed.runner.inspectRecovery(seeded.jobId).status, 'terminal'); - const entries = completed.reopened.readEvents(seeded.jobId); + const entries = structuredClone(completed.reopened.readEvents(seeded.jobId)); const prepared = entries.filter(item => item.type === 'prepared'); const dispatches = entries.filter(item => item.type === 'dispatch-started'); const firstTerminal = entries.find(item => item.type === 'terminal' && item.attempt_id === prepared[0].attempt_id); @@ -968,7 +968,7 @@ test('completed retry inspection rejects mismatched and duplicate resume-window const completed = await completeSeededRetry(seeded, ({ phase }) => { if (phase === 'dispatch-confirmed') resumedCalls++; }); - const entries = completed.reopened.readEvents(seeded.jobId); + const entries = structuredClone(completed.reopened.readEvents(seeded.jobId)); const firstPrepared = entries.find(item => item.type === 'prepared'); const firstWindow = entries.find(item => item.type === 'resume-window'); const secondPrepared = entries.find(item => item.type === 'prepared' From 190a31b489a32d02cac15b6c8f4fb3ea08778bef Mon Sep 17 00:00:00 2001 From: Andrew Peris Date: Tue, 10 Nov 2026 11:07:33 -0500 Subject: [PATCH 21/33] test: assert safe resultless recovery statuses --- tests/offline-orchestration-prototype/runner.test.js | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/tests/offline-orchestration-prototype/runner.test.js b/tests/offline-orchestration-prototype/runner.test.js index 4464206..5148dc7 100644 --- a/tests/offline-orchestration-prototype/runner.test.js +++ b/tests/offline-orchestration-prototype/runner.test.js @@ -2261,8 +2261,8 @@ for (const fault of ['outcome-readback', 'mapping-append', 'close-append', 'ambi assert.equal(second.job_closed, undefined); const inspection = h.value.inspectRecovery(first.job_id); assert.equal(inspection.read_only, true); - assert.equal(inspection.status, fault === 'ambiguous-close' ? 'reconciliation-required' - : fault === 'close-append' ? 'contract-mapping-blocked' : 'read-only-inspection-required'); + assert.equal(inspection.status, fault === 'close-append' + ? 'contract-mapping-blocked' : 'reconciliation-required'); if (!unknownEvents) assert.equal(store.readEvents(first.job_id).some(e => e.type === 'job-closed'), false); await assert.rejects(() => h.value.retry({ authorizeRetry: true }), e => e.code === 'RETRY_NOT_AVAILABLE'); }); @@ -2295,16 +2295,16 @@ test('closed jobs without a result expose a fixed stop diagnostic and reject orp assert.equal(stopped.status, 'budget-exhausted'); const validInspection = h.value.inspectRecovery(stopped.job_id); assert.deepEqual(validInspection, { - status: 'closed-without-result', - stage: 'terminal', - code: 'JOB_CLOSED_WITHOUT_RESULT', + status: 'budget-exhausted', + stage: 'limits', + code: 'BUDGET_EXHAUSTED', read_only: true, no_writes: true, no_provider_calls: true, authority_check_required: false }); const originalReadEvents = h.store.readEvents.bind(h.store); - const events = originalReadEvents(stopped.job_id); + const events = structuredClone(originalReadEvents(stopped.job_id)); const prepared = events.find(item => item.type === 'prepared'); assert.ok(prepared); const orphanDispatch = { From d2a3f717680bc20dccef0f67ac2a1a71c5125ea3 Mon Sep 17 00:00:00 2001 From: Andrew Peris Date: Tue, 10 Nov 2026 11:21:13 -0500 Subject: [PATCH 22/33] Validate contradictory and job-scoped retry stops --- src/offline-orchestration-prototype/runner.js | 46 +++++++++++++++++-- 1 file changed, 43 insertions(+), 3 deletions(-) diff --git a/src/offline-orchestration-prototype/runner.js b/src/offline-orchestration-prototype/runner.js index a33770f..8233254 100644 --- a/src/offline-orchestration-prototype/runner.js +++ b/src/offline-orchestration-prototype/runner.js @@ -2154,6 +2154,22 @@ function createRunner({ runtime = defaultRuntime, store = new InMemoryPrototypeS const [outcome] = outcomes; const [persistingRecord] = persistingMatches; const [terminal] = terminalMatches; + const attemptCancellationStops = matching('cancelled-before-dispatch', attemptId); + const attemptMappingStops = matching('contract-mapping-blocked', attemptId); + const attemptBudgetStops = matching('budget-exhausted', attemptId); + if (attemptCancellationStops.length !== 0 || attemptMappingStops.length !== 0 + || attemptBudgetStops.length > 1) return reconciliationRequired(); + if (attemptBudgetStops.length === 1) { + const [stop] = attemptBudgetStops; + const stopKeys = ['attempt_id', 'deadline_monotonic_ms', 'execution_id', 'job_id', 'reason', 'type']; + if (Object.keys(stop).sort().join('|') !== stopKeys.join('|') + || stop.job_id !== jobId || stop.reason !== 'time' + || stop.execution_id !== executionId + || !Number.isSafeInteger(admitted.deadline_monotonic_ms) + || stop.deadline_monotonic_ms !== admitted.deadline_monotonic_ms + || entries.indexOf(stop) <= entries.indexOf(outcome) + || entries.indexOf(stop) >= entries.indexOf(preparedResult)) return reconciliationRequired(); + } if (priorChain) { const priorWindows = matching('resume-window', priorChain.attemptId); if (priorWindows.length > 1) return reconciliationRequired(); @@ -2308,7 +2324,11 @@ function createRunner({ runtime = defaultRuntime, store = new InMemoryPrototypeS const resultAttemptEventTypes = new Set(['prepared', 'dispatch-started', 'provider-outcome', 'result-prepared', 'persisting', 'terminal', 'resume-window', 'contract-mapping-blocked', 'budget-exhausted', 'cancelled-before-dispatch']); - if (entries.some(item => resultAttemptEventTypes.has(item.type) && item.attempt_id === undefined)) { + const jobScopedBudgetStops = entries.filter(item => item.type === 'budget-exhausted' + && item.attempt_id === undefined); + if (jobScopedBudgetStops.length > 1 + || entries.some(item => resultAttemptEventTypes.has(item.type) && item.attempt_id === undefined + && item.type !== 'budget-exhausted')) { return reconciliationRequired(); } const allowedAttemptIdTypes = new Set([...resultAttemptEventTypes, 'closed-without-retry']); @@ -2379,6 +2399,25 @@ function createRunner({ runtime = defaultRuntime, store = new InMemoryPrototypeS } const closedWithoutRetry = entries.filter(item => item.type === 'closed-without-retry'); const jobClosedForRetry = entries.find(item => item.type === 'job-closed'); + if (jobScopedBudgetStops.length === 1) { + const [stop] = jobScopedBudgetStops; + const stopKeys = ['deadline_monotonic_ms', 'job_id', 'reason', 'type']; + const afterResultIndex = priorChain?.resumeWindowIndex ?? priorChain?.terminalIndex; + if (!priorChain || priorChain.result.status !== 'failed' || priorChain.result.outputs.length !== 0 + || !eligibleRateLimit(priorChain.providerResult) + || Object.keys(stop).sort().join('|') !== stopKeys.join('|') + || stop.job_id !== jobId || stop.type !== 'budget-exhausted' + || !['time', 'attempts'].includes(stop.reason) + || !Number.isSafeInteger(admitted.deadline_monotonic_ms) + || stop.deadline_monotonic_ms !== admitted.deadline_monotonic_ms + || (stop.reason === 'attempts' + && resultPrepared.length < OFFLINE_ORCHESTRATION_LIMITS.maxAttemptsPerJob) + || entries.indexOf(stop) <= afterResultIndex + || !jobClosedForRetry || jobClosedForRetry.reason !== 'retry-budget-exhausted' + || entries.indexOf(stop) >= entries.indexOf(jobClosedForRetry)) { + return reconciliationRequired(); + } + } if (closedWithoutRetry.length > 1 || (closedWithoutRetry.length === 1 && (!priorChain || (admitted.resume_time !== undefined && priorChain.resumeWindowIndex === undefined) || !jobClosedForRetry @@ -2495,8 +2534,9 @@ function createRunner({ runtime = defaultRuntime, store = new InMemoryPrototypeS if (terminal) return recoveryDiagnostic(trailingNoResultAttempt ? blocked ? 'contract-mapping-blocked' : budgetExhausted ? 'budget-exhausted' : 'closed-without-result' - : resultPrepared.length > 0 ? 'terminal' - : blocked ? 'contract-mapping-blocked' + : jobScopedBudgetStops?.length > 0 ? 'budget-exhausted' + : resultPrepared.length > 0 ? 'terminal' + : blocked ? 'contract-mapping-blocked' : budgetExhausted ? 'budget-exhausted' : 'closed-without-result'); const resumeClassification = classifyResumeCandidate(jobId, entries, admitted, verifiedBlobs); From 6bd743f1b9879fa48cac7674258548e6e8074fb4 Mon Sep 17 00:00:00 2001 From: Andrew Peris Date: Tue, 10 Nov 2026 11:21:39 -0500 Subject: [PATCH 23/33] Keep retry stop diagnostic in inspection scope --- src/offline-orchestration-prototype/runner.js | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/offline-orchestration-prototype/runner.js b/src/offline-orchestration-prototype/runner.js index 8233254..3e97a09 100644 --- a/src/offline-orchestration-prototype/runner.js +++ b/src/offline-orchestration-prototype/runner.js @@ -2102,6 +2102,8 @@ function createRunner({ runtime = defaultRuntime, store = new InMemoryPrototypeS return reconciliationRequired(); } let trailingNoResultAttempt = false; + const jobScopedBudgetStops = entries.filter(item => item.type === 'budget-exhausted' + && item.attempt_id === undefined); if (resultPrepared.length > 0) { const productionBytes = verifiedBlobs.get(admitted.input_key); let production; @@ -2324,8 +2326,6 @@ function createRunner({ runtime = defaultRuntime, store = new InMemoryPrototypeS const resultAttemptEventTypes = new Set(['prepared', 'dispatch-started', 'provider-outcome', 'result-prepared', 'persisting', 'terminal', 'resume-window', 'contract-mapping-blocked', 'budget-exhausted', 'cancelled-before-dispatch']); - const jobScopedBudgetStops = entries.filter(item => item.type === 'budget-exhausted' - && item.attempt_id === undefined); if (jobScopedBudgetStops.length > 1 || entries.some(item => resultAttemptEventTypes.has(item.type) && item.attempt_id === undefined && item.type !== 'budget-exhausted')) { From ab1544860b071e1ba3a97cb7ce839341cd5b4f4a Mon Sep 17 00:00:00 2001 From: Andrew Peris Date: Tue, 10 Nov 2026 11:22:28 -0500 Subject: [PATCH 24/33] Test contradictory stops and retry budget expiry --- .../local-file-store.test.js | 105 +++++++++++++++++- 1 file changed, 103 insertions(+), 2 deletions(-) diff --git a/tests/offline-orchestration-prototype/local-file-store.test.js b/tests/offline-orchestration-prototype/local-file-store.test.js index 789d317..18ab0d8 100644 --- a/tests/offline-orchestration-prototype/local-file-store.test.js +++ b/tests/offline-orchestration-prototype/local-file-store.test.js @@ -86,10 +86,10 @@ function runtime() { }; } -function prototype(store, onMockCall = () => {}) { +function prototype(store, onMockCall = () => {}, runtimeOverride = runtime()) { return createOfflineOrchestrationPrototypeForTest({ store, - runtime: runtime(), + runtime: runtimeOverride, idFactory: randomUUID, executionAuthorityProvider: authority(), onMockCall @@ -573,3 +573,104 @@ test('reopened no-result close requires its linked stop and rejects orphan dispa assert.equal(restartedCalls, 0); assert.equal(calls, 0); }); + + +test('reopened retry expiry validates a job-scoped budget stop against its last eligible result', async t => { + const root = temporaryDirectory(); + t.after(() => rmSync(root, { recursive: true, force: true })); + const store = new LocalFilePrototypeStore(root); + const clockState = { now: 10_000 }; + const controlledRuntime = { ...runtime(), now: () => clockState.now }; + let calls = 0; + const value = prototype(store, ({ phase }) => { if (phase === 'dispatch-confirmed') calls++; }, controlledRuntime); + const first = await value.submit({ + productionSource, + noOutputResultVersion: '1.1.0', + mockOutcome: { kind: 'rate-limit', retry_after_ms: 10 } + }); + assert.equal(first.retry_eligible, true); + const admitted = store.readEvents(first.job_id).find(item => item.type === 'admitted'); + assert.ok(Number.isSafeInteger(admitted.deadline_monotonic_ms)); + clockState.now = admitted.deadline_monotonic_ms; + + const stopped = await value.retry({ authorizeRetry: true }); + assert.equal(stopped.status, 'budget-exhausted'); + const events = store.readEvents(first.job_id); + const budgetStop = events.find(item => item.type === 'budget-exhausted' && item.attempt_id === undefined); + assert.deepEqual(budgetStop, { + job_id: first.job_id, + type: 'budget-exhausted', + reason: 'time', + deadline_monotonic_ms: admitted.deadline_monotonic_ms + }); + assert.equal(events.at(-1).type, 'job-closed'); + assert.equal(events.at(-1).reason, 'retry-budget-exhausted'); + assert.equal(calls, 1); + + const reopened = new LocalFilePrototypeStore(root); + let restartedCalls = 0; + const restarted = prototype(reopened, () => { restartedCalls++; }, controlledRuntime); + const beforeEvents = structuredClone(reopened.readEvents(first.job_id)); + const beforeBlobs = reopened.blobCount; + assert.deepEqual(restarted.inspectRecovery(first.job_id), { + status: 'budget-exhausted', + stage: 'limits', + code: 'BUDGET_EXHAUSTED', + read_only: true, + no_writes: true, + no_provider_calls: true, + authority_check_required: false + }); + assert.deepEqual(reopened.readEvents(first.job_id), beforeEvents); + assert.equal(reopened.blobCount, beforeBlobs); + assert.equal(restartedCalls, 0); + assert.equal(calls, 1); +}); + +test('reopened result chain rejects cancelled-before-dispatch naming a completed attempt', async t => { + const root = temporaryDirectory(); + t.after(() => rmSync(root, { recursive: true, force: true })); + const store = new LocalFilePrototypeStore(root); + const clockState = { now: 10_000 }; + const controlledRuntime = { ...runtime(), now: () => clockState.now }; + let calls = 0; + const value = prototype(store, ({ phase }) => { if (phase === 'dispatch-confirmed') calls++; }, controlledRuntime); + const first = await value.submit({ + productionSource, + noOutputResultVersion: '1.1.0', + mockOutcome: { kind: 'rate-limit', retry_after_ms: 10 } + }); + clockState.now += 10; + const completed = await value.retry({ authorizeRetry: true }); + assert.equal(completed.kind, 'terminal'); + assert.equal(completed.result.status, 'complete'); + assert.equal(calls, 2); + + const entries = structuredClone(store.readEvents(first.job_id)); + assert.ok(entries.some(item => item.type === 'dispatch-started' && item.attempt_id === completed.attempt_id)); + assert.ok(entries.some(item => item.type === 'terminal' && item.attempt_id === completed.attempt_id)); + const closeIndex = entries.findIndex(item => item.type === 'job-closed'); + assert.ok(closeIndex >= 0); + entries.splice(closeIndex, 0, { + job_id: first.job_id, + type: 'cancelled-before-dispatch', + attempt_id: completed.attempt_id, + reason: 'caller-cancelled', + private_content: 'CONTRADICTORY-STOP-PRIVATE-SENTINEL' + }); + writeLocalEventLog(root, first.job_id, entries); + + const reopened = new LocalFilePrototypeStore(root); + let restartedCalls = 0; + const restarted = prototype(reopened, () => { restartedCalls++; }, controlledRuntime); + const beforeEvents = structuredClone(reopened.readEvents(first.job_id)); + const beforeBlobs = reopened.blobCount; + assertSafeReconciliation(restarted.inspectRecovery(first.job_id), [ + root, first.job_id, first.attempt_id, first.execution_id, completed.attempt_id, + completed.execution_id, completed.result.result_id, 'CONTRADICTORY-STOP-PRIVATE-SENTINEL' + ]); + assert.deepEqual(reopened.readEvents(first.job_id), beforeEvents); + assert.equal(reopened.blobCount, beforeBlobs); + assert.equal(restartedCalls, 0); + assert.equal(calls, 2); +}); From 4ee9006a1df0c542d26265ec48b432daef86731e Mon Sep 17 00:00:00 2001 From: Andrew Peris Date: Tue, 10 Nov 2026 11:23:09 -0500 Subject: [PATCH 25/33] Assert valid reopened retry remains terminal --- tests/offline-orchestration-prototype/local-file-store.test.js | 2 ++ 1 file changed, 2 insertions(+) diff --git a/tests/offline-orchestration-prototype/local-file-store.test.js b/tests/offline-orchestration-prototype/local-file-store.test.js index 18ab0d8..12851b9 100644 --- a/tests/offline-orchestration-prototype/local-file-store.test.js +++ b/tests/offline-orchestration-prototype/local-file-store.test.js @@ -645,6 +645,8 @@ test('reopened result chain rejects cancelled-before-dispatch naming a completed assert.equal(completed.kind, 'terminal'); assert.equal(completed.result.status, 'complete'); assert.equal(calls, 2); + const validReopened = new LocalFilePrototypeStore(root); + assert.equal(prototype(validReopened, () => {}, controlledRuntime).inspectRecovery(first.job_id).status, 'terminal'); const entries = structuredClone(store.readEvents(first.job_id)); assert.ok(entries.some(item => item.type === 'dispatch-started' && item.attempt_id === completed.attempt_id)); From c70b57c3f5e8cfd302f71ec4021e1e723c82fb29 Mon Sep 17 00:00:00 2001 From: Andrew Peris Date: Tue, 10 Nov 2026 11:26:24 -0500 Subject: [PATCH 26/33] Validate budget stop event ordering and closure --- src/offline-orchestration-prototype/runner.js | 24 +++++++++++++++++-- 1 file changed, 22 insertions(+), 2 deletions(-) diff --git a/src/offline-orchestration-prototype/runner.js b/src/offline-orchestration-prototype/runner.js index 3e97a09..06979b0 100644 --- a/src/offline-orchestration-prototype/runner.js +++ b/src/offline-orchestration-prototype/runner.js @@ -2169,8 +2169,9 @@ function createRunner({ runtime = defaultRuntime, store = new InMemoryPrototypeS || stop.execution_id !== executionId || !Number.isSafeInteger(admitted.deadline_monotonic_ms) || stop.deadline_monotonic_ms !== admitted.deadline_monotonic_ms - || entries.indexOf(stop) <= entries.indexOf(outcome) - || entries.indexOf(stop) >= entries.indexOf(preparedResult)) return reconciliationRequired(); + || entries.indexOf(stop) <= entries.indexOf(dispatch) + || entries.indexOf(stop) >= entries.indexOf(outcome) + || entries.indexOf(outcome) >= entries.indexOf(preparedResult)) return reconciliationRequired(); } if (priorChain) { const priorWindows = matching('resume-window', priorChain.attemptId); @@ -2445,6 +2446,25 @@ function createRunner({ runtime = defaultRuntime, store = new InMemoryPrototypeS const noResultStopCounts = new Map(); for (const item of noResultStops) noResultStopCounts.set(item.type, (noResultStopCounts.get(item.type) ?? 0) + 1); if ([...noResultStopCounts.values()].some(count => count > 1)) return reconciliationRequired(); + const jobScopedBudgetStopsWithoutResult = noResultStops.filter(item => + item.type === 'budget-exhausted' && item.attempt_id === undefined); + if (jobScopedBudgetStopsWithoutResult.length > 1) return reconciliationRequired(); + if (jobScopedBudgetStopsWithoutResult.length === 1) { + const [stop] = jobScopedBudgetStopsWithoutResult; + const closed = entries.filter(item => item.type === 'job-closed'); + const timeStopKeys = ['deadline_monotonic_ms', 'job_id', 'reason', 'type']; + const materialStopKeys = ['job_id', 'reason', 'type']; + const expectedKeys = stop.reason === 'time' ? timeStopKeys + : ['prompt', 'material'].includes(stop.reason) ? materialStopKeys : []; + if (attemptIds.size !== 0 || expectedKeys.length === 0 + || Object.keys(stop).sort().join('|') !== [...expectedKeys].sort().join('|') + || stop.job_id !== jobId || stop.type !== 'budget-exhausted' + || (stop.reason === 'time' && (!Number.isSafeInteger(admitted.deadline_monotonic_ms) + || stop.deadline_monotonic_ms !== admitted.deadline_monotonic_ms)) + || closed.length !== 1 || closed[0].reason !== `budget-${stop.reason}` + || entries.indexOf(stop) >= entries.indexOf(closed[0]) + || entries.at(-1) !== closed[0]) return reconciliationRequired(); + } if (attemptIds.size === 1) { const [attemptId] = attemptIds; const attemptRecords = noResultAttemptRecords.filter(item => item.attempt_id === attemptId); From ac8b92b5886b64c36bb854da4427cf9c3c800167 Mon Sep 17 00:00:00 2001 From: Andrew Peris Date: Tue, 10 Nov 2026 11:29:07 -0500 Subject: [PATCH 27/33] Cover stop corruption and deadline-observed results --- .../local-file-store.test.js | 86 ++++++++++++++++++- 1 file changed, 85 insertions(+), 1 deletion(-) diff --git a/tests/offline-orchestration-prototype/local-file-store.test.js b/tests/offline-orchestration-prototype/local-file-store.test.js index 12851b9..4d2ec8a 100644 --- a/tests/offline-orchestration-prototype/local-file-store.test.js +++ b/tests/offline-orchestration-prototype/local-file-store.test.js @@ -86,12 +86,13 @@ function runtime() { }; } -function prototype(store, onMockCall = () => {}, runtimeOverride = runtime()) { +function prototype(store, onMockCall = () => {}, runtimeOverride = runtime(), mockAdapterFactoryOverride) { return createOfflineOrchestrationPrototypeForTest({ store, runtime: runtimeOverride, idFactory: randomUUID, executionAuthorityProvider: authority(), + ...(mockAdapterFactoryOverride ? { mockAdapterFactory: mockAdapterFactoryOverride } : {}), onMockCall }); } @@ -625,6 +626,39 @@ test('reopened retry expiry validates a job-scoped budget stop against its last assert.equal(reopened.blobCount, beforeBlobs); assert.equal(restartedCalls, 0); assert.equal(calls, 1); + + for (const corruption of ['deadline', 'reason', 'close', 'missing-result-chain']) { + const corrupted = structuredClone(events); + const stop = corrupted.find(item => item.type === 'budget-exhausted' && item.attempt_id === undefined); + const close = corrupted.find(item => item.type === 'job-closed'); + assert.ok(stop); + assert.ok(close); + if (corruption === 'deadline') stop.deadline_monotonic_ms++; + if (corruption === 'reason') stop.reason = 'attempts'; + if (corruption === 'close') close.reason = 'budget-time'; + if (corruption === 'missing-result-chain') { + for (let index = corrupted.length - 1; index >= 0; index--) { + if (['result-prepared', 'persisting', 'terminal'].includes(corrupted[index].type)) { + corrupted.splice(index, 1); + } + } + } + writeLocalEventLog(root, first.job_id, corrupted); + + const corruptedStore = new LocalFilePrototypeStore(root); + let corruptedCalls = 0; + const corruptedRunner = prototype(corruptedStore, () => { corruptedCalls++; }, controlledRuntime); + const unchangedEvents = structuredClone(corruptedStore.readEvents(first.job_id)); + const unchangedBlobs = corruptedStore.blobCount; + assertSafeReconciliation(corruptedRunner.inspectRecovery(first.job_id), [ + root, first.job_id, first.attempt_id, first.execution_id, + first.result.result_id, 'RETRY-BUDGET-PRIVATE-SENTINEL' + ]); + assert.deepEqual(corruptedStore.readEvents(first.job_id), unchangedEvents); + assert.equal(corruptedStore.blobCount, unchangedBlobs); + assert.equal(corruptedCalls, 0); + writeLocalEventLog(root, first.job_id, events); + } }); test('reopened result chain rejects cancelled-before-dispatch naming a completed attempt', async t => { @@ -676,3 +710,53 @@ test('reopened result chain rejects cancelled-before-dispatch naming a completed assert.equal(restartedCalls, 0); assert.equal(calls, 2); }); + + +test('reopened inspection accepts a result after the linked attempt observes its deadline', async t => { + const root = temporaryDirectory(); + t.after(() => rmSync(root, { recursive: true, force: true })); + const store = new LocalFilePrototypeStore(root); + const clockState = { now: 10_000 }; + const controlledRuntime = { ...runtime(), now: () => clockState.now }; + let calls = 0; + const mockAdapterFactory = configuration => new (class extends MockTextAdapter { + async execute(...args) { + const admitted = store.readEvents(store.readJobIds()[0]).find(item => item.type === 'admitted'); + clockState.now = admitted.deadline_monotonic_ms; + return super.execute(...args); + } + })(configuration); + const value = prototype(store, + ({ phase }) => { if (phase === 'dispatch-confirmed') calls++; }, + controlledRuntime, mockAdapterFactory); + const completed = await value.submit({ productionSource }); + assert.equal(completed.result.status, 'complete'); + assert.equal(calls, 1); + const entries = store.readEvents(completed.job_id); + const dispatch = entries.find(item => item.type === 'dispatch-started'); + const budgetStop = entries.find(item => item.type === 'budget-exhausted'); + const outcome = entries.find(item => item.type === 'provider-outcome'); + const preparedResult = entries.find(item => item.type === 'result-prepared'); + assert.deepEqual(budgetStop, { + job_id: completed.job_id, + type: 'budget-exhausted', + reason: 'time', + attempt_id: completed.attempt_id, + execution_id: completed.execution_id, + deadline_monotonic_ms: entries.find(item => item.type === 'admitted').deadline_monotonic_ms + }); + assert.ok(entries.indexOf(dispatch) < entries.indexOf(budgetStop)); + assert.ok(entries.indexOf(budgetStop) < entries.indexOf(outcome)); + assert.ok(entries.indexOf(outcome) < entries.indexOf(preparedResult)); + + const reopened = new LocalFilePrototypeStore(root); + let restartedCalls = 0; + const restarted = prototype(reopened, () => { restartedCalls++; }, controlledRuntime); + const beforeEvents = structuredClone(reopened.readEvents(completed.job_id)); + const beforeBlobs = reopened.blobCount; + assert.equal(restarted.inspectRecovery(completed.job_id).status, 'terminal'); + assert.deepEqual(reopened.readEvents(completed.job_id), beforeEvents); + assert.equal(reopened.blobCount, beforeBlobs); + assert.equal(restartedCalls, 0); + assert.equal(calls, 1); +}); From 7b0d5c9cb8a4129b06753c828cc124a875af8378 Mon Sep 17 00:00:00 2001 From: Andrew Peris Date: Tue, 10 Nov 2026 11:30:32 -0500 Subject: [PATCH 28/33] Reject competing stops after retry budget closure --- src/offline-orchestration-prototype/runner.js | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/offline-orchestration-prototype/runner.js b/src/offline-orchestration-prototype/runner.js index 06979b0..e4b4f25 100644 --- a/src/offline-orchestration-prototype/runner.js +++ b/src/offline-orchestration-prototype/runner.js @@ -2404,7 +2404,8 @@ function createRunner({ runtime = defaultRuntime, store = new InMemoryPrototypeS const [stop] = jobScopedBudgetStops; const stopKeys = ['deadline_monotonic_ms', 'job_id', 'reason', 'type']; const afterResultIndex = priorChain?.resumeWindowIndex ?? priorChain?.terminalIndex; - if (!priorChain || priorChain.result.status !== 'failed' || priorChain.result.outputs.length !== 0 + if (!priorChain || orphanIds.size !== 0 || closedWithoutRetry.length !== 0 + || priorChain.result.status !== 'failed' || priorChain.result.outputs.length !== 0 || !eligibleRateLimit(priorChain.providerResult) || Object.keys(stop).sort().join('|') !== stopKeys.join('|') || stop.job_id !== jobId || stop.type !== 'budget-exhausted' From 7f2fe4afe759ad56da87e09c42fdce83236aae08 Mon Sep 17 00:00:00 2001 From: Andrew Peris Date: Tue, 10 Nov 2026 11:36:11 -0500 Subject: [PATCH 29/33] Verify deadline stop ordering for resultless flows --- src/offline-orchestration-prototype/runner.js | 120 +++++++++++++++--- 1 file changed, 105 insertions(+), 15 deletions(-) diff --git a/src/offline-orchestration-prototype/runner.js b/src/offline-orchestration-prototype/runner.js index e4b4f25..ead7372 100644 --- a/src/offline-orchestration-prototype/runner.js +++ b/src/offline-orchestration-prototype/runner.js @@ -2377,9 +2377,9 @@ function createRunner({ runtime = defaultRuntime, store = new InMemoryPrototypeS || entries.indexOf(orphanOutcome) <= entries.indexOf(orphanDispatch)))) { return reconciliationRequired(); } + let orphanProviderResult; if (orphanOutcome) { const orphanOutcomeBytes = verifiedBlobs.get(orphanOutcome.payload_key); - let orphanProviderResult; try { orphanProviderResult = JSON.parse(orphanOutcomeBytes.toString('utf8')); } catch { return reconciliationRequired(); } @@ -2387,16 +2387,64 @@ function createRunner({ runtime = defaultRuntime, store = new InMemoryPrototypeS || orphanProviderResult.execution_id !== orphanExecutionId || orphanProviderResult.status !== orphanOutcome.status) return reconciliationRequired(); } - const lastAttemptIndex = entries.indexOf(orphanOutcome ?? orphanDispatch ?? orphanPrepared[0]); + const orphanBudgetStops = orphanStops.filter(item => item.type === 'budget-exhausted'); + const orphanCancellationStops = orphanStops.filter(item => item.type === 'cancelled-before-dispatch'); + const orphanMappingStops = orphanStops.filter(item => item.type === 'contract-mapping-blocked'); const stopIndices = orphanStops.map(item => entries.indexOf(item)); const closedEvents = entries.filter(item => item.type === 'job-closed'); if (orphanStops.some(item => item.execution_id !== undefined - && item.execution_id !== orphanExecutionId) - || stopIndices.some(index => index <= lastAttemptIndex) + && item.execution_id !== orphanExecutionId)) return reconciliationRequired(); + if (orphanCancellationStops.length === 1) { + const [stop] = orphanCancellationStops; + const stopKeys = ['attempt_id', 'job_id', 'reason', 'type']; + if (orphanDispatch || orphanOutcome || orphanBudgetStops.length !== 0 || orphanMappingStops.length !== 0 + || Object.keys(stop).sort().join('|') !== stopKeys.join('|') + || stop.job_id !== jobId || stop.attempt_id !== orphanId || stop.reason !== 'caller-cancelled' + || entries.indexOf(stop) <= entries.indexOf(orphanPrepared[0])) return reconciliationRequired(); + } + if (orphanBudgetStops.length === 1) { + const [stop] = orphanBudgetStops; + const stopKeys = ['attempt_id', 'deadline_monotonic_ms', 'execution_id', 'job_id', 'reason', 'type']; + const previousAttemptEvent = orphanDispatch ?? orphanPrepared[0]; + if (Object.keys(stop).sort().join('|') !== stopKeys.join('|') + || stop.job_id !== jobId || stop.attempt_id !== orphanId || stop.execution_id !== orphanExecutionId + || stop.reason !== 'time' || !Number.isSafeInteger(admitted.deadline_monotonic_ms) + || stop.deadline_monotonic_ms !== admitted.deadline_monotonic_ms + || entries.indexOf(stop) <= entries.indexOf(previousAttemptEvent) + || (orphanOutcome && entries.indexOf(stop) >= entries.indexOf(orphanOutcome))) { + return reconciliationRequired(); + } + } + if (orphanMappingStops.length === 1) { + const [mapping] = orphanMappingStops; + const mappingKeys = ['attempt_id', 'execution_id', 'job_id', 'provider_outcome_sha256', 'reason', 'type']; + const allowedReasons = new Set(['comic-result-validation-rejected', 'deadline-unverifiable', + 'no-output-result-not-representable-under-current-validator', 'provider-timeout-mapping-deferred', + 'unsupported-normalized-result-mapping']); + if (!orphanOutcome || Object.keys(mapping).sort().join('|') !== mappingKeys.join('|') + || mapping.job_id !== jobId || mapping.attempt_id !== orphanId + || mapping.execution_id !== orphanExecutionId + || !allowedReasons.has(mapping.reason) || mapping.provider_outcome_sha256 !== orphanOutcome.sha256 + || entries.indexOf(mapping) <= entries.indexOf(orphanOutcome)) return reconciliationRequired(); + } + if (orphanCancellationStops.length > 1 || orphanBudgetStops.length > 1 || orphanMappingStops.length > 1 + || (orphanOutcome && orphanMappingStops.length !== 1) + || (!orphanOutcome && orphanMappingStops.length !== 0) || (closedEvents.length === 1 && (entries.at(-1) !== closedEvents[0] || entries.indexOf(closedEvents[0]) <= Math.max(...stopIndices))) - || (closedEvents.length === 0 && (orphanStops.length !== 1 - || orphanStops[0].type !== 'contract-mapping-blocked'))) return reconciliationRequired(); + || (closedEvents.length === 0 && (orphanCancellationStops.length !== 0 + || orphanBudgetStops.length !== 0 || orphanMappingStops.length !== 1)) + || (closedEvents.length === 1 && orphanCancellationStops.length === 1 + && closedEvents[0].reason !== 'cancelled-before-dispatch') + || (closedEvents.length === 1 && orphanBudgetStops.length === 1 + && orphanMappingStops.length === 0 && closedEvents[0].reason !== 'budget-time') + || (closedEvents.length === 1 && orphanMappingStops.length === 1 + && (!orphanOutcome || !['failed', 'cancelled', 'succeeded'].includes(orphanProviderResult.status) + || closedEvents[0].reason !== 'retry-contract-mapping-blocked')) + || (closedEvents.length === 1 && orphanCancellationStops.length === 0 + && orphanBudgetStops.length === 0 && orphanMappingStops.length === 0)) { + return reconciliationRequired(); + } } const closedWithoutRetry = entries.filter(item => item.type === 'closed-without-retry'); const jobClosedForRetry = entries.find(item => item.type === 'job-closed'); @@ -2506,9 +2554,9 @@ function createRunner({ runtime = defaultRuntime, store = new InMemoryPrototypeS || !Number.isSafeInteger(outcome.byte_size) || outcome.byte_size < 0 || typeof outcome.sha256 !== 'string' || !/^sha256:[0-9a-f]{64}$/.test(outcome.sha256) || entries.indexOf(outcome) <= entries.indexOf(dispatch)))) return reconciliationRequired(); + let providerResult; if (outcome) { const outcomeBytes = verifiedBlobs.get(outcome.payload_key); - let providerResult; try { providerResult = JSON.parse(outcomeBytes.toString('utf8')); } catch { return reconciliationRequired(); } @@ -2516,18 +2564,60 @@ function createRunner({ runtime = defaultRuntime, store = new InMemoryPrototypeS || providerResult.execution_id !== prepared.execution_id || providerResult.status !== outcome.status) return reconciliationRequired(); } + const budgetStops = stops.filter(item => item.type === 'budget-exhausted'); + const cancellationStops = stops.filter(item => item.type === 'cancelled-before-dispatch'); + const mappingStops = stops.filter(item => item.type === 'contract-mapping-blocked'); + const preparedIndex = entries.indexOf(prepared); const closedEventsForAttempt = entries.filter(item => item.type === 'job-closed'); - const lastAttemptIndex = entries.indexOf(outcome ?? dispatch ?? prepared); + if (cancellationStops.length === 1) { + const [stop] = cancellationStops; + const stopKeys = ['attempt_id', 'job_id', 'reason', 'type']; + if (dispatch || outcome || budgetStops.length !== 0 || mappingStops.length !== 0 + || Object.keys(stop).sort().join('|') !== stopKeys.join('|') + || stop.job_id !== jobId || stop.attempt_id !== attemptId || stop.reason !== 'caller-cancelled' + || entries.indexOf(stop) <= preparedIndex) return reconciliationRequired(); + } + if (budgetStops.length === 1) { + const [stop] = budgetStops; + const stopKeys = ['attempt_id', 'deadline_monotonic_ms', 'execution_id', 'job_id', 'reason', 'type']; + const previousAttemptEvent = dispatch ?? prepared; + if (Object.keys(stop).sort().join('|') !== stopKeys.join('|') + || stop.job_id !== jobId || stop.attempt_id !== attemptId + || stop.execution_id !== prepared.execution_id || stop.reason !== 'time' + || !Number.isSafeInteger(admitted.deadline_monotonic_ms) + || stop.deadline_monotonic_ms !== admitted.deadline_monotonic_ms + || entries.indexOf(stop) <= entries.indexOf(previousAttemptEvent) + || (outcome && entries.indexOf(stop) >= entries.indexOf(outcome))) return reconciliationRequired(); + } + if (mappingStops.length === 1) { + const [mapping] = mappingStops; + const mappingKeys = ['attempt_id', 'execution_id', 'job_id', 'provider_outcome_sha256', 'reason', 'type']; + const allowedReasons = new Set(['comic-result-validation-rejected', 'deadline-unverifiable', + 'no-output-result-not-representable-under-current-validator', 'provider-timeout-mapping-deferred', + 'unsupported-normalized-result-mapping']); + if (!outcome || Object.keys(mapping).sort().join('|') !== mappingKeys.join('|') + || mapping.job_id !== jobId || mapping.attempt_id !== attemptId + || mapping.execution_id !== prepared.execution_id + || !allowedReasons.has(mapping.reason) || mapping.provider_outcome_sha256 !== outcome.sha256 + || entries.indexOf(mapping) <= entries.indexOf(outcome)) return reconciliationRequired(); + } + if (cancellationStops.length > 1 || budgetStops.length > 1 || mappingStops.length > 1 + || (outcome && mappingStops.length !== 1) + || (!outcome && mappingStops.length !== 0)) return reconciliationRequired(); const stopIndices = stops.map(item => entries.indexOf(item)); - if (stopIndices.some(index => index <= lastAttemptIndex) + if (closedEventsForAttempt.length > 1 || (closedEventsForAttempt.length === 1 && (entries.at(-1) !== closedEventsForAttempt[0] || stopIndices.length === 0 || entries.indexOf(closedEventsForAttempt[0]) <= Math.max(...stopIndices))) - || (stops.some(item => item.type === 'cancelled-before-dispatch') && (dispatch || outcome)) - || (closedEventsForAttempt.length === 1 && !stops.some(item => - item.type === 'budget-exhausted' || item.type === 'cancelled-before-dispatch')) - || (closedEventsForAttempt.length === 0 && stops.some(item => item.type !== 'contract-mapping-blocked'))) { - return reconciliationRequired(); - } + || (closedEventsForAttempt.length === 1 && cancellationStops.length === 1 + && closedEventsForAttempt[0].reason !== 'cancelled-before-dispatch') + || (closedEventsForAttempt.length === 1 && budgetStops.length === 1 + && mappingStops.length === 0 && closedEventsForAttempt[0].reason !== 'budget-time') + || (closedEventsForAttempt.length === 1 && mappingStops.length !== 0) + || (closedEventsForAttempt.length === 1 && cancellationStops.length === 0 + && budgetStops.length === 0 && mappingStops.length === 0) + || (closedEventsForAttempt.length === 0 + && (cancellationStops.length !== 0 || (budgetStops.length !== 0 && mappingStops.length === 0) + || mappingStops.length !== 1))) return reconciliationRequired(); } if (entries.some(item => ['prepared', 'dispatch-started', 'provider-outcome', 'contract-mapping-blocked'].includes(item.type) && item.attempt_id === undefined)) { From 5698392be62805494ac8af06f17166505cda7de9 Mon Sep 17 00:00:00 2001 From: Andrew Peris Date: Tue, 10 Nov 2026 11:37:42 -0500 Subject: [PATCH 30/33] Test reopened initial and retry deadline stops --- .../local-file-store.test.js | 156 ++++++++++++++++++ 1 file changed, 156 insertions(+) diff --git a/tests/offline-orchestration-prototype/local-file-store.test.js b/tests/offline-orchestration-prototype/local-file-store.test.js index 4d2ec8a..f46df0d 100644 --- a/tests/offline-orchestration-prototype/local-file-store.test.js +++ b/tests/offline-orchestration-prototype/local-file-store.test.js @@ -86,6 +86,28 @@ function runtime() { }; } +function controlledDeadlineRuntime(clockState) { + const timers = new Map(); + let nextTimerId = 0; + return { + runtime: { + ...runtime(), + now: () => clockState.now, + setTimer(callback) { + const timerId = ++nextTimerId; + timers.set(timerId, callback); + return timerId; + }, + clearTimer(timerId) { timers.delete(timerId); } + }, + fireTimers() { + const callbacks = [...timers.values()]; + timers.clear(); + for (const callback of callbacks) callback(); + } + }; +} + function prototype(store, onMockCall = () => {}, runtimeOverride = runtime(), mockAdapterFactoryOverride) { return createOfflineOrchestrationPrototypeForTest({ store, @@ -760,3 +782,137 @@ test('reopened inspection accepts a result after the linked attempt observes its assert.equal(restartedCalls, 0); assert.equal(calls, 1); }); + + +test('reopened initial deadline cancellation preserves budget then mapping order', async t => { + const root = temporaryDirectory(); + t.after(() => rmSync(root, { recursive: true, force: true })); + const store = new LocalFilePrototypeStore(root); + const clockState = { now: 10_000 }; + const deadlineRuntime = controlledDeadlineRuntime(clockState); + const mockAdapterFactory = configuration => new (class extends MockTextAdapter { + async execute(...args) { + const admitted = store.readEvents(store.readJobIds()[0]).find(item => item.type === 'admitted'); + clockState.now = admitted.deadline_monotonic_ms; + deadlineRuntime.fireTimers(); + return super.execute(...args); + } + })(configuration); + let calls = 0; + const value = prototype(store, + ({ phase }) => { if (phase === 'dispatch-confirmed') calls++; }, + deadlineRuntime.runtime, mockAdapterFactory); + const result = await value.submit({ + productionSource, + mockOutcome: { kind: 'success', delay_ms: 5_000 } + }); + assert.equal(result.status, 'contract-mapping-blocked'); + assert.equal(calls, 1); + const entries = store.readEvents(result.job_id); + const dispatch = entries.find(item => item.type === 'dispatch-started'); + const budgetStop = entries.find(item => item.type === 'budget-exhausted'); + const outcome = entries.find(item => item.type === 'provider-outcome'); + const mapping = entries.find(item => item.type === 'contract-mapping-blocked'); + assert.ok(dispatch && budgetStop && outcome && mapping); + assert.ok(entries.indexOf(dispatch) < entries.indexOf(budgetStop)); + assert.ok(entries.indexOf(budgetStop) < entries.indexOf(outcome)); + assert.ok(entries.indexOf(outcome) < entries.indexOf(mapping)); + assert.equal(entries.some(item => item.type === 'job-closed' || item.type === 'terminal'), false); + + const reopened = new LocalFilePrototypeStore(root); + let restartedCalls = 0; + const restarted = prototype(reopened, () => { restartedCalls++; }, deadlineRuntime.runtime); + const beforeEvents = structuredClone(reopened.readEvents(result.job_id)); + const beforeBlobs = reopened.blobCount; + const inspection = restarted.inspectRecovery(result.job_id); + assert.deepEqual(inspection, { + status: 'contract-mapping-blocked', + stage: 'mapping', + code: 'CONTRACT_MAPPING_BLOCKED', + read_only: true, + no_writes: true, + no_provider_calls: true, + authority_check_required: false + }); + for (const value of [root, result.job_id, result.attempt_id, result.execution_id, + 'PRIVATE-DEADLINE-MAPPING-SENTINEL', 'exception_text']) { + assert.equal(JSON.stringify(inspection).includes(value), false); + } + assert.deepEqual(reopened.readEvents(result.job_id), beforeEvents); + assert.equal(reopened.blobCount, beforeBlobs); + assert.equal(restartedCalls, 0); + assert.equal(calls, 1); +}); + +test('reopened retry deadline cancellation links budget, outcome, mapping, and close', async t => { + const root = temporaryDirectory(); + t.after(() => rmSync(root, { recursive: true, force: true })); + const store = new LocalFilePrototypeStore(root); + const clockState = { now: 10_000 }; + const deadlineRuntime = controlledDeadlineRuntime(clockState); + let mockInstances = 0; + const mockAdapterFactory = configuration => { + const instanceNumber = ++mockInstances; + return new (class extends MockTextAdapter { + async execute(...args) { + if (instanceNumber === 2) { + const admitted = store.readEvents(store.readJobIds()[0]).find(item => item.type === 'admitted'); + clockState.now = admitted.deadline_monotonic_ms; + deadlineRuntime.fireTimers(); + } + return super.execute(...args); + } + })(configuration); + }; + let calls = 0; + const value = prototype(store, + ({ phase }) => { if (phase === 'dispatch-confirmed') calls++; }, + deadlineRuntime.runtime, mockAdapterFactory); + const first = await value.submit({ + productionSource, + noOutputResultVersion: '1.1.0', + mockOutcome: { kind: 'rate-limit', retry_after_ms: 10 } + }); + assert.equal(first.retry_eligible, true); + clockState.now += 10; + const stopped = await value.retry({ authorizeRetry: true, mockOutcome: { kind: 'success', delay_ms: 5_000 } }); + assert.equal(stopped.status, 'contract-mapping-blocked'); + assert.equal(stopped.job_closed, true); + assert.equal(calls, 2); + const entries = store.readEvents(first.job_id); + const secondAttempt = entries.find(item => item.type === 'prepared' && item.attempt_id !== first.attempt_id); + const dispatch = entries.find(item => item.type === 'dispatch-started' && item.attempt_id === secondAttempt.attempt_id); + const budgetStop = entries.find(item => item.type === 'budget-exhausted' && item.attempt_id === secondAttempt.attempt_id); + const outcome = entries.find(item => item.type === 'provider-outcome' && item.attempt_id === secondAttempt.attempt_id); + const mapping = entries.find(item => item.type === 'contract-mapping-blocked' && item.attempt_id === secondAttempt.attempt_id); + assert.ok(secondAttempt && dispatch && budgetStop && outcome && mapping); + assert.ok(entries.indexOf(dispatch) < entries.indexOf(budgetStop)); + assert.ok(entries.indexOf(budgetStop) < entries.indexOf(outcome)); + assert.ok(entries.indexOf(outcome) < entries.indexOf(mapping)); + assert.equal(entries.at(-1).type, 'job-closed'); + assert.equal(entries.at(-1).reason, 'retry-contract-mapping-blocked'); + + const reopened = new LocalFilePrototypeStore(root); + let restartedCalls = 0; + const restarted = prototype(reopened, () => { restartedCalls++; }, deadlineRuntime.runtime); + const beforeEvents = structuredClone(reopened.readEvents(first.job_id)); + const beforeBlobs = reopened.blobCount; + const inspection = restarted.inspectRecovery(first.job_id); + assert.deepEqual(inspection, { + status: 'contract-mapping-blocked', + stage: 'mapping', + code: 'CONTRACT_MAPPING_BLOCKED', + read_only: true, + no_writes: true, + no_provider_calls: true, + authority_check_required: false + }); + for (const value of [root, first.job_id, first.attempt_id, first.execution_id, + secondAttempt.attempt_id, secondAttempt.execution_id, 'PRIVATE-DEADLINE-MAPPING-SENTINEL']) { + assert.equal(JSON.stringify(inspection).includes(value), false); + } + assert.deepEqual(reopened.readEvents(first.job_id), beforeEvents); + assert.equal(reopened.blobCount, beforeBlobs); + assert.equal(restartedCalls, 0); + assert.equal(calls, 2); +}); From 7395256b3b8b1b068f7f0c24567dfb815b37f54b Mon Sep 17 00:00:00 2001 From: Andrew Peris Date: Tue, 10 Nov 2026 11:38:52 -0500 Subject: [PATCH 31/33] Fail closed on unfinished retry mappings --- src/offline-orchestration-prototype/runner.js | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/src/offline-orchestration-prototype/runner.js b/src/offline-orchestration-prototype/runner.js index ead7372..c7b8993 100644 --- a/src/offline-orchestration-prototype/runner.js +++ b/src/offline-orchestration-prototype/runner.js @@ -2433,7 +2433,9 @@ function createRunner({ runtime = defaultRuntime, store = new InMemoryPrototypeS || (closedEvents.length === 1 && (entries.at(-1) !== closedEvents[0] || entries.indexOf(closedEvents[0]) <= Math.max(...stopIndices))) || (closedEvents.length === 0 && (orphanCancellationStops.length !== 0 - || orphanBudgetStops.length !== 0 || orphanMappingStops.length !== 1)) + || orphanBudgetStops.length !== 0 || orphanMappingStops.length !== 1 + || (orphanMappingStops[0].reason !== 'deadline-unverifiable' + && orphanProviderResult.status !== 'timed-out'))) || (closedEvents.length === 1 && orphanCancellationStops.length === 1 && closedEvents[0].reason !== 'cancelled-before-dispatch') || (closedEvents.length === 1 && orphanBudgetStops.length === 1 From b2af35feaf4ebff861cc15d2bab376d486cd7341 Mon Sep 17 00:00:00 2001 From: Andrew Peris Date: Tue, 10 Nov 2026 11:42:39 -0500 Subject: [PATCH 32/33] Cover unfinished orphan mapping guard --- .../local-file-store.test.js | 108 ++++++++++++++++++ 1 file changed, 108 insertions(+) diff --git a/tests/offline-orchestration-prototype/local-file-store.test.js b/tests/offline-orchestration-prototype/local-file-store.test.js index f46df0d..827dd63 100644 --- a/tests/offline-orchestration-prototype/local-file-store.test.js +++ b/tests/offline-orchestration-prototype/local-file-store.test.js @@ -916,3 +916,111 @@ test('reopened retry deadline cancellation links budget, outcome, mapping, and c assert.equal(restartedCalls, 0); assert.equal(calls, 2); }); + + +test('reopened inspection rejects an unfinished ordinary orphan retry mapping', async t => { + const root = temporaryDirectory(); + t.after(() => rmSync(root, { recursive: true, force: true })); + const store = new LocalFilePrototypeStore(root); + const clockState = { now: 10_000 }; + const controlledRuntime = { ...runtime(), now: () => clockState.now }; + let calls = 0; + const value = prototype(store, ({ phase }) => { if (phase === 'dispatch-confirmed') calls++; }, controlledRuntime); + const first = await value.submit({ + productionSource, + noOutputResultVersion: '1.1.0', + mockOutcome: { kind: 'rate-limit', retry_after_ms: 10 } + }); + clockState.now += 10; + const stopped = await value.retry({ authorizeRetry: true, mockOutcome: { kind: 'output-validation' } }); + assert.equal(stopped.status, 'contract-mapping-blocked'); + assert.equal(stopped.job_closed, true); + assert.equal(calls, 2); + + const events = structuredClone(store.readEvents(first.job_id)); + const mapping = events.find(item => item.type === 'contract-mapping-blocked' + && item.attempt_id === stopped.attempt_id); + assert.ok(mapping); + assert.equal(mapping.reason, 'no-output-result-not-representable-under-current-validator'); + const outcome = events.find(item => item.type === 'provider-outcome' && item.attempt_id === stopped.attempt_id); + assert.ok(outcome); + assert.equal(outcome.status, 'failed'); + const closed = events.findIndex(item => item.type === 'job-closed'); + assert.ok(closed >= 0); + events.splice(closed, 1); + writeLocalEventLog(root, first.job_id, events); + + const reopened = new LocalFilePrototypeStore(root); + let restartedCalls = 0; + const restarted = prototype(reopened, () => { restartedCalls++; }, controlledRuntime); + const beforeEvents = structuredClone(reopened.readEvents(first.job_id)); + const beforeBlobs = reopened.blobCount; + assertSafeReconciliation(restarted.inspectRecovery(first.job_id), [ + root, first.job_id, first.attempt_id, first.execution_id, + stopped.attempt_id, stopped.execution_id, first.result.result_id, + 'ORDINARY-ORPHAN-MAPPING-PRIVATE-SENTINEL' + ]); + assert.deepEqual(reopened.readEvents(first.job_id), beforeEvents); + assert.equal(reopened.blobCount, beforeBlobs); + assert.equal(restartedCalls, 0); + assert.equal(calls, 2); +}); + +test('reopened inspection accepts an unfinished provider-timeout orphan mapping', async t => { + const root = temporaryDirectory(); + t.after(() => rmSync(root, { recursive: true, force: true })); + const store = new LocalFilePrototypeStore(root); + const clockState = { now: 10_000 }; + const controlledRuntime = { ...runtime(), now: () => clockState.now }; + let calls = 0; + const value = prototype(store, ({ phase }) => { if (phase === 'dispatch-confirmed') calls++; }, controlledRuntime); + const first = await value.submit({ + productionSource, + noOutputResultVersion: '1.1.0', + mockOutcome: { kind: 'rate-limit', retry_after_ms: 10 } + }); + clockState.now += 10; + const stopped = await value.retry({ authorizeRetry: true, mockOutcome: { kind: 'timeout' } }); + assert.equal(stopped.status, 'contract-mapping-blocked'); + assert.equal(stopped.job_closed, undefined); + assert.equal(calls, 2); + + const events = store.readEvents(first.job_id); + const secondPrepared = events.find(item => item.type === 'prepared' && item.attempt_id !== first.attempt_id); + const secondDispatch = events.find(item => item.type === 'dispatch-started' + && item.attempt_id === secondPrepared.attempt_id); + const secondOutcome = events.find(item => item.type === 'provider-outcome' + && item.attempt_id === secondPrepared.attempt_id); + const mapping = events.find(item => item.type === 'contract-mapping-blocked' + && item.attempt_id === secondPrepared.attempt_id); + assert.ok(secondPrepared && secondDispatch && secondOutcome && mapping); + assert.equal(secondOutcome.status, 'timed-out'); + assert.equal(mapping.reason, 'provider-timeout-mapping-deferred'); + assert.ok(events.indexOf(secondDispatch) < events.indexOf(secondOutcome)); + assert.ok(events.indexOf(secondOutcome) < events.indexOf(mapping)); + assert.equal(events.some(item => item.type === 'job-closed'), false); + + const reopened = new LocalFilePrototypeStore(root); + let restartedCalls = 0; + const restarted = prototype(reopened, () => { restartedCalls++; }, controlledRuntime); + const beforeEvents = structuredClone(reopened.readEvents(first.job_id)); + const beforeBlobs = reopened.blobCount; + const inspection = restarted.inspectRecovery(first.job_id); + assert.deepEqual(inspection, { + status: 'contract-mapping-blocked', + stage: 'mapping', + code: 'CONTRACT_MAPPING_BLOCKED', + read_only: true, + no_writes: true, + no_provider_calls: true, + authority_check_required: false + }); + for (const value of [root, first.job_id, first.attempt_id, first.execution_id, + secondPrepared.attempt_id, secondPrepared.execution_id, 'PROVIDER-TIMEOUT-PRIVATE-SENTINEL']) { + assert.equal(JSON.stringify(inspection).includes(value), false); + } + assert.deepEqual(reopened.readEvents(first.job_id), beforeEvents); + assert.equal(reopened.blobCount, beforeBlobs); + assert.equal(restartedCalls, 0); + assert.equal(calls, 2); +}); From 52e42fb305187e2287d0a44f0a4b3b58fa265422 Mon Sep 17 00:00:00 2001 From: Andrew Peris Date: Tue, 10 Nov 2026 12:01:49 -0500 Subject: [PATCH 33/33] Align close-append inspection with fail-closed state --- tests/offline-orchestration-prototype/runner.test.js | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/tests/offline-orchestration-prototype/runner.test.js b/tests/offline-orchestration-prototype/runner.test.js index 5148dc7..d70e2b7 100644 --- a/tests/offline-orchestration-prototype/runner.test.js +++ b/tests/offline-orchestration-prototype/runner.test.js @@ -2261,8 +2261,9 @@ for (const fault of ['outcome-readback', 'mapping-append', 'close-append', 'ambi assert.equal(second.job_closed, undefined); const inspection = h.value.inspectRecovery(first.job_id); assert.equal(inspection.read_only, true); - assert.equal(inspection.status, fault === 'close-append' - ? 'contract-mapping-blocked' : 'reconciliation-required'); + // A rejected close append and a removed close marker have identical persisted + // logs, so both must remain unresolved during read-only inspection. + assert.equal(inspection.status, 'reconciliation-required'); if (!unknownEvents) assert.equal(store.readEvents(first.job_id).some(e => e.type === 'job-closed'), false); await assert.rejects(() => h.value.retry({ authorizeRetry: true }), e => e.code === 'RETRY_NOT_AVAILABLE'); });