diff --git a/docs/offline-orchestration-prototype.md b/docs/offline-orchestration-prototype.md index 8422e06..79ee9ad 100644 --- a/docs/offline-orchestration-prototype.md +++ b/docs/offline-orchestration-prototype.md @@ -355,5 +355,46 @@ 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 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 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 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. diff --git a/src/offline-orchestration-prototype/runner.js b/src/offline-orchestration-prototype/runner.js index 82a45f7..c7b8993 100644 --- a/src/offline-orchestration-prototype/runner.js +++ b/src/offline-orchestration-prototype/runner.js @@ -46,6 +46,26 @@ 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' }), + 'closed-without-result': Object.freeze({ stage: 'terminal', code: 'JOB_CLOSED_WITHOUT_RESULT' }) +}); const defaultRuntime = Object.freeze({ now: () => Math.floor(performance.now()), @@ -70,6 +90,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 +2035,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 +2067,605 @@ 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(); + } + 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; + 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')) + || 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 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(dispatch) + || entries.indexOf(stop) >= entries.indexOf(outcome) + || entries.indexOf(outcome) >= entries.indexOf(preparedResult)) return reconciliationRequired(); + } + if (priorChain) { + const priorWindows = matching('resume-window', priorChain.attemptId); + 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)); + 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 + || !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(); + } + + 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)) { + 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 { + const resultSource = canonicalJson(result); + resultValidation = result.spec_version === '1.1.0' + ? 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 || !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.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) { + 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(); + } + 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) + || 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 + || !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']); + 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']); + 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(); + const orphanIds = new Set(orphanAttemptRecords.map(item => item.attempt_id)); + if (orphanIds.size > 0) { + if (orphanIds.size !== 1 || !priorChain + || (admitted.resume_time !== undefined && 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 ?? priorChain.terminalIndex)) { + 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(); + } + let orphanProviderResult; + if (orphanOutcome) { + const orphanOutcomeBytes = verifiedBlobs.get(orphanOutcome.payload_key); + 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 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)) 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 && (orphanCancellationStops.length !== 0 + || 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 + && 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'); + if (jobScopedBudgetStops.length === 1) { + const [stop] = jobScopedBudgetStops; + const stopKeys = ['deadline_monotonic_ms', 'job_id', 'reason', 'type']; + const afterResultIndex = priorChain?.resumeWindowIndex ?? priorChain?.terminalIndex; + 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' + || !['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 + || closedWithoutRetry[0].attempt_id !== priorChain.attemptId + || closedWithoutRetry[0].result_id !== priorChain.resultId + || entries.indexOf(closedWithoutRetry[0]) <= (priorChain.resumeWindowIndex ?? priorChain.terminalIndex) + || (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, + // 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)); + 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); + 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) + || !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 + || 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(); + let providerResult; + if (outcome) { + const outcomeBytes = verifiedBlobs.get(outcome.payload_key); + 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 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'); + 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 (closedEventsForAttempt.length > 1 + || (closedEventsForAttempt.length === 1 && (entries.at(-1) !== closedEventsForAttempt[0] + || stopIndices.length === 0 || entries.indexOf(closedEventsForAttempt[0]) <= Math.max(...stopIndices))) + || (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)) { + 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'); + 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(trailingNoResultAttempt + ? blocked ? 'contract-mapping-blocked' + : budgetExhausted ? 'budget-exhausted' : 'closed-without-result' + : 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); 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); } diff --git a/tests/offline-orchestration-prototype/local-file-store.test.js b/tests/offline-orchestration-prototype/local-file-store.test.js index feb9c90..827dd63 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-')); @@ -85,12 +86,35 @@ function runtime() { }; } -function prototype(store, onMockCall = () => {}) { +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, - runtime: runtime(), + runtime: runtimeOverride, idFactory: randomUUID, executionAuthorityProvider: authority(), + ...(mockAdapterFactoryOverride ? { mockAdapterFactory: mockAdapterFactoryOverride } : {}), onMockCall }); } @@ -229,12 +253,774 @@ 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); +}); + + +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, ({ 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); + 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 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, ({ 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; + 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-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 => { + 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, ({ phase }) => { if (phase === 'dispatch-confirmed') 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 = structuredClone(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, ({ 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'; + const bytes = Buffer.from(canonicalJson(result), 'utf8'); + 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; + 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); +}); + + +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(); + const value = prototype(store, ({ phase }) => { + if (phase === 'created') controller.abort(); + if (phase === 'dispatch-confirmed') calls++; + }); + const stopped = await value.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 = structuredClone(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); +}); + + +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); + + 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 => { + 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 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)); + 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); +}); + + +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); +}); + + +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); +}); + + +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); +}); diff --git a/tests/offline-orchestration-prototype/resume-candidate.test.js b/tests/offline-orchestration-prototype/resume-candidate.test.js index 5f756aa..5db33cd 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); @@ -850,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 = 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); + 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 = 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' + && 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); + }); + } +}); diff --git a/tests/offline-orchestration-prototype/runner.test.js b/tests/offline-orchestration-prototype/runner.test.js index eceb870..d70e2b7 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'); }); @@ -2231,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'); }); @@ -2252,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 === 'ambiguous-close' ? 'reconciliation-required' - : fault === 'close-append' ? 'contract-mapping-blocked' : 'read-only-inspection-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'); }); @@ -2270,3 +2280,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: '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 = structuredClone(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); +});