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 { type ChronologicalValidationPreview } from '@stock-bot/stock-config/chronological-validation'; import type { 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 { walkForwardPolicy, type WalkForwardDetail, type WalkForwardPreview, type WalkForwardReceipt, } from '@stock-bot/stock-config/walk-forward'; import { buildExperimentPreview } from '../../apps/stock/web-api/src/services/experiment-input'; import { prepareChronologicalValidation } from '../../apps/stock/web-api/src/services/validation-preview'; import type { Backtest } from '../../apps/stock/web-app/src/features/backtest/services/backtestApiV2'; import { parseWalkForwardDetail } from '../../apps/stock/web-app/src/features/experiments/services/walkForwardApi'; import { nativeReplayFixture } from '../fixtures/native-replay'; import { walkForwardDataset } from '../fixtures/walk-forward'; test('saved walk-forward report preserves agent authorship across nested validation evidence', () => { const value = document('reported'); if (!value.report) { throw new Error('Reported fixture needs its immutable report'); } const actor = 'agent:aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa'; value.report.principal = actor; for (const window of value.windows) { if (!window.validation?.selection || !window.validation.report) { throw new Error('Reported window needs its selection and report'); } window.validation.selection.principal = actor; window.validation.report.principal = actor; } const parsed = parseWalkForwardDetail(value); expect(parsed.report?.principal).toBe(actor); expect(parsed.windows.map(window => window.validation?.report?.principal)).toEqual([ actor, actor, ]); expect(() => parseWalkForwardDetail({ ...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 basePath = '/api/v2/experiments/walk-forward'; const endpoint = `${basePath}/preview`; const seriesId = 'eeeeeeee-eeee-4eee-8eee-eeeeeeeeeeee'; const otherId = 'ffffffff-ffff-4fff-8fff-ffffffffffff'; const detailPath = `${basePath}/${seriesId}`; 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 WalkForwardDetailPage: typeof import('../../apps/stock/web-app/src/features/experiments/WalkForwardDetailPage').WalkForwardDetailPage; 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 } = nativeReplayFixture(72, 1, [owner]); const { dataset } = walkForwardDataset(); 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: 4 }, })); const source: ExperimentPreview = { 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: 4 }, }, }, 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: [], }), }; return buildExperimentPreview(source.input, source.request, source.dataset); } 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, }; } function prepared(): WalkForwardPreview { const source = sourcePreview(), fixture = walkForwardDataset(); const input = { ...source.input, windows: fixture.windows }; return { version: 'walk-forward-preview/v1', execution: 'preview-only', previewHash: 'f'.repeat(64), input, source, policy: walkForwardPolicy, windows: input.windows.map((recipe, index) => { const windowSource = buildExperimentPreview( { ...source.input, name: `${input.name} · window ${index + 1}` }, source.request, source.dataset ); return { index, preview: prepareChronologicalValidation( { ...windowSource.input, recipe }, windowSource, fixture.dataset ).preview, }; }), counts: { windows: 2, trainingRuns: 4, holdoutRuns: 4, totalRuns: 8, maxRuns: 100 }, }; } const id = (number: number) => `99999999-9999-4999-8999-${String(number).padStart(12, '0')}`; function memberDocument( preview: ChronologicalValidationPreview, index: number, sealed: boolean ): ChronologicalValidationDetail { const base = 100 * (index + 1), winner = preview.source.candidates[1]!; const phaseIds = { train: id(base), validation: id(base + 1), test: id(base + 2) }; const experiments = preview.partitions.map((part, phaseIndex): ExperimentDetail => { const candidates = phaseIndex === 0 ? preview.source.candidates : [{ ...winner, index: 0 }], request = structuredClone(part.request); if (phaseIndex !== 0) { request.strategy.selection.parameters = winner.parameters as never; } const input = { ...preview.source.input, name: `${preview.input.name} · ${part.phase}`, grid: phaseIndex === 0 ? preview.input.grid : {}, }; const childPreview: ExperimentPreview = { version: 'research-experiment-preview/v1', previewHash: String(phaseIndex + 1).repeat(64), input, request, dataset: part.dataset, candidates, }; const trials: ExperimentTrial[] = candidates.map((candidate, trialIndex) => ({ ...candidate, runId: id(base + 10 + phaseIndex * 10 + trialIndex), attemptNumber: sealed ? 1 : 0, retryCount: 0, status: sealed ? 'completed' : 'pending', progress: sealed ? 100 : 0, cancelRequested: false, error: null, comparable: sealed, diagnostic: null, metrics: sealed ? { ...metrics(), totalReturn: phaseIndex === 0 && trialIndex === 0 ? -0.1 : 0 } : null, unavailable: sealed ? { sharpeRatio: 'insufficient-periods' } : null, limitations: ['Reviewed fixture limitation.'], })); return { id: phaseIds[part.phase], name: input.name, backtestId, createdAt: '2026-10-24T10:00:00Z', cancelRequested: false, trialCount: trials.length, counts: { pending: sealed ? 0 : trials.length, running: 0, paused: 0, completed: sealed ? trials.length : 0, failed: 0, cancelled: 0, }, datasetHash: part.dataset.hash, strategyVersionId: versionId, previewHash: childPreview.previewHash, preview: childPreview, trials, }; }); const evidence = (phaseIndex: number, trialIndex: number): ValidationResultEvidence => { const experiment = experiments[phaseIndex]!, trial = experiment.trials[trialIndex]!; return { phase: preview.partitions[phaseIndex]!.phase, experimentId: experiment.id, runId: trial.runId!, sourceCandidateIndex: phaseIndex === 0 ? trialIndex : 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, }; }; const selection = sealed ? { version: 'chronological-validation-selection/v1' as const, id: id(base + 3), validationId: phaseIds.train, previewHash: preview.previewHash, selectionHash: 'd'.repeat(64), createdAt: '2026-10-24T11:00:00Z', principal: 'operator' as const, reviewId: preview.source.request.strategy.reviewId, winner, training: experiments[0]!.trials.map((_, i) => evidence(0, i)), holdoutExperimentIds: { validation: phaseIds.validation, test: phaseIds.test }, } : null; return { id: phaseIds.train, name: preview.input.name, backtestId, createdAt: experiments[0]!.createdAt, cancelRequested: false, previewHash: preview.previewHash, trainingCandidateCount: 2, stage: sealed ? 'reported' : 'training', preview, phases: preview.partitions.map((part, i) => ({ phase: part.phase, status: i === 0 || sealed ? 'admitted' : 'not-admitted', experimentId: i === 0 || sealed ? experiments[i]!.id : null, experiment: i === 0 || sealed ? experiments[i]! : null, })) as ChronologicalValidationDetail['phases'], selection, report: sealed ? { version: 'chronological-validation-report/v1', id: id(base + 4), validationId: phaseIds.train, 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: evidence(1, 0), test: evidence(2, 0), limitations: ['Independent reset accounts.'], } : null, actions: { select: { available: false, reason: sealed ? null : 'Every training candidate must complete.', }, finalize: { available: false, reason: sealed ? null : 'Waiting for holdout evidence.' }, }, }; } function document(stage: 'training' | 'ready' | 'reported' = 'training'): WalkForwardDetail { const preview = prepared(), members = preview.windows.map(item => memberDocument(item.preview, item.index, stage !== 'training') ); return { id: seriesId, backtestId, name: preview.input.name, previewHash: preview.previewHash, createdAt: '2026-10-24T10:00:00Z', cancelRequested: false, windowCount: 2, reportedWindowCount: stage === 'training' ? 0 : 2, trainingRunCount: 4, plannedRunCount: 8, stage: stage === 'reported' ? 'reported' : 'windows', preview, windows: members.map((validation, index) => ({ index, validationId: validation.id, status: 'admitted', validation, })), report: stage === 'reported' ? { version: 'walk-forward-report/v1', id: id(999), walkForwardId: seriesId, previewHash: preview.previewHash, reportHash: 'a'.repeat(64), createdAt: '2026-10-24T13:00:00Z', principal: 'operator', reset: 'initial-capital-empty-positions', segments: members.map((member, index) => ({ index, validationId: member.id, previewHash: member.previewHash, selectionHash: member.report!.selectionHash, reportId: member.report!.id, reportHash: member.report!.reportHash, validation: member.report!.validation, test: member.report!.test, })), limitations: ['No compounding or averaged metrics.'], } : null, actions: { finalize: { available: stage === 'ready', reason: stage === 'training' ? 'Every window requires a complete immutable report.' : null, }, }, }; } function receipt(value: WalkForwardDetail): WalkForwardReceipt { const report = value.report!; return { id: report.id, walkForwardId: value.id, operation: 'finalize-walk-forward-report', previewHash: value.previewHash, reportHash: report.reportHash, createdAt: report.createdAt, principal: report.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), }), createElement(router.Route, { path: '/experiments/walk-forward/:walkForwardId', element: createElement(WalkForwardDetailPage), }) ); await flush(() => root!.render( createElement(router.MemoryRouter, { initialEntries: [path] }, routes, createElement(Probe)) ) ); } async function show(value = document()) { await mount(`/experiments/walk-forward/${value.id}`); await flush(() => reply(request(`${basePath}/${value.id}`), { walkForward: 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}`), { walkForwards: [] }); reply(request(`/api/v2/experiments/validation?backtestId=${backtestId}`), { validations: [] }); }); await flush(() => { change('Experiment name', value.input.name); change('Parameter grid (JSON)', JSON.stringify(value.input.grid)); for (const [index, recipe] of value.input.windows.entries()) { for (const phase of ['train', 'validation', 'test'] as const) { const label = phase[0]!.toUpperCase() + phase.slice(1); for (const [field, key] of [ ['warmup start', 'warmupStart'], ['trading start', 'tradeStart'], ['trading end', 'tradeEnd'], ] as const) { change( `Window ${index + 1} ${label} ${field} (UTC)`, new Date(recipe[phase][key]).toISOString() ); } } } }); await flush(() => button('Preview walk-forward').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')); ({ WalkForwardDetailPage } = await import( '../../apps/stock/web-app/src/features/experiments/WalkForwardDetailPage' )); ({ 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('walk-forward editor and exact admission', () => { test('preview is read-only, shows the full budget, and submission is duplicate-safe', async () => { const preview = await editor(); expect(host.textContent).toContain( '2 windows · 4 training runs · 4 future holdout runs · 8 total planned runs' ); expect(host.textContent).toContain('No saved walk-forward validations.'); expect(requests.filter(item => item.path === basePath && item.method === 'POST')).toHaveLength( 0 ); const submit = button('Submit walk-forward training'); await flush(() => { submit.click(); submit.click(); }); const accepted = request(basePath, 'POST'); expect(accepted.body).toEqual({ ...preview.input, previewHash: preview.previewHash }); expect(accepted.headers.get('Idempotency-Key')).toBeTruthy(); expect(accepted.credentials).toBe('include'); expect(requests.filter(item => item.path === basePath && item.method === 'POST')).toHaveLength( 1 ); await flush(() => reply(accepted, { walkForward: document() }, 202)); expect(location).toBe(`/experiments/walk-forward/${seriesId}`); }); test.each(['network', 'malformed', 'foreign'] as const)( '%s submission retains exact body/key through failure and locks every other flow', async kind => { await editor(); await flush(() => button('Submit walk-forward training').click()); const original = request(basePath, 'POST'); if (kind === 'network') { await lose(original); } else { await flush(() => { const value = document(); if (kind === 'foreign') { value.preview.input.name = 'Foreign'; } reply(original, kind === 'malformed' ? { walkForward: {} } : { walkForward: value }, 202); }); } expect(host.textContent).toContain('Acceptance is unconfirmed.'); expect(field('Experiment name').disabled).toBe(true); expect(button('Preview experiment').disabled).toBe(true); expect(button('Preview chronological validation').disabled).toBe(true); await flush(() => button('Retry walk-forward submission').click()); const retry = request(basePath, 'POST'); expect(retry.rawBody).toBe(original.rawBody); expect(retry.headers.get('Idempotency-Key')).toBe(original.headers.get('Idempotency-Key')); await flush(() => reply(retry, { walkForward: document('reported') }, 202)); expect(location).toBe(`/experiments/walk-forward/${seriesId}`); } ); test('explicit discard preserves draft but requires a new preview and key', async () => { await editor(); await flush(() => button('Submit walk-forward training').click()); const original = request(basePath, 'POST'); await lose(original); Object.defineProperty(browser, 'confirm', { configurable: true, value: () => false }); await flush(() => button('Discard walk-forward submission').click()); expect(field('Experiment name').disabled).toBe(true); Object.defineProperty(browser, 'confirm', { configurable: true, value: () => true }); await flush(() => button('Discard walk-forward submission').click()); expect(field('Experiment name').disabled).toBe(false); expect(host.querySelector('[aria-label="Prepared walk-forward inputs"]')).toBeNull(); await flush(() => button('Preview walk-forward').click()); await flush(() => reply(request(endpoint, 'POST'), { preview: prepared() })); await flush(() => button('Submit walk-forward training').click()); expect(request(basePath, 'POST').headers.get('Idempotency-Key')).not.toBe( original.headers.get('Idempotency-Key') ); }); test.each(['ordinary', 'walk-forward'] as const)( '%s wins same-event ownership against the other submission', async winner => { const value = await editor(); await flush(() => button('Preview experiment').click()); await flush(() => reply(request('/api/v2/experiments/preview', 'POST'), { preview: value.source }) ); const ordinary = button('Confirm experiment'), series = button('Submit walk-forward training'); await flush(() => { if (winner === 'ordinary') { ordinary.click(); series.click(); } else { series.click(); ordinary.click(); } }); expect( requests.filter( item => item.method === 'POST' && item.path === (winner === 'ordinary' ? '/api/v2/experiments' : basePath) ) ).toHaveLength(1); expect( requests.filter( item => item.method === 'POST' && item.path === (winner === 'ordinary' ? basePath : '/api/v2/experiments') ) ).toHaveLength(0); } ); test.each(['chronological', 'walk-forward'] as const)( '%s wins same-event ownership against the other validation flow', async winner => { const value = await editor(), single = value.windows[0]!.preview; await flush(() => { for (const phase of ['train', 'validation', 'test'] as const) { const label = phase[0]!.toUpperCase() + phase.slice(1); for (const [field, key] of [ ['warmup start', 'warmupStart'], ['trading start', 'tradeStart'], ['trading end', 'tradeEnd'], ] as const) { change( `${label} ${field} (UTC)`, new Date(single.input.recipe[phase][key]).toISOString() ); } } }); await flush(() => button('Preview chronological validation').click()); // Single preflight shares the original name, not the derived member name. const source = sourcePreview(), preparedSingle = prepareChronologicalValidation( { ...source.input, recipe: single.input.recipe }, source, walkForwardDataset().dataset ).preview; await flush(() => reply(request('/api/v2/experiments/validation/preview', 'POST'), { preview: preparedSingle, }) ); const singleSubmit = button('Submit training runs'), series = button('Submit walk-forward training'); await flush(() => { if (winner === 'chronological') { singleSubmit.click(); series.click(); } else { series.click(); singleSubmit.click(); } }); expect( requests.filter( item => item.method === 'POST' && item.path === (winner === 'chronological' ? '/api/v2/experiments/validation' : basePath) ) ).toHaveLength(1); expect( requests.filter( item => item.method === 'POST' && item.path === (winner === 'chronological' ? basePath : '/api/v2/experiments/validation') ) ).toHaveLength(0); } ); test('editing windows invalidates pending previews; add/remove retains explicit blank inputs', async () => { await editor(); await flush(() => button('Preview walk-forward').click()); const old = request(endpoint, 'POST'); await flush(() => change('Window 2 Test trading end (UTC)', '2024-01-01T10:11:00Z')); expect(old.signal?.aborted).toBe(true); await flush(() => reply(old, { preview: prepared() })); expect(host.querySelector('[aria-label="Prepared walk-forward inputs"]')).toBeNull(); await flush(() => button('Add walk-forward window').click()); expect(field('Window 3 Train warmup start (UTC)').value).toBe(''); await flush(() => button('Remove window 3').click()); expect(host.querySelector('[aria-label="Walk-forward window 3"]')).toBeNull(); for (let i = 2; i < 10; i++) { await flush(() => button('Add walk-forward window').click()); } expect(button('Add walk-forward window').disabled).toBe(true); }); test('invalid UTC never submits preview and window-only draft guards owned navigation', async () => { await editor(); await flush(() => change('Window 1 Train warmup start (UTC)', '2024-02-30T09:00:00Z')); const before = requests.length; await flush(() => button('Preview walk-forward').click()); expect(requests.length).toBe(before); expect(host.textContent).toContain('must be a real UTC instant'); Object.defineProperty(browser, 'confirm', { configurable: true, value: () => false }); await flush(() => [...host.querySelectorAll('a')] .find(item => item.textContent === 'Show all experiments')! .click() ); expect(location).toContain(backtestId); }); test('late accepted response cannot navigate a different selected source', async () => { await editor(); await flush(() => button('Submit walk-forward training').click()); const original = request(basePath, 'POST'); await flush(() => navigate(`/experiments?backtestId=${otherBacktestId}`)); await flush(() => reply(original, { walkForward: document() }, 202)); expect(location).toContain(otherBacktestId); }); test.each(['counts', 'source', 'order', 'chronology', 'window-name', 'budget'] as const)( 'malformed %s preview fails closed', async kind => { await editor(); await flush(() => button('Preview walk-forward').click()); const value = prepared(); if (kind === 'counts') { value.counts.holdoutRuns = 0; } if (kind === 'source') { value.windows[1]!.preview.source.request.build.workerSha256 = '0'.repeat(64); } if (kind === 'order') { value.windows.reverse(); } if (kind === 'chronology') { value.input.windows[1]!.train.tradeEnd = value.input.windows[0]!.train.tradeEnd; } if (kind === 'window-name') { value.windows[1]!.preview.input.name = 'Unrelated'; } if (kind === 'budget') { value.counts.totalRuns = 101; } await flush(() => reply(request(endpoint, 'POST'), { preview: value })); expect(host.textContent).toContain('could not be verified'); expect(host.querySelector('[aria-label="Prepared walk-forward inputs"]')).toBeNull(); } ); }); describe('walk-forward detail, immutable report and recovery', () => { test('GET and refresh never advance members; explicit report finalization displays exact evidence', async () => { await show(); expect(button('Save walk-forward report').disabled).toBe(true); expect(host.textContent).toContain('0/2 window reports saved'); expect(host.textContent).toContain('Not admitted'); expect(requests.every(item => item.method === 'GET')).toBe(true); expect( [...host.querySelectorAll('a')] .find(item => item.textContent === 'Open window 1 validation') ?.getAttribute('href') ).toBe(`/experiments/validation/${id(100)}`); await flush(() => button('Refresh walk-forward').click()); await flush(() => reply(request(detailPath), { walkForward: document('ready') })); expect(button('Save walk-forward report').disabled).toBe(false); const save = button('Save walk-forward report'); await flush(() => { save.click(); save.click(); }); const action = request(`${detailPath}/finalize`, 'POST'); expect(action.body).toEqual({ previewHash: document().previewHash }); expect(requests.filter(item => item.method === 'POST')).toHaveLength(1); const saved = document('reported'); await flush(() => reply(action, { receipt: receipt(saved), walkForward: saved }, 202)); expect(host.textContent).toContain('Execution complete · walk-forward report saved'); expect(host.textContent).toContain('Window 2 reset segment'); expect(host.textContent).toContain('Unavailable: insufficient-periods'); expect(host.textContent).toContain('Insufficient periodic samples'); expect(host.textContent).toContain('Fills: 0'); expect( host.querySelectorAll('section[aria-label$="validation and test evidence"]') ).toHaveLength(2); const zero = [...host.querySelectorAll('td')].filter(item => item.textContent === '0'); expect(zero.length).toBeGreaterThan(0); expect(host.textContent).toContain(saved.report!.segments[1]!.reportId); }); test('unconfirmed finalization survives refresh failure, cancellation and later report before exact replay', async () => { await show(document('ready')); await flush(() => button('Save walk-forward report').click()); const original = request(`${detailPath}/finalize`, 'POST'); await lose(original); await flush(() => button('Refresh walk-forward').click()); await flush(() => reply(request(detailPath), { error: 'Temporarily unavailable' }, 500)); expect(host.textContent).toContain('Showing the last loaded state.'); await flush(() => button('Cancel remaining walk-forward work').click()); const later = document('reported'); later.cancelRequested = true; await flush(() => reply(request(`${detailPath}/cancel`, 'POST'), { walkForward: later })); await flush(() => button('Retry walk-forward report request').click()); const retry = request(`${detailPath}/finalize`, 'POST'); expect(retry.rawBody).toBe(original.rawBody); expect(retry.headers.get('Idempotency-Key')).toBe(original.headers.get('Idempotency-Key')); await flush(() => reply(retry, { receipt: receipt(later), walkForward: later }, 202)); expect(host.textContent).toContain('Walk-forward report accepted.'); expect(host.textContent).not.toContain('Report acceptance is unconfirmed.'); }); test.each(['id', 'principal', 'time', 'hash', 'operation'] as const)( 'malformed receipt %s preserves retry intent', async kind => { await show(document('ready')); await flush(() => button('Save walk-forward report').click()); const saved = document('reported'), accepted: Record = { ...receipt(saved) }; accepted[ { id: 'id', principal: 'principal', time: 'createdAt', hash: 'reportHash', operation: 'operation', }[kind] ] = kind === 'principal' ? 'service' : kind === 'hash' ? 'b'.repeat(64) : kind === 'id' ? otherId : 'wrong'; await flush(() => reply( request(`${detailPath}/finalize`, 'POST'), { receipt: accepted, walkForward: saved }, 202 ) ); expect(host.textContent).toContain('could not be verified'); expect(button('Retry walk-forward report request').disabled).toBe(false); expect(host.textContent).not.toContain('Walk-forward report accepted.'); } ); test.each([ 'member-order', 'member-preview', 'count', 'segment-id', 'segment-metrics', 'segment-samples', 'segment-limits', 'segment-count', 'wrong-series', ] as const)('malformed %s detail cannot present a report', async kind => { await mount(`/experiments/walk-forward/${seriesId}`); const value = document('reported'); if (kind === 'member-order') { value.windows.reverse(); } if (kind === 'member-preview') { value.windows[1]!.validation!.preview.input.name = 'Other window'; } if (kind === 'count') { value.reportedWindowCount = 1; } if (kind === 'segment-id') { value.report!.segments[0]!.validationId = otherId; } if (kind === 'segment-metrics') { value.report!.segments[0]!.test = { ...value.report!.segments[0]!.test, metrics: { ...metrics(), totalReturn: 999 }, }; } if (kind === 'segment-samples') { value.report!.segments[0]!.test = { ...value.report!.segments[0]!.test, periodicSampleCount: 99, }; } if (kind === 'segment-limits') { value.report!.segments[0]!.test = { ...value.report!.segments[0]!.test, limitations: [] }; } if (kind === 'segment-count') { value.report!.segments.pop(); } if (kind === 'wrong-series') { value.id = otherId; } await flush(() => reply(request(detailPath), { walkForward: value })); expect(host.textContent).toContain('could not be verified'); expect(host.textContent).not.toContain('Execution complete'); }); test.each(['cancelled-phase', 'cancelled-trial', 'missing-phase'] as const)( 'invalid finalization capability with a %s fails closed', async kind => { await mount(`/experiments/walk-forward/${seriesId}`); const value = document('ready'); const phase = value.windows[0]!.validation!.phases[1]; if (kind === 'cancelled-phase') { phase.experiment!.cancelRequested = true; } else if (kind === 'cancelled-trial') { phase.experiment!.trials[0]!.cancelRequested = true; } else { phase.status = 'missing'; phase.experiment = null; } await flush(() => reply(request(detailPath), { walkForward: value })); expect(host.textContent).toContain('could not be verified'); expect(host.textContent).not.toContain('Window progress and evidence'); } ); test('missing and cancelled member outcomes remain visible and block finalization', async () => { const value = document(); value.windows[1]!.status = 'missing'; value.windows[1]!.validation = null; const first = value.windows[0]!.validation!; first.cancelRequested = true; const experiment = first.phases[0].experiment!; experiment.counts.pending = 1; experiment.counts.failed = 1; Object.assign(experiment.trials[0]!, { status: 'failed', error: 'Worker failed before execution', }); await show(value); expect(host.textContent).toContain('Window 2 validation is missing'); expect(host.textContent).toContain('Cancellation requested for this window'); expect(host.textContent).toContain('Worker failed before execution'); expect(button('Save walk-forward report').disabled).toBe(true); }); test.each(['Save walk-forward report', 'Cancel remaining walk-forward work'])( 'same-event refresh prevents %s from overtaking the read', async label => { await show(document('ready')); const action = button(label), refresh = button('Refresh walk-forward'); await flush(() => { refresh.click(); action.click(); }); expect(requests.filter(item => item.method === 'POST')).toHaveLength(0); await flush(() => reply(request(detailPath), { walkForward: document('ready') })); await flush(() => button(label).click()); expect(requests.filter(item => item.method === 'POST')).toHaveLength(1); } ); test('cancellation serializes against finalization and refresh', async () => { await show(document('ready')); const cancel = button('Cancel remaining walk-forward work'), save = button('Save walk-forward report'), refresh = button('Refresh walk-forward'); await flush(() => { cancel.click(); save.click(); refresh.click(); }); expect(requests.filter(item => item.method === 'POST')).toHaveLength(1); expect(requests.filter(item => item.path === detailPath)).toHaveLength(1); const value = document('ready'); value.cancelRequested = true; value.actions.finalize = { available: false, reason: 'Walk-forward cancelled' }; await flush(() => reply(request(`${detailPath}/cancel`, 'POST'), { walkForward: value })); expect(host.textContent).toContain('Cancellation requested for all windows'); }); test('owned member navigation refuses discarding an uncertain report request', async () => { await show(document('ready')); await flush(() => button('Save walk-forward report').click()); const original = request(`${detailPath}/finalize`, 'POST'); await lose(original); Object.defineProperty(browser, 'confirm', { configurable: true, value: () => false }); await flush(() => [...host.querySelectorAll('a')] .find(item => item.textContent === 'Open window 1 validation')! .click() ); expect(location).toBe(`/experiments/walk-forward/${seriesId}`); await flush(() => button('Retry walk-forward report request').click()); expect(request(`${detailPath}/finalize`, 'POST').rawBody).toBe(original.rawBody); }); test('late read and mutation completions cannot replace another route', async () => { await show(document('ready')); await flush(() => button('Save walk-forward report').click()); const original = request(`${detailPath}/finalize`, 'POST'); await flush(() => navigate(`/experiments/walk-forward/${otherId}`)); const other = document(); other.id = otherId; await flush(() => reply(request(`${basePath}/${otherId}`), { walkForward: other })); const saved = document('reported'); await flush(() => reply(original, { receipt: receipt(saved), walkForward: saved }, 202)); expect(location).toBe(`/experiments/walk-forward/${otherId}`); expect(host.textContent).not.toContain('Walk-forward report accepted.'); await flush(() => button('Refresh walk-forward').click()); const stale = request(`${basePath}/${otherId}`); await flush(() => navigate(`/experiments/walk-forward/${seriesId}`)); await flush(() => reply(request(detailPath), { walkForward: saved })); await flush(() => reply(stale, { walkForward: other })); expect(host.textContent).toContain('Execution complete · walk-forward report saved'); }); test.each([400, 401, 404, 409, 500])( 'HTTP %i finalization errors keep retry inputs', async status => { await show(document('ready')); await flush(() => button('Save walk-forward report').click()); const original = request(`${detailPath}/finalize`, 'POST'); await flush(() => reply(original, { error: `Failure ${status}` }, status)); expect(host.textContent).toContain(`Failure ${status}`); await flush(() => button('Retry walk-forward report request').click()); expect(request(`${detailPath}/finalize`, 'POST').headers.get('Idempotency-Key')).toBe( original.headers.get('Idempotency-Key') ); } ); }); describe('saved walk-forward list', () => { test('list errors are distinct from empty and refresh reopens exact saved report', async () => { await mount(); await flush(() => reply(request(`${basePath}?backtestId=${backtestId}`), { error: 'List unavailable' }, 500) ); expect(host.textContent).toContain('List unavailable'); expect(host.textContent).not.toContain('No saved walk-forward validations.'); await flush(() => button('Refresh walk-forward validations').click()); const saved = document('reported'); await flush(() => reply(request(`${basePath}?backtestId=${backtestId}`), { walkForwards: [saved] }) ); await flush(() => [...host.querySelectorAll('a')].find(item => item.textContent === saved.name)!.click() ); expect(location).toBe(`/experiments/walk-forward/${seriesId}`); await flush(() => reply(request(detailPath), { walkForward: saved })); expect(host.textContent).toContain(saved.report!.reportHash); }); test('filter change fences an older list and rejects foreign parents', async () => { await mount(); const stale = request(`${basePath}?backtestId=${backtestId}`); await flush(() => navigate(`/experiments?backtestId=${otherBacktestId}`)); await flush(() => reply(stale, { walkForwards: [document('reported')] })); expect([...host.querySelectorAll('a')].some(item => item.textContent === 'Trend study')).toBe( false ); await flush(() => reply(request(`${basePath}?backtestId=${otherBacktestId}`), { walkForwards: [document('reported')], }) ); expect(host.textContent).toContain('could not be verified'); }); });