From dd4a4665a28330575dc59c84927a5d23a607cd55 Mon Sep 17 00:00:00 2001 From: Andrew Peris Date: Fri, 13 Nov 2026 14:05:04 -0500 Subject: [PATCH] Fix bounded O10 retry authority and recovery findings --- CHANGELOG.md | 8 + docs/offline-orchestration-prototype.md | 39 +++ src/offline-orchestration-prototype/runner.js | 89 +++++- .../o10-recovery-regressions.test.js | 298 ++++++++++++++++++ .../retry-package-use-authority.test.js | 99 +++++- .../runner.test.js | 24 +- 6 files changed, 542 insertions(+), 15 deletions(-) create mode 100644 tests/offline-orchestration-prototype/o10-recovery-regressions.test.js diff --git a/CHANGELOG.md b/CHANGELOG.md index da6dea9..5c983af 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,13 @@ # Changelog +## O10 review fixes — 2026-11-10 + +Refresh retry authority after asynchronous preflight before cached input use or +attempt preparation. Bind resumed deadline inspection to the recorded clock +translation and validate confirmed authorization-denied retry closure without +misreporting it as corruption. Add synthetic regression and contradictory-record +tests; preserve the original result, provider-call limits and production scope. + ## Review fixes — 2026-11-04 Close the exhausted host job after a confirmed unmappable retry outcome while diff --git a/docs/offline-orchestration-prototype.md b/docs/offline-orchestration-prototype.md index b892508..8cc365a 100644 --- a/docs/offline-orchestration-prototype.md +++ b/docs/offline-orchestration-prototype.md @@ -404,3 +404,42 @@ compatibility tampering. This does not authenticate same-account edits to the local store, establish power-loss durability or support for other filesystems, add providers or infrastructure, use production data, or close Studio issue #110. + + +## O10 corrective boundaries (2026-11-10) + +Ordinary retry refreshes current execution and, when installed, package-use +authority immediately after asynchronous mock description and before reusing +the cached prompt, allocating attempt/execution IDs, reserving output material +or appending a prepared attempt. Cancellation and the original deadline are +checked again across that authority await. A rejection at this boundary raises +the fixed authority or deadline error without preparing another attempt; the +first immutable result is preserved. The final dispatch checks remain in place. + +A resumed prepared attempt retains a `resumed_clock` record with its monotonic +epoch, paired post-claim stable and monotonic samples, and translated monotonic +deadline. Inspection verifies the exact shape, safe integer bounds, placement +after the prior resume window, inclusive retry bound, exclusive stable deadline +and the translation from the original stable deadline. Deadline-stop evidence +must match that attempt's verified deadline, not the original process's +unrelated monotonic reading. Same-process records without this optional mapping +still use the admitted deadline. Missing or inconsistent evidence for a +translated deadline requires reconciliation. This is local consistency +validation, not clock authenticity or same-account tamper protection. + +A confirmed authorization-denied retry can be inspected as +`closed-without-result`. It requires a verified eligible first result, one +fresh prepared retry, an optional single dispatch marker, one exactly linked +`authorization-blocked` record for action `retry`, and the matching final +`job-closed` record. No second provider outcome, result or contradictory stop +may be present. A dispatch marker records intent before the final authority +gate; the confirmed authorization stop records that the mock effect was denied. +The prior result remains immutable and is not relabeled as the retry's result. +Missing, duplicate, misordered or contradictory evidence still fails closed. + +Regression coverage includes reopened pre-effect and in-flight resumed deadline +stops, late execution/package-use denial, cancellation and deadline during retry +preflight and authority waits, ordinary and resumed authorization stops, and +corrupted clock/stop evidence. The existing synthetic-only, two-attempt, +local-file-store scope and all production exclusions remain unchanged. These +corrections do not close Studio issue #111 or declare a broader O10 pass. diff --git a/src/offline-orchestration-prototype/runner.js b/src/offline-orchestration-prototype/runner.js index cc3fa3f..ccc1a3e 100644 --- a/src/offline-orchestration-prototype/runner.js +++ b/src/offline-orchestration-prototype/runner.js @@ -972,6 +972,24 @@ function createRunner({ runtime = defaultRuntime, store = new InMemoryPrototypeS if (error instanceof OfflineOrchestrationError) throw error; throw new OfflineOrchestrationError('INVALID_MOCK_ADAPTER'); } + // Retry preflight may await host code. Refresh every input-use boundary + // before touching the cached prompt, allocating IDs or reserving material. + // submit/resume supply descriptors whose boundaries were already checked. + if (!preflight) { + if (useRequest) { + const current = await requireContextBoundary(authorizationAction, useRequest, cancellation, + job.authorityClock, job.clockEpochId, job.deadlineMonotonicMs); + contextEvidence = current.contextEvidence; + assertContextBoundaryCurrent(authorizationAction, useRequest, current.executionEvidence, + contextEvidence, cancellation, job.authorityClock, job.clockEpochId, job.deadlineMonotonicMs); + job.contextUseEvidence = contextEvidence; + } else { + const evidence = await requireExecutionAuthority(authorizationAction, cancellation, job.authorityClock); + const failure = currentAuthorityFailure(evidence, authorizationAction, cancellation, job.authorityClock) + ?? hostBoundaryFailure(cancellation, job.clockEpochId, job.deadlineMonotonicMs); + if (failure) throw new OfflineOrchestrationError(failure); + } + } if (!(mock instanceof MockTextAdapter) || !validateExecutionDocument(descriptor).valid) { throw new OfflineOrchestrationError('MOCK_ADAPTER_REQUIRED'); } @@ -1022,6 +1040,7 @@ function createRunner({ runtime = defaultRuntime, store = new InMemoryPrototypeS attempt_id: attemptId, execution_id: executionId, retry_of_attempt_id: retryOfAttemptId ?? null, + ...(job.resumedClock ? { resumed_clock: job.resumedClock } : {}), production: job.production.reference, reservation: { prompt_bytes: job.promptBytes.byteLength, @@ -1881,6 +1900,12 @@ function createRunner({ runtime = defaultRuntime, store = new InMemoryPrototypeS retryNotBefore: undefined, state: 'retry-eligible', closed: false, clockEpochId: postClaimMonotonic.epochId, admittedMonotonicMs: postClaimMonotonic.now, deadlineMonotonicMs, authorityClock: authorityState, + resumedClock: { + clock_epoch_id: postClaimMonotonic.epochId, + sampled_monotonic_ms: postClaimMonotonic.now, + sampled_at_ms: postClaimTime.now, + deadline_monotonic_ms: deadlineMonotonicMs + }, resumeTimeState, resumeTimeBounds: timeBounds, resumeAuthorityEvidence: authorityEvidence }; @@ -2051,6 +2076,37 @@ function createRunner({ runtime = defaultRuntime, store = new InMemoryPrototypeS || item.job_id !== jobId || typeof item.type !== 'string' || !RECOVERY_EVENT_TYPES.has(item.type))) { return reconciliationRequired(); } + // A resumed attempt has a different monotonic epoch. Bind its translated + // deadline to the original stable-time window rather than comparing the + // unrelated absolute monotonic readings. Legacy same-process attempts keep + // using the admitted deadline; unverifiable translations fail closed. + const preparedDeadlines = new Map(); + for (const prepared of entries.filter(item => item.type === 'prepared')) { + let deadline = admitted.deadline_monotonic_ms; + if (Object.hasOwn(prepared, 'resumed_clock')) { + const mapping = prepared.resumed_clock; + const time = admitted.resume_time; + const windows = entries.filter(item => item.type === 'resume-window' + && item.attempt_id === prepared.retry_of_attempt_id); + const keys = 'clock_epoch_id|deadline_monotonic_ms|sampled_at_ms|sampled_monotonic_ms'; + if (!mapping || typeof mapping !== 'object' || Array.isArray(mapping) + || Object.keys(mapping).sort().join('|') !== keys + || typeof mapping.clock_epoch_id !== 'string' || !mapping.clock_epoch_id + || !Number.isSafeInteger(mapping.sampled_monotonic_ms) || mapping.sampled_monotonic_ms < 0 + || !Number.isSafeInteger(mapping.sampled_at_ms) || mapping.sampled_at_ms < 0 + || !time || time.context_enabled !== false || windows.length !== 1 + || !Number.isSafeInteger(time.deadline_at_ms) + || !Number.isSafeInteger(windows[0].retry_not_before_at_ms) + || mapping.sampled_at_ms < windows[0].retry_not_before_at_ms + || mapping.sampled_at_ms >= time.deadline_at_ms + || entries.indexOf(windows[0]) >= entries.indexOf(prepared) + || !Number.isSafeInteger(mapping.deadline_monotonic_ms) + || mapping.deadline_monotonic_ms !== checkedAdd(mapping.sampled_monotonic_ms, + time.deadline_at_ms - mapping.sampled_at_ms)) return reconciliationRequired(); + deadline = mapping.deadline_monotonic_ms; + } + preparedDeadlines.set(prepared, deadline); + } const verifiedBlobs = new Map(); const readVerifiedBlob = (key, expectedSize, expectedSha) => { beforeProtectedRead?.(); @@ -2160,6 +2216,7 @@ function createRunner({ runtime = defaultRuntime, store = new InMemoryPrototypeS const attemptMappingStops = matching('contract-mapping-blocked', attemptId); const attemptBudgetStops = matching('budget-exhausted', attemptId); if (attemptCancellationStops.length !== 0 || attemptMappingStops.length !== 0 + || matching('authorization-blocked', attemptId).length !== 0 || attemptBudgetStops.length > 1) return reconciliationRequired(); if (attemptBudgetStops.length === 1) { const [stop] = attemptBudgetStops; @@ -2167,8 +2224,8 @@ function createRunner({ runtime = defaultRuntime, store = new InMemoryPrototypeS if (Object.keys(stop).sort().join('|') !== stopKeys.join('|') || stop.job_id !== jobId || stop.reason !== 'time' || stop.execution_id !== executionId - || !Number.isSafeInteger(admitted.deadline_monotonic_ms) - || stop.deadline_monotonic_ms !== admitted.deadline_monotonic_ms + || !Number.isSafeInteger(preparedDeadlines.get(prepared)) + || stop.deadline_monotonic_ms !== preparedDeadlines.get(prepared) || entries.indexOf(stop) <= entries.indexOf(dispatch) || entries.indexOf(stop) >= entries.indexOf(outcome) || entries.indexOf(outcome) >= entries.indexOf(preparedResult)) return reconciliationRequired(); @@ -2326,7 +2383,7 @@ function createRunner({ runtime = defaultRuntime, store = new InMemoryPrototypeS // only allowed trailing attempt is an explicitly stopped retry with no result. const resultAttemptEventTypes = new Set(['prepared', 'dispatch-started', 'provider-outcome', 'result-prepared', 'persisting', 'terminal', 'resume-window', - 'contract-mapping-blocked', 'budget-exhausted', 'cancelled-before-dispatch']); + 'contract-mapping-blocked', 'budget-exhausted', 'cancelled-before-dispatch', 'authorization-blocked']); if (jobScopedBudgetStops.length > 1 || entries.some(item => resultAttemptEventTypes.has(item.type) && item.attempt_id === undefined && item.type !== 'budget-exhausted')) { @@ -2342,6 +2399,9 @@ function createRunner({ runtime = defaultRuntime, store = new InMemoryPrototypeS const orphanIds = new Set(orphanAttemptRecords.map(item => item.attempt_id)); if (orphanIds.size > 0) { if (orphanIds.size !== 1 || !priorChain + || seenAttempts.size >= OFFLINE_ORCHESTRATION_LIMITS.maxAttemptsPerJob + || priorChain.result.status !== 'failed' || priorChain.result.outputs.length !== 0 + || !eligibleRateLimit(priorChain.providerResult) || (admitted.resume_time !== undefined && priorChain.resumeWindowIndex === undefined)) { return reconciliationRequired(); } @@ -2353,7 +2413,7 @@ function createRunner({ runtime = defaultRuntime, store = new InMemoryPrototypeS const orphanDispatches = ofType('dispatch-started'); const orphanOutcomes = ofType('provider-outcome'); const orphanStops = orphanEvents.filter(item => ['contract-mapping-blocked', - 'budget-exhausted', 'cancelled-before-dispatch'].includes(item.type)); + 'budget-exhausted', 'cancelled-before-dispatch', 'authorization-blocked'].includes(item.type)); const orphanResults = orphanEvents.filter(item => ['result-prepared', 'persisting', 'terminal', 'resume-window'].includes(item.type)); const stopCounts = new Map(); @@ -2399,10 +2459,24 @@ function createRunner({ runtime = defaultRuntime, store = new InMemoryPrototypeS const orphanBudgetStops = orphanStops.filter(item => item.type === 'budget-exhausted'); const orphanCancellationStops = orphanStops.filter(item => item.type === 'cancelled-before-dispatch'); const orphanMappingStops = orphanStops.filter(item => item.type === 'contract-mapping-blocked'); + const orphanAuthorizationStops = orphanStops.filter(item => item.type === 'authorization-blocked'); const stopIndices = orphanStops.map(item => entries.indexOf(item)); const closedEvents = entries.filter(item => item.type === 'job-closed'); if (orphanStops.some(item => item.execution_id !== undefined && item.execution_id !== orphanExecutionId)) return reconciliationRequired(); + if (orphanAuthorizationStops.length === 1) { + const [stop] = orphanAuthorizationStops; + const stopKeys = 'action|attempt_id|execution_id|job_id|type'; + if (Object.keys(stop).sort().join('|') !== stopKeys + || stop.job_id !== jobId || stop.attempt_id !== orphanId + || stop.execution_id !== orphanExecutionId || stop.action !== 'retry' + || orphanOutcome || orphanStops.length !== 1 + || entries.indexOf(stop) <= entries.indexOf(orphanDispatch ?? orphanPrepared[0]) + || closedEvents.length !== 1 || closedEvents[0].reason !== 'execution-authority-denied' + || Object.keys(closedEvents[0]).sort().join('|') !== 'job_id|reason|type') { + return reconciliationRequired(); + } + } if (orphanCancellationStops.length === 1) { const [stop] = orphanCancellationStops; const stopKeys = ['attempt_id', 'job_id', 'reason', 'type']; @@ -2417,8 +2491,8 @@ function createRunner({ runtime = defaultRuntime, store = new InMemoryPrototypeS const previousAttemptEvent = orphanDispatch ?? orphanPrepared[0]; if (Object.keys(stop).sort().join('|') !== stopKeys.join('|') || stop.job_id !== jobId || stop.attempt_id !== orphanId || stop.execution_id !== orphanExecutionId - || stop.reason !== 'time' || !Number.isSafeInteger(admitted.deadline_monotonic_ms) - || stop.deadline_monotonic_ms !== admitted.deadline_monotonic_ms + || stop.reason !== 'time' || !Number.isSafeInteger(preparedDeadlines.get(orphanPrepared[0])) + || stop.deadline_monotonic_ms !== preparedDeadlines.get(orphanPrepared[0]) || entries.indexOf(stop) <= entries.indexOf(previousAttemptEvent) || (orphanOutcome && entries.indexOf(stop) >= entries.indexOf(orphanOutcome))) { return reconciliationRequired(); @@ -2453,7 +2527,8 @@ function createRunner({ runtime = defaultRuntime, store = new InMemoryPrototypeS && (!orphanOutcome || !['failed', 'cancelled', 'succeeded'].includes(orphanProviderResult.status) || closedEvents[0].reason !== 'retry-contract-mapping-blocked')) || (closedEvents.length === 1 && orphanCancellationStops.length === 0 - && orphanBudgetStops.length === 0 && orphanMappingStops.length === 0)) { + && orphanBudgetStops.length === 0 && orphanMappingStops.length === 0 + && orphanAuthorizationStops.length === 0)) { return reconciliationRequired(); } } diff --git a/tests/offline-orchestration-prototype/o10-recovery-regressions.test.js b/tests/offline-orchestration-prototype/o10-recovery-regressions.test.js new file mode 100644 index 0000000..42d1351 --- /dev/null +++ b/tests/offline-orchestration-prototype/o10-recovery-regressions.test.js @@ -0,0 +1,298 @@ +import '../support/offline-network-tripwire.mjs'; +import assert from 'node:assert/strict'; +import { randomUUID } from 'node:crypto'; +import { mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import test from 'node:test'; +import { MockTextAdapter } from '../../src/prompt-sdk/index.js'; +import { createSyntheticExecutionAuthorityVerifier, SYNTHETIC_EXECUTION_PURPOSE } + from '../../src/offline-orchestration-prototype/execution-authority.js'; +import { createOfflineOrchestrationPrototypeForTest, LocalFilePrototypeStore } + from '../../src/offline-orchestration-prototype/testing.js'; + +const fixture = JSON.parse(readFileSync(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'); +const retryDecision = '20000000-0000-4000-8000-000000000002'; + +function authority() { + return createSyntheticExecutionAuthorityVerifier(['execute', 'retry'].map((action, index) => ({ + decision_id: `20000000-0000-4000-8000-${String(index + 1).padStart(12, '0')}`, + decision: 'allow', action, purpose: SYNTHETIC_EXECUTION_PURPOSE, + production: { + production_id: fixture.production.production_id, revision: fixture.production.revision, + identity_sha256: 'sha256:9250217ad23125b0356a9e7002f57a55dacf9d982f069caa403b89f8c6c234dc' + }, + 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/studio/issues/111' + }))); +} + +function clock(epochId) { + let monotonic = 10_000; + const timers = new Map(); + let nextTimer = 0; + return { + now: () => monotonic, epochId, wallNow: () => stableStart, + setTimer(callback) { const id = ++nextTimer; timers.set(id, callback); return id; }, + clearTimer(id) { timers.delete(id); }, + advance(delta) { monotonic += delta; }, + fireTimers() { + const callbacks = [...timers.values()]; + timers.clear(); + for (const callback of callbacks) callback(); + } + }; +} + +function eventPath(h) { + return join(h.root, 'events', `${Buffer.from(h.first.job_id).toString('base64url')}.jsonl`); +} +function rewriteEvents(h, entries) { + writeFileSync(eventPath(h), entries.map(entry => JSON.stringify(entry)).join('\n') + '\n'); +} +function reopened(h) { + return createOfflineOrchestrationPrototypeForTest({ store: new LocalFilePrototypeStore(h.root), + runtime: clock('inspection-epoch'), executionAuthorityProvider: authority().verifier }); +} +function assertInspection(h, status) { + const before = readFileSync(eventPath(h)); + for (const runner of [h.runner, reopened(h)]) { + const result = runner.inspectRecovery(h.first.job_id); + assert.equal(result.status, status, JSON.stringify(result)); + assert.equal(result.read_only, true); + assert.equal(result.no_writes, true); + assert.equal(result.no_provider_calls, true); + } + assert.deepEqual(readFileSync(eventPath(h)), before); + // Retrying or stopping must never rewrite the first terminal result. + assert.deepEqual(readFileSync(h.firstResultPath), h.firstResultBytes); +} +function assertIntegrity(h) { + for (const runner of [h.runner, reopened(h)]) { + const result = runner.inspectRecovery(h.first.job_id); + assert.equal(result.code, 'RECONCILIATION_REQUIRED', JSON.stringify(result)); + assert.equal(result.stage, 'integrity'); + } +} + +async function stoppedRetry(t, { resumed = true, phase = 'created', reason = 'deadline', claimDelay = 0 } = {}) { + const root = mkdtempSync(join(tmpdir(), 'dss-o10-recovery-')); + t.after(() => rmSync(root, { recursive: true, force: true })); + const store = new LocalFilePrototypeStore(root); + const execution = authority(); + const originalClock = clock('original-epoch'); + let activeClock = originalClock; + let stableNow = stableStart; + let stopping = false; + const mocks = []; + function stop() { + if (reason === 'authorization') execution.revoke(retryDecision); + else { activeClock.advance(300_000); stableNow += 300_000; } + } + function makeRunner(selectedStore) { + if (claimDelay && selectedStore !== store) { + const claimResume = selectedStore.claimResume.bind(selectedStore); + selectedStore.claimResume = (...args) => { + const result = claimResume(...args); + activeClock.advance(claimDelay); + stableNow += claimDelay; + return result; + }; + } + return createOfflineOrchestrationPrototypeForTest({ + store: selectedStore, runtime: activeClock, idFactory: randomUUID, + executionAuthorityProvider: execution.verifier, + resumeTimeAuthority: { + id: 'studio.synthetic.resume-time-v1', mode: 'synthetic', + domain_id: 'synthetic-resume-time-v1', epoch_id: 'fixture-epoch-1', now: () => stableNow + }, + onMockCall({ phase: observed }) { if (stopping && phase === observed) stop(); }, + mockAdapterFactory(configuration) { + const mock = new MockTextAdapter(configuration); + if (stopping && phase === 'in-flight') { + const execute = mock.execute.bind(mock); + mock.execute = (...args) => { stop(); activeClock.fireTimers(); return execute(...args); }; + } + mocks.push(mock); + return mock; + } + }); + } + let runner = makeRunner(store); + const first = await runner.submit({ productionSource, noOutputResultVersion: '1.1.0', + mockOutcome: { kind: 'rate-limit', retry_after_ms: 10 } }); + assert.equal(first.retry_eligible, true); + const initial = store.readEvents(first.job_id); + const firstResult = initial.find(entry => entry.type === 'result-prepared'); + const firstResultPath = join(root, 'blobs', `${Buffer.from(`result:${firstResult.result_id}`).toString('base64url')}.blob`); + const firstResultBytes = readFileSync(firstResultPath); + stableNow += 10; + if (resumed) { + activeClock = clock('new-restarted-epoch'); + runner = makeRunner(new LocalFilePrototypeStore(root)); + } else originalClock.advance(10); + stopping = true; + const options = { mockOutcome: { kind: 'success', delay_ms: phase === 'in-flight' ? 5_000 : 0 } }; + const stopped = resumed + ? await runner.resume({ jobId: first.job_id, authorizeResume: true, ...options }) + : await runner.retry({ authorizeRetry: true, ...options }); + return { root, store, runner, first, stopped, mocks, initial, firstResultPath, firstResultBytes }; +} + +for (const phase of ['created', 'dispatch-confirmed', 'in-flight']) { + test(`O10 F1: resumed deadline at ${phase} retains truthful recovery across epochs`, async t => { + const h = await stoppedRetry(t, { phase }); + const status = phase === 'in-flight' ? 'contract-mapping-blocked' : 'budget-exhausted'; + assert.equal(h.stopped.status, status); + assert.deepEqual(h.mocks.map(mock => mock.calls.length), [1, phase === 'in-flight' ? 1 : 0]); + const entries = h.store.readEvents(h.first.job_id); + const prepared = entries.findLast(entry => entry.type === 'prepared'); + const admitted = entries.find(entry => entry.type === 'admitted'); + assert.deepEqual(prepared.resumed_clock, { + clock_epoch_id: 'new-restarted-epoch', sampled_monotonic_ms: 10_000, + sampled_at_ms: stableStart + 10, deadline_monotonic_ms: 309_990 + }); + assert.equal(prepared.resumed_clock.deadline_monotonic_ms, + prepared.resumed_clock.sampled_monotonic_ms + admitted.resume_time.deadline_at_ms + - prepared.resumed_clock.sampled_at_ms); + const stop = entries.findLast(entry => entry.type === 'budget-exhausted'); + assert.equal(stop.deadline_monotonic_ms, prepared.resumed_clock.deadline_monotonic_ms); + assert.notEqual(stop.deadline_monotonic_ms, admitted.deadline_monotonic_ms); + const outcomes = entries.filter(entry => entry.type === 'provider-outcome' && entry.attempt_id === prepared.attempt_id); + assert.equal(outcomes.length, phase === 'in-flight' ? 1 : 0); + if (phase === 'in-flight') assert.equal(outcomes[0].status, 'cancelled'); + assertInspection(h, status); + }); +} + +test('O10 F1: resumed mapping samples both clocks after the durable claim', async t => { + const h = await stoppedRetry(t, { claimDelay: 25 }); + const prepared = h.store.readEvents(h.first.job_id).findLast(e => e.type === 'prepared'); + assert.deepEqual(prepared.resumed_clock, { + clock_epoch_id: 'new-restarted-epoch', sampled_monotonic_ms: 10_025, + sampled_at_ms: stableStart + 35, deadline_monotonic_ms: 309_990 + }); + assert.deepEqual(h.mocks.map(mock => mock.calls.length), [1, 0]); + assertInspection(h, 'budget-exhausted'); +}); + +const clockCorruptions = { + 'missing mapping': prepared => { delete prepared.resumed_clock; }, + 'null mapping': prepared => { prepared.resumed_clock = null; }, + 'extra mapping field': prepared => { prepared.resumed_clock.extra = true; }, + 'array mapping': prepared => { prepared.resumed_clock = []; }, + 'negative stable date': prepared => { prepared.resumed_clock.sampled_at_ms = -1; }, + 'fractional stable date': prepared => { prepared.resumed_clock.sampled_at_ms += 0.5; }, + 'negative monotonic sample': prepared => { prepared.resumed_clock.sampled_monotonic_ms = -1; }, + 'noninteger translated deadline': prepared => { prepared.resumed_clock.deadline_monotonic_ms += 0.5; }, + 'missing epoch': prepared => { delete prepared.resumed_clock.clock_epoch_id; }, + 'empty epoch': prepared => { prepared.resumed_clock.clock_epoch_id = ''; }, + 'noninteger monotonic sample': prepared => { prepared.resumed_clock.sampled_monotonic_ms = 10_000.5; }, + 'invalid stable date': prepared => { prepared.resumed_clock.sampled_at_ms = Number.MAX_SAFE_INTEGER; }, + 'sample before retry bound': (prepared, entries) => { + prepared.resumed_clock.sampled_at_ms = entries.find(e => e.type === 'resume-window').retry_not_before_at_ms - 1; + prepared.resumed_clock.deadline_monotonic_ms += 1; + }, + 'sample at stable deadline': (prepared, entries) => { + prepared.resumed_clock.sampled_at_ms = entries.find(e => e.type === 'admitted').resume_time.deadline_at_ms; + prepared.resumed_clock.deadline_monotonic_ms = prepared.resumed_clock.sampled_monotonic_ms; + }, + 'incorrect translation': prepared => { prepared.resumed_clock.deadline_monotonic_ms += 1; }, + 'conflicting stop deadline': (_prepared, entries) => { + entries.findLast(e => e.type === 'budget-exhausted').deadline_monotonic_ms += 1; + }, + 'original epoch deadline substituted': (_prepared, entries) => { + entries.findLast(e => e.type === 'budget-exhausted').deadline_monotonic_ms = entries.find(e => e.type === 'admitted').deadline_monotonic_ms; + } +}; +for (const [name, corrupt] of Object.entries(clockCorruptions)) { + test(`O10 F1: reject ${name}`, async t => { + const h = await stoppedRetry(t); + const entries = structuredClone(h.store.readEvents(h.first.job_id)); + corrupt(entries.findLast(e => e.type === 'prepared'), entries); + rewriteEvents(h, entries); + assertIntegrity(h); + }); +} + +test('O10 F1: historical same-process deadline records need no resumed mapping', async t => { + const h = await stoppedRetry(t, { resumed: false }); + const entries = h.store.readEvents(h.first.job_id); + assert.equal(entries.findLast(e => e.type === 'prepared').resumed_clock, undefined); + assertInspection(h, 'budget-exhausted'); +}); + +for (const resumed of [false, true]) { + for (const phase of ['created', 'dispatch-confirmed']) { + test(`O10 F3: ${resumed ? 'resumed' : 'ordinary'} retry denied at ${phase} is safely closed`, async t => { + const h = await stoppedRetry(t, { resumed, phase, reason: 'authorization' }); + assert.equal(h.stopped.status, 'authorization-denied'); + assert.deepEqual(h.mocks.map(mock => mock.calls.length), [1, 0]); + const entries = h.store.readEvents(h.first.job_id); + const prepared = entries.findLast(e => e.type === 'prepared'); + const trailing = entries.slice(entries.indexOf(prepared)); + assert.deepEqual(trailing.map(e => e.type), phase === 'created' + ? ['prepared', 'authorization-blocked', 'job-closed'] + : ['prepared', 'dispatch-started', 'authorization-blocked', 'job-closed']); + assert.deepEqual(trailing.at(-2), { type: 'authorization-blocked', job_id: h.first.job_id, + attempt_id: prepared.attempt_id, execution_id: prepared.execution_id, action: 'retry' }); + assert.equal(trailing.at(-1).reason, 'execution-authority-denied'); + assertInspection(h, 'closed-without-result'); + }); + } +} + +const authorizationCorruptions = { + 'wrong action': (stop) => { stop.action = 'execute'; }, + 'wrong job': (stop) => { stop.job_id = randomUUID(); }, + 'wrong attempt': (stop) => { stop.attempt_id = randomUUID(); }, + 'wrong execution': (stop) => { stop.execution_id = randomUUID(); }, + 'missing execution': (stop) => { delete stop.execution_id; }, + 'extra field': (stop) => { stop.reason = 'denied'; }, + 'stop before preparation': (stop, entries) => { + entries.splice(entries.indexOf(stop), 1); + entries.splice(entries.findLastIndex(e => e.type === 'prepared'), 0, stop); + }, + 'stop before dispatch': (stop, entries) => { + entries.splice(entries.indexOf(stop), 1); + entries.splice(entries.findLastIndex(e => e.type === 'dispatch-started'), 0, stop); + }, + 'closure before stop': (stop, entries) => { + const closure = entries.pop(); entries.splice(entries.indexOf(stop), 0, closure); + }, + 'wrong closure reason': (_stop, entries) => { entries.at(-1).reason = 'retry-budget-exhausted'; }, + 'missing closure': (_stop, entries) => { entries.pop(); }, + 'missing stop': (stop, entries) => { entries.splice(entries.indexOf(stop), 1); }, + 'duplicate stop': (stop, entries) => { entries.splice(-1, 0, { ...stop }); }, + 'duplicate closure': (_stop, entries) => { entries.push({ ...entries.at(-1) }); }, + 'contradictory budget stop': (stop, entries) => { entries.splice(-1, 0, { + type: 'budget-exhausted', job_id: stop.job_id, attempt_id: stop.attempt_id, + execution_id: stop.execution_id, reason: 'time', + deadline_monotonic_ms: entries.find(e => e.type === 'admitted').deadline_monotonic_ms + }); }, + 'contradictory cancellation stop': (stop, entries) => { entries.splice(-1, 0, { + type: 'cancelled-before-dispatch', job_id: stop.job_id, + attempt_id: stop.attempt_id, reason: 'caller-cancelled' + }); }, + 'contradictory provider outcome': (stop, entries) => { entries.splice(-1, 0, { + ...entries.find(e => e.type === 'provider-outcome'), attempt_id: stop.attempt_id, + execution_id: stop.execution_id + }); }, + 'contradictory result': (stop, entries) => { entries.splice(-1, 0, { + ...entries.find(e => e.type === 'result-prepared'), attempt_id: stop.attempt_id, + execution_id: stop.execution_id + }); } +}; +for (const [name, corrupt] of Object.entries(authorizationCorruptions)) { + test(`O10 F3: reject authorization closure with ${name}`, async t => { + const h = await stoppedRetry(t, { reason: 'authorization', phase: 'dispatch-confirmed' }); + const entries = structuredClone(h.store.readEvents(h.first.job_id)); + corrupt(entries.findLast(e => e.type === 'authorization-blocked'), entries); + rewriteEvents(h, entries); + assertIntegrity(h); + assert.deepEqual(h.mocks.map(mock => mock.calls.length), [1, 0]); + }); +} diff --git a/tests/offline-orchestration-prototype/retry-package-use-authority.test.js b/tests/offline-orchestration-prototype/retry-package-use-authority.test.js index 254ae44..8e9abff 100644 --- a/tests/offline-orchestration-prototype/retry-package-use-authority.test.js +++ b/tests/offline-orchestration-prototype/retry-package-use-authority.test.js @@ -13,13 +13,15 @@ import { createOfflineOrchestrationPrototypeForTest, InMemoryPrototypeStore } from '../../src/offline-orchestration-prototype/testing.js'; +import { OFFLINE_ORCHESTRATION_LIMITS } from '../../src/offline-orchestration-prototype/limits.js'; import { SYNTHETIC_EXECUTION_PURPOSE } from '../../src/offline-orchestration-prototype/execution-authority.js'; const fixture = JSON.parse(await readFile(new URL('../fixtures/comic-manifest-v1.json', import.meta.url), 'utf8')); const contextFixture = JSON.parse(await readFile(new URL('../fixtures/context-builder-v1.json', import.meta.url), 'utf8')); const productionSource = JSON.stringify(fixture.production); -function makeHarness({ shortRetryUseWindow = false } = {}) { +function makeHarness({ shortRetryUseWindow = false, onRetryDescribe, onFreshAuthority } = {}) { + let descriptions = 0; let monotonic = 10_000; let wallNow = Date.parse(fixture.at); let nextId = 1; @@ -80,20 +82,51 @@ function makeHarness({ shortRetryUseWindow = false } = {}) { }])); const store = new InMemoryPrototypeStore(); const mocks = []; + const blobs = new Map(); + const writeImmutable = store.writeImmutable.bind(store); + store.writeImmutable = (key, bytes) => { + const result = writeImmutable(key, bytes); + blobs.set(key, Buffer.from(bytes)); + return result; + }; + const authorityProvider = (provider, kind) => ({ + ...provider, + async verify(request) { + const evidence = await provider.verify(request); + if (descriptions >= 2) await onFreshAuthority?.(kind); + return evidence; + } + }); + class DeferredMock extends MockTextAdapter { + async describe() { + if (++descriptions === 2) await onRetryDescribe?.(); + return super.describe(); + } + } const value = createOfflineOrchestrationPrototypeForTest({ runtime, store, idFactory: () => `80000000-0000-4000-8000-${String(nextId++).padStart(12, '0')}`, - executionAuthorityProvider: execution.verifier, + executionAuthorityProvider: authorityProvider(execution.verifier, 'execution'), syntheticContextReaders: { id: 'studio.synthetic.comic-context-readers', mode: 'synthetic', readers }, - contextUseAuthorityProvider: use.verifier, + contextUseAuthorityProvider: authorityProvider(use.verifier, 'context'), mockAdapterFactory(configuration) { - const mock = new MockTextAdapter(configuration); + const mock = new DeferredMock(configuration); mocks.push(mock); return mock; } }); return { - value, store, reads, mocks, revoke: use.revoke, + value, store, reads, mocks, revoke: use.revoke, revokeExecution: execution.revoke, + snapshot(jobId) { + return { + ids: nextId - 1, + events: store.readEvents(jobId), + eventCount: store.eventCount, + blobCount: store.blobCount, + blobs: [...blobs.keys()].map(key => [key, store.readImmutable(key)]), + reads: [...reads] + }; + }, setWallNow(value) { wallNow = value; }, advance(value) { monotonic += value; } }; @@ -129,3 +162,59 @@ for (const denied of ['revoked', 'expired']) test(`cached retry with ${denied} p assert.equal(harness.mocks[0].calls.length, 1); assert.equal(harness.store.eventCount, eventCount); }); + +function deferred() { + let resolve; + const promise = new Promise(done => { resolve = done; }); + return { promise, resolve }; +} + +const lateDenials = [ + { name: 'execution revocation', code: 'EXECUTION_AUTHORITY_DENIED', + deny: harness => harness.revokeExecution('60000000-0000-4000-8000-000000000002') }, + { name: 'package-use revocation', code: 'SYNTHETIC_CONTEXT_AUTHORITY_DENIED', + deny: harness => harness.revoke('70000000-0000-4000-8000-000000000002') }, + { name: 'package-use expiry', code: 'SYNTHETIC_CONTEXT_AUTHORITY_DENIED', shortRetryUseWindow: true, + deny: harness => harness.setWallNow(Date.parse('2026-09-15T12:10:01Z')) }, + { name: 'cancellation', code: 'EXECUTION_AUTHORITY_DENIED', + deny: (_harness, controller) => controller.abort() }, + { name: 'deadline expiry', code: 'EXECUTION_DEADLINE_EXPIRED', + deny: harness => harness.advance(OFFLINE_ORCHESTRATION_LIMITS.jobBudgetMs) } +]; + +for (const boundary of ['describe', 'execution', 'context']) { + const denials = boundary === 'describe' ? lateDenials : lateDenials.slice(3); + for (const denial of denials) test(`cached retry rejects ${denial.name} during awaited ${boundary} before allocating an attempt`, async () => { + const entered = deferred(); + const release = deferred(); + const pause = async () => { + entered.resolve(); + await release.promise; + }; + const harness = makeHarness({ + shortRetryUseWindow: denial.shortRetryUseWindow, + onRetryDescribe: boundary === 'describe' ? pause : undefined, + onFreshAuthority: kind => kind === boundary ? pause() : undefined + }); + const first = await harness.value.submit({ + productionSource, syntheticContext: true, noOutputResultVersion: '1.1.0', + mockOutcome: { kind: 'rate-limit', retry_after_ms: 5 } + }); + assert.equal(first.retry_eligible, true); + const originalFirst = canonicalJson(first); + const before = harness.snapshot(first.job_id); + harness.advance(5); + const controller = new AbortController(); + const retry = harness.value.retry({ authorizeRetry: true, signal: controller.signal }); + const expectedCode = boundary === 'context' && denial.name === 'cancellation' + ? 'SYNTHETIC_CONTEXT_AUTHORITY_DENIED' : denial.code; + const rejected = assert.rejects(retry, error => error.code === expectedCode); + await entered.promise; + denial.deny(harness, controller); + release.resolve(); + await rejected; + assert.deepEqual(harness.mocks.map(mock => mock.calls.length), [1, 0]); + assert.deepEqual(harness.snapshot(first.job_id), before); + assert.equal(canonicalJson(first), originalFirst); + }); +} diff --git a/tests/offline-orchestration-prototype/runner.test.js b/tests/offline-orchestration-prototype/runner.test.js index d70e2b7..b45bb39 100644 --- a/tests/offline-orchestration-prototype/runner.test.js +++ b/tests/offline-orchestration-prototype/runner.test.js @@ -1904,6 +1904,8 @@ test('retry authority is rechecked after asynchronous mock preflight', async () const clock = createRuntime(); const authority = authorityFixture(); let descriptions = 0; + let allocatedIds = 0; + const freshId = idFactory(); const mocks = []; class RevokingMock extends MockTextAdapter { async describe() { @@ -1913,12 +1915,24 @@ test('retry authority is rechecked after asynchronous mock preflight', async () } const h = runner({ runtime: clock.runtime, + idFactory: () => { allocatedIds++; return freshId(); }, executionAuthorityProvider: authority.verifier, mockAdapterFactory: configuration => { const mock = new RevokingMock(configuration); mocks.push(mock); return mock; } }); const first = await h.value.submit(candidateOptions); + const beforeIds = allocatedIds; + const beforeEvents = h.store.readEvents(first.job_id); + const beforeBlobs = h.store.blobCount; + const firstResultKey = `result:${first.result.result_id}`; + const firstResultBytes = h.store.readImmutable(firstResultKey); clock.advance(10); - assert.equal((await h.value.retry({ authorizeRetry: true })).status, 'authorization-denied'); + await assert.rejects(() => h.value.retry({ authorizeRetry: true }), + error => error.code === 'EXECUTION_AUTHORITY_DENIED'); + assert.equal(allocatedIds, beforeIds); + assert.deepEqual(h.store.readEvents(first.job_id), beforeEvents); + assert.equal(h.store.blobCount, beforeBlobs); + assert.deepEqual(h.store.readImmutable(firstResultKey), firstResultBytes); + assert.deepEqual(mocks.map(mock => mock.calls.length), [1, 0]); assert.equal(mocks.reduce((count, mock) => count + mock.calls.length, 0), 1); assert.equal(h.store.readEvents(first.job_id).filter(e => e.type === 'dispatch-started').length, 1); }); @@ -1930,12 +1944,15 @@ test('retry evidence is revalidated after final authority await before mock disp unknownBlob: key => unknownEvidence && key.startsWith('provider-outcome:') }); const authority = authorityFixture(); - let retryVerifications = 0; + let jobId; const provider = { ...authority.verifier, async verify(request) { const evidence = await authority.verifier.verify(request); - if (request.action === 'retry' && ++retryVerifications === 3) unknownEvidence = true; + if (request.action === 'retry' + && store.readEvents(jobId).filter(item => item.type === 'dispatch-started').length === 2) { + unknownEvidence = true; + } return evidence; } }; @@ -1949,6 +1966,7 @@ test('retry evidence is revalidated after final authority await before mock disp } }); const first = await h.value.submit(candidateOptions); + jobId = first.job_id; clock.advance(10); const result = await h.value.retry({ authorizeRetry: true }); assert.equal(result.status, 'reconciliation-required');