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 { ExperimentPreview } 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 { nativeReplayFixture } from '../fixtures/native-replay'; 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; 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', }); 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, }; } async function mount() { root ??= createRoot(host); await flush(() => root!.render( createElement( router.MemoryRouter, { initialEntries: [`/experiments?backtestId=${backtestId}`] }, createElement(ExperimentListPage), createElement(Probe) ) ) ); await flush(() => { reply(request('/api/v2/backtests?limit=50&offset=0'), [template(), template(otherBacktestId)]); reply(request(`/api/v2/experiments?backtestId=${backtestId}`), { experiments: [] }); }); } async function fill(value = prepared()) { await mount(); 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 label = phase[0]!.toUpperCase() + phase.slice(1); change( `${label} warmup start (UTC)`, new Date(value.input.recipe[phase].warmupStart).toISOString() ); change( `${label} trading start (UTC)`, new Date(value.input.recipe[phase].tradeStart).toISOString() ); change( `${label} trading end (UTC)`, new Date(value.input.recipe[phase].tradeEnd).toISOString() ); } }); return value; } async function ready(value = prepared()) { await fill(value); await flush(() => button('Preview chronological validation').click()); await flush(() => reply(request(endpoint, 'POST'), { preview: value })); return value; } 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')); }); 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', 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; // Ignore abort so generation/identity fencing is exercised. }, }); }); afterEach(async () => { if (root) { await flush(() => root!.unmount()); } root = undefined; host.remove(); }); afterAll(async () => { await browser.happyDOM.close(); for (const key of keys) { const old = originals.get(key); if (old) { Object.defineProperty(globalThis, key, old); } else { Reflect.deleteProperty(globalThis, key); } } }); describe('chronological validation preflight', () => { test('explicit UTC preparation sends only read-only preview and displays all phase assumptions and counts', async () => { const value = await fill(); expect(host.textContent).toContain('No chronological preview prepared'); expect(host.textContent).toContain('Previewing does not save datasets, experiments or runs.'); expect(requests.filter(item => item.method === 'POST')).toHaveLength(0); await flush(() => { button('Preview chronological validation').click(); button('Preview chronological validation').click(); }); expect(host.textContent).toContain('Preparing chronological validation preview...'); const post = request(endpoint, 'POST'); expect(post.body).toEqual(value.input); expect(post.headers.has('Idempotency-Key')).toBe(false); expect(post.credentials).toBe('include'); expect(requests.filter(item => item.method === 'POST')).toHaveLength(1); await flush(() => reply(post, { preview: value })); expect(host.querySelector('[aria-label="Prepared chronological inputs"]')).not.toBeNull(); expect(host.textContent).toContain('2 parameter candidates checked'); expect(host.textContent).toContain('No candidate has been selected or evaluated.'); expect(host.textContent).toContain('maximize train total return'); expect(host.textContent).toContain('Validation is diagnostic only; test is holdout only'); expect(host.textContent).toContain('independent reset segments'); for (const phase of ['Train', 'Validation', 'Test']) { const card = host.querySelector(`[aria-label="${phase} partition"]`)!; expect(card.textContent).toContain('21 / 21'); expect(card.textContent).toContain('Available exactly at end (terminal mark only)'); expect(card.textContent).toContain('Input history sufficiency'); } expect( host .querySelector('[aria-label="Chronological validation preflight"]')! .querySelectorAll('button') ).toHaveLength(2); expect(host.textContent).not.toContain('Confirm experiment'); expect(location).toBe(`/experiments?backtestId=${backtestId}`); }); test.each([ 'Experiment name', 'Parameter grid (JSON)', 'Saved backtest', 'Train trading end (UTC)', ])( '%s changes invalidate visible and pending previews without automatically reposting', async label => { const value = await ready(); await flush(() => button('Preview chronological validation').click()); const old = request(endpoint, 'POST'); const next = label === 'Experiment name' ? 'Changed' : label === 'Parameter grid (JSON)' ? '{}' : label === 'Saved backtest' ? otherBacktestId : '2024-01-01T09:29:00Z'; await flush(() => change(label, next)); expect(host.querySelector('[aria-label="Prepared chronological inputs"]')).toBeNull(); expect(old.signal?.aborted).toBe(true); await flush(() => reply(old, { preview: value })); expect(host.querySelector('[aria-label="Prepared chronological inputs"]')).toBeNull(); expect(requests.filter(item => item.path === endpoint)).toHaveLength(2); } ); test.each([ '2024-01-01T09:00:00', '2024-01-01T09:00:00+00:00', '2024-02-30T09:00:00Z', '2024-01-01T09:00:00.0001Z', '', ])('rejects ambiguous or invalid UTC value %s before any request', async text => { await fill(); await flush(() => change('Train warmup start (UTC)', text)); await flush(() => button('Preview chronological validation').click()); expect(host.textContent).toContain('must be a real UTC instant ending in Z'); expect(requests.filter(item => item.method === 'POST')).toHaveLength(0); }); test('chronology and invalid grid reject locally, including overlapping evaluation windows', async () => { await fill(); await flush(() => change('Validation trading start (UTC)', '2024-01-01T09:29:00Z')); await flush(() => button('Preview chronological validation').click()); expect(host.textContent).toContain('chronological and nonoverlapping'); expect(requests.filter(item => item.method === 'POST')).toHaveLength(0); await flush(() => { change('Validation trading start (UTC)', '2024-01-01T09:32:00Z'); change('Parameter grid (JSON)', '{"__proto__":[1]}'); }); await flush(() => button('Preview chronological validation').click()); expect(host.textContent).toContain('Invalid parameter name'); expect(requests.filter(item => item.method === 'POST')).toHaveLength(0); }); test.each([400, 401, 404, 409, 500])( 'HTTP %s has a visible retryable error and never admits a sweep', async status => { const value = await fill(); await flush(() => button('Preview chronological validation').click()); await flush(() => reply( request(endpoint, 'POST'), { error: 'Train has insufficient admitted warmup: 4 of 21 observations' }, status ) ); expect(host.textContent).toContain('Train has insufficient admitted warmup'); expect(button('Preview chronological validation').disabled).toBe(false); expect(host.querySelector('[aria-label="Prepared chronological inputs"]')).toBeNull(); await flush(() => button('Preview chronological validation').click()); await flush(() => reply(request(endpoint, 'POST'), { preview: value })); expect(host.querySelector('[aria-label="Prepared chronological inputs"]')).not.toBeNull(); expect( requests.filter(item => item.method === 'POST').every(item => item.path === endpoint) ).toBe(true); } ); test.each([ 'wrong-parent', 'wrong-name', 'wrong-grid', 'wrong-policy', 'phase-order', 'phase-bounds', 'changed-finance', 'changed-metadata', 'count-mismatch', 'manifest-count', 'missing-terminal', 'invalid-warmup', 'partial', ] as const)('malformed %s response fails closed', async kind => { const value = await fill(); await flush(() => button('Preview chronological validation').click()); const invalid = structuredClone(value); if (kind === 'wrong-parent') { invalid.source.input.backtestId = otherBacktestId; } if (kind === 'wrong-name') { invalid.source.input.name = 'Different'; } if (kind === 'wrong-grid') { invalid.source.input.grid = {}; } if (kind === 'wrong-policy') { (invalid.policy.selection as unknown as Record).metric = 'sharpeRatio'; } if (kind === 'phase-order') { invalid.partitions.reverse(); } if (kind === 'phase-bounds') { invalid.partitions[0].dataset = { ...invalid.partitions[0].dataset, bounds: { ...invalid.partitions[0].dataset.bounds, tradeEnd: value.input.recipe.train.tradeEnd - 60000, }, }; } if (kind === 'changed-finance') { invalid.partitions[0].request.policy.matching.risk.maxDailyLoss = '123.00000000' as never; } if (kind === 'changed-metadata') { invalid.partitions[0].dataset = { ...invalid.partitions[0].dataset, series: invalid.partitions[0].dataset.series.map(item => ({ ...item, interval: '5m' })), }; } if (kind === 'count-mismatch') { invalid.partitions[0].counts.totalBars = 99; } if (kind === 'manifest-count') { invalid.partitions[0].dataset = { ...invalid.partitions[0].dataset, barCount: 99 }; } if (kind === 'missing-terminal') { delete (invalid.partitions[0].counts as Partial<(typeof invalid.partitions)[0]['counts']>) .terminalAtEnd; } if (kind === 'invalid-warmup') { invalid.partitions[0].requiredWarmup = 22; } await flush(() => reply( request(endpoint, 'POST'), kind === 'partial' ? { preview: { previewHash: value.previewHash } } : { preview: invalid } ) ); expect(host.textContent).toContain('could not be verified'); expect(host.querySelector('[aria-label="Prepared chronological inputs"]')).toBeNull(); }); test('network loss and stale route responses are recoverable without creating records', async () => { const value = await fill(); await flush(() => button('Preview chronological validation').click()); const post = request(endpoint, 'POST'); await flush(() => { post.settled = true; post.reject(new Error('Connection lost')); }); expect(host.textContent).toContain('Connection lost'); await flush(() => button('Preview chronological validation').click()); const stale = request(endpoint, 'POST'); await flush(() => navigate(`/experiments?backtestId=${otherBacktestId}`)); await flush(() => reply(stale, { preview: value })); expect(location).toBe(`/experiments?backtestId=${otherBacktestId}`); expect(host.querySelector('[aria-label="Prepared chronological inputs"]')).toBeNull(); expect(field('Train warmup start (UTC)').value).toBe(''); }); test('ordinary unresolved submission disables and invalidates preflight without changing its exact sweep body', async () => { const value = await fill(); await flush(() => button('Preview chronological validation').click()); const stale = request(endpoint, 'POST'); await flush(() => button('Preview experiment').click()); await flush(() => reply(request('/api/v2/experiments/preview', 'POST'), { preview: value.source }) ); await flush(() => button('Confirm experiment').click()); const ordinary = request('/api/v2/experiments', 'POST'); expect(ordinary.body).toEqual({ ...value.source.input, previewHash: value.source.previewHash }); expect(ordinary.headers.has('Idempotency-Key')).toBe(true); await flush(() => { ordinary.settled = true; ordinary.reject(new Error('Lost ordinary receipt')); }); await flush(() => reply(stale, { preview: value })); expect(button('Preview chronological validation').disabled).toBe(true); expect(field('Train warmup start (UTC)').closest('fieldset')!.disabled).toBe(true); expect(host.querySelector('[aria-label="Prepared chronological inputs"]')).toBeNull(); expect(host.textContent).toContain('Resolve or explicitly release the other submission'); await flush(() => button('Start new experiment').click()); expect(button('Preview chronological validation').disabled).toBe(false); expect(field('Train warmup start (UTC)').value).toBe( new Date(value.input.recipe.train.warmupStart).toISOString() ); expect(host.querySelector('[aria-label="Prepared chronological inputs"]')).toBeNull(); }); test('window-only draft participates in the existing owned-navigation discard guard', async () => { await mount(); await flush(() => change('Train warmup start (UTC)', '2024-01-01T09:00:00Z')); Object.defineProperty(browser, 'confirm', { configurable: true, value: () => false }); await flush(() => (host.querySelector('a[href="/experiments"]') as HTMLAnchorElement).click()); expect(location).toBe(`/experiments?backtestId=${backtestId}`); expect(field('Train warmup start (UTC)').value).toBe('2024-01-01T09:00:00Z'); }); test('delayed observations remain explicit and tiny evaluation warnings are not performance evidence', async () => { const value = prepared(); value.partitions[2].counts.availableEvaluation = 1; value.partitions[2].counts.unavailableAtEnd = 7; value.partitions[2].warnings = [ 'Only one evaluation observation is available.', 'Seven delayed observations remain unavailable at the end.', ]; await ready(value); const card = host.querySelector('[aria-label="Test partition"]')!; expect(card.textContent).toContain('Only one evaluation observation'); expect(card.textContent).toContain('Seven delayed observations'); expect(host.textContent).toContain( 'Warmup sufficiency is not evidence of profitability or statistical adequacy' ); }); });