import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, test } from 'bun:test'; import { GlobalWindow } from 'happy-dom'; import { act, createElement } from 'react'; import type { Root } from 'react-dom/client'; import { canonicalRunRequestSchema } from '@stock-bot/stock-config/canonical-research'; import { chronologicalValidationPolicy, type ChronologicalValidationInput, type ChronologicalValidationPreview, } from '@stock-bot/stock-config/chronological-validation'; import type { ChronologicalValidationActionReceipt, ChronologicalValidationDetail, ValidationResultEvidence, } from '@stock-bot/stock-config/chronological-validation'; import type { ExperimentDetail, ExperimentPreview, ExperimentTrial, } from '@stock-bot/stock-config/experiments'; import { builtinCatalogDescriptors } from '@stock-bot/stock-config/strategy'; import type { Backtest } from '../../apps/stock/web-app/src/features/backtest/services/backtestApiV2'; import { parseValidationDetail } from '../../apps/stock/web-app/src/features/experiments/services/chronologicalValidationDurableApi'; import { nativeReplayFixture } from '../fixtures/native-replay'; test('saved validation decodes explicit research agent actors without accepting malformed identities', () => { const value = document('reported'); if (!value.selection || !value.report) { throw new Error('Reported fixture needs immutable selection and report'); } const actor = 'agent:aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa'; value.selection.principal = actor; value.report.principal = actor; const parsed = parseValidationDetail(value); expect(parsed.selection?.principal).toBe(actor); expect(parsed.report?.principal).toBe(actor); expect(() => parseValidationDetail({ ...value, report: { ...value.report, principal: 'agent:operator' } }) ).toThrow(); }); const browser = new GlobalWindow({ url: 'http://localhost:5173' }); const keys = ['window', 'document', 'Event', 'ResizeObserver', 'IS_REACT_ACT_ENVIRONMENT'] as const; const originals = new Map(keys.map(key => [key, Object.getOwnPropertyDescriptor(globalThis, key)])); let createRoot: typeof import('react-dom/client').createRoot; let router: typeof import('react-router-dom'); let ExperimentListPage: typeof import('../../apps/stock/web-app/src/features/experiments').ExperimentListPage; let root: Root | undefined; let host: HTMLDivElement; let navigate: ReturnType; let location = ''; const backtestId = '11111111-1111-4111-8111-111111111111'; const otherBacktestId = '22222222-2222-4222-8222-222222222222'; const versionId = '55555555-5555-4555-8555-555555555555'; const endpoint = '/api/v2/experiments/validation/preview'; function deferred() { let resolve!: (value: T) => void; let reject!: (cause: Error) => void; const promise = new Promise((yes, no) => { resolve = yes; reject = no; }); return { promise, resolve, reject }; } type Pending = ReturnType> & { path: string; method: string; body: unknown; rawBody: unknown; headers: Headers; settled: boolean; signal?: AbortSignal | null; credentials?: RequestCredentials; }; const requests: Pending[] = []; function request(path: string, method = 'GET') { const found = requests.find( item => item.path === path && item.method === method && !item.settled ); if (!found) { throw new Error(`Missing ${method} ${path}`); } return found; } function reply(item: Pending, value: unknown, status = 200) { item.settled = true; item.resolve(Response.json(value, { status })); } async function flush(action: () => void = () => {}) { await act(async () => { action(); await Promise.resolve(); }); } function button(label: string) { const found = [...host.querySelectorAll('button')].find( item => item.textContent?.trim() === label ); if (!found) { throw new Error(`Missing button ${label}: ${host.textContent}`); } return found; } function field(label: string) { const found = [...host.querySelectorAll('label')] .find( item => item.firstChild?.textContent?.trim() === label || item.textContent?.trim() === label ) ?.querySelector('input,select,textarea'); if (!found) { throw new Error(`Missing field ${label}`); } return found as HTMLInputElement | HTMLSelectElement | HTMLTextAreaElement; } function change(label: string, value: string) { const input = field(label); const prototype = input.tagName === 'SELECT' ? browser.HTMLSelectElement.prototype : input.tagName === 'TEXTAREA' ? browser.HTMLTextAreaElement.prototype : browser.HTMLInputElement.prototype; Object.getOwnPropertyDescriptor(prototype, 'value')!.set!.call(input, value); input.dispatchEvent( new browser.Event(input.tagName === 'SELECT' ? 'change' : 'input', { bubbles: true, }) as unknown as Event ); } function Probe() { navigate = router.useNavigate(); location = router.useLocation().pathname + router.useLocation().search; return null; } const template = (id = backtestId): Backtest => ({ id, name: `Template ${id}`, strategy: 'sma', strategyVersionId: versionId, symbols: ['X0.US'], startDate: '2024-01-01', endDate: '2024-01-02', initialCapital: 100, config: { canonical: {}, datasetHash: 'a'.repeat(64) }, archivedAt: null, createdAt: '2026-10-24', updatedAt: '2026-10-24', }); let ChronologicalValidationDetailPage: typeof import('../../apps/stock/web-app/src/features/experiments/ChronologicalValidationDetailPage').ChronologicalValidationDetailPage; function sourcePreview(count = 2, parent = backtestId): ExperimentPreview { const owner = `strategy:${versionId}`; const { config, dataset } = nativeReplayFixture(60, 1, [owner]); const previewId = '00000000-0000-4000-8000-000000000001'; config.matching.risk.ledger.sessionId = previewId; config.matching.risk.ledger.accountId = `research:${previewId}`; const builtin = builtinCatalogDescriptors[0]!; const candidates = Array.from({ length: count }, (_, index) => ({ index, trialKey: String(index + 1).padStart(64, '0'), parameters: { fastPeriod: index + 2, slowPeriod: 20 }, })); return { version: 'research-experiment-preview/v1', previewHash: 'e'.repeat(64), input: { backtestId: parent, name: 'Trend study', grid: { fastPeriod: candidates.map(item => item.parameters.fastPeriod) }, }, dataset: dataset.manifest, candidates, request: canonicalRunRequestSchema.parse({ kind: 'canonical-research/v1', runId: previewId, backtestId: parent, name: 'Frozen template name', strategy: { familyId: '66666666-6666-4666-8666-666666666666', versionId, origin: 'builtin', reviewId: '88888888-8888-4888-8888-888888888888', package: { version: 1, program: builtin.program, parameterSchema: builtin.parameterSchema, artifact: { format: 'esm-bundle/v1', entryExport: builtin.entryExport, content: 'Never execute fixture code', sha256: 'a'.repeat(64), }, dependencyLock: { format: 'bun-lock/v1', content: 'Retained lock', sha256: 'b'.repeat(64), }, source: { revision: 'c'.repeat(40), dirty: false }, build: { tool: 'bun', version: '1.2.17', target: 'browser' }, }, selection: { strategyId: builtin.program.strategyId, strategyVersion: builtin.program.strategyVersion, ownerId: owner, seed: 17, instrumentId: 'X0.US', seriesId: 'X0.US:1m', ownerBudget: '100', parameters: { fastPeriod: 2, slowPeriod: 20 }, }, }, datasetHash: dataset.manifest.hash, policy: config, analyticsPolicy: { version: 1, periodsPerYear: 252, annualRiskFreeRate: 0, benchmark: null }, build: { version: 1, workerSha256: 'a'.repeat(64), engineWrapperSha256: 'b'.repeat(64), engineBinarySha256: 'c'.repeat(64), dependencyLockSha256: 'd'.repeat(64), runtime: 'bun', runtimeVersion: '1.2.17', platform: 'linux', arch: 'x64', }, modelArtifacts: [], }), }; } function prepared(): ChronologicalValidationPreview { const source = sourcePreview(); const start = source.dataset.bounds.warmupStart; const minute = 60000; const bounds = (offset: number) => ({ warmupStart: start + offset * minute, tradeStart: start + (offset + 22) * minute, tradeEnd: start + (offset + 30) * minute, }); const input: ChronologicalValidationInput = { ...source.input, recipe: { version: 1, train: bounds(0), validation: bounds(10), test: bounds(20), labelHorizonMs: 0, }, }; const phases = ['train', 'validation', 'test'] as const; const partitions = phases.map((phase, index) => { const dataset = { ...structuredClone(source.dataset), hash: ['a', 'b', 'c'][index]!.repeat(64), bounds: input.recipe[phase], barCount: 30, }; const request = { ...structuredClone(source.request), datasetHash: dataset.hash }; return { phase, dataset, request, counts: { totalBars: 30, availableWarmup: 21, admittedWarmup: 21, ignoredLateWarmup: 0, availableEvaluation: 8, terminalAtEnd: 1, unavailableAtEnd: 0, }, requiredWarmup: 21, warnings: ['Input history sufficiency does not establish statistical adequacy.'], }; }) as ChronologicalValidationPreview['partitions']; return { version: 'chronological-validation-preview/v1', execution: 'preview-only', previewHash: 'f'.repeat(64), input, source, policy: chronologicalValidationPolicy, partitions, }; } function metrics(): NonNullable { return { totalReturn: 0, cagr: null, maxDrawdown: 0, exposureTime: 0, volatility: null, downsideDeviation: null, sharpeRatio: null, sortinoRatio: null, var95: null, cvar95: null, var99: null, alpha: null, beta: null, informationRatio: null, roundTripCount: null, winRate: null, profitFactor: null, avgWin: null, avgLoss: null, }; } const validationId = '33333333-3333-4333-8333-333333333333'; const otherId = '44444444-4444-4444-8444-444444444444'; const childIds = { train: validationId, validation: '66666666-6666-4666-8666-666666666666', test: '77777777-7777-4777-8777-777777777777', }; const basePath = '/api/v2/experiments/validation'; const detailPath = `${basePath}/${validationId}`; const currentReview = 'aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa'; function phaseExperiment( source: ChronologicalValidationPreview, phase: 'train' | 'validation' | 'test', completed: boolean ): ExperimentDetail { const index = ['train', 'validation', 'test'].indexOf(phase), prototype = source.partitions[index]!; const winner = source.source.candidates[1]!; const candidates = phase === 'train' ? source.source.candidates : [{ ...winner, index: 0 }]; const input = { ...source.source.input, name: `${source.input.name} · ${phase}`, grid: phase === 'train' ? source.input.grid : {}, }; const request = structuredClone(prototype.request); if (phase !== 'train') { request.strategy.reviewId = currentReview; request.strategy.selection.parameters = winner.parameters as never; } const preview: ExperimentPreview = { version: 'research-experiment-preview/v1', previewHash: String(index + 1).repeat(64), input, dataset: prototype.dataset, request, candidates, }; const trials: ExperimentTrial[] = candidates.map((candidate, item) => ({ ...candidate, runId: `99999999-9999-4999-8999-${String(index * 10 + item + 1).padStart(12, '0')}`, attemptNumber: completed ? 1 : 0, retryCount: 0, status: completed ? 'completed' : 'pending', progress: completed ? 100 : 0, cancelRequested: false, error: null, comparable: completed, diagnostic: null, metrics: completed ? { ...metrics(), totalReturn: phase === 'train' && item === 0 ? -0.1 : 0 } : null, unavailable: completed ? { sharpeRatio: 'insufficient-periods' } : null, limitations: [], })); return { id: childIds[phase], name: input.name, backtestId: source.input.backtestId, createdAt: '2026-10-24T10:00:00Z', cancelRequested: false, trialCount: trials.length, counts: { pending: completed ? 0 : trials.length, running: 0, paused: 0, completed: completed ? trials.length : 0, failed: 0, cancelled: 0, }, datasetHash: prototype.dataset.hash, strategyVersionId: versionId, previewHash: preview.previewHash, preview, trials, }; } function evidenceFor( phase: 'train' | 'validation' | 'test', experiment: ExperimentDetail, index: number ): ValidationResultEvidence { const trial = experiment.trials[index]!; return { phase, experimentId: experiment.id, runId: trial.runId!, sourceCandidateIndex: phase === 'train' ? index : 1, trialKey: trial.trialKey, parameters: trial.parameters, datasetHash: experiment.datasetHash, requestHash: 'b'.repeat(64), economicHash: 'c'.repeat(64), metrics: trial.metrics!, unavailable: trial.unavailable!, completePeriodCount: 1, periodicSampleCount: 1, fillCount: 0, limitations: trial.limitations, }; } function document( stage: 'training' | 'ready' | 'holdouts' | 'holdouts-ready' | 'reported' = 'training' ): ChronologicalValidationDetail { const preview = prepared(); const train = phaseExperiment(preview, 'train', stage !== 'training'); const heldout = stage === 'holdouts' || stage === 'holdouts-ready' || stage === 'reported'; const validation = phaseExperiment(preview, 'validation', stage !== 'holdouts'); const test = phaseExperiment(preview, 'test', stage !== 'holdouts'); const selection: ChronologicalValidationDetail['selection'] = heldout ? { version: 'chronological-validation-selection/v1', id: 'bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb', validationId, previewHash: preview.previewHash, selectionHash: 'd'.repeat(64), createdAt: '2026-10-24T11:00:00Z', principal: 'operator', reviewId: currentReview, winner: preview.source.candidates[1]!, training: train.trials.map((_, index) => evidenceFor('train', train, index)), holdoutExperimentIds: { validation: childIds.validation, test: childIds.test }, } : null; return { id: validationId, name: preview.input.name, backtestId, createdAt: train.createdAt, cancelRequested: false, previewHash: preview.previewHash, trainingCandidateCount: 2, stage: stage === 'reported' ? 'reported' : heldout ? 'holdouts' : 'training', preview, phases: [ { phase: 'train', status: 'admitted', experimentId: train.id, experiment: train }, { phase: 'validation', status: heldout ? 'admitted' : 'not-admitted', experimentId: heldout ? validation.id : null, experiment: heldout ? validation : null, }, { phase: 'test', status: heldout ? 'admitted' : 'not-admitted', experimentId: heldout ? test.id : null, experiment: heldout ? test : null, }, ], selection, report: stage === 'reported' ? { version: 'chronological-validation-report/v1', id: 'cccccccc-cccc-4ccc-8ccc-cccccccccccc', validationId, previewHash: preview.previewHash, selectionHash: selection!.selectionHash, reportHash: 'e'.repeat(64), createdAt: '2026-10-24T12:00:00Z', principal: 'operator', reset: 'initial-capital-empty-positions', training: selection!.training, validation: evidenceFor('validation', validation, 0), test: evidenceFor('test', test, 0), limitations: ['Independent reset accounts; no continuous portfolio claim.'], } : null, actions: { select: { available: stage === 'ready', reason: stage === 'training' ? 'Every training candidate must complete with a comparable finite score.' : null, }, finalize: { available: stage === 'holdouts-ready', reason: stage === 'holdouts' ? 'Waiting for validation and test results.' : null, }, }, }; } function receipt( value: ChronologicalValidationDetail, operation: 'select' | 'finalize' ): ChronologicalValidationActionReceipt { const saved = operation === 'select' ? value.selection! : value.report!; return { id: saved.id, validationId: value.id, operation: operation === 'select' ? 'select-and-admit-holdouts' : 'finalize-report', previewHash: value.previewHash, selectionHash: value.selection!.selectionHash, createdAt: saved.createdAt, principal: saved.principal, }; } async function mount(path = `/experiments?backtestId=${backtestId}`) { root ??= createRoot(host); const routes = createElement( router.Routes, null, createElement(router.Route, { path: '/experiments', element: createElement(ExperimentListPage), }), createElement(router.Route, { path: '/experiments/validation/:validationId', element: createElement(ChronologicalValidationDetailPage), }) ); await flush(() => root!.render( createElement(router.MemoryRouter, { initialEntries: [path] }, routes, createElement(Probe)) ) ); } async function show(value = document()) { await mount(`/experiments/validation/${value.id}`); await flush(() => reply(request(`${basePath}/${value.id}`), { validation: value })); } async function editor() { const value = prepared(); await mount(); await flush(() => { reply(request('/api/v2/backtests?limit=50&offset=0'), [template(), template(otherBacktestId)]); reply(request(`/api/v2/experiments?backtestId=${backtestId}`), { experiments: [] }); reply(request(`${basePath}?backtestId=${backtestId}`), { validations: [] }); }); await flush(() => { change('Experiment name', value.input.name); change('Parameter grid (JSON)', JSON.stringify(value.input.grid)); for (const phase of ['train', 'validation', 'test'] as const) { const name = phase[0]!.toUpperCase() + phase.slice(1); change( `${name} warmup start (UTC)`, new Date(value.input.recipe[phase].warmupStart).toISOString() ); change( `${name} trading start (UTC)`, new Date(value.input.recipe[phase].tradeStart).toISOString() ); change( `${name} trading end (UTC)`, new Date(value.input.recipe[phase].tradeEnd).toISOString() ); } }); await flush(() => button('Preview chronological validation').click()); await flush(() => reply(request(endpoint, 'POST'), { preview: value })); return value; } async function lose(post: Pending) { await flush(() => { post.settled = true; post.reject(new Error('Response lost')); }); } beforeAll(async () => { for (const [key, value] of Object.entries({ window: browser, document: browser.document, Event: browser.Event, ResizeObserver: browser.ResizeObserver, IS_REACT_ACT_ENVIRONMENT: true, })) { Object.defineProperty(globalThis, key, { configurable: true, writable: true, value }); } ({ createRoot } = await import('react-dom/client')); router = await import('react-router-dom'); ({ ExperimentListPage } = await import('../../apps/stock/web-app/src/features/experiments')); ({ ChronologicalValidationDetailPage } = await import( '../../apps/stock/web-app/src/features/experiments/ChronologicalValidationDetailPage' )); }); beforeEach(() => { requests.length = 0; location = ''; host = browser.document.createElement('div') as unknown as HTMLDivElement; browser.document.body.append(host as never); Object.defineProperty(browser, 'confirm', { configurable: true, value: () => true }); Object.defineProperty(browser, 'fetch', { configurable: true, value: (input: unknown, init?: RequestInit) => { const url = new URL(String(input)); const item: Pending = { ...deferred(), path: url.pathname + url.search, method: init?.method ?? 'GET', rawBody: init?.body, body: typeof init?.body === 'string' ? JSON.parse(init.body) : undefined, headers: new Headers(init?.headers), signal: init?.signal, credentials: init?.credentials, settled: false, }; requests.push(item); return item.promise; }, }); }); afterEach(async () => { if (root) { await flush(() => root!.unmount()); } root = undefined; host.remove(); }); afterAll(async () => { await browser.happyDOM.close(); for (const key of keys) { const value = originals.get(key); if (value) { Object.defineProperty(globalThis, key, value); } else { Reflect.deleteProperty(globalThis, key); } } }); describe('durable chronological training admission', () => { test('preflight remains read-only until explicit duplicate-safe training admission', async () => { const source = await editor(); expect(host.textContent).toContain('No saved chronological validations.'); expect(requests.filter(item => item.path === basePath && item.method === 'POST')).toHaveLength( 0 ); await flush(() => { button('Submit training runs').click(); button('Submit training runs').click(); }); const post = request(basePath, 'POST'); expect(post.body).toEqual({ ...source.input, previewHash: source.previewHash }); expect(post.headers.get('Idempotency-Key')).toBeTruthy(); expect(post.credentials).toBe('include'); expect(requests.filter(item => item.path === basePath && item.method === 'POST')).toHaveLength( 1 ); expect(field('Experiment name').disabled).toBe(true); expect(field('Saved backtest').disabled).toBe(true); expect(button('Preview experiment').disabled).toBe(true); await flush(() => reply(post, { validation: document() }, 202)); expect(location).toBe(`/experiments/validation/${validationId}`); await flush(() => reply(request(detailPath), { validation: document() })); expect(host.textContent).toContain('Not admitted. No validation run exists'); }); test.each(['ordinary', 'chronological'] as const)( '%s wins synchronous shared-editor admission ownership', async winner => { const source = await editor(); await flush(() => button('Preview experiment').click()); await flush(() => reply(request('/api/v2/experiments/preview', 'POST'), { preview: source.source }) ); const ordinary = button('Confirm experiment'), chronological = button('Submit training runs'); await flush(() => { if (winner === 'ordinary') { ordinary.click(); chronological.click(); } else { chronological.click(); ordinary.click(); } }); const admitted = requests.filter( item => item.method === 'POST' && [basePath, '/api/v2/experiments'].includes(item.path) ); expect(admitted).toHaveLength(1); expect(admitted[0]!.path).toBe(winner === 'ordinary' ? '/api/v2/experiments' : basePath); await lose(admitted[0]!); expect(field('Experiment name').disabled).toBe(true); expect( button(winner === 'ordinary' ? 'Preview chronological validation' : 'Preview experiment') .disabled ).toBe(true); } ); test.each(['network', 'malformed', 'foreign'] as const)( '%s training response retains exact body/key and locks shared fields until explicit release', async kind => { await editor(); await flush(() => button('Submit training runs').click()); const first = request(basePath, 'POST'); if (kind === 'network') { await lose(first); } else { const foreign = document(); foreign.backtestId = otherBacktestId; await flush(() => reply( first, kind === 'malformed' ? { validation: { id: validationId } } : { validation: foreign }, 202 ) ); } expect(host.textContent).toContain('Training admission is unconfirmed'); expect(field('Parameter grid (JSON)').disabled).toBe(true); await flush(() => button('Refresh chronological validations').click()); await flush(() => reply(request(`${basePath}?backtestId=${backtestId}`), { validations: [document()] }) ); await flush(() => button('Retry training submission').click()); const retry = request(basePath, 'POST'); expect(retry.rawBody).toBe(first.rawBody); expect(retry.headers.get('Idempotency-Key')).toBe(first.headers.get('Idempotency-Key')); await flush(() => reply(retry, { validation: document('reported') }, 202)); expect(location).toBe(`/experiments/validation/${validationId}`); } ); test('training intent is discarded only explicitly, and requires a fresh preview afterward', async () => { await editor(); await flush(() => button('Submit training runs').click()); await lose(request(basePath, 'POST')); Object.defineProperty(browser, 'confirm', { configurable: true, value: () => false }); await flush(() => button('Discard training submission').click()); expect(field('Experiment name').disabled).toBe(true); Object.defineProperty(browser, 'confirm', { configurable: true, value: () => true }); await flush(() => button('Discard training submission').click()); expect(field('Experiment name').disabled).toBe(false); expect(host.textContent).not.toContain('Retry training submission'); expect(button('Preview experiment').disabled).toBe(false); expect( [...host.querySelectorAll('button')].some(item => item.textContent === 'Submit training runs') ).toBe(false); }); test('late accepted training response cannot navigate a different selected template', async () => { await editor(); await flush(() => button('Submit training runs').click()); const old = request(basePath, 'POST'); await flush(() => navigate(`/experiments?backtestId=${otherBacktestId}`)); await flush(() => reply(old, { validation: document() }, 202)); expect(location).toBe(`/experiments?backtestId=${otherBacktestId}`); expect(field('Experiment name').value).toBe(''); }); }); describe('explicit selection and immutable reporting', () => { test('training → fixed selection → holdouts → report requires separate POSTs; refresh never advances', async () => { await show(document()); expect(button('Freeze selection and run holdouts').disabled).toBe(true); expect(host.textContent).toContain('Every training candidate must complete'); await flush(() => button('Refresh validation').click()); await flush(() => reply(request(detailPath), { validation: document('ready') })); expect(requests.filter(item => item.method === 'POST')).toHaveLength(0); await flush(() => { button('Freeze selection and run holdouts').click(); button('Freeze selection and run holdouts').click(); }); const select = request(`${detailPath}/select`, 'POST'); expect(select.body).toEqual({ previewHash: prepared().previewHash }); expect(requests.filter(item => item.method === 'POST')).toHaveLength(1); await flush(() => reply( select, { receipt: receipt(document('holdouts'), 'select'), validation: document('holdouts') }, 202 ) ); expect(host.textContent).toContain('Selected training candidate 2'); expect(button('Save validation report').disabled).toBe(true); for (const phase of ['train', 'validation', 'test'] as const) { expect(host.querySelector(`a[href="/experiments/${childIds[phase]}"]`)?.textContent).toBe( `Open ${phase} experiment` ); } await flush(() => button('Refresh validation').click()); await flush(() => reply(request(detailPath), { validation: document('holdouts-ready') })); expect(requests.filter(item => item.method === 'POST')).toHaveLength(1); await flush(() => button('Save validation report').click()); const finalize = request(`${detailPath}/finalize`, 'POST'); expect(finalize.body).toEqual({ previewHash: prepared().previewHash, selectionHash: 'd'.repeat(64), }); const reported = document('reported'); await flush(() => reply(finalize, { receipt: receipt(reported, 'finalize'), validation: reported }, 202) ); expect(host.textContent).toContain('Execution complete · report saved'); expect(host.textContent).toContain(reported.report!.reportHash); expect(host.textContent).toContain('Insufficient periodic samples'); expect(host.textContent).toContain('Unavailable: insufficient-periods'); const firstHoldout = host.querySelector( '[aria-label="Retained validation and test evidence"] tbody tr' )!; expect(firstHoldout.querySelectorAll('td')[2]!.textContent).toBe('0'); expect(host.textContent).not.toContain('strategy validated'); await flush(() => button('Refresh validation').click()); await flush(() => reply(request(detailPath), { validation: reported })); expect(host.textContent).toContain(reported.report!.id); expect(requests.filter(item => item.method === 'POST')).toHaveLength(2); }); test.each(['select', 'finalize'] as const)( 'lost %s receipt survives refresh to reported/cancelled state and retains its original operation', async operation => { await show(document(operation === 'select' ? 'ready' : 'holdouts-ready')); await flush(() => button( operation === 'select' ? 'Freeze selection and run holdouts' : 'Save validation report' ).click() ); const first = request(`${detailPath}/${operation}`, 'POST'); await lose(first); const current = document('reported'); current.cancelRequested = true; await flush(() => button('Refresh validation').click()); await flush(() => reply(request(detailPath), { validation: current })); expect(host.textContent).toContain('Action acceptance is unconfirmed'); const label = operation === 'select' ? 'Retry selection request' : 'Retry report request'; await flush(() => button(label).click()); const repeated = request(`${detailPath}/${operation}`, 'POST'); expect(repeated.rawBody).toBe(first.rawBody); expect(repeated.headers.get('Idempotency-Key')).toBe(first.headers.get('Idempotency-Key')); await flush(() => reply(repeated, { receipt: receipt(current, operation), validation: current }, 202) ); expect(host.textContent).not.toContain('Action acceptance is unconfirmed'); expect(host.textContent).toContain('Execution complete · report saved'); expect( requests .filter(item => item.method === 'POST') .every(item => item.path.endsWith(`/${operation}`)) ).toBe(true); } ); test('read failure preserves unresolved action and exact replay while cancellation remains separate', async () => { await show(document('ready')); await flush(() => button('Freeze selection and run holdouts').click()); const first = request(`${detailPath}/select`, 'POST'); await lose(first); await flush(() => button('Refresh validation').click()); await flush(() => reply(request(detailPath), { error: 'Read unavailable' }, 500)); expect(host.textContent).toContain('Showing the last loaded state'); await flush(() => button('Cancel remaining validation work').click()); const cancelled = document('holdouts'); cancelled.cancelRequested = true; await flush(() => reply(request(`${detailPath}/cancel`, 'POST'), { validation: cancelled })); expect(host.textContent).toContain('Action acceptance is unconfirmed'); await flush(() => button('Retry selection request').click()); const repeated = request(`${detailPath}/select`, 'POST'); expect(repeated.rawBody).toBe(first.rawBody); expect(repeated.headers.get('Idempotency-Key')).toBe(first.headers.get('Idempotency-Key')); await flush(() => reply(repeated, { receipt: receipt(cancelled, 'select'), validation: cancelled }, 202) ); expect(host.textContent).toContain('Selection and holdout admission accepted.'); }); test.each([ 'receipt-id', 'receipt-actor', 'receipt-operation', 'receipt-hash', 'evidence-metric', 'evidence-status', 'evidence-order', 'winner-index', ] as const)( 'malformed %s select result does not fabricate success and keeps the exact request', async kind => { await show(document('ready')); await flush(() => button('Freeze selection and run holdouts').click()); const first = request(`${detailPath}/select`, 'POST'); const value = document('holdouts'), accepted = receipt(value, 'select'); if (kind === 'receipt-id') { accepted.id = otherId; } if (kind === 'receipt-actor') { accepted.principal = 'service'; } if (kind === 'receipt-operation') { accepted.operation = 'finalize-report'; } if (kind === 'receipt-hash') { accepted.selectionHash = '1'.repeat(64); } if (kind === 'evidence-metric') { value.selection!.training[0]!.metrics = { ...value.selection!.training[0]!.metrics, totalReturn: 5, }; } if (kind === 'evidence-status') { const train = value.phases[0].experiment!; train.trials[0]!.status = 'failed'; train.trials[0]!.comparable = false; train.counts.failed = 1; train.counts.completed = 1; } if (kind === 'evidence-order') { value.selection!.training.reverse(); } if (kind === 'winner-index') { value.selection!.winner = { ...value.selection!.winner, index: 0 }; } await flush(() => reply(first, { receipt: accepted, validation: value }, 202)); expect(host.textContent).toContain('could not be verified'); expect(host.textContent).toContain('Action acceptance is unconfirmed'); expect(host.textContent).not.toContain('Selection and holdout admission accepted.'); await flush(() => button('Retry selection request').click()); const retry = request(`${detailPath}/select`, 'POST'); expect(retry.rawBody).toBe(first.rawBody); expect(retry.headers.get('Idempotency-Key')).toBe(first.headers.get('Idempotency-Key')); } ); test('failed, missing and not-admitted phases remain distinct with no invented pending jobs', async () => { const value = document('holdouts'); value.phases[2] = { ...value.phases[2], status: 'missing', experiment: null }; const heldout = value.phases[1].experiment!; heldout.trials[0]!.status = 'failed'; heldout.trials[0]!.error = 'Worker failed'; heldout.counts.pending = 0; heldout.counts.failed = 1; await show(value); expect(host.textContent).toContain('Expected test experiment is missing'); expect(host.textContent).toContain('Worker failed'); expect(host.textContent).toContain('Total return (fraction): Unavailable'); expect(button('Save validation report').disabled).toBe(true); expect(host.textContent).not.toContain('No test run exists before'); }); test.each([400, 401, 404, 409, 500])( 'action HTTP %s preserves explicit error and performs no automatic next step', async status => { await show(document('ready')); await flush(() => button('Freeze selection and run holdouts').click()); await flush(() => reply(request(`${detailPath}/select`, 'POST'), { error: 'Selection not available' }, status) ); expect(host.textContent).toContain('Selection not available'); expect(requests.filter(item => item.method === 'POST')).toHaveLength(1); Object.defineProperty(browser, 'confirm', { configurable: true, value: () => false }); await flush(() => button('Discard action request').click()); expect(host.textContent).toContain('Retry selection request'); } ); }); describe('durable validation read and navigation isolation', () => { test.each(['Freeze selection and run holdouts', 'Cancel remaining validation work'])( 'same-event refresh fences %s before another action captures an intent', async label => { await show(document('ready')); await flush(() => { button('Refresh validation').click(); button(label).click(); }); expect(requests.filter(item => item.method === 'POST')).toHaveLength(0); expect(host.textContent).not.toContain('Retry selection request'); await flush(() => reply(request(detailPath), { validation: document('ready') })); await flush(() => button(label).click()); expect(requests.filter(item => item.method === 'POST')).toHaveLength(1); } ); test('select/cancel and refresh share synchronous mutation exclusion', async () => { await show(document('ready')); await flush(() => { button('Cancel remaining validation work').click(); button('Freeze selection and run holdouts').click(); button('Refresh validation').click(); }); expect(requests.filter(item => item.method === 'POST')).toHaveLength(1); expect(requests.filter(item => item.path === detailPath && item.method === 'GET')).toHaveLength( 1 ); expect(requests.find(item => item.method === 'POST')!.path).toBe(`${detailPath}/cancel`); }); test('owned navigation preserves the unresolved action when discard is declined', async () => { await show(document('ready')); await flush(() => button('Freeze selection and run holdouts').click()); const first = request(`${detailPath}/select`, 'POST'); await lose(first); Object.defineProperty(browser, 'confirm', { configurable: true, value: () => false }); await flush(() => (host.querySelector('a[href="/experiments"]') as HTMLAnchorElement).click()); await flush(() => (host.querySelector(`a[href="/experiments/${validationId}"]`) as HTMLAnchorElement).click() ); expect(location).toBe(`/experiments/validation/${validationId}`); await flush(() => button('Retry selection request').click()); expect(request(`${detailPath}/select`, 'POST').headers.get('Idempotency-Key')).toBe( first.headers.get('Idempotency-Key') ); }); test('late action and read responses cannot overwrite a different validation route', async () => { await show(document('ready')); await flush(() => button('Freeze selection and run holdouts').click()); const old = request(`${detailPath}/select`, 'POST'); await flush(() => navigate(`/experiments/validation/${otherId}`)); await flush(() => reply(request(`${basePath}/${otherId}`), { error: 'Other validation unavailable' }, 404) ); const value = document('holdouts'); await flush(() => reply(old, { receipt: receipt(value, 'select'), validation: value }, 202)); expect(host.textContent).toContain('Other validation unavailable'); expect(host.textContent).not.toContain('Selected training candidate'); await flush(() => button('Refresh validation').click()); const read = request(`${basePath}/${otherId}`); await flush(() => navigate(`/experiments/validation/${validationId}`)); await flush(() => reply(request(detailPath), { validation: document('ready') })); await flush(() => reply(read, { error: 'Stale failure' }, 500)); expect(host.textContent).not.toContain('Stale failure'); expect(button('Freeze selection and run holdouts').disabled).toBe(false); }); test('saved validation list loads independently, recovers errors and reopens exact root identity', async () => { await mount(); expect(host.textContent).toContain('Loading chronological validations...'); await flush(() => reply(request(`${basePath}?backtestId=${backtestId}`), { error: 'List unavailable' }, 500) ); expect(host.textContent).toContain('List unavailable'); await flush(() => button('Refresh chronological validations').click()); const saved = document('reported'); await flush(() => reply(request(`${basePath}?backtestId=${backtestId}`), { validations: [saved] }) ); const link = host.querySelector( `a[href="/experiments/validation/${validationId}"]` ) as HTMLAnchorElement; expect(link.textContent).toBe(saved.name); await flush(() => link.click()); await flush(() => reply(request(detailPath), { validation: saved })); expect(host.textContent).toContain(saved.report!.id); expect(host.textContent).toContain(saved.report!.reportHash); }); test('old list filter response cannot expose another template validation', async () => { await mount(); const old = request(`${basePath}?backtestId=${backtestId}`); await flush(() => navigate(`/experiments?backtestId=${otherBacktestId}`)); await flush(() => reply(request(`${basePath}?backtestId=${otherBacktestId}`), { validations: [] }) ); await flush(() => reply(old, { validations: [document()] })); expect(host.textContent).toContain('No saved chronological validations.'); expect(host.querySelector(`a[href="/experiments/validation/${validationId}"]`)).toBeNull(); }); });