From c2dd3bf0a9575609252ae4386b7db81b35154dfa Mon Sep 17 00:00:00 2001 From: Andrew Peris Date: Sun, 8 Nov 2026 16:25:03 +0000 Subject: [PATCH 1/3] Add bounded synthetic writable resume path --- docs/o08-durable-resume-decision-packet.md | 59 ++- src/offline-orchestration-prototype/index.js | 4 + src/offline-orchestration-prototype/runner.js | 287 +++++++++++- .../resume-candidate.test.js | 428 +++++++++++++++++- .../runner.test.js | 2 +- 5 files changed, 753 insertions(+), 27 deletions(-) diff --git a/docs/o08-durable-resume-decision-packet.md b/docs/o08-durable-resume-decision-packet.md index 4cf976e..2c137ac 100644 --- a/docs/o08-durable-resume-decision-packet.md +++ b/docs/o08-durable-resume-decision-packet.md @@ -15,10 +15,10 @@ 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 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 ordinary prototype defaults to in-memory state and monotonic retry timing. +The opt-in local-file store supplies the durable primitives used by the +no-context resume path below. The job deadline and same-process 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 @@ -185,8 +185,46 @@ 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 classifier by itself is not proof of durable resume safety or exactly-once +behavior; the separately bounded runtime slice below adds a narrow synthetic +resume path, without making either broader claim. + +## Narrow no-context writable resume slice — 2026-11-08 + +The experimental prototype now exposes `resume({ jobId, authorizeResume: true, +signal?, mockOutcome? })` when constructed with an explicit `LocalFilePrototypeStore`, +execution authority provider, and synthetic resume-time authority. No local +wall-clock substitution is permitted for cross-restart eligibility. The new +JavaScript method and local-store export are experimental; no wire schema or +production service contract is added. + +Resume first reads only lifecycle routing metadata and checks that it names the +single pinned, no-context, first-attempt rate-limit candidate. It verifies +current retry authority and stable time before an atomic one-shot claim. A +missing, held, malformed, or uncertain claim fails closed. After claim, it +rechecks authority/time before reading protected input, prompt, provider +outcome, and result blobs; the guard is repeated around each synchronous blob +read. It validates the exact prior outcome/result evidence, reconstructs the +material ledger from the verified blobs, and performs mock preflight. After the +awaited preflight it rechecks authority and the original time interval. + +The existing attempt path creates a new attempt and idempotency key, writes +the durable `dispatch-started` marker before the mock effect, then performs the +final current-authority/time and pinned-evidence checks immediately before the +single mock call. The persisted deadline and retry bound are unchanged, and +the event history enforces a maximum of two attempts. Any acquired claim is +never released or taken over. Uncertain marker, evidence, or outcome writes +remain quarantined; a restart cannot replay them. This is bounded at-most-one +mock invocation for this claimed attempt, not provider-level deduplication or +generic exactly-once behavior. + +Tests cover explicit authorization, authority denial before claim, revocation +during claim/preflight, retry and deadline boundaries, concurrent callers, +unknown claims, final evidence uncertainty, marker uncertainty, uncertain +provider-outcome persistence, successful attempt-two linkage, and repeated +resume. Context-enabled recovery, live providers, production data, automatic +claim takeover, and O09 remain out of scope. O08 stays open pending remaining +criteria and independent review. 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 @@ -282,10 +320,11 @@ durable store/time authority, prove storage authenticity, or satisfy O08. ## Scope estimate and exclusions -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 +The owner-approved local store slice was estimated at 1–2 focused days. The +read-only candidate slice was separately bounded to roughly one focused day. +The no-context writable slice above is likewise narrow; the broader O08 +durable-resume acceptance remains incomplete and subject to independent review. +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/index.js b/src/offline-orchestration-prototype/index.js index f75b88c..ac4b853 100644 --- a/src/offline-orchestration-prototype/index.js +++ b/src/offline-orchestration-prototype/index.js @@ -5,6 +5,10 @@ export { export { OFFLINE_ORCHESTRATION_LIMITS } from './limits.js'; +export { + LocalFilePrototypeStore, + LOCAL_FILE_STORE_TRUST_BOUNDARY +} from './local-file-store.js'; export { createSyntheticExecutionAuthorityVerifier, SYNTHETIC_EXECUTION_PURPOSE, diff --git a/src/offline-orchestration-prototype/runner.js b/src/offline-orchestration-prototype/runner.js index 59e42ed..a7ac10c 100644 --- a/src/offline-orchestration-prototype/runner.js +++ b/src/offline-orchestration-prototype/runner.js @@ -20,6 +20,7 @@ import { OFFLINE_ORCHESTRATION_LIMITS } from './limits.js'; import { InMemoryPrototypeStore, UNKNOWN_STORE_STATE } from './memory-store.js'; +import { LocalFilePrototypeStore } from './local-file-store.js'; import { renderOfflineComicPrompt } from './prompt.js'; import { SYNTHETIC_EXECUTION_PURPOSE, validateExecutionAuthorityEvidence @@ -382,6 +383,9 @@ function createRunner({ runtime = defaultRuntime, store = new InMemoryPrototypeS } installedResumeTimeAuthority = Object.freeze({ id: configured.id, mode: configured.mode, domain_id: configured.domain_id, epoch_id: configured.epoch_id, now: configured.now.bind(resumeTimeAuthority) }); + if (!(store instanceof LocalFilePrototypeStore)) { + throw new OfflineOrchestrationError('RESUME_STORE_UNAVAILABLE'); + } } const verifyExecutionAuthority = executionAuthorityProvider.verify.bind(executionAuthorityProvider); const checkExecutionAuthorityCurrent = executionAuthorityProvider.isCurrent.bind(executionAuthorityProvider); @@ -572,6 +576,12 @@ function createRunner({ runtime = defaultRuntime, store = new InMemoryPrototypeS if (contextFailure) return 'authority'; } if (currentPermitTimeFailure(evidence, contextEvidence, job.authorityClock)) return 'authority'; + if (job.resumeTimeBounds) { + const resumeNow = sampleResumeTime(job.resumeTimeState); + if (resumeNow === undefined) return 'resume-time-unverifiable'; + if (resumeNow < job.resumeTimeBounds.retryNotBeforeAtMs) return 'resume-delay'; + if (resumeNow >= job.resumeTimeBounds.deadlineAtMs) return 'resume-deadline'; + } const after = safeClock(runtime); if (!after || after.epochId !== job.clockEpochId) return 'clock-unverifiable'; if (deadlineExpired || after.now >= job.deadlineMonotonicMs) return 'time'; @@ -865,11 +875,19 @@ function createRunner({ runtime = defaultRuntime, store = new InMemoryPrototypeS if (!prior?.terminalResult || !eligibleRateLimit(prior.providerResult)) return false; const result = stableResult(prior.terminalResult); const outcome = stableResult(prior.providerResult); + const readPinned = (key, bytes, sha) => { + try { + job.resumeBoundary?.(); + const valid = readBackBlob(key, bytes, sha); + job.resumeBoundary?.(); + return valid; + } catch { return false; } + }; if (!validateComicBuildResultCandidate(result.source, job.production.canonical).valid - || !readBackBlob(`input:${job.jobId}`, Buffer.from(job.production.canonical), job.production.identity.sha256) - || !readBackBlob(`prompt:${job.jobId}`, job.promptBytes, job.renderedPrompt.sha256) - || !readBackBlob(`result:${prior.resultId}`, result.bytes, result.sha256) - || !readBackBlob(`provider-outcome:${prior.executionId}`, outcome.bytes, outcome.sha256)) return false; + || !readPinned(`input:${job.jobId}`, Buffer.from(job.production.canonical), job.production.identity.sha256) + || !readPinned(`prompt:${job.jobId}`, job.promptBytes, job.renderedPrompt.sha256) + || !readPinned(`result:${prior.resultId}`, result.bytes, result.sha256) + || !readPinned(`provider-outcome:${prior.executionId}`, outcome.bytes, outcome.sha256)) return false; let entries; try { entries = store.readEvents(job.jobId); } catch { return false; } if (!Array.isArray(entries) || entries.some(e => ['job-closed', 'contract-mapping-blocked'].includes(e.type))) return false; @@ -1580,6 +1598,233 @@ function createRunner({ runtime = defaultRuntime, store = new InMemoryPrototypeS } } + function readResumeRoutingMetadata(jobId) { + let entries; + try { entries = store.readEvents(jobId); } catch { + return { status: 'reconciliation-required' }; + } + const expectedTypes = ['admitted', 'prepared', 'dispatch-started', 'provider-outcome', + 'result-prepared', 'persisting', 'terminal', 'resume-window']; + if (entries === UNKNOWN_STORE_STATE || !Array.isArray(entries) || entries.length !== expectedTypes.length + || entries.some((item, index) => item.type !== expectedTypes[index])) { + return { status: 'resume-not-eligible' }; + } + const [admitted, prepared, dispatch, outcome, resultPrepared, persisting, terminal, resumeWindow] = entries; + const timeRecord = admitted.resume_time; + const timeKeys = 'authority_id|context_enabled|deadline_at_ms|domain_id|epoch_id|started_at_ms'; + const attemptId = prepared.attempt_id; + const executionId = prepared.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 (!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.isSafeInteger(timeRecord.deadline_at_ms) + || timeRecord.deadline_at_ms !== checkedAdd(timeRecord.started_at_ms, OFFLINE_ORCHESTRATION_LIMITS.jobBudgetMs) + || admitted.production?.production_id !== EXPECTED_PRODUCTION_ID + || admitted.production?.revision !== 1 + || admitted.production?.identity?.sha256 !== EXPECTED_PRODUCTION_SHA256 + || admitted.no_output_result_version !== '1.1.0' + || prepared.retry_of_attempt_id !== null || !isResourceId(attemptId) || !isExecutionId(executionId) + || dispatch.attempt_id !== attemptId || dispatch.execution_id !== executionId || dispatch.call_number !== 1 + || outcome.attempt_id !== attemptId || outcome.execution_id !== executionId || outcome.status !== 'failed' + || outcome.payload_key !== `provider-outcome:${executionId}` + || resultPrepared.attempt_id !== attemptId || resultPrepared.execution_id !== executionId + || resultPrepared.status !== 'failed' + || persisting.attempt_id !== attemptId || persisting.execution_id !== executionId + || terminal.attempt_id !== attemptId || terminal.execution_id !== executionId + || !isResourceId(terminal.result_id) + || resumeWindow.attempt_id !== attemptId || resumeWindow.execution_id !== executionId + || resumeWindow.terminal_result_id !== terminal.result_id + || resumeWindow.deadline_at_ms !== timeRecord.deadline_at_ms + || !Number.isSafeInteger(resumeWindow.checked_at_ms) || resumeWindow.checked_at_ms < timeRecord.started_at_ms + || !Number.isSafeInteger(resumeWindow.retry_not_before_at_ms) + || resumeWindow.retry_not_before_at_ms < 0 + || resumeWindow.checked_at_ms >= timeRecord.deadline_at_ms) { + return { status: 'resume-not-eligible' }; + } + if (resumeWindow.retry_not_before_at_ms >= timeRecord.deadline_at_ms) { + return { status: 'resume-window-empty' }; + } + return { status: 'metadata-candidate', entries, admitted, prepared, dispatch, outcome, + resultPrepared, persisting, terminal, resumeWindow, timeRecord }; + } + + function resumeTimeStatus(bounds, state) { + const now = sampleResumeTime(state); + if (now === undefined) return { status: 'deadline-unverifiable' }; + if (now < bounds.retryNotBeforeAtMs) return { status: 'retry-delay-not-elapsed' }; + if (now >= bounds.deadlineAtMs) return { status: 'budget-exhausted' }; + return { status: 'eligible', now }; + } + + async function resume(options = {}) { + const { jobId, authorizeResume, signal, mockOutcome } = optionValues( + options, new Set(['jobId', 'authorizeResume', 'signal', 'mockOutcome']), 'INVALID_RESUME_OPTIONS' + ); + if (typeof jobId !== 'string' || !jobId) throw new OfflineOrchestrationError('INVALID_JOB_ID'); + if (authorizeResume !== true) throw new OfflineOrchestrationError('EXPLICIT_RESUME_AUTHORIZATION_REQUIRED'); + if (!installedResumeTimeAuthority || typeof store.claimResume !== 'function') { + throw new OfflineOrchestrationError('RESUME_AUTHORITY_OR_CLAIM_UNAVAILABLE'); + } + if (running || (openJob && !openJob.closed)) throw new OfflineOrchestrationError('JOB_ALREADY_ACTIVE'); + const cancellation = cancellationSignal(signal); + if (cancellation?.aborted) return freezeDeep({ kind: 'resume-outcome', status: 'resume-cancelled', job_id: jobId }); + let configuration; + try { mockConfiguration(mockOutcome, { transcript: '' }); } + catch { throw new OfflineOrchestrationError('INVALID_MOCK_OUTCOME'); } + + running = true; + const authorityState = { lastMs: undefined }; + const timeBounds = { retryNotBeforeAtMs: undefined, deadlineAtMs: undefined }; + let authorityEvidence; + let monotonic; + try { + const routing = readResumeRoutingMetadata(jobId); + if (routing.status !== 'metadata-candidate') { + return freezeDeep({ kind: 'resume-outcome', status: routing.status, job_id: jobId }); + } + timeBounds.retryNotBeforeAtMs = routing.resumeWindow.retry_not_before_at_ms; + timeBounds.deadlineAtMs = routing.timeRecord.deadline_at_ms; + const firstTime = resumeTimeStatus(timeBounds, resumeTimeState); + if (firstTime.status !== 'eligible') { + return freezeDeep({ kind: 'resume-outcome', status: firstTime.status, job_id: jobId }); + } + monotonic = safeClock(runtime); + if (!monotonic) return freezeDeep({ kind: 'resume-outcome', status: 'deadline-unverifiable', job_id: jobId }); + + try { authorityEvidence = await requireExecutionAuthority('retry', cancellation, authorityState); } + catch { return freezeDeep({ kind: 'resume-outcome', status: 'execution-authority-denied', job_id: jobId }); } + let failure = currentAuthorityFailure(authorityEvidence, 'retry', cancellation, authorityState); + if (failure) return freezeDeep({ kind: 'resume-outcome', status: 'execution-authority-denied', job_id: jobId }); + const afterAuthorityTime = resumeTimeStatus(timeBounds, resumeTimeState); + if (afterAuthorityTime.status !== 'eligible') { + return freezeDeep({ kind: 'resume-outcome', status: afterAuthorityTime.status, job_id: jobId }); + } + + let claim; + try { claim = store.claimResume(jobId); } catch { claim = { status: 'unknown' }; } + if (claim?.status === 'held') { + return freezeDeep({ kind: 'resume-outcome', status: 'resume-claim-held', job_id: jobId }); + } + if (claim?.status !== 'acquired' || !UUID.test(claim.claim_id ?? '')) { + return freezeDeep({ kind: 'resume-outcome', status: 'reconciliation-required', job_id: jobId }); + } + + try { authorityEvidence = await requireExecutionAuthority('retry', cancellation, authorityState); } + catch { return freezeDeep({ kind: 'resume-outcome', status: 'execution-authority-denied', job_id: jobId }); } + failure = currentAuthorityFailure(authorityEvidence, 'retry', cancellation, authorityState); + if (failure) return freezeDeep({ kind: 'resume-outcome', status: 'execution-authority-denied', job_id: jobId }); + const postClaimTime = resumeTimeStatus(timeBounds, resumeTimeState); + if (postClaimTime.status !== 'eligible') { + return freezeDeep({ kind: 'resume-outcome', status: postClaimTime.status, job_id: jobId }); + } + + const currentResumeBoundary = () => { + const authorityFailure = currentAuthorityFailure(authorityEvidence, 'retry', cancellation, authorityState); + if (authorityFailure) throw new OfflineOrchestrationError('EXECUTION_AUTHORITY_DENIED'); + const currentTime = resumeTimeStatus(timeBounds, resumeTimeState); + if (currentTime.status !== 'eligible') throw new OfflineOrchestrationError(currentTime.status); + const clock = safeClock(runtime); + const currentDeadline = checkedAdd(monotonic.now, timeBounds.deadlineAtMs - postClaimTime.now); + if (!clock || clock.epochId !== monotonic.epochId || currentDeadline === undefined + || clock.now >= currentDeadline) { + throw new OfflineOrchestrationError('EXECUTION_DEADLINE_EXPIRED'); + } + }; + let candidate; + let inspection; + try { + inspection = inspectRecoveryCore(jobId, { + beforeProtectedRead: currentResumeBoundary, + onCandidate: value => { candidate = value; } + }); + currentResumeBoundary(); + } catch { + return freezeDeep({ kind: 'resume-outcome', status: 'reconciliation-required', job_id: jobId }); + } + if (inspection.status !== 'resume-candidate' || !candidate) { + return freezeDeep({ kind: 'resume-outcome', status: 'resume-not-eligible', job_id: jobId }); + } + + const remainingMs = timeBounds.deadlineAtMs - postClaimTime.now; + const deadlineMonotonicMs = checkedAdd(monotonic.now, remainingMs); + if (deadlineMonotonicMs === undefined) { + return freezeDeep({ kind: 'resume-outcome', status: 'deadline-unverifiable', job_id: jobId }); + } + const ledger = new MaterialLedger(); + if (!ledger.charge(`input:${candidate.production.identity.sha256}`, candidate.productionBytes.byteLength) + || !ledger.charge(`prompt:${candidate.renderedPrompt.sha256}`, candidate.promptBytes.byteLength) + || !ledger.charge(`provider-outcome:${digest(candidate.outcomeBytes)}`, candidate.outcomeBytes.byteLength) + || !ledger.charge(`result:${digest(candidate.resultBytes)}`, candidate.resultBytes.byteLength)) { + return freezeDeep({ kind: 'resume-outcome', status: 'budget-exhausted', job_id: jobId }); + } + + let mock; + let descriptor; + try { + configuration = mockConfiguration(mockOutcome, candidate.production.value.renditions[0]); + mock = mockAdapterFactory(configuration); + if (!(mock instanceof MockTextAdapter)) throw new TypeError(); + descriptor = await mock.describe(); + } catch { + return freezeDeep({ kind: 'resume-outcome', status: 'mock-preflight-failed', job_id: jobId }); + } + if (!validateExecutionDocument(descriptor).valid) { + return freezeDeep({ kind: 'resume-outcome', status: 'mock-preflight-failed', job_id: jobId }); + } + try { authorityEvidence = await requireExecutionAuthority('retry', cancellation, authorityState); } + catch { return freezeDeep({ kind: 'resume-outcome', status: 'execution-authority-denied', job_id: jobId }); } + failure = currentAuthorityFailure(authorityEvidence, 'retry', cancellation, authorityState); + if (failure) return freezeDeep({ kind: 'resume-outcome', status: 'execution-authority-denied', job_id: jobId }); + const postPreflightTime = resumeTimeStatus(timeBounds, resumeTimeState); + if (postPreflightTime.status !== 'eligible') { + return freezeDeep({ kind: 'resume-outcome', status: postPreflightTime.status, job_id: jobId }); + } + + const priorAttempt = { + attemptId: candidate.attemptId, + executionId: candidate.executionId, + resultId: candidate.terminal.result_id, + terminalResult: candidate.result, + providerResult: candidate.providerResult, + providerCorrelationId: candidate.providerResult.correlation_id, + completedMonotonicMs: undefined, + state: 'terminal' + }; + for (const value of [jobId, candidate.attemptId, candidate.executionId, priorAttempt.resultId]) { + const token = value.startsWith('urn:uuid:') ? value.slice(9) + : value.startsWith('exec-offline-') ? value.slice(13) : value; + if (UUID.test(token)) usedIds.add(token); + } + const job = { + jobId, production: candidate.production, noOutputResultVersion: '1.1.0', + contextEnabled: false, contextUseRequest: undefined, contextUseEvidence: undefined, + renderedPrompt: candidate.renderedPrompt, promptBytes: candidate.promptBytes, + ledger, attempts: [priorAttempt], lastAttempt: priorAttempt, retryOpen: true, + retryNotBefore: undefined, state: 'retry-eligible', closed: false, + clockEpochId: monotonic.epochId, admittedMonotonicMs: monotonic.now, + deadlineMonotonicMs, authorityClock: authorityState, + resumeTimeState, resumeTimeBounds: timeBounds, + resumeAuthorityEvidence: authorityEvidence + }; + job.resumeBoundary = currentResumeBoundary; + openJob = job; + return await performAttempt(job, { + correlationId: priorAttempt.providerCorrelationId, + mockOutcome, signal: cancellation, retryOfAttemptId: priorAttempt.attemptId, + preflight: { mock, descriptor }, authorizationAction: 'retry' + }); + } finally { + running = false; + } + } + function closeJob() { if (running) throw new OfflineOrchestrationError('JOB_ALREADY_ACTIVE'); const job = openJob; @@ -1706,10 +1951,18 @@ function createRunner({ runtime = defaultRuntime, store = new InMemoryPrototypeS 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' }; + return { + status: 'resume-candidate', + candidate: { + admitted, first, outcomeRecord, terminal, resumeWindow, + production, renderedPrompt, providerResult, result, + productionBytes, promptBytes, outcomeBytes, resultBytes, + attemptId, executionId + } + }; } - function inspectRecovery(jobId) { + function inspectRecoveryCore(jobId, { beforeProtectedRead, onCandidate } = {}) { if (typeof jobId !== 'string' || !jobId) throw new OfflineOrchestrationError('INVALID_JOB_ID'); let entries; try { entries = store.readEvents(jobId); } catch { @@ -1725,8 +1978,12 @@ function createRunner({ runtime = defaultRuntime, store = new InMemoryPrototypeS } const verifiedBlobs = new Map(); const readVerifiedBlob = (key, expectedSize, expectedSha) => { + beforeProtectedRead?.(); let bytes; - try { bytes = store.readImmutable(key); } catch { return false; } + let readFailed = false; + try { bytes = store.readImmutable(key); } catch { readFailed = true; } + beforeProtectedRead?.(); + if (readFailed) return false; if (bytes === UNKNOWN_STORE_STATE || !Buffer.isBuffer(bytes) || bytes.byteLength !== expectedSize || digest(bytes) !== expectedSha) return false; verifiedBlobs.set(key, bytes); @@ -1771,6 +2028,7 @@ function createRunner({ runtime = defaultRuntime, store = new InMemoryPrototypeS } 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, @@ -1793,12 +2051,21 @@ function createRunner({ runtime = defaultRuntime, store = new InMemoryPrototypeS }); } - return Object.freeze({ submit, retry, closeJob, inspectRecovery }); + function inspectRecovery(jobId) { + return inspectRecoveryCore(jobId); + } + + return Object.freeze({ submit, retry, resume, closeJob, inspectRecovery }); } export function createOfflineOrchestrationPrototype({ executionAuthorityProvider, syntheticContextReaders, - contextUseAuthorityProvider } = {}) { - return createRunner({ executionAuthorityProvider, syntheticContextReaders, contextUseAuthorityProvider }); + contextUseAuthorityProvider, resumeTimeAuthority, store } = {}) { + if ((store !== undefined && !(store instanceof LocalFilePrototypeStore)) + || (resumeTimeAuthority !== undefined && !(store instanceof LocalFilePrototypeStore))) { + throw new OfflineOrchestrationError('RESUME_STORE_UNAVAILABLE'); + } + return createRunner({ executionAuthorityProvider, syntheticContextReaders, contextUseAuthorityProvider, + resumeTimeAuthority, store }); } /** Internal factory for deterministic tests; never exported from the package entry point. */ diff --git a/tests/offline-orchestration-prototype/resume-candidate.test.js b/tests/offline-orchestration-prototype/resume-candidate.test.js index 5307d51..5872187 100644 --- a/tests/offline-orchestration-prototype/resume-candidate.test.js +++ b/tests/offline-orchestration-prototype/resume-candidate.test.js @@ -6,14 +6,16 @@ import { tmpdir } from 'node:os'; import { join } from 'node:path'; import test from 'node:test'; import { readFile } from 'node:fs/promises'; -import { - createSyntheticExecutionAuthorityVerifier, +import { createSyntheticExecutionAuthorityVerifier, SYNTHETIC_EXECUTION_PURPOSE } from '../../src/offline-orchestration-prototype/execution-authority.js'; +import { createOfflineOrchestrationPrototype } from '../../src/offline-orchestration-prototype/index.js'; +import { MockTextAdapter } from '../../src/prompt-sdk/index.js'; import { createOfflineOrchestrationPrototypeForTest, LocalFilePrototypeStore } from '../../src/offline-orchestration-prototype/testing.js'; +import { UNKNOWN_STORE_STATE } from '../../src/offline-orchestration-prototype/memory-store.js'; import { canonicalJson } from '../../src/prompt-sdk/index.js'; import { OFFLINE_ORCHESTRATION_LIMITS } from '../../src/offline-orchestration-prototype/limits.js'; @@ -34,7 +36,7 @@ function authority() { 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; + return createSyntheticExecutionAuthorityVerifier([record('execute', '1'), record('retry', '2')]); } function runtime(epochId = 'original-monotonic-epoch') { @@ -57,13 +59,15 @@ function resumeAuthority({ domain = 'synthetic-resume-time-v1', epoch = 'fixture }; } -function createRunner(store, { timeAuthority = resumeAuthority(), monotonicEpoch = 'original-monotonic-epoch', onMockCall } = {}) { +function createRunner(store, { timeAuthority = resumeAuthority(), monotonicEpoch = 'original-monotonic-epoch', + onMockCall, executionAuthorityProvider, mockAdapterFactory, runtimeOverride } = {}) { return createOfflineOrchestrationPrototypeForTest({ store, - runtime: runtime(monotonicEpoch), + runtime: runtimeOverride ?? runtime(monotonicEpoch), idFactory: randomUUID, - executionAuthorityProvider: authority(), + executionAuthorityProvider: executionAuthorityProvider ?? authority().verifier, resumeTimeAuthority: timeAuthority, + mockAdapterFactory, onMockCall }); } @@ -265,3 +269,415 @@ test('malformed or cross-execution provider outcomes never yield candidates', as assert.equal(providerCalls, 0); }); }); + +test('explicit writable resume uses a one-shot claim and appends attempt two before one mock call', async t => { + const seeded = await seedRetryEligible(t, 10); + const store = new LocalFilePrototypeStore(seeded.root); + const resumeClaimCalls = observeResumeClaims(store); + const callObservations = []; + const resumed = createRunner(store, { + monotonicEpoch: 'resume-happy-path', + timeAuthority: resumeAuthority({ now: () => seeded.window.retry_not_before_at_ms }), + onMockCall({ phase, mock, executionId }) { + if (phase === 'dispatch-confirmed') { + callObservations.push({ executionId, existingCalls: mock.calls.length, + dispatches: store.readEvents(seeded.jobId).filter(item => item.type === 'dispatch-started').length }); + } + } + }); + + const result = await resumed.resume({ jobId: seeded.jobId, authorizeResume: true }); + assert.equal(result.kind, 'terminal'); + assert.equal(result.retry_eligible, false); + assert.equal(resumeClaimCalls(), 1); + assert.equal(callObservations.length, 1); + assert.equal(callObservations[0].existingCalls, 0); + assert.equal(callObservations[0].dispatches, 2); + assert.notEqual(callObservations[0].executionId, seeded.result.execution_id); + assert.equal(resumed.inspectRecovery(seeded.jobId).status, 'terminal'); + + const entries = store.readEvents(seeded.jobId); + const prepared = entries.filter(item => item.type === 'prepared'); + const dispatches = entries.filter(item => item.type === 'dispatch-started'); + assert.equal(prepared.length, 2); + assert.equal(prepared[1].retry_of_attempt_id, prepared[0].attempt_id); + assert.equal(dispatches.length, 2); + assert.equal(dispatches[1].execution_id, prepared[1].execution_id); + assert.equal(entries.filter(item => item.type === 'resume-window').length, 1); + assert.equal(entries.find(item => item.type === 'resume-window').retry_not_before_at_ms, + seeded.window.retry_not_before_at_ms); + assert.equal(entries.find(item => item.type === 'admitted').resume_time.deadline_at_ms, + seeded.admitted.resume_time.deadline_at_ms); + assert.equal(store.claimResume(seeded.jobId).status, 'held'); + + const repeat = await resumed.resume({ jobId: seeded.jobId, authorizeResume: true }); + assert.notEqual(repeat.status, 'terminal'); + assert.equal(callObservations.length, 1); +}); + +test('public prototype can resume a candidate only with an installed local store and synthetic time authority', async t => { + const seeded = await seedRetryEligible(t, 10); + const prototype = createOfflineOrchestrationPrototype({ + store: new LocalFilePrototypeStore(seeded.root), + executionAuthorityProvider: authority().verifier, + resumeTimeAuthority: resumeAuthority({ now: () => seeded.window.retry_not_before_at_ms }) + }); + const result = await prototype.resume({ jobId: seeded.jobId, authorizeResume: true }); + assert.equal(result.kind, 'terminal'); + assert.equal(prototype.inspectRecovery(seeded.jobId).status, 'terminal'); + assert.throws(() => createOfflineOrchestrationPrototype({ + executionAuthorityProvider: authority().verifier, + resumeTimeAuthority: resumeAuthority() + }), error => error.code === 'RESUME_STORE_UNAVAILABLE'); +}); + +test('resume requires explicit intent and current authority before claim or protected reads', async t => { + const seeded = await seedRetryEligible(t, 10); + const store = new LocalFilePrototypeStore(seeded.root); + const claimCalls = observeResumeClaims(store); + const originalRead = store.readImmutable.bind(store); + let protectedReads = 0; + store.readImmutable = key => { protectedReads++; return originalRead(key); }; + let providerCalls = 0; + const runner = createRunner(store, { + timeAuthority: resumeAuthority({ now: () => seeded.window.retry_not_before_at_ms }), + onMockCall: ({ phase }) => { if (phase === 'dispatch-confirmed') providerCalls++; } + }); + + await assert.rejects(() => runner.resume({ jobId: seeded.jobId }), + error => error.code === 'EXPLICIT_RESUME_AUTHORIZATION_REQUIRED'); + assert.equal(claimCalls(), 0); + assert.equal(protectedReads, 0); + assert.equal(providerCalls, 0); + + const deniedAuthority = authority(); + deniedAuthority.revoke('20000000-0000-4000-8000-000000000002'); + const deniedRunner = createRunner(store, { + timeAuthority: resumeAuthority({ now: () => seeded.window.retry_not_before_at_ms }), + executionAuthorityProvider: deniedAuthority.verifier, + onMockCall: ({ phase }) => { if (phase === 'dispatch-confirmed') providerCalls++; } + }); + const denied = await deniedRunner.resume({ jobId: seeded.jobId, authorizeResume: true }); + assert.equal(denied.status, 'execution-authority-denied'); + assert.equal(claimCalls(), 0); + assert.equal(protectedReads, 0); + assert.equal(providerCalls, 0); +}); + +test('resume time boundaries stop before claim, protected reads, or provider calls', async t => { + const seeded = await seedRetryEligible(t, 10); + for (const [label, now, expected] of [ + ['before retry bound', seeded.window.retry_not_before_at_ms - 1, 'retry-delay-not-elapsed'], + ['at original deadline', seeded.admitted.resume_time.deadline_at_ms, 'budget-exhausted'] + ]) await t.test(label, async t => { + const store = new LocalFilePrototypeStore(seeded.root); + const claimCalls = observeResumeClaims(store); + let protectedReads = 0; + const originalRead = store.readImmutable.bind(store); + store.readImmutable = key => { protectedReads++; return originalRead(key); }; + let providerCalls = 0; + const runner = createRunner(store, { + monotonicEpoch: `resume-${label.replaceAll(' ', '-')}`, + timeAuthority: resumeAuthority({ now: () => now }), + onMockCall: ({ phase }) => { if (phase === 'dispatch-confirmed') providerCalls++; } + }); + const result = await runner.resume({ jobId: seeded.jobId, authorizeResume: true }); + assert.equal(result.status, expected); + assert.equal(claimCalls(), 0); + assert.equal(protectedReads, 0); + assert.equal(providerCalls, 0); + }); +}); + +test('concurrent resume calls share one atomic claim and make at most one provider call', async t => { + const seeded = await seedRetryEligible(t, 10); + const firstStore = new LocalFilePrototypeStore(seeded.root); + const secondStore = new LocalFilePrototypeStore(seeded.root); + let providerCalls = 0; + const timeAuthority = resumeAuthority({ now: () => seeded.window.retry_not_before_at_ms }); + const first = createRunner(firstStore, { + monotonicEpoch: 'resume-racer-one', timeAuthority, + onMockCall: ({ phase }) => { if (phase === 'dispatch-confirmed') providerCalls++; } + }); + const second = createRunner(secondStore, { + monotonicEpoch: 'resume-racer-two', timeAuthority, + onMockCall: ({ phase }) => { if (phase === 'dispatch-confirmed') providerCalls++; } + }); + const results = await Promise.all([ + first.resume({ jobId: seeded.jobId, authorizeResume: true }), + second.resume({ jobId: seeded.jobId, authorizeResume: true }) + ]); + assert.equal(results.filter(result => result.kind === 'terminal').length, 1); + assert.equal(results.filter(result => result.status === 'resume-claim-held').length, 1); + assert.equal(providerCalls, 1); +}); + +test('revocation during claim acquisition stops before any protected read or provider call', async t => { + const seeded = await seedRetryEligible(t, 10); + const store = new LocalFilePrototypeStore(seeded.root); + const claimResume = store.claimResume.bind(store); + let claimCalls = 0; + store.claimResume = jobId => { + claimCalls++; + const claim = claimResume(jobId); + if (claim.status === 'acquired') executionAuthority.revoke('20000000-0000-4000-8000-000000000002'); + return claim; + }; + let protectedReads = 0; + const originalRead = store.readImmutable.bind(store); + store.readImmutable = key => { protectedReads++; return originalRead(key); }; + let providerCalls = 0; + const executionAuthority = authority(); + const runner = createRunner(store, { + timeAuthority: resumeAuthority({ now: () => seeded.window.retry_not_before_at_ms }), + executionAuthorityProvider: executionAuthority.verifier, + onMockCall: ({ phase }) => { if (phase === 'dispatch-confirmed') providerCalls++; } + }); + const result = await runner.resume({ jobId: seeded.jobId, authorizeResume: true }); + assert.equal(result.status, 'execution-authority-denied'); + assert.equal(claimCalls, 1); + assert.equal(protectedReads, 0); + assert.equal(providerCalls, 0); + assert.equal(claimResume(seeded.jobId).status, 'held'); +}); + +test('stable-time rollback during claim acquisition stops before protected reads', async t => { + const seeded = await seedRetryEligible(t, 10); + const store = new LocalFilePrototypeStore(seeded.root); + let now = seeded.window.retry_not_before_at_ms + 1; + const claimResume = store.claimResume.bind(store); + store.claimResume = jobId => { + const claim = claimResume(jobId); + now = seeded.window.retry_not_before_at_ms; + return claim; + }; + let protectedReads = 0; + const originalRead = store.readImmutable.bind(store); + store.readImmutable = key => { protectedReads++; return originalRead(key); }; + let providerCalls = 0; + const runner = createRunner(store, { + timeAuthority: resumeAuthority({ now: () => now }), + onMockCall: ({ phase }) => { if (phase === 'dispatch-confirmed') providerCalls++; } + }); + const result = await runner.resume({ jobId: seeded.jobId, authorizeResume: true }); + assert.equal(result.status, 'deadline-unverifiable'); + assert.equal(protectedReads, 0); + assert.equal(providerCalls, 0); + assert.equal(claimResume(seeded.jobId).status, 'held'); +}); + +test('unknown one-shot claim fails closed before protected reads or provider calls', async t => { + const seeded = await seedRetryEligible(t, 10); + const store = new LocalFilePrototypeStore(seeded.root); + let claimCalls = 0; + store.claimResume = () => { claimCalls++; return { status: 'unknown' }; }; + let protectedReads = 0; + const originalRead = store.readImmutable.bind(store); + store.readImmutable = key => { protectedReads++; return originalRead(key); }; + let providerCalls = 0; + const runner = createRunner(store, { + timeAuthority: resumeAuthority({ now: () => seeded.window.retry_not_before_at_ms }), + onMockCall: ({ phase }) => { if (phase === 'dispatch-confirmed') providerCalls++; } + }); + const result = await runner.resume({ jobId: seeded.jobId, authorizeResume: true }); + assert.equal(result.status, 'reconciliation-required'); + assert.equal(claimCalls, 1); + assert.equal(protectedReads, 0); + assert.equal(providerCalls, 0); +}); + +test('stable deadline expiry during asynchronous mock preflight prevents dispatch', async t => { + const seeded = await seedRetryEligible(t, 10); + const store = new LocalFilePrototypeStore(seeded.root); + let now = seeded.window.retry_not_before_at_ms; + const deadline = seeded.admitted.resume_time.deadline_at_ms; + class AdvancingMock extends MockTextAdapter { + async describe() { + const descriptor = await super.describe(); + now = deadline; + return descriptor; + } + } + let dispatches = 0; + const runner = createRunner(store, { + timeAuthority: resumeAuthority({ now: () => now }), + mockAdapterFactory: configuration => new AdvancingMock(configuration), + onMockCall: ({ phase }) => { if (phase === 'dispatch-confirmed') dispatches++; } + }); + const result = await runner.resume({ jobId: seeded.jobId, authorizeResume: true }); + assert.equal(result.status, 'budget-exhausted'); + assert.equal(dispatches, 0); + assert.equal(store.claimResume(seeded.jobId).status, 'held'); +}); + +test('authority revocation during asynchronous mock preflight prevents dispatch', async t => { + const seeded = await seedRetryEligible(t, 10); + const store = new LocalFilePrototypeStore(seeded.root); + const executionAuthority = authority(); + class RevokingMock extends MockTextAdapter { + async describe() { + const descriptor = await super.describe(); + executionAuthority.revoke('20000000-0000-4000-8000-000000000002'); + return descriptor; + } + } + let dispatches = 0; + const runner = createRunner(store, { + timeAuthority: resumeAuthority({ now: () => seeded.window.retry_not_before_at_ms }), + executionAuthorityProvider: executionAuthority.verifier, + mockAdapterFactory: configuration => new RevokingMock(configuration), + onMockCall: ({ phase }) => { if (phase === 'dispatch-confirmed') dispatches++; } + }); + const result = await runner.resume({ jobId: seeded.jobId, authorizeResume: true }); + assert.equal(result.status, 'execution-authority-denied'); + assert.equal(dispatches, 0); + assert.equal(store.claimResume(seeded.jobId).status, 'held'); +}); + +test('stable deadline expiry during final awaited authority check blocks the mock effect', async t => { + const seeded = await seedRetryEligible(t, 10); + const store = new LocalFilePrototypeStore(seeded.root); + const deadline = seeded.admitted.resume_time.deadline_at_ms; + let now = seeded.window.retry_not_before_at_ms; + const baseAuthority = authority(); + let retryVerifications = 0; + const executionAuthorityProvider = Object.freeze({ + id: baseAuthority.verifier.id, + mode: 'synthetic', + async verify(request) { + if (request.action === 'retry') retryVerifications++; + const evidence = await baseAuthority.verifier.verify(request); + if (retryVerifications === 5) now = deadline; + return evidence; + }, + isCurrent: baseAuthority.verifier.isCurrent.bind(baseAuthority.verifier) + }); + let providerCalls = 0; + const runner = createRunner(store, { + timeAuthority: resumeAuthority({ now: () => now }), + executionAuthorityProvider, + onMockCall({ phase, mock }) { + if (phase !== 'dispatch-confirmed') return; + const execute = mock.execute.bind(mock); + mock.execute = (...args) => { providerCalls++; return execute(...args); }; + } + }); + const result = await runner.resume({ jobId: seeded.jobId, authorizeResume: true }); + assert.equal(result.status, 'reconciliation-required'); + assert.equal(retryVerifications, 5); + assert.equal(providerCalls, 0); + assert.equal(store.readEvents(seeded.jobId).filter(item => item.type === 'dispatch-started').length, 2); +}); + +test('ambiguous prior result read after final authority verification quarantines without another provider call', async t => { + const seeded = await seedRetryEligible(t, 10); + const store = new LocalFilePrototypeStore(seeded.root); + const originalResultKey = `result:${seeded.terminal.result_id}`; + const readImmutable = store.readImmutable.bind(store); + let hidePriorResult = false; + store.readImmutable = key => key === originalResultKey && hidePriorResult + ? UNKNOWN_STORE_STATE : readImmutable(key); + const baseAuthority = authority(); + let retryVerifications = 0; + const executionAuthorityProvider = Object.freeze({ + id: baseAuthority.verifier.id, + mode: 'synthetic', + async verify(request) { + if (request.action === 'retry') retryVerifications++; + const evidence = await baseAuthority.verifier.verify(request); + if (retryVerifications === 5) hidePriorResult = true; + return evidence; + }, + isCurrent: baseAuthority.verifier.isCurrent.bind(baseAuthority.verifier) + }); + let providerCalls = 0; + const runner = createRunner(store, { + timeAuthority: resumeAuthority({ now: () => seeded.window.retry_not_before_at_ms }), + executionAuthorityProvider, + onMockCall({ phase, mock }) { + if (phase !== 'dispatch-confirmed') return; + const execute = mock.execute.bind(mock); + mock.execute = (...args) => { providerCalls++; return execute(...args); }; + } + }); + const result = await runner.resume({ jobId: seeded.jobId, authorizeResume: true }); + assert.equal(result.status, 'reconciliation-required'); + assert.equal(providerCalls, 0); + assert.equal(retryVerifications, 5); + assert.equal(store.claimResume(seeded.jobId).status, 'held'); +}); + +test('unverifiable dispatch marker is quarantined and never replayed after restart', async t => { + const seeded = await seedRetryEligible(t, 10); + const store = new LocalFilePrototypeStore(seeded.root); + const append = store.append.bind(store); + const readEvents = store.readEvents.bind(store); + let hideDispatchReadback = false; + store.append = entry => { + append(entry); + if (entry.type === 'dispatch-started' && entry.attempt_id !== seeded.terminal.attempt_id) { + hideDispatchReadback = true; + } + }; + store.readEvents = jobId => { + if (hideDispatchReadback) { hideDispatchReadback = false; return UNKNOWN_STORE_STATE; } + return readEvents(jobId); + }; + let providerCalls = 0; + const runner = createRunner(store, { + timeAuthority: resumeAuthority({ now: () => seeded.window.retry_not_before_at_ms }), + onMockCall: ({ phase }) => { if (phase === 'dispatch-confirmed') providerCalls++; } + }); + const result = await runner.resume({ jobId: seeded.jobId, authorizeResume: true }); + assert.equal(result.status, 'reconciliation-required'); + assert.equal(providerCalls, 0); + const restarted = createRunner(new LocalFilePrototypeStore(seeded.root), { + monotonicEpoch: 'resume-after-ambiguous-marker', + timeAuthority: resumeAuthority({ now: () => seeded.window.retry_not_before_at_ms }), + onMockCall: ({ phase }) => { if (phase === 'dispatch-confirmed') providerCalls++; } + }); + const repeat = await restarted.resume({ jobId: seeded.jobId, authorizeResume: true }); + assert.equal(repeat.status, 'resume-not-eligible'); + assert.equal(providerCalls, 0); + assert.equal(readEvents(seeded.jobId).filter(item => item.type === 'dispatch-started').length, 2); +}); + +test('uncertain new provider-outcome write is not replayed after restart', async t => { + const seeded = await seedRetryEligible(t, 10); + const store = new LocalFilePrototypeStore(seeded.root); + const originalOutcomeKey = `provider-outcome:${seeded.terminal.execution_id}`; + const readImmutable = store.readImmutable.bind(store); + const writeImmutable = store.writeImmutable.bind(store); + let unknownNewOutcome = false; + store.readImmutable = key => key.startsWith('provider-outcome:') && key !== originalOutcomeKey && unknownNewOutcome + ? UNKNOWN_STORE_STATE : readImmutable(key); + store.writeImmutable = (key, bytes) => { + const result = writeImmutable(key, bytes); + if (key.startsWith('provider-outcome:') && key !== originalOutcomeKey) unknownNewOutcome = true; + return result; + }; + let providerCalls = 0; + const runner = createRunner(store, { + timeAuthority: resumeAuthority({ now: () => seeded.window.retry_not_before_at_ms }), + onMockCall({ phase, mock }) { + if (phase !== 'dispatch-confirmed') return; + const execute = mock.execute.bind(mock); + mock.execute = (...args) => { providerCalls++; return execute(...args); }; + } + }); + const result = await runner.resume({ jobId: seeded.jobId, authorizeResume: true }); + assert.equal(result.status, 'reconciliation-required'); + assert.equal(providerCalls, 1); + const restarted = createRunner(new LocalFilePrototypeStore(seeded.root), { + monotonicEpoch: 'resume-after-uncertain-outcome', + timeAuthority: resumeAuthority({ now: () => seeded.window.retry_not_before_at_ms }), + onMockCall({ phase, mock }) { + if (phase !== 'dispatch-confirmed') return; + const execute = mock.execute.bind(mock); + mock.execute = (...args) => { providerCalls++; return execute(...args); }; + } + }); + const repeat = await restarted.resume({ jobId: seeded.jobId, authorizeResume: true }); + assert.equal(repeat.status, 'resume-not-eligible'); + assert.equal(providerCalls, 1); +}); diff --git a/tests/offline-orchestration-prototype/runner.test.js b/tests/offline-orchestration-prototype/runner.test.js index be3a046..eceb870 100644 --- a/tests/offline-orchestration-prototype/runner.test.js +++ b/tests/offline-orchestration-prototype/runner.test.js @@ -620,7 +620,7 @@ test('explicit synthetic context retry reauthorizes cached context evidence with test('package subpath exposes only the synthetic offline runner surface', async () => { const authority = authorityFixture(); const value = createOfflineOrchestrationPrototype({ executionAuthorityProvider: authority.verifier }); - assert.deepEqual(Object.keys(value).sort(), ['closeJob', 'inspectRecovery', 'retry', 'submit']); + assert.deepEqual(Object.keys(value).sort(), ['closeJob', 'inspectRecovery', 'resume', 'retry', 'submit']); const result = await value.submit({ productionSource }); assert.equal(result.kind, 'terminal'); assert.equal(result.result.status, 'complete'); From deea536fc4ef8a5ab44cb8c46fb1e27bbb071455 Mon Sep 17 00:00:00 2001 From: Andrew Peris Date: Sun, 8 Nov 2026 16:35:43 +0000 Subject: [PATCH 2/3] Share durable claim across retry and resume --- docs/o08-durable-resume-decision-packet.md | 6 + src/offline-orchestration-prototype/runner.js | 27 +++++ .../resume-candidate.test.js | 103 +++++++++++++++++- 3 files changed, 130 insertions(+), 6 deletions(-) diff --git a/docs/o08-durable-resume-decision-packet.md b/docs/o08-durable-resume-decision-packet.md index 2c137ac..e2a0e03 100644 --- a/docs/o08-durable-resume-decision-packet.md +++ b/docs/o08-durable-resume-decision-packet.md @@ -208,6 +208,12 @@ read. It validates the exact prior outcome/result evidence, reconstructs the material ledger from the verified blobs, and performs mock preflight. After the awaited preflight it rechecks authority and the original time interval. +The same durable one-shot claim is acquired by the original runner's ordinary +`retry()` path before protected retry evidence is read. Thus an in-flight +resume and a same-process retry cannot both proceed to a second dispatch. If +the other path already owns the claim, the caller fails closed; a held claim is +never taken over or released. + The existing attempt path creates a new attempt and idempotency key, writes the durable `dispatch-started` marker before the mock effect, then performs the final current-authority/time and pinned-evidence checks immediately before the diff --git a/src/offline-orchestration-prototype/runner.js b/src/offline-orchestration-prototype/runner.js index a7ac10c..c906936 100644 --- a/src/offline-orchestration-prototype/runner.js +++ b/src/offline-orchestration-prototype/runner.js @@ -702,6 +702,10 @@ function createRunner({ runtime = defaultRuntime, store = new InMemoryPrototypeS }); if (!appendConfirmed(store, job.jobId, resumeWindow)) return markUnresolved(job); job.resumeRetryNotBeforeAtMs = retryNotBeforeAtMs; + job.resumeTimeBounds = { + retryNotBeforeAtMs, + deadlineAtMs: job.resumeDeadlineAtMs + }; } } } @@ -1584,6 +1588,29 @@ function createRunner({ runtime = defaultRuntime, store = new InMemoryPrototypeS job.contextUseRequest = request; job.contextUseEvidence = current.contextEvidence; } + if (typeof store.claimResume === 'function') { + let claim; + try { claim = store.claimResume(job.jobId); } catch { claim = { status: 'unknown' }; } + if (claim?.status === 'held') throw new OfflineOrchestrationError('RETRY_CLAIM_HELD'); + if (claim?.status !== 'acquired' || !UUID.test(claim.claim_id ?? '')) { + throw new OfflineOrchestrationError('RETRY_CLAIM_UNCERTAIN'); + } + const durableRetryBoundary = () => { + const failure = currentAuthorityFailure(retryAuthority, 'retry', cancellation, job.authorityClock) + ?? (job.contextEnabled + ? currentContextUseFailure(job.contextUseEvidence, job.contextUseRequest, cancellation, job.authorityClock) + : undefined) + ?? currentPermitTimeFailure(retryAuthority, job.contextUseEvidence, job.authorityClock) + ?? hostBoundaryFailure(cancellation, job.clockEpochId, job.deadlineMonotonicMs); + if (failure) throw new OfflineOrchestrationError(failure); + if (job.resumeTimeBounds) { + const time = resumeTimeStatus(job.resumeTimeBounds, job.resumeTimeState); + if (time.status !== 'eligible') throw new OfflineOrchestrationError(time.status); + } + }; + job.resumeBoundary = durableRetryBoundary; + durableRetryBoundary(); + } if (!verifyRetryEvidence(job, job.lastAttempt)) return markUnresolved(job); // Identity is pinned in the job and cannot be replaced on retry. return await performAttempt(job, { diff --git a/tests/offline-orchestration-prototype/resume-candidate.test.js b/tests/offline-orchestration-prototype/resume-candidate.test.js index 5872187..4cd8e43 100644 --- a/tests/offline-orchestration-prototype/resume-candidate.test.js +++ b/tests/offline-orchestration-prototype/resume-candidate.test.js @@ -40,12 +40,14 @@ function authority() { } function runtime(epochId = 'original-monotonic-epoch') { + let monotonic = 10_000; return { - now: () => 10_000, + now: () => monotonic, epochId, wallNow: () => Date.parse('2026-11-08T02:40:00Z'), setTimer: () => 1, - clearTimer: () => {} + clearTimer: () => {}, + advance: delta => { monotonic += delta; } }; } @@ -95,12 +97,21 @@ function rewriteProviderOutcome(root, jobId, transform) { writeFileSync(eventPath, `${lines.map(item => canonicalJson(item)).join('\n')}\n`); } -async function seedRetryEligible(t, retryAfterMs = 10) { +async function seedRetryEligible(t, retryAfterMs = 10, { + mockAdapterFactory, runtimeOverride = runtime(), timeAuthority +} = {}) { 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 runner = createRunner(store, { + mockAdapterFactory, + runtimeOverride, + timeAuthority: timeAuthority ?? resumeAuthority({ + now: () => stableStart + runtimeOverride.now() - 10_000 + }), + onMockCall: ({ phase }) => { if (phase === 'dispatch-confirmed') providerCalls++; } + }); const result = await runner.submit({ productionSource, noOutputResultVersion: '1.1.0', @@ -115,7 +126,8 @@ async function seedRetryEligible(t, retryAfterMs = 10) { 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 }; + return { root, jobId: result.job_id, store, runner, result, admitted, terminal, window, + providerCalls: () => providerCalls, runtime: runtimeOverride }; } test('reopened local store reports a read-only candidate at the inclusive retry bound', async t => { @@ -141,7 +153,7 @@ test('reopened local store reports a read-only candidate at the inclusive retry assert.equal(reopened.blobCount, beforeBlobs); assert.equal(resumeClaimCalls(), 0); assert.equal(laterCalls, 0); - assert.equal(seeded.providerCalls, 1); + assert.equal(seeded.providerCalls(), 1); }); test('read-only resume candidate classification enforces retry and deadline boundaries', async t => { @@ -412,6 +424,85 @@ test('concurrent resume calls share one atomic claim and make at most one provid assert.equal(providerCalls, 1); }); +test('resume claim blocks the original runner retry while resumed adapter preflight is pending', async t => { + const seeded = await seedRetryEligible(t, 10); + seeded.runtime.advance(10); + let enteredDescribeResolve; + const enteredDescribe = new Promise(resolve => { enteredDescribeResolve = resolve; }); + let releaseDescribe; + const describeGate = new Promise(resolve => { releaseDescribe = resolve; }); + class PendingDescriptionMock extends MockTextAdapter { + async describe() { + enteredDescribeResolve(); + await describeGate; + return super.describe(); + } + } + let resumedDispatches = 0; + const resumed = createRunner(new LocalFilePrototypeStore(seeded.root), { + timeAuthority: resumeAuthority({ now: () => seeded.window.retry_not_before_at_ms }), + mockAdapterFactory: configuration => new PendingDescriptionMock(configuration), + onMockCall: ({ phase }) => { if (phase === 'dispatch-confirmed') resumedDispatches++; } + }); + + const resumePending = resumed.resume({ jobId: seeded.jobId, authorizeResume: true }); + await enteredDescribe; + await assert.rejects( + () => seeded.runner.retry({ authorizeRetry: true }), + error => error.code === 'RETRY_CLAIM_HELD' + ); + assert.equal(seeded.providerCalls(), 1); + assert.equal(resumedDispatches, 0); + + releaseDescribe(); + const result = await resumePending; + assert.equal(result.kind, 'terminal'); + assert.equal(seeded.providerCalls(), 1); + assert.equal(resumedDispatches, 1); + assert.equal(seeded.store.readEvents(seeded.jobId).filter(item => item.type === 'dispatch-started').length, 2); +}); + +test('pending original retry owns the durable claim and blocks resumed dispatch', async t => { + let executeCount = 0; + let executionStartedResolve; + const executionStarted = new Promise(resolve => { executionStartedResolve = resolve; }); + let releaseExecution; + const executionGate = new Promise(resolve => { releaseExecution = resolve; }); + class PendingOutcomeMock extends MockTextAdapter { + async execute(request, options) { + if (++executeCount === 2) { + executionStartedResolve(); + await executionGate; + } + return super.execute(request, options); + } + } + const retryRuntime = runtime(); + const seeded = await seedRetryEligible(t, 10, { + mockAdapterFactory: configuration => new PendingOutcomeMock(configuration), + runtimeOverride: retryRuntime + }); + retryRuntime.advance(10); + let resumedDispatches = 0; + const resumed = createRunner(new LocalFilePrototypeStore(seeded.root), { + timeAuthority: resumeAuthority({ now: () => seeded.window.retry_not_before_at_ms }), + onMockCall: ({ phase }) => { if (phase === 'dispatch-confirmed') resumedDispatches++; } + }); + + const retryPending = seeded.runner.retry({ authorizeRetry: true }); + await executionStarted; + const resumeResult = await resumed.resume({ jobId: seeded.jobId, authorizeResume: true }); + assert.equal(resumeResult.status, 'resume-not-eligible'); + assert.equal(resumedDispatches, 0); + assert.equal(seeded.providerCalls(), 2); + + releaseExecution(); + const retryResult = await retryPending; + assert.equal(retryResult.kind, 'terminal'); + assert.equal(seeded.providerCalls(), 2); + assert.equal(seeded.store.readEvents(seeded.jobId).filter(item => item.type === 'dispatch-started').length, 2); +}); + test('revocation during claim acquisition stops before any protected read or provider call', async t => { const seeded = await seedRetryEligible(t, 10); const store = new LocalFilePrototypeStore(seeded.root); From 064fab2e3ef8fab10934234c9b3709804cfbb7cf Mon Sep 17 00:00:00 2001 From: Andrew Peris Date: Sun, 8 Nov 2026 17:18:29 +0000 Subject: [PATCH 3/3] Revalidate resume clock pairs and unknown state --- docs/o08-durable-resume-decision-packet.md | 6 +- src/offline-orchestration-prototype/runner.js | 19 +++-- .../resume-candidate.test.js | 78 +++++++++++++++++++ 3 files changed, 97 insertions(+), 6 deletions(-) diff --git a/docs/o08-durable-resume-decision-packet.md b/docs/o08-durable-resume-decision-packet.md index e2a0e03..cc702f4 100644 --- a/docs/o08-durable-resume-decision-packet.md +++ b/docs/o08-durable-resume-decision-packet.md @@ -206,7 +206,11 @@ rechecks authority/time before reading protected input, prompt, provider outcome, and result blobs; the guard is repeated around each synchronous blob read. It validates the exact prior outcome/result evidence, reconstructs the material ledger from the verified blobs, and performs mock preflight. After the -awaited preflight it rechecks authority and the original time interval. +awaited preflight it rechecks authority and the original time interval. After +post-claim authorization it pairs the validated stable-time sample with a fresh +monotonic sample from the same epoch to map the remaining original deadline. +Unreadable or unknown lifecycle state before or after claim returns +`reconciliation-required` and never triggers replay. The same durable one-shot claim is acquired by the original runner's ordinary `retry()` path before protected retry evidence is read. Thus an in-flight diff --git a/src/offline-orchestration-prototype/runner.js b/src/offline-orchestration-prototype/runner.js index c906936..82a45f7 100644 --- a/src/offline-orchestration-prototype/runner.js +++ b/src/offline-orchestration-prototype/runner.js @@ -1632,8 +1632,10 @@ function createRunner({ runtime = defaultRuntime, store = new InMemoryPrototypeS } const expectedTypes = ['admitted', 'prepared', 'dispatch-started', 'provider-outcome', 'result-prepared', 'persisting', 'terminal', 'resume-window']; - if (entries === UNKNOWN_STORE_STATE || !Array.isArray(entries) || entries.length !== expectedTypes.length - || entries.some((item, index) => item.type !== expectedTypes[index])) { + if (entries === UNKNOWN_STORE_STATE || !Array.isArray(entries)) { + return { status: 'reconciliation-required' }; + } + if (entries.length !== expectedTypes.length || entries.some((item, index) => item.type !== expectedTypes[index])) { return { status: 'resume-not-eligible' }; } const [admitted, prepared, dispatch, outcome, resultPrepared, persisting, terminal, resumeWindow] = entries; @@ -1751,6 +1753,10 @@ function createRunner({ runtime = defaultRuntime, store = new InMemoryPrototypeS if (postClaimTime.status !== 'eligible') { return freezeDeep({ kind: 'resume-outcome', status: postClaimTime.status, job_id: jobId }); } + const postClaimMonotonic = safeClock(runtime); + if (!postClaimMonotonic || postClaimMonotonic.epochId !== monotonic.epochId) { + return freezeDeep({ kind: 'resume-outcome', status: 'deadline-unverifiable', job_id: jobId }); + } const currentResumeBoundary = () => { const authorityFailure = currentAuthorityFailure(authorityEvidence, 'retry', cancellation, authorityState); @@ -1758,7 +1764,7 @@ function createRunner({ runtime = defaultRuntime, store = new InMemoryPrototypeS const currentTime = resumeTimeStatus(timeBounds, resumeTimeState); if (currentTime.status !== 'eligible') throw new OfflineOrchestrationError(currentTime.status); const clock = safeClock(runtime); - const currentDeadline = checkedAdd(monotonic.now, timeBounds.deadlineAtMs - postClaimTime.now); + const currentDeadline = checkedAdd(postClaimMonotonic.now, timeBounds.deadlineAtMs - postClaimTime.now); if (!clock || clock.epochId !== monotonic.epochId || currentDeadline === undefined || clock.now >= currentDeadline) { throw new OfflineOrchestrationError('EXECUTION_DEADLINE_EXPIRED'); @@ -1775,12 +1781,15 @@ function createRunner({ runtime = defaultRuntime, store = new InMemoryPrototypeS } catch { return freezeDeep({ kind: 'resume-outcome', status: 'reconciliation-required', job_id: jobId }); } + if (inspection.status === 'reconciliation-required') { + return freezeDeep({ kind: 'resume-outcome', status: 'reconciliation-required', job_id: jobId }); + } if (inspection.status !== 'resume-candidate' || !candidate) { return freezeDeep({ kind: 'resume-outcome', status: 'resume-not-eligible', job_id: jobId }); } const remainingMs = timeBounds.deadlineAtMs - postClaimTime.now; - const deadlineMonotonicMs = checkedAdd(monotonic.now, remainingMs); + const deadlineMonotonicMs = checkedAdd(postClaimMonotonic.now, remainingMs); if (deadlineMonotonicMs === undefined) { return freezeDeep({ kind: 'resume-outcome', status: 'deadline-unverifiable', job_id: jobId }); } @@ -1835,7 +1844,7 @@ function createRunner({ runtime = defaultRuntime, store = new InMemoryPrototypeS renderedPrompt: candidate.renderedPrompt, promptBytes: candidate.promptBytes, ledger, attempts: [priorAttempt], lastAttempt: priorAttempt, retryOpen: true, retryNotBefore: undefined, state: 'retry-eligible', closed: false, - clockEpochId: monotonic.epochId, admittedMonotonicMs: monotonic.now, + clockEpochId: postClaimMonotonic.epochId, admittedMonotonicMs: postClaimMonotonic.now, deadlineMonotonicMs, authorityClock: authorityState, resumeTimeState, resumeTimeBounds: timeBounds, resumeAuthorityEvidence: authorityEvidence diff --git a/tests/offline-orchestration-prototype/resume-candidate.test.js b/tests/offline-orchestration-prototype/resume-candidate.test.js index 4cd8e43..5f756aa 100644 --- a/tests/offline-orchestration-prototype/resume-candidate.test.js +++ b/tests/offline-orchestration-prototype/resume-candidate.test.js @@ -401,6 +401,84 @@ test('resume time boundaries stop before claim, protected reads, or provider cal }); }); +test('unknown event state is reconciliation-required before claiming or after a held claim', async t => { + const before = await seedRetryEligible(t, 10); + const beforeStore = new LocalFilePrototypeStore(before.root); + beforeStore.readEvents = () => UNKNOWN_STORE_STATE; + let beforeClaims = 0; + const claimBefore = beforeStore.claimResume.bind(beforeStore); + beforeStore.claimResume = jobId => { beforeClaims++; return claimBefore(jobId); }; + const beforeRunner = createRunner(beforeStore, { + timeAuthority: resumeAuthority({ now: () => before.window.retry_not_before_at_ms }) + }); + assert.equal((await beforeRunner.resume({ jobId: before.jobId, authorizeResume: true })).status, + 'reconciliation-required'); + assert.equal(beforeClaims, 0); + + const after = await seedRetryEligible(t, 10); + const afterStore = new LocalFilePrototypeStore(after.root); + const claimAfter = afterStore.claimResume.bind(afterStore); + afterStore.claimResume = jobId => { + const claim = claimAfter(jobId); + if (claim.status === 'acquired') afterStore.readEvents = () => UNKNOWN_STORE_STATE; + return claim; + }; + let protectedReads = 0; + afterStore.readImmutable = () => { protectedReads++; return UNKNOWN_STORE_STATE; }; + let providerCalls = 0; + const afterRunner = createRunner(afterStore, { + timeAuthority: resumeAuthority({ now: () => after.window.retry_not_before_at_ms }), + onMockCall: ({ phase }) => { if (phase === 'dispatch-confirmed') providerCalls++; } + }); + const afterResult = await afterRunner.resume({ jobId: after.jobId, authorizeResume: true }); + assert.equal(afterResult.status, 'reconciliation-required'); + assert.equal(protectedReads, 0); + assert.equal(providerCalls, 0); + assert.equal(claimAfter(after.jobId).status, 'held'); +}); + +test('deadline mapping pairs post-claim stable and monotonic samples after asynchronous authority advances both clocks', async t => { + const seeded = await seedRetryEligible(t, 10); + let stableNow = seeded.window.retry_not_before_at_ms; + const monotonic = runtime('resume-post-claim-paired-clock'); + const base = authority(); + let retryVerifications = 0; + const executionAuthorityProvider = Object.freeze({ + id: base.verifier.id, + mode: 'synthetic', + async verify(request) { + const evidence = await base.verifier.verify(request); + if (request.action === 'retry' && ++retryVerifications === 2) { + stableNow += 50_000; + monotonic.advance(50_000); + } + return evidence; + }, + isCurrent: base.verifier.isCurrent.bind(base.verifier) + }); + class AdvancingDescriptionMock extends MockTextAdapter { + async describe() { + const result = await super.describe(); + monotonic.advance(25_000); + return result; + } + } + let dispatches = 0; + const runner = createRunner(new LocalFilePrototypeStore(seeded.root), { + monotonicEpoch: 'resume-post-claim-paired-clock', + runtimeOverride: monotonic, + timeAuthority: resumeAuthority({ now: () => stableNow }), + executionAuthorityProvider, + mockAdapterFactory: configuration => new AdvancingDescriptionMock(configuration), + onMockCall: ({ phase }) => { if (phase === 'dispatch-confirmed') dispatches++; } + }); + const result = await runner.resume({ jobId: seeded.jobId, authorizeResume: true }); + assert.equal(result.kind, 'terminal'); + assert.equal(retryVerifications, 5); + assert.equal(dispatches, 1); + assert.equal(monotonic.now(), 85_000); +}); + test('concurrent resume calls share one atomic claim and make at most one provider call', async t => { const seeded = await seedRetryEligible(t, 10); const firstStore = new LocalFilePrototypeStore(seeded.root);