diff --git a/docs/o08-durable-resume-decision-packet.md b/docs/o08-durable-resume-decision-packet.md index 6d494ae..4cf976e 100644 --- a/docs/o08-durable-resume-decision-packet.md +++ b/docs/o08-durable-resume-decision-packet.md @@ -7,15 +7,18 @@ creative material. ## Current evidence and gap -Platform `main` at `94e4fe60c84a455b524d14f57b1adaa4c4ad7c9f` has a bounded -same-process retry. The first attempt is retry-eligible only when its verified +Platform `main` at `e0d31cf9505858aea81f94615dc18eb546197c60` has a bounded +same-process retry and an experimental local file store with atomic claims and +durable writes. The first attempt is retry-eligible only when its verified provider outcome is the exact rate-limit-before-acceptance case. Explicit retry then rechecks current authority and immutable evidence, honors the original deadline and two-attempt limit, and creates one new attempt with a new execution ID and idempotency key. Recovery after a new runner/process is read-only. -The supported store is in-memory only. The job deadline and retry delay are -monotonic and tied to the current clock epoch. Retry eligibility also retains +The ordinary prototype still uses in-memory state and monotonic retry timing; +the separately exported local-file testing/store implementation supplies +durable primitives but is not yet wired to resumed jobs. The job deadline and +retry delay are monotonic and tied to the current clock epoch. Retry eligibility also retains the original `retry_not_before`; resume must preserve and verify both that value and the original job deadline. The mock adapter records calls but does not deduplicate them. Provider Execution v1 carries an `idempotency_key`; the @@ -145,12 +148,53 @@ Stored digests detect mismatch against trusted event metadata; they do not authenticate an event log and do not resist an actor who can rewrite both data and metadata. No signing key or separate integrity service is introduced. -The implementation is deliberately split at the storage boundary to fit the -issue's 1–2 focused-day cap: this slice supplies local persistent store and -claim primitives plus restart/corruption tests, but does not reconstruct jobs -or dispatch resumed attempts. Writable resume rehydration and effect -authorization remain the next bounded implementation slice. O09 remains open -and is not satisfied by this store primitive. +The initial storage slice supplies local persistent store and claim primitives +plus restart/corruption tests, but does not reconstruct jobs or dispatch resumed +attempts. The bounded follow-up below adds only read-only candidate +rehydration/classification; it does not consume a claim or dispatch. A later +slice must integrate writable resume and effect authorization. O09 remains open +and is not satisfied by these primitives. + +## Bounded read-only candidate rehydration slice — 2026-11-08 + +The runner's internal test factory accepts an explicitly injected synthetic +resume-time authority with fixed authority, domain, and epoch identifiers. +There is no fallback to the machine wall clock. At admission, the runner stores +the stable start and original deadline alongside the existing pinned +production/prompt evidence. After a safe first-attempt terminal result, it +samples that same authority and appends a separate `resume-window` event with +the sample time, original deadline, and `retry_not_before` derived from the +provider's verified before-acceptance rate-limit result. This event is appended +after terminal persistence so the bound cannot be shortened by an earlier +sample. Same-process retry behavior is unchanged. + +On a reopened local store, read-only recovery first validates the exact +no-context synthetic path: the pinned comic-manifest-v1 production and prompt, +single first-attempt lifecycle, immutable provider outcome/result bytes, +terminal links, stable time authority identity, and the separate resume-window +link. It then samples the injected stable time and classifies inclusive +`retry_not_before <= now < original_deadline`, expired, not-yet-eligible, +empty-window, and unverifiable cases. Corrupt or mismatched evidence cannot +produce a candidate. A candidate response is explicitly read-only and says +current authority must still be checked. This slice does not read package +content, support context-enabled jobs, acquire a resume claim, rebuild the +material ledger/job, issue a new attempt, or call the mock/provider. + +The deterministic tests use the pinned synthetic fixture and a fixed test time +inside its review period. A real-time run does not rewind the fixture's review +date. The time authority is an injected test seam, not a production clock +service. The local-store trust assumption above still applies: a writer able to +rewrite both persisted records and digests can forge self-consistent evidence. +This is a candidate classifier only, not proof of durable resume safety or +exactly-once behavior. + +The slice is bounded to roughly one focused day: persist/link the stable retry +window, validate and classify read-only restart evidence, and add a finite +boundary/corruption matrix. Actual resume integration remains a separate slice +because it must reconstruct job and ledger state and compose current execution +authority, atomic one-shot claim, fresh stable-time checks, durable dispatch +marker, and uncertain-outcome quarantine at every asynchronous boundary. O09 +remains a separate dependency gate. ## Finite synthetic restart and crash-point fixtures @@ -238,9 +282,10 @@ durable store/time authority, prove storage authenticity, or satisfy O08. ## Scope estimate and exclusions -The owner-approved local store slice is estimated at 1–2 focused days, including -focused tests and handoff. The complete writable-resume/reconstruction flow is -estimated above that bound and is intentionally split. Production-grade +The owner-approved local store slice was estimated at 1–2 focused days. This +read-only candidate slice is separately bounded to roughly one focused day. +The complete writable-resume/reconstruction flow is estimated above that bound +and is intentionally split. Production-grade persistent storage, an authenticated integrity root, provider-specific deduplication, and O09's result linkage remain separate decisions. This slice does not introduce a provider, alter current retry behavior, close O08, or diff --git a/src/offline-orchestration-prototype/runner.js b/src/offline-orchestration-prototype/runner.js index 86a1551..59e42ed 100644 --- a/src/offline-orchestration-prototype/runner.js +++ b/src/offline-orchestration-prototype/runner.js @@ -39,6 +39,7 @@ const MAX_TIMER_DELAY_MS = 2_147_483_647; const MAX_PROVIDER_RETRY_AFTER_MS = 86_400_000; const RETRY_PROVIDER_CODE = 'RATE_LIMITED_BEFORE_ACCEPTANCE'; const AUTHORITY_CHECK_TIMEOUT_MS = 1000; +const SYNTHETIC_RESUME_TIME_AUTHORITY_ID = 'studio.synthetic.resume-time-v1'; const EXPECTED_EXECUTION_SCOPE = Object.freeze({ production_id: EXPECTED_PRODUCTION_ID, revision: 1, @@ -254,6 +255,17 @@ function eligibleRateLimit(providerResult) { && providerResult.output === undefined; } +function isEligiblePersistedProviderOutcome(providerResult, executionId) { + if (!providerResult || providerResult.kind !== 'execution-result') return false; + try { + return validateExecutionDocument(providerResult).valid + && providerResult.execution_id === executionId + && eligibleRateLimit(providerResult); + } catch { + return false; + } +} + function sameBytes(actual, expected, expectedSha256) { return Buffer.isBuffer(actual) && actual.byteLength === expected.byteLength && digest(actual) === expectedSha256 && actual.equals(expected); @@ -343,7 +355,7 @@ function defaultMockFactory(configuration) { function createRunner({ runtime = defaultRuntime, store = new InMemoryPrototypeStore(), idFactory = randomUUID, mockAdapterFactory = defaultMockFactory, onMockCall, executionAuthorityProvider, - syntheticContextReaders, contextUseAuthorityProvider } = {}) { + syntheticContextReaders, contextUseAuthorityProvider, resumeTimeAuthority } = {}) { if (!executionAuthorityProvider || executionAuthorityProvider.mode !== 'synthetic' || typeof executionAuthorityProvider.id !== 'string' || typeof executionAuthorityProvider.verify !== 'function' @@ -355,6 +367,22 @@ function createRunner({ runtime = defaultRuntime, store = new InMemoryPrototypeS || !validateContextUseProvider(contextUseAuthorityProvider)))) { throw new OfflineOrchestrationError('SYNTHETIC_CONTEXT_AUTHORITY_UNAVAILABLE'); } + let installedResumeTimeAuthority; + if (resumeTimeAuthority !== undefined) { + let configured; + try { + configured = optionValues(resumeTimeAuthority, + new Set(['id', 'mode', 'domain_id', 'epoch_id', 'now']), 'RESUME_TIME_AUTHORITY_UNAVAILABLE'); + } catch { throw new OfflineOrchestrationError('RESUME_TIME_AUTHORITY_UNAVAILABLE'); } + if (configured.id !== SYNTHETIC_RESUME_TIME_AUTHORITY_ID || configured.mode !== 'synthetic' + || typeof configured.domain_id !== 'string' || !SAFE_ID.test(configured.domain_id) + || typeof configured.epoch_id !== 'string' || !SAFE_ID.test(configured.epoch_id) + || typeof configured.now !== 'function') { + throw new OfflineOrchestrationError('RESUME_TIME_AUTHORITY_UNAVAILABLE'); + } + installedResumeTimeAuthority = Object.freeze({ id: configured.id, mode: configured.mode, + domain_id: configured.domain_id, epoch_id: configured.epoch_id, now: configured.now.bind(resumeTimeAuthority) }); + } const verifyExecutionAuthority = executionAuthorityProvider.verify.bind(executionAuthorityProvider); const checkExecutionAuthorityCurrent = executionAuthorityProvider.isCurrent.bind(executionAuthorityProvider); const verifyContextUse = contextUseAuthorityProvider?.verify.bind(contextUseAuthorityProvider); @@ -365,6 +393,17 @@ function createRunner({ runtime = defaultRuntime, store = new InMemoryPrototypeS let openJob; let running = false; const usedIds = new Set(); + const resumeTimeState = { lastMs: undefined }; + + function sampleResumeTime(state) { + if (!installedResumeTimeAuthority) return undefined; + let now; + try { now = installedResumeTimeAuthority.now(); } catch { return undefined; } + if (!Number.isSafeInteger(now) || now < 0 || !Number.isFinite(new Date(now).getTime()) + || (state.lastMs !== undefined && now < state.lastMs)) return undefined; + state.lastMs = now; + return now; + } function authorityClock(state, errorCode = 'EXECUTION_AUTHORITY_UNAVAILABLE') { let now; @@ -637,6 +676,25 @@ function createRunner({ runtime = defaultRuntime, store = new InMemoryPrototypeS job.state = 'attempt-terminal'; const isEligibleRetry = job.attempts.length === 1 && job.retryOpen && eligibleRateLimit(attempt.providerResult) && terminalClock?.epochId === job.clockEpochId && terminalClock.now < job.deadlineMonotonicMs; + if (isEligibleRetry && installedResumeTimeAuthority && !job.contextEnabled + && Number.isSafeInteger(job.resumeDeadlineAtMs)) { + const checkedAt = sampleResumeTime(job.resumeTimeState); + if (checkedAt !== undefined) { + const retryNotBeforeAtMs = checkedAdd(checkedAt, attempt.providerResult.error.retry_after_ms); + if (retryNotBeforeAtMs !== undefined) { + const resumeWindow = event(job.jobId, 'resume-window', { + attempt_id: attempt.attemptId, + execution_id: attempt.executionId, + terminal_result_id: result.result_id, + checked_at_ms: checkedAt, + retry_not_before_at_ms: retryNotBeforeAtMs, + deadline_at_ms: job.resumeDeadlineAtMs + }); + if (!appendConfirmed(store, job.jobId, resumeWindow)) return markUnresolved(job); + job.resumeRetryNotBeforeAtMs = retryNotBeforeAtMs; + } + } + } if (!isEligibleRetry || job.attempts.length >= OFFLINE_ORCHESTRATION_LIMITS.maxAttemptsPerJob) { if (!closeIfTerminal(job, isEligibleRetry ? 'attempt-limit-reached' : 'no-eligible-retry')) return markUnresolved(job); } @@ -1244,6 +1302,8 @@ function createRunner({ runtime = defaultRuntime, store = new InMemoryPrototypeS const production = readProduction(productionSource); let initialClock; let deadlineMonotonicMs; + let resumeTimeStartedAtMs; + let resumeDeadlineAtMs; let contextInput; let contextRequest; if (syntheticContext === true) { @@ -1277,6 +1337,14 @@ function createRunner({ runtime = defaultRuntime, store = new InMemoryPrototypeS if (!initialClock) return freezeDeep({ kind: 'host-outcome', status: 'deadline-unverifiable' }); deadlineMonotonicMs ??= checkedAdd(initialClock.now, OFFLINE_ORCHESTRATION_LIMITS.jobBudgetMs); if (deadlineMonotonicMs === undefined) return freezeDeep({ kind: 'host-outcome', status: 'deadline-unverifiable' }); + if (installedResumeTimeAuthority) { + resumeTimeStartedAtMs = sampleResumeTime(resumeTimeState); + resumeDeadlineAtMs = resumeTimeStartedAtMs === undefined ? undefined + : checkedAdd(resumeTimeStartedAtMs, OFFLINE_ORCHESTRATION_LIMITS.jobBudgetMs); + if (resumeDeadlineAtMs === undefined) { + return freezeDeep({ kind: 'host-outcome', status: 'deadline-unverifiable' }); + } + } const ledger = new MaterialLedger(); const productionBytes = Buffer.from(production.canonical, 'utf8'); @@ -1340,6 +1408,15 @@ function createRunner({ runtime = defaultRuntime, store = new InMemoryPrototypeS if (postAuthorityClock.now >= deadlineMonotonicMs) { return freezeDeep({ kind: 'host-outcome', status: 'budget-exhausted', reason: 'time-before-admission' }); } + if (installedResumeTimeAuthority) { + const postPreflightResumeTime = sampleResumeTime(resumeTimeState); + if (postPreflightResumeTime === undefined) { + return freezeDeep({ kind: 'host-outcome', status: 'deadline-unverifiable' }); + } + if (postPreflightResumeTime >= resumeDeadlineAtMs) { + return freezeDeep({ kind: 'host-outcome', status: 'budget-exhausted', reason: 'time-before-admission' }); + } + } const slotReservation = store.reserveJobSlot(); if (slotReservation === 'reserved') throw new OfflineOrchestrationError('JOB_ALREADY_ACTIVE'); @@ -1364,6 +1441,9 @@ function createRunner({ runtime = defaultRuntime, store = new InMemoryPrototypeS admittedMonotonicMs: initialClock.now, deadlineMonotonicMs, authorityClock: authorityClockState, + resumeTimeState, + resumeTimeStartedAtMs, + resumeDeadlineAtMs, attempts: [], retryOpen: false, retryNotBefore: undefined, @@ -1400,6 +1480,14 @@ function createRunner({ runtime = defaultRuntime, store = new InMemoryPrototypeS admitted_monotonic_ms: initialClock.now, clock_epoch_id: initialClock.epochId, deadline_monotonic_ms: deadlineMonotonicMs, + ...(installedResumeTimeAuthority ? { resume_time: { + authority_id: installedResumeTimeAuthority.id, + domain_id: installedResumeTimeAuthority.domain_id, + epoch_id: installedResumeTimeAuthority.epoch_id, + started_at_ms: resumeTimeStartedAtMs, + deadline_at_ms: resumeDeadlineAtMs, + context_enabled: job.contextEnabled + } } : {}), limits: OFFLINE_ORCHESTRATION_LIMITS, material: ledger.snapshot }); @@ -1507,6 +1595,120 @@ function createRunner({ runtime = defaultRuntime, store = new InMemoryPrototypeS return freezeDeep({ kind: 'host-outcome', status: 'closed-without-retry', job_id: job.jobId }); } + function classifyResumeCandidate(jobId, entries, admitted, verifiedBlobs) { + if (!installedResumeTimeAuthority) return undefined; + 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 !== installedResumeTimeAuthority.id + || timeRecord.domain_id !== installedResumeTimeAuthority.domain_id + || timeRecord.epoch_id !== installedResumeTimeAuthority.epoch_id + || timeRecord.context_enabled !== false + || !Number.isSafeInteger(timeRecord.started_at_ms) || !Number.isFinite(new Date(timeRecord.started_at_ms).getTime()) + || !Number.isSafeInteger(timeRecord.deadline_at_ms) + || timeRecord.deadline_at_ms !== checkedAdd(timeRecord.started_at_ms, OFFLINE_ORCHESTRATION_LIMITS.jobBudgetMs)) { + return undefined; + } + + const prepared = entries.filter(item => item.type === 'prepared'); + const dispatches = entries.filter(item => item.type === 'dispatch-started'); + const outcomes = entries.filter(item => item.type === 'provider-outcome'); + 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'); + const resumeWindows = entries.filter(item => item.type === 'resume-window'); + const expectedTypes = ['admitted', 'prepared', 'dispatch-started', 'provider-outcome', + 'result-prepared', 'persisting', 'terminal', 'resume-window']; + if (entries.length !== expectedTypes.length + || entries.some((item, index) => item.type !== expectedTypes[index]) + || prepared.length !== 1 || dispatches.length !== 1 + || outcomes.length !== 1 || resultPrepared.length !== 1 || persisting.length !== 1 || terminals.length !== 1 + || resumeWindows.length !== 1 + || entries.some(item => ['job-closed', 'contract-mapping-blocked', 'budget-exhausted', 'authorization-blocked'].includes(item.type))) { + return undefined; + } + const first = prepared[0]; + const dispatch = dispatches[0]; + const outcomeRecord = outcomes[0]; + const terminal = terminals[0]; + const resumeWindow = resumeWindows[0]; + const attemptId = first.attempt_id; + const executionId = first.execution_id; + 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)); + if (first.retry_of_attempt_id !== null || !isResourceId(attemptId) + || !isExecutionId(executionId) + || dispatch.attempt_id !== attemptId || dispatch.execution_id !== executionId || dispatch.call_number !== 1 + || outcomeRecord.attempt_id !== attemptId || outcomeRecord.execution_id !== executionId + || resultPrepared[0].attempt_id !== attemptId || persisting[0].attempt_id !== attemptId + || resultPrepared[0].execution_id !== executionId || persisting[0].execution_id !== executionId + || terminal.attempt_id !== attemptId || terminal.execution_id !== executionId + || !isResourceId(terminal.result_id) || resultPrepared[0].status !== 'failed' + || resumeWindow.attempt_id !== attemptId || resumeWindow.execution_id !== executionId + || resumeWindow.terminal_result_id !== terminal.result_id + || !Number.isSafeInteger(resumeWindow.checked_at_ms) || resumeWindow.checked_at_ms < 0 + || !Number.isSafeInteger(resumeWindow.retry_not_before_at_ms) || resumeWindow.retry_not_before_at_ms < 0 + || resumeWindow.deadline_at_ms !== timeRecord.deadline_at_ms) return undefined; + const eventIndices = [entries.indexOf(admitted), entries.indexOf(first), entries.indexOf(dispatch), + entries.indexOf(outcomeRecord), entries.indexOf(resultPrepared[0]), entries.indexOf(persisting[0]), + entries.indexOf(terminal), entries.indexOf(resumeWindow)]; + if (eventIndices.some((value, index) => index > 0 && value <= eventIndices[index - 1])) return undefined; + if (entries.some(item => item.attempt_id !== undefined && item.attempt_id !== attemptId)) return undefined; + + const productionBytes = verifiedBlobs.get(admitted.input_key); + const promptBytes = verifiedBlobs.get(admitted.prompt_key); + const outcomeBytes = verifiedBlobs.get(outcomeRecord.payload_key); + const resultBytes = verifiedBlobs.get(`result:${terminal.result_id}`); + if (!Buffer.isBuffer(productionBytes) || !Buffer.isBuffer(promptBytes) + || !Buffer.isBuffer(outcomeBytes) || !Buffer.isBuffer(resultBytes)) return undefined; + let production; + let providerResult; + let result; + let admittedProduction; + let preparedProduction; + try { + production = readProduction(productionBytes.toString('utf8')); + providerResult = JSON.parse(outcomeBytes.toString('utf8')); + result = JSON.parse(resultBytes.toString('utf8')); + admittedProduction = canonicalJson(admitted.production); + preparedProduction = canonicalJson(first.production); + } catch { return undefined; } + const renderedPrompt = renderOfflineComicPrompt(production.value); + if (!productionBytes.equals(Buffer.from(production.canonical, 'utf8')) + || production.identity.sha256 !== EXPECTED_PRODUCTION_SHA256 + || admittedProduction !== canonicalJson(production.reference) + || preparedProduction !== admittedProduction + || admitted.input_key !== `input:${jobId}` || admitted.prompt_key !== `prompt:${jobId}` + || !promptBytes.equals(Buffer.from(renderedPrompt.canonical, 'utf8')) + || admitted.prompt_sha256 !== renderedPrompt.sha256 + || admitted.no_output_result_version !== '1.1.0' + || !isEligiblePersistedProviderOutcome(providerResult, executionId) + || outcomeRecord.status !== 'failed' + || outcomeRecord.payload_key !== `provider-outcome:${executionId}` + || terminal.result_sha256 !== digest(resultBytes) || terminal.result_byte_size !== resultBytes.byteLength + || resumeWindow.checked_at_ms >= timeRecord.deadline_at_ms + || resultPrepared[0].result_id !== terminal.result_id || persisting[0].result_id !== terminal.result_id + || resultPrepared[0].result_sha256 !== terminal.result_sha256 + || persisting[0].result_sha256 !== terminal.result_sha256 + || resultPrepared[0].result_byte_size !== terminal.result_byte_size + || persisting[0].result_byte_size !== terminal.result_byte_size + || !validateComicBuildResultCandidate(canonicalJson(result), production.canonical).valid + || result.attempt_id !== attemptId || result.result_id !== terminal.result_id || result.status !== 'failed' + || (result.outputs?.length ?? 0) !== 0 + || resumeWindow.retry_not_before_at_ms !== checkedAdd(resumeWindow.checked_at_ms, + providerResult.error.retry_after_ms) + || resumeWindow.checked_at_ms < timeRecord.started_at_ms) return undefined; + + const now = sampleResumeTime(resumeTimeState); + if (now === undefined || now < resumeWindow.checked_at_ms) return { status: 'deadline-unverifiable' }; + if (resumeWindow.retry_not_before_at_ms >= timeRecord.deadline_at_ms) return { status: 'resume-window-empty' }; + if (now >= timeRecord.deadline_at_ms) return { status: 'budget-exhausted' }; + if (now < resumeWindow.retry_not_before_at_ms) return { status: 'retry-delay-not-elapsed' }; + return { status: 'resume-candidate' }; + } + function inspectRecovery(jobId) { if (typeof jobId !== 'string' || !jobId) throw new OfflineOrchestrationError('INVALID_JOB_ID'); let entries; @@ -1521,12 +1723,16 @@ function createRunner({ runtime = defaultRuntime, store = new InMemoryPrototypeS if (!admitted || entries.filter(item => item.type === 'admitted').length !== 1) { return freezeDeep({ kind: 'recovery-inspection', status: 'reconciliation-required', job_id: jobId, read_only: true }); } - const verifyBlob = (key, expectedSize, expectedSha) => { + const verifiedBlobs = new Map(); + const readVerifiedBlob = (key, expectedSize, expectedSha) => { let bytes; try { bytes = store.readImmutable(key); } catch { return false; } - return bytes !== UNKNOWN_STORE_STATE && Buffer.isBuffer(bytes) - && bytes.byteLength === expectedSize && digest(bytes) === expectedSha; + if (bytes === UNKNOWN_STORE_STATE || !Buffer.isBuffer(bytes) + || bytes.byteLength !== expectedSize || digest(bytes) !== expectedSha) return false; + verifiedBlobs.set(key, bytes); + return bytes; }; + 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 }); @@ -1537,12 +1743,8 @@ function createRunner({ runtime = defaultRuntime, store = new InMemoryPrototypeS return freezeDeep({ kind: 'recovery-inspection', status: 'reconciliation-required', job_id: jobId, read_only: true }); } if (item.type === 'persisting' || item.type === 'terminal') { - let resultBytes; - try { resultBytes = store.readImmutable(`result:${item.result_id}`); } catch { - return freezeDeep({ kind: 'recovery-inspection', status: 'reconciliation-required', job_id: jobId, read_only: true }); - } - if (resultBytes === UNKNOWN_STORE_STATE || !Buffer.isBuffer(resultBytes) - || resultBytes.byteLength !== item.result_byte_size || digest(resultBytes) !== item.result_sha256) { + 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 }); } let result; @@ -1567,6 +1769,13 @@ function createRunner({ runtime = defaultRuntime, store = new InMemoryPrototypeS 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 }); } + const resumeClassification = classifyResumeCandidate(jobId, entries, admitted, verifiedBlobs); + if (resumeClassification) { + 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 }); + } const clock = safeClock(runtime); const deadlineUnverifiable = !clock || clock.epochId !== admitted.clock_epoch_id || !Number.isSafeInteger(admitted.deadline_monotonic_ms); diff --git a/tests/offline-orchestration-prototype/resume-candidate.test.js b/tests/offline-orchestration-prototype/resume-candidate.test.js new file mode 100644 index 0000000..5307d51 --- /dev/null +++ b/tests/offline-orchestration-prototype/resume-candidate.test.js @@ -0,0 +1,267 @@ +import assert from 'node:assert/strict'; +import { createHash } from 'node:crypto'; +import { mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'; +import { randomUUID } from 'node:crypto'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import test from 'node:test'; +import { readFile } from 'node:fs/promises'; +import { + createSyntheticExecutionAuthorityVerifier, + SYNTHETIC_EXECUTION_PURPOSE +} from '../../src/offline-orchestration-prototype/execution-authority.js'; +import { + createOfflineOrchestrationPrototypeForTest, + LocalFilePrototypeStore +} from '../../src/offline-orchestration-prototype/testing.js'; +import { canonicalJson } from '../../src/prompt-sdk/index.js'; +import { OFFLINE_ORCHESTRATION_LIMITS } from '../../src/offline-orchestration-prototype/limits.js'; + +const fixture = JSON.parse(await readFile(new URL('../fixtures/comic-manifest-v1.json', import.meta.url), 'utf8')); +const productionSource = JSON.stringify(fixture.production); +const stableStart = Date.parse('2026-11-08T02:40:00Z'); + +function authority() { + const production = { + production_id: 'urn:uuid:10000000-0000-4000-8000-000000000001', + revision: 1, + identity_sha256: 'sha256:9250217ad23125b0356a9e7002f57a55dacf9d982f069caa403b89f8c6c234dc' + }; + const record = (action, suffix) => ({ + decision_id: `20000000-0000-4000-8000-${suffix.padStart(12, '0')}`, + decision: 'allow', action, purpose: SYNTHETIC_EXECUTION_PURPOSE, production, + not_before: '2026-01-01T00:00:00Z', review_after: '2027-01-01T00:00:00Z', + expires_at: '2027-02-01T00:00:00Z', + authority_reference: 'https://github.com/DefinitelySecureStudio/platform/issues/109' + }); + return createSyntheticExecutionAuthorityVerifier([record('execute', '1'), record('retry', '2')]).verifier; +} + +function runtime(epochId = 'original-monotonic-epoch') { + return { + now: () => 10_000, + epochId, + wallNow: () => Date.parse('2026-11-08T02:40:00Z'), + setTimer: () => 1, + clearTimer: () => {} + }; +} + +function resumeAuthority({ domain = 'synthetic-resume-time-v1', epoch = 'fixture-epoch-1', now } = {}) { + return { + id: 'studio.synthetic.resume-time-v1', + mode: 'synthetic', + domain_id: domain, + epoch_id: epoch, + now: now ?? (() => stableStart) + }; +} + +function createRunner(store, { timeAuthority = resumeAuthority(), monotonicEpoch = 'original-monotonic-epoch', onMockCall } = {}) { + return createOfflineOrchestrationPrototypeForTest({ + store, + runtime: runtime(monotonicEpoch), + idFactory: randomUUID, + executionAuthorityProvider: authority(), + resumeTimeAuthority: timeAuthority, + onMockCall + }); +} + +function observeResumeClaims(store) { + const claimResume = store.claimResume.bind(store); + let calls = 0; + store.claimResume = (...args) => { + calls++; + return claimResume(...args); + }; + return () => calls; +} + +function rewriteProviderOutcome(root, jobId, transform) { + const eventPath = join(root, 'events', `${Buffer.from(jobId).toString('base64url')}.jsonl`); + const lines = readFileSync(eventPath, 'utf8').trimEnd().split('\n').map(line => JSON.parse(line)); + const row = lines.find(item => item.type === 'provider-outcome'); + const blobPath = join(root, 'blobs', `${Buffer.from(row.payload_key).toString('base64url')}.blob`); + const value = transform(JSON.parse(readFileSync(blobPath, 'utf8'))); + const bytes = Buffer.from(canonicalJson(value), 'utf8'); + writeFileSync(blobPath, bytes); + row.byte_size = bytes.byteLength; + row.sha256 = `sha256:${createHash('sha256').update(bytes).digest('hex')}`; + writeFileSync(eventPath, `${lines.map(item => canonicalJson(item)).join('\n')}\n`); +} + +async function seedRetryEligible(t, retryAfterMs = 10) { + const root = mkdtempSync(join(tmpdir(), 'dss-o08-resume-candidate-')); + t.after(() => rmSync(root, { recursive: true, force: true })); + const store = new LocalFilePrototypeStore(root); + let providerCalls = 0; + const runner = createRunner(store, { onMockCall: ({ phase }) => { if (phase === 'dispatch-confirmed') providerCalls++; } }); + const result = await runner.submit({ + productionSource, + noOutputResultVersion: '1.1.0', + mockOutcome: { kind: 'rate-limit', retry_after_ms: retryAfterMs } + }); + assert.equal(result.kind, 'terminal'); + assert.equal(result.retry_eligible, true); + const entries = store.readEvents(result.job_id); + const admitted = entries.find(item => item.type === 'admitted'); + const terminal = entries.find(item => item.type === 'terminal'); + const window = entries.find(item => item.type === 'resume-window'); + assert.ok(admitted.resume_time); + assert.equal(typeof window?.retry_not_before_at_ms, 'number'); + assert.equal(providerCalls, 1); + return { root, jobId: result.job_id, store, result, admitted, terminal, window, providerCalls }; +} + +test('reopened local store reports a read-only candidate at the inclusive retry bound', async t => { + const seeded = await seedRetryEligible(t, 10); + const reopened = new LocalFilePrototypeStore(seeded.root); + const resumeClaimCalls = observeResumeClaims(reopened); + const beforeEvents = reopened.eventCount; + const beforeBlobs = reopened.blobCount; + let laterCalls = 0; + const restarted = createRunner(reopened, { + monotonicEpoch: 'new-process-monotonic-epoch', + timeAuthority: resumeAuthority({ now: () => seeded.window.retry_not_before_at_ms }), + onMockCall: () => { laterCalls++; } + }); + + 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.equal(reopened.eventCount, beforeEvents); + assert.equal(reopened.blobCount, beforeBlobs); + assert.equal(resumeClaimCalls(), 0); + assert.equal(laterCalls, 0); + assert.equal(seeded.providerCalls, 1); +}); + +test('read-only resume candidate classification enforces retry and deadline boundaries', async t => { + const early = await seedRetryEligible(t, 10); + const earlyRunner = createRunner(new LocalFilePrototypeStore(early.root), { + monotonicEpoch: 'restart-early', + timeAuthority: resumeAuthority({ now: () => early.window.retry_not_before_at_ms - 1 }) + }); + assert.equal(earlyRunner.inspectRecovery(early.jobId).status, 'retry-delay-not-elapsed'); + + const late = await seedRetryEligible(t, 10); + const deadline = late.admitted.resume_time.deadline_at_ms; + const beforeDeadline = createRunner(new LocalFilePrototypeStore(late.root), { + monotonicEpoch: 'restart-before-deadline', timeAuthority: resumeAuthority({ now: () => deadline - 1 }) + }); + assert.equal(beforeDeadline.inspectRecovery(late.jobId).status, 'resume-candidate'); + const candidateStore = new LocalFilePrototypeStore(late.root); + const resumeClaimCalls = observeResumeClaims(candidateStore); + const repeatedCandidateRunner = createRunner(candidateStore, { + monotonicEpoch: 'restart-repeated-candidate', + timeAuthority: resumeAuthority({ now: () => deadline - 1 }) + }); + assert.equal(repeatedCandidateRunner.inspectRecovery(late.jobId).status, 'resume-candidate'); + assert.equal(resumeClaimCalls(), 0); + const atDeadline = createRunner(new LocalFilePrototypeStore(late.root), { + monotonicEpoch: 'restart-at-deadline', timeAuthority: resumeAuthority({ now: () => deadline }) + }); + assert.equal(atDeadline.inspectRecovery(late.jobId).status, 'budget-exhausted'); + + const empty = await seedRetryEligible(t, OFFLINE_ORCHESTRATION_LIMITS.jobBudgetMs); + const noWindow = createRunner(new LocalFilePrototypeStore(empty.root), { + monotonicEpoch: 'restart-empty-window', timeAuthority: resumeAuthority({ + now: () => empty.window.retry_not_before_at_ms + }) + }); + assert.equal(empty.window.retry_not_before_at_ms, empty.admitted.resume_time.deadline_at_ms); + assert.equal(noWindow.inspectRecovery(empty.jobId).status, 'resume-window-empty'); +}); + +test('unknown or rolled-back stable time never yields a resume candidate', async t => { + const seeded = await seedRetryEligible(t, 10); + for (const [label, provider] of [ + ['domain mismatch', resumeAuthority({ domain: 'different-domain', now: () => stableStart + 100 })], + ['epoch mismatch', resumeAuthority({ epoch: 'different-epoch', now: () => stableStart + 100 })], + ['rollback', resumeAuthority({ now: () => seeded.window.checked_at_ms - 1 })], + ['unavailable', resumeAuthority({ now: () => { throw new Error('fixture unavailable'); } })], + ['non-finite', resumeAuthority({ now: () => Number.NaN })] + ]) await t.test(label, () => { + const restarted = createRunner(new LocalFilePrototypeStore(seeded.root), { + monotonicEpoch: `restart-${label.replaceAll(' ', '-')}`, timeAuthority: provider + }); + assert.equal(restarted.inspectRecovery(seeded.jobId).status, 'deadline-unverifiable'); + }); +}); + +test('repeated read-only inspection detects rollback within the otherwise eligible interval', async t => { + const seeded = await seedRetryEligible(t, 10); + let now = seeded.window.retry_not_before_at_ms + 1; + const store = new LocalFilePrototypeStore(seeded.root); + const resumeClaimCalls = observeResumeClaims(store); + const restarted = createRunner(store, { + monotonicEpoch: 'restart-eligible-time-rollback', + timeAuthority: resumeAuthority({ now: () => now }) + }); + + assert.equal(restarted.inspectRecovery(seeded.jobId).status, 'resume-candidate'); + now--; + assert.equal(now, seeded.window.retry_not_before_at_ms); + assert.equal(restarted.inspectRecovery(seeded.jobId).status, 'deadline-unverifiable'); + assert.equal(resumeClaimCalls(), 0); +}); + +test('corrupt or mismatched persisted resume evidence never yields a candidate', async t => { + const badInput = await seedRetryEligible(t, 10); + const inputPath = join(badInput.root, 'blobs', `${Buffer.from(`input:${badInput.jobId}`).toString('base64url')}.blob`); + writeFileSync(inputPath, Buffer.from('tampered synthetic input')); + const corruptRunner = createRunner(new LocalFilePrototypeStore(badInput.root), { + monotonicEpoch: 'restart-corrupt-input', timeAuthority: resumeAuthority({ now: () => stableStart + 100 }) + }); + assert.equal(corruptRunner.inspectRecovery(badInput.jobId).status, 'reconciliation-required'); + + const badBound = await seedRetryEligible(t, 10); + const resumeWindow = badBound.store.readEvents(badBound.jobId).find(item => item.type === 'resume-window'); + const eventPath = join(badBound.root, 'events', `${Buffer.from(badBound.jobId).toString('base64url')}.jsonl`); + const lines = readFileSync(eventPath, 'utf8').trimEnd().split('\n').map(line => JSON.parse(line)); + const row = lines.find(item => item.type === 'resume-window'); + row.retry_not_before_at_ms++; + writeFileSync(eventPath, `${lines.map(item => canonicalJson(item)).join('\n')}\n`); + assert.equal(resumeWindow.retry_not_before_at_ms + 1, row.retry_not_before_at_ms); + const mismatchRunner = createRunner(new LocalFilePrototypeStore(badBound.root), { + monotonicEpoch: 'restart-bad-retry-bound', timeAuthority: resumeAuthority({ now: () => stableStart + 100 }) + }); + assert.notEqual(mismatchRunner.inspectRecovery(badBound.jobId).status, 'resume-candidate'); +}); + +test('malformed or cross-execution provider outcomes never yield candidates', async t => { + const cases = [ + ['malformed provider outcome', value => ({ ...value, unexpected_field: 'invalid' })], + ['wrong-kind provider document with malformed descriptor field', value => ({ + ...value, kind: 'provider-adapter-descriptor', supported_extensions: 1 + })], + ['malformed same-kind error category', value => ({ + ...value, error: { ...value.error, category: { toString: null } } + })], + ['provider outcome for a different execution', value => ({ + ...value, execution_id: `exec-offline-${randomUUID()}` + })] + ]; + for (const [name, transform] of cases) await t.test(name, async t => { + const seeded = await seedRetryEligible(t, 10); + rewriteProviderOutcome(seeded.root, seeded.jobId, transform); + const store = new LocalFilePrototypeStore(seeded.root); + const resumeClaimCalls = observeResumeClaims(store); + let providerCalls = 0; + const restarted = createRunner(store, { + monotonicEpoch: `restart-${name.replaceAll(' ', '-')}`, + timeAuthority: resumeAuthority({ now: () => seeded.window.retry_not_before_at_ms }), + onMockCall: () => { providerCalls++; } + }); + + const inspected = restarted.inspectRecovery(seeded.jobId); + assert.notEqual(inspected.status, 'resume-candidate'); + assert.equal(inspected.read_only, true); + assert.equal(resumeClaimCalls(), 0); + assert.equal(providerCalls, 0); + }); +});