import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, spyOn, test, } from 'bun:test'; import { GlobalWindow } from 'happy-dom'; import { act, createElement, type ReactElement } from 'react'; import type { Root } from 'react-dom/client'; import { replayConfigSchema, type ReplayReportResult, } from '@stock-bot/stock-config/canonical-replay'; import type { CanonicalDatasetCatalogEntry, CanonicalRunResult, } from '@stock-bot/stock-config/canonical-research'; import type { StrategyParameterSchema, StrategyRecord, StrategyVersionPackage, StrategyVersionSummary, } from '@stock-bot/types'; import { parseFinancialDecimal as decimal } from '@stock-bot/types'; import { buildCanonicalBacktestReport } from '@stock-bot/research/results'; import type { CreateBacktestRequest, Run, } 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', '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 backtestApiV2: typeof import('../../apps/stock/web-app/src/features/backtest/services/backtestApiV2').backtestApiV2; let CanonicalSetup: typeof import('../../apps/stock/web-app/src/features/backtest/components/CanonicalSetup').CanonicalSetup; let CanonicalResults: typeof import('../../apps/stock/web-app/src/features/backtest/components/CanonicalResults').CanonicalResults; let RunsListWithMetrics: typeof import('../../apps/stock/web-app/src/features/backtest/components/RunsListWithMetrics').RunsListWithMetrics; let VirtuosoMockContext: typeof import('react-virtuoso').VirtuosoMockContext; let BuiltinReview: typeof import('../../apps/stock/web-app/src/features/strategies/components/BuiltinReview').BuiltinReview; let useBacktestV2: typeof import('../../apps/stock/web-app/src/features/backtest/hooks/useBacktestV2').useBacktestV2; let root: Root | undefined; let host: HTMLDivElement; let latest: ReturnType; function deferred() { let resolve!: (value: T) => void; let reject!: (error: Error) => void; const promise = new Promise((yes, no) => { resolve = yes; reject = no; }); return { promise, resolve, reject }; } type Pending = ReturnType> & { path: string; search: string; signal: AbortSignal | null | undefined; method: string; body: unknown; headers: Headers; settled: boolean; }; 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( `No pending ${method} ${path}; requests: ${requests.map(item => `${item.method} ${item.path} ${item.settled}`).join(', ')}` ); } return found; } function reply(item: Pending, body: unknown, status = 200) { item.settled = true; item.resolve(Response.json(body, { status })); } function fail(item: Pending) { item.settled = true; item.reject(new Error('Response lost')); } 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 || item.getAttribute('aria-label') === label ); if (!found) { throw new Error(`Missing button ${label}: ${host.textContent}`); } return found; } function click(label: string) { button(label).click(); } function field(label: string) { const found = host.querySelector(`[aria-label="${label}"]`) as | HTMLInputElement | HTMLSelectElement | HTMLTextAreaElement | null; if (!found) { throw new Error(`Missing field ${label}`); } return found; } function edit(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() { return null; } async function mount(element: ReactElement, path = '/') { root = createRoot(host); await flush(() => root!.render( createElement(router.MemoryRouter, { initialEntries: [path] }, element, createElement(Probe)) ) ); } const family = (id = 'family', extra: Partial = {}): StrategyRecord => ({ id, name: `Strategy ${id}`, description: 'Reviewed fixture', ownerPrincipal: 'operator', updatedBy: 'operator', archived: false, createdAt: '2026-01-01', updatedAt: '2026-01-01', ...extra, }); const schema: StrategyParameterSchema = { version: 1, type: 'object', additionalProperties: false, required: [], properties: { fastPeriod: { type: 'integer', minimum: 1, default: 5 }, slowPeriod: { type: 'integer', minimum: 2, default: 15 }, }, }; const pkg = ( content = 'globalThis.CATALOG_MUST_NOT_EXECUTE = true; ' ): StrategyVersionPackage => ({ version: 1, program: { strategyId: 'fixture', strategyVersion: 'v1', apiVersion: 'canonical-ts/v1', checkpointVersion: 'fixture/v1', }, artifact: { format: 'esm-bundle/v1', entryExport: 'createFixture', content, sha256: 'a'.repeat(64), }, dependencyLock: { format: 'bun-lock/v1', content: 'lock', sha256: 'b'.repeat(64) }, parameterSchema: schema, source: { revision: 'c'.repeat(40), dirty: false }, build: { tool: 'bun', version: '1.2.17', target: 'browser' }, }); const version = ( id = 'version-one', extra: Partial = {} ): StrategyVersionSummary => { const full = pkg(); const { content: _artifact, ...artifact } = full.artifact; const { content: _lock, ...dependencyLock } = full.dependencyLock; return { id, strategyId: 'family', ordinal: 1, parentVersionId: null, createdBy: 'operator', origin: 'builtin', createdAt: '2026-01-01', package: { ...full, artifact, dependencyLock }, reviewStatus: 'approved', runnable: false, reason: 'Execution unavailable', ...extra, }; }; const definition = { id: 'definition', name: 'Catalog fixture', strategy: 'catalog', strategyVersionId: 'version-one', strategyParameters: { fastPeriod: 5, slowPeriod: 15 }, symbols: ['AAPL.US'], startDate: '2024-01-01', endDate: '2024-03-01', initialCapital: 100000, config: {}, archivedAt: null, createdAt: '2026-01-01', updatedAt: '2026-01-01', }; async function selected(archived = false) { await flush(() => { reply(request('/api/v2/strategies'), { strategies: [family('family', { archived })] }); reply(request('/api/v2/strategy-versions/version-one'), { version: version(), reviews: [] }); }); await flush(() => reply(request('/api/v2/strategies/family'), { strategy: family('family', { archived }) }) ); await flush(() => reply(request('/api/v2/strategies/family/versions'), { versions: [version()] }) ); } beforeAll(async () => { for (const [key, value] of Object.entries({ window: browser, document: browser.document, 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'); ({ backtestApiV2 } = await import( '../../apps/stock/web-app/src/features/backtest/services/backtestApiV2' )); ({ CanonicalSetup } = await import( '../../apps/stock/web-app/src/features/backtest/components/CanonicalSetup' )); ({ CanonicalResults } = await import( '../../apps/stock/web-app/src/features/backtest/components/CanonicalResults' )); ({ RunsListWithMetrics } = await import( '../../apps/stock/web-app/src/features/backtest/components/RunsListWithMetrics' )); ({ VirtuosoMockContext } = await import('react-virtuoso')); ({ BuiltinReview } = await import( '../../apps/stock/web-app/src/features/strategies/components/BuiltinReview' )); ({ useBacktestV2 } = await import( '../../apps/stock/web-app/src/features/backtest/hooks/useBacktestV2' )); }); beforeEach(() => { requests.length = 0; host = browser.document.createElement('div') as unknown as HTMLDivElement; browser.document.body.append(host as never); Object.defineProperty(browser, 'confirm', { configurable: true, writable: true, value: () => true, }); browser.fetch = ((url: RequestInfo | URL, init?: RequestInit) => { const item: Pending = { ...deferred(), path: new URL(String(url)).pathname, search: new URL(String(url)).search, signal: init?.signal, method: init?.method ?? 'GET', headers: new Headers(init?.headers), body: typeof init?.body === 'string' ? JSON.parse(init.body) : undefined, settled: false, }; requests.push(item); return item.promise; // Ignore abort deliberately: stale-response fences must still hold. }) as unknown as typeof browser.fetch; }); afterEach(async () => { if (root) { await flush(() => root!.unmount()); } root = undefined; host.remove(); }); afterAll(async () => { await browser.happyDOM.close(); for (const key of keys) { const descriptor = originals.get(key); if (descriptor) { Object.defineProperty(globalThis, key, descriptor); } else { delete (globalThis as Record)[key]; } } }); const fixture = nativeReplayFixture(); const hash = fixture.dataset.manifest.hash; const entry: CanonicalDatasetCatalogEntry = { hash, createdAt: '2026-01-01T00:00:00Z', available: true, reason: null, manifest: { ...fixture.dataset.manifest, // A retained daily dataset's actual bounds need not be midnight. series: fixture.dataset.manifest.series.map(series => ({ ...series, interval: '1d' })), bounds: { warmupStart: fixture.start, tradeStart: fixture.start + 123, tradeEnd: fixture.start + 86400000 + 456, }, }, }; function report(): CanonicalRunResult { const policy = replayConfigSchema.parse(fixture.config); const riskSession = policy.matching.risk.ledger.riskSession; const zero = decimal('0'); const financial: ReplayReportResult = { identity: { version: 1, sessionId: 'run', datasetHash: hash }, status: 'complete', manifest: {}, policy, format: 'report', projectionVersion: 1, financialVersion: 1, reportingVersion: 1, limitations: ['Retained fixture limitation'], modelLimitations: ['No market impact model'], projection: { valuation: { cash: decimal('9995'), markedHoldings: decimal('5'), equity: decimal('10000'), remainingCost: decimal('5'), realizedGrossPnl: zero, unrealizedPnl: zero, fees: zero, owners: [ { ownerId: 'A', initialCapital: decimal('10000'), markedHoldings: decimal('5'), remainingCost: decimal('5'), realizedGrossPnl: zero, unrealizedPnl: zero, fees: zero, equityContribution: decimal('10000'), }, ], }, fills: [ { commandId: 'command', eventTime: fixture.start, ownerId: 'A', decision: { ownerId: 'A', decisionId: 'decision', sequence: 1 }, orderId: 'order', fillId: 'fill', instrumentId: 'X0.US', side: 'buy', quantity: decimal('0.125'), price: decimal('40'), fee: { feeId: 'fee', amount: zero }, cashDelta: decimal('-5'), quantityDelta: decimal('0.125'), releasedBasis: zero, realizedGrossPnl: zero, }, ], }, view: { admissionRevision: 1, portfolio: { version: 1, sessionId: 'run', accountId: 'research:run', revision: 1, baseCurrency: 'USD', reserveOwnerId: 'reserve', cash: decimal('9995'), positions: [ { ownerId: 'A', instrumentId: 'X0.US', quantity: decimal('0.125'), remainingCost: decimal('5'), realizedGrossPnl: zero, }, ], fees: [{ ownerId: 'A', amount: zero }], riskSession, }, equity: decimal('10000'), availableCash: decimal('9995'), orders: [], reservations: [], risk: { dailyBaseline: decimal('10000'), peakEquity: decimal('10000'), dailyHalted: false, drawdownHalted: false, riskSession, lastEventTime: fixture.start + 86400000, }, }, reporting: { calendarId: 'account', calendarRevision: '1', tradeStart: fixture.start, tradeEnd: fixture.start + 86400000, initialEquity: decimal('10000'), sampling: 'account-boundary-after-observations-v1', exposureBasis: 'elapsed-calendar-time', sessions: [ { session: riskSession, periodStart: fixture.start, periodEnd: fixture.start + 86400000, partialStart: false, partialEnd: true, equity: decimal('10000'), }, ], occupiedIntervals: [{ start: fixture.start, end: fixture.start + 86400000 }], occupiedMs: '86400000', elapsedMs: '86400000', }, }; const analytics = buildCanonicalBacktestReport(financial, { version: 1, periodsPerYear: 252, annualRiskFreeRate: 0, benchmark: null, }).analytics; return { kind: 'canonical-result/v1', runId: 'run', backtestId: 'definition', status: 'completed', completedAt: '2026-01-01', executionTime: 0, financialEngine: 'rust', strategyExecution: 'typescript-retained-builtin/v1', financial, analytics, request: { kind: 'canonical-research/v1', runId: 'run', backtestId: 'definition', name: 'Canonical fixture', datasetHash: hash, policy, strategy: { familyId: 'family', versionId: 'version-one', reviewId: 'review', origin: 'builtin', package: pkg(), selection: { strategyId: 'sma_crossover', strategyVersion: 'sma-crossover-long-only/v1', seed: 1, ownerId: 'A', instrumentId: 'X0.US', seriesId: 'X0.US:1m', ownerBudget: decimal('10000'), parameters: { fastPeriod: 2, slowPeriod: 5 }, }, }, analyticsPolicy: { version: 1, periodsPerYear: 252, annualRiskFreeRate: 0, benchmark: null }, build: { version: 1, workerSha256: '1'.repeat(64), engineWrapperSha256: '2'.repeat(64), engineBinarySha256: '3'.repeat(64), dependencyLockSha256: '4'.repeat(64), runtime: 'bun', runtimeVersion: Bun.version, platform: 'linux', arch: 'x64', }, modelArtifacts: [], }, }; } async function validateSelected() { await flush(() => click('Validate parameters')); await flush(() => reply(request('/api/v2/strategy-versions/version-one/validate', 'POST'), { parameters: definition.strategyParameters, runnable: false, reason: 'Execution gated', }) ); } function Hook() { latest = useBacktestV2(); return null; } function completedRun(extra: Partial = {}): Run { return { id: 'run', backtestId: 'definition', status: 'completed', runNumber: 1, speedMultiplier: null, progress: 100, createdAt: '2026-01-01', updatedAt: '2026-01-01', ...extra, }; } async function loadDefinition(value = definition) { let completion: Promise; await flush(() => { completion = latest.loadBacktest(value.id); }); await flush(() => reply(request(`/api/v2/backtests/${value.id}`), value)); await flush(() => reply(request(`/api/v2/backtests/${value.id}/runs`), [])); await completion!; } describe('canonical research workbench', () => { for (const wrongIdentity of [{ id: 'other-run' }, { backtestId: 'other-definition' }]) { test(`rejects a selected run with mismatched ${Object.keys(wrongIdentity)[0]}`, async () => { await mount(createElement(Hook)); await loadDefinition(); await flush(() => { void latest.selectRun('run'); }); await flush(() => reply(request('/api/v2/runs/run'), completedRun(wrongIdentity))); expect(latest.currentRun).toBeNull(); expect(latest.runResults).toBeNull(); expect(latest.runs).toEqual([]); expect(latest.error).toContain('different backtest or run'); expect(latest.isLoading).toBe(false); expect(requests.some(item => item.path.endsWith('/results'))).toBe(false); }); } for (const wrongIdentity of [{ runId: 'other-run' }, { backtestId: 'other-definition' }]) { test(`rejects selected results with mismatched ${Object.keys(wrongIdentity)[0]}`, async () => { await mount(createElement(Hook)); await loadDefinition(); await flush(() => { void latest.selectRun('run'); }); await flush(() => reply(request('/api/v2/runs/run'), completedRun())); await flush(() => reply(request('/api/v2/runs/run/results'), { ...report(), ...wrongIdentity }) ); expect(latest.currentRun?.backtestId).toBe('definition'); expect(latest.runResults).toBeNull(); expect(latest.error).toContain('different backtest or run'); expect(latest.isLoading).toBe(false); }); } for (const lateResponse of ['status', 'results']) { test(`parent-only navigation fences a late ${lateResponse} response and rechecks the same run`, async () => { await mount(createElement(Hook)); await loadDefinition(); await flush(() => { void latest.selectRun('run'); }); if (lateResponse === 'results') { await flush(() => reply(request('/api/v2/runs/run'), completedRun())); } const stale = request(`/api/v2/runs/run${lateResponse === 'results' ? '/results' : ''}`); await loadDefinition({ ...definition, id: 'other-definition' }); expect(latest.currentRun).toBeNull(); expect(latest.runResults).toBeNull(); expect(latest.runs).toEqual([]); await flush(() => reply(stale, lateResponse === 'results' ? report() : completedRun())); expect(latest.currentRun).toBeNull(); expect(latest.runResults).toBeNull(); expect(latest.runs).toEqual([]); expect(latest.error).toBeNull(); await flush(() => reply(request('/api/v2/runs/run'), completedRun())); expect(latest.error).toContain('different backtest or run'); expect(latest.currentRun).toBeNull(); expect(latest.runResults).toBeNull(); expect(latest.runs).toEqual([]); }); } test('accepts matching canonical results and retains them when refreshing the same parent', async () => { await mount(createElement(Hook)); await loadDefinition(); await flush(() => { void latest.selectRun('run'); }); await flush(() => reply(request('/api/v2/runs/run'), completedRun())); await flush(() => reply(request('/api/v2/runs/run/results'), report())); expect(latest.runResults?.backtestId).toBe('definition'); expect(latest.error).toBeNull(); await loadDefinition(); expect(latest.currentRun?.id).toBe('run'); expect(latest.runResults?.runId).toBe('run'); expect(requests.filter(item => item.path === '/api/v2/runs/run')).toHaveLength(1); }); test('rejects foreign run history without installing the mismatched definition data', async () => { await mount(createElement(Hook)); await flush(() => { void latest.loadBacktest('definition'); }); await flush(() => { reply(request('/api/v2/backtests/definition'), definition); reply(request('/api/v2/backtests/definition/runs'), [ completedRun({ backtestId: 'other-definition' }), ]); }); expect(latest.backtest).toBeNull(); expect(latest.runs).toEqual([]); expect(latest.error).toContain('different backtest'); }); test('history does not render metrics belonging to a different parent', async () => { await mount( createElement( VirtuosoMockContext.Provider, { value: { viewportHeight: 400, itemHeight: 40 }, }, createElement(RunsListWithMetrics, { runs: [completedRun()], onSelectRun: () => {} }) ) ); const result = report(); result.backtestId = 'other-definition'; result.analytics.metrics.totalReturn = 123; await flush(() => reply(request('/api/v2/runs/run/results'), result)); const row = host.querySelector('tbody tr[data-index]')!; expect(row.querySelectorAll('td')[3]!.textContent).toBe('-'); expect(host.textContent).not.toContain('12300.00%'); expect(host.textContent).not.toContain('Canonical'); }); describe('nonblocking run history metrics', () => { const rows = () => [...host.querySelectorAll('tbody tr[data-index]')]; const view = (runs: Run[], onSelectRun = (_id: string) => {}) => createElement( VirtuosoMockContext.Provider, { value: { viewportHeight: 1000, itemHeight: 40 } }, createElement(RunsListWithMetrics, { runs, onSelectRun }) ); const update = (runs: Run[]) => flush(() => root!.render( createElement( router.MemoryRouter, { initialEntries: ['/'] }, view(runs), createElement(Probe) ) ) ); const resultFor = (run: Run, totalReturn: number) => { const value = report(); value.runId = run.id; value.backtestId = run.backtestId; value.analytics.metrics.totalReturn = totalReturn; return value; }; test('pending metrics leave every current row visible and selectable without submitting', async () => { const selected: string[] = []; const runs = [ completedRun(), completedRun({ id: 'failed', runNumber: 2, status: 'failed' }), completedRun({ id: 'active', runNumber: 3, status: 'pending', progress: 0 }), ]; await mount(view(runs, id => selected.push(id))); expect(request('/api/v2/runs/run/results')).toBeTruthy(); expect(rows()).toHaveLength(3); expect(rows()[0]!.textContent).toContain('Loading metrics...'); expect(rows()[0]!.querySelectorAll('td')[3]!.textContent).toBe('-'); expect(rows()[1]!.textContent).toContain('Failed'); expect(rows()[2]!.textContent).toContain('Pending'); await flush(() => (rows()[1] as HTMLElement).click()); expect(selected).toEqual(['failed']); expect(requests).toHaveLength(1); expect(requests.every(item => item.method === 'GET')).toBe(true); }); test('status polls and another completion preserve pending reads and publish healthy metrics independently', async () => { const first = completedRun(); const slow = completedRun({ id: 'slow', runNumber: 2 }); const active = completedRun({ id: 'active', runNumber: 3, status: 'running', progress: 20 }); await mount(view([first, slow, active])); const firstRead = request('/api/v2/runs/run/results'); const slowRead = request('/api/v2/runs/slow/results'); await update([{ ...first }, { ...slow }, { ...active, status: 'paused', progress: 40 }]); expect(requests).toHaveLength(2); expect(firstRead.signal?.aborted).toBe(false); expect(slowRead.signal?.aborted).toBe(false); expect(rows()[2]!.textContent).toContain('Paused'); expect(rows()[2]!.textContent).toContain('40%'); await flush(() => reply(firstRead, resultFor(first, 0.125))); expect(rows()[0]!.textContent).toContain('12.50%'); expect(rows()[1]!.textContent).toContain('Loading metrics...'); await update([first, slow, { ...active, status: 'completed', progress: 100 }]); expect(requests).toHaveLength(3); expect(request('/api/v2/runs/active/results')).toBeTruthy(); expect(slowRead.signal?.aborted).toBe(false); expect(rows()[0]!.textContent).toContain('12.50%'); await flush(() => reply(slowRead, resultFor(slow, 0.25))); expect(rows()[1]!.textContent).toContain('25.00%'); expect(rows()[2]!.textContent).toContain('Loading metrics...'); }); test('failed metrics stay unavailable until explicit row-local retry without navigation or duplicate reads', async () => { const selected: string[] = []; const first = completedRun(); const healthy = completedRun({ id: 'healthy', runNumber: 2 }); await mount(view([first, healthy], id => selected.push(id))); await flush(() => { reply(request('/api/v2/runs/run/results'), { error: 'Result store offline' }, 503); reply(request('/api/v2/runs/healthy/results'), resultFor(healthy, 0.25)); }); expect(rows()).toHaveLength(2); expect(rows()[0]!.textContent).toContain('Metrics unavailable'); expect(rows()[0]!.querySelector('[title="Result store offline"]')).not.toBeNull(); expect(rows()[0]!.querySelectorAll('td')[3]!.textContent).toBe('-'); expect(rows()[1]!.textContent).toContain('25.00%'); const retry = button('Retry metrics for run 1'); await flush(() => { retry.click(); retry.click(); }); expect(selected).toEqual([]); expect(requests).toHaveLength(3); expect(requests.filter(item => item.path === '/api/v2/runs/healthy/results')).toHaveLength(1); expect(rows()[0]!.textContent).toContain('Loading metrics...'); await flush(() => reply(request('/api/v2/runs/run/results'), resultFor(first, 0.125))); expect(rows()[0]!.textContent).toContain('12.50%'); expect(host.textContent).not.toContain('Metrics unavailable'); expect(requests.every(item => item.method === 'GET')).toBe(true); }); test.each(['removed', 'parent', 'status'] as const)( '%s collection change fences late metrics and keeps current records authoritative', async change => { const original = completedRun(); await mount(view([original])); const stale = request('/api/v2/runs/run/results'); const current = change === 'removed' ? [] : [ change === 'parent' ? { ...original, backtestId: 'other-definition' } : { ...original, status: 'failed' as const }, ]; await update(current); expect(stale.signal?.aborted).toBe(true); await flush(() => reply(stale, resultFor(original, 1.23))); expect(host.textContent).not.toContain('123.00%'); expect(rows()).toHaveLength(current.length); if (change === 'removed') { expect(host.textContent).toContain('No runs yet'); await update([original]); expect(rows()[0]!.textContent).toContain('Loading metrics...'); await flush(() => reply(request('/api/v2/runs/run/results'), resultFor(original, 0.25))); expect(rows()[0]!.textContent).toContain('25.00%'); } else if (change === 'parent') { expect(rows()[0]!.textContent).toContain('Loading metrics...'); await flush(() => reply(request('/api/v2/runs/run/results'), resultFor(current[0]!, 0.25)) ); expect(rows()[0]!.textContent).toContain('25.00%'); } else { expect(rows()[0]!.textContent).toContain('Failed'); expect(rows()[0]!.textContent).toContain('Not completed'); expect(requests).toHaveLength(1); } } ); test('unmount aborts ownership and a late result cannot affect a remounted history', async () => { const original = completedRun(); await mount(view([original])); const stale = request('/api/v2/runs/run/results'); await flush(() => root!.unmount()); root = undefined; expect(stale.signal?.aborted).toBe(true); await mount(view([original])); await flush(() => reply(stale, resultFor(original, 1.23))); expect(rows()).toHaveLength(1); expect(rows()[0]!.textContent).toContain('Loading metrics...'); expect(host.textContent).not.toContain('123.00%'); await flush(() => reply(request('/api/v2/runs/run/results'), resultFor(original, 0.25))); expect(rows()[0]!.textContent).toContain('25.00%'); }); }); test('history uses positive canonical drawdown severity and preserves signed legacy thresholds', async () => { const cases = [ { kind: 'canonical', value: 0, color: 'text-success' }, { kind: 'canonical', value: 0.05, color: 'text-success' }, { kind: 'canonical', value: 0.1, color: 'text-warning' }, { kind: 'canonical', value: 0.2, color: 'text-error' }, { kind: 'canonical', value: 0.5, color: 'text-error' }, { kind: 'canonical', value: null, color: 'text-text-secondary' }, { kind: 'legacy', value: -0.05, color: 'text-success' }, { kind: 'legacy', value: -0.1, color: 'text-warning' }, { kind: 'legacy', value: -0.2, color: 'text-error' }, { kind: 'legacy', value: 0.5, color: 'text-success' }, ]; const runs = cases.map((_, index) => completedRun({ id: `run-${index}`, runNumber: index + 1 }) ); await mount( createElement( VirtuosoMockContext.Provider, { value: { viewportHeight: 1000, itemHeight: 40 }, }, createElement(RunsListWithMetrics, { runs, onSelectRun: () => {} }) ) ); await flush(() => { cases.forEach((item, index) => { const result = report(); result.runId = `run-${index}`; result.analytics.metrics.maxDrawdown = item.value; reply( request(`/api/v2/runs/run-${index}/results`), item.kind === 'canonical' ? result : { runId: result.runId, backtestId: result.backtestId, metrics: result.analytics.metrics, } ); }); }); const rows = [...host.querySelectorAll('tbody tr[data-index]')]; expect(rows).toHaveLength(cases.length); cases.forEach((item, index) => { const cell = rows[index]!.querySelectorAll('td')[5]!.querySelector('span')!; expect(cell.textContent).toBe( item.value === null ? '-' : `${(item.value * 100).toFixed(2)}%` ); expect(cell.classList.contains(item.color)).toBe(true); }); }); for (const [dailyHalted, drawdownHalted] of [ [false, false], [true, false], [false, true], [true, true], ] as const) { test(`renders the final risk snapshot with daily=${dailyHalted}, drawdown=${drawdownHalted}`, async () => { const value = report(); Object.assign(value.financial.view.risk, { dailyHalted, drawdownHalted }); const before = structuredClone(value); await mount(createElement(CanonicalResults, { result: value })); const section = host.querySelector('[aria-label="Final risk state"]'); expect(section).not.toBeNull(); const fact = (label: string) => [...section!.querySelectorAll('dt')].find(item => item.textContent === label) ?.nextElementSibling?.textContent; expect(fact('Daily-loss halt')).toBe(dailyHalted ? 'Active at end' : 'Inactive at end'); expect(fact('Drawdown halt')).toBe(drawdownHalted ? 'Active at end' : 'Inactive at end'); expect(fact('Daily-loss limit')).toBe(value.financial.policy.matching.risk.maxDailyLoss); expect(fact('Drawdown limit')).toBe(value.financial.policy.matching.risk.maxDrawdownAmount); expect(fact('Daily equity baseline')).toBe(value.financial.view.risk.dailyBaseline); expect(fact('Peak equity')).toBe(value.financial.view.risk.peakEquity); expect(fact('Risk session')).toBe(value.financial.view.risk.riskSession.sessionId); expect(fact('Risk calendar')).toContain(value.financial.view.risk.riskSession.calendarId); expect(fact('Risk calendar')).toContain( value.financial.view.risk.riskSession.calendarRevision ); expect(fact('Risk session start (UTC)')).toBe( new Date(value.financial.view.risk.riskSession.startsAt).toISOString() ); expect(fact('Last processed risk event (UTC)')).toBe( new Date(value.financial.view.risk.lastEventTime).toISOString() ); expect(section!.textContent).toContain('Amounts are in USD'); expect(section!.textContent).toContain('risk-increasing orders'); expect(section!.textContent).toContain('exposure-reducing orders'); expect(section!.querySelector('button, input, select')).toBeNull(); expect(value).toEqual(before); expect(requests).toHaveLength(0); }); } test('retains a latched drawdown despite recovered terminal equity and unchanged sampled metrics', async () => { const value = report(); const risk = value.financial.view.risk; risk.drawdownHalted = true; risk.peakEquity = decimal('10000.00000001'); risk.dailyBaseline = decimal('10000.12345678'); value.financial.policy.matching.risk.maxDailyLoss = decimal('100.12345678'); value.financial.policy.matching.risk.maxDrawdownAmount = decimal('200.00000001'); // The retained halt survives recovery; the view must not infer it from current balances // or sampled drawdown. The existing fixture has equity 10000 and sampled drawdown zero. const before = structuredClone(value); await mount(createElement(CanonicalResults, { result: value })); const section = host.querySelector('[aria-label="Final risk state"]')!; const fact = (label: string) => [...section.querySelectorAll('dt')].find(item => item.textContent === label) ?.nextElementSibling?.textContent; expect(fact('Drawdown halt')).toBe('Active at end'); expect(fact('Daily-loss limit')).toBe('100.12345678'); expect(fact('Drawdown limit')).toBe('200.00000001'); expect(fact('Daily equity baseline')).toBe('10000.12345678'); expect(fact('Peak equity')).toBe('10000.00000001'); expect(section.textContent).toContain( 'Price recovery alone does not clear a latched drawdown halt' ); expect(section.textContent).toContain('not the first halt time'); expect(section.textContent).toContain('does not contain halt history or rejection counts'); const sampled = [...host.querySelectorAll('dt')].find( item => item.textContent === 'Sampled maximum drawdown' ); expect(sampled?.nextElementSibling?.textContent).toBe('0.00%'); expect(value).toEqual(before); expect(requests).toHaveLength(0); }); test('renders a later daily-session snapshot without claiming that an inactive flag never halted', async () => { const value = report(); // This is a final snapshot after a session boundary, not a reconstructed halt history. value.financial.view.risk = { ...value.financial.view.risk, dailyHalted: false, dailyBaseline: decimal('9899.76543210'), riskSession: { ...value.financial.view.risk.riskSession, sessionId: 'following-session', startsAt: fixture.start + 43200000, }, }; const before = structuredClone(value); await mount(createElement(CanonicalResults, { result: value })); const section = host.querySelector('[aria-label="Final risk state"]')!; const daily = [...section.querySelectorAll('dt')].find( item => item.textContent === 'Daily-loss halt' ); expect(daily?.nextElementSibling?.textContent).toBe('Inactive at end'); expect(section.textContent).toContain('following-session'); expect(section.textContent).toContain('9899.76543210'); expect(section.textContent).toContain( 'Daily-loss state can reset at an account risk-session boundary' ); expect(section.textContent).toContain('not whether earlier halts or other rejections occurred'); expect(value).toEqual(before); expect(requests).toHaveLength(0); }); test('keeps final risk facts for empty fills and replaces them when switching runs', async () => { const first = report(); first.financial.projection.fills = []; first.analytics.fillCount = 0; first.financial.view.risk.riskSession.sessionId = 'first-run-session'; const second = structuredClone(first); second.runId = 'next-run'; second.financial.view.risk = { ...second.financial.view.risk, dailyHalted: true, drawdownHalted: true, peakEquity: decimal('12345.67890123'), riskSession: { ...second.financial.view.risk.riskSession, sessionId: 'second-run-session', }, lastEventTime: fixture.start + 86400000 - 123, }; const before = structuredClone([first, second]); await mount(createElement(CanonicalResults, { result: first })); expect(host.querySelector('[aria-label="Final risk state"]')?.textContent).toContain( 'first-run-session' ); await flush(() => root!.render(createElement(CanonicalResults, { result: second }))); const section = host.querySelector('[aria-label="Final risk state"]')!; expect(section.textContent).toContain('second-run-session'); expect(section.textContent).not.toContain('first-run-session'); expect(section.textContent).toContain('12345.67890123'); expect(section.textContent).toContain( new Date(second.financial.view.risk.lastEventTime).toISOString() ); expect(section.textContent!.match(/Active at end/g)).toHaveLength(2); expect( [...section.querySelectorAll('dd')].some(item => item.textContent === 'Inactive at end') ).toBe(false); await flush(() => root!.render(createElement(CanonicalResults, { result: second, fillsOnly: true })) ); expect(host.querySelector('[aria-label="Final risk state"]')).toBeNull(); expect(host.textContent).toContain('No fills were executed in this completed run'); expect([first, second]).toEqual(before); expect(requests).toHaveLength(0); }); test('renders exact financial facts, fractional positions, genuine zero and unavailable analytics with provenance', async () => { const value = report(); await mount(createElement(CanonicalResults, { result: value })); const metric = (name: string) => [...host.querySelectorAll('dt')].find(el => el.textContent === name)?.nextElementSibling ?.textContent; expect(metric('Total return')).toBe('0.00%'); expect(metric('Sampled maximum drawdown')).toBe('0.00%'); expect(metric('Annualized volatility')).toBe('Unavailable — insufficient periods'); expect(metric('Completed round trips')).toBe('Unavailable — unsupported round trips'); expect(metric('Fees')).toBe('0.00000000'); expect(host.textContent).toContain('0.12500000'); expect(host.textContent).toContain( 'Per-position marks, average prices and unrealized P&L are unavailable' ); expect(host.textContent).toContain(hash); expect(host.textContent).toContain('3'.repeat(64)); expect(host.textContent).toContain('Retained fixture limitation'); expect(host.textContent).toContain('Risk-free rate: 0.00%'); expect(host.textContent).toContain('Partial'); expect(host.textContent).not.toContain('globalThis.CATALOG_MUST_NOT_EXECUTE'); value.analytics.metrics.totalReturn = 0.125; value.analytics.policy.annualRiskFreeRate = null; await flush(() => root!.render(createElement(CanonicalResults, { result: value }))); expect(metric('Total return')).toBe('12.50%'); expect(host.textContent).toContain('Risk-free rate: unknown'); await flush(() => root!.render(createElement(CanonicalResults, { result: value, fillsOnly: true })) ); expect(host.textContent).toContain('0.12500000'); expect(host.textContent).toContain('40.00000000'); expect(host.textContent).toContain('order'); expect(host.textContent).toContain('Win rate and round-trip statistics are unavailable'); expect(host.querySelector('[aria-label="Evaluation horizon"]')).toBeNull(); expect(host.textContent).not.toContain('CAGR extrapolates'); value.financial.projection.fills = []; await flush(() => root!.render(createElement(CanonicalResults, { result: value, fillsOnly: true })) ); expect(host.textContent).toContain('No fills'); }); test('download uses the immutable result request hash and remains absent from fills-only view', async () => { const value = report(); // The action must follow the retained request, without looking up an editable template. const originalHash = 'e'.repeat(64); value.request.datasetHash = originalHash; await mount(createElement(CanonicalResults, { result: value })); expect(requests).toHaveLength(0); await flush(() => click('Download retained dataset')); expect(requests).toHaveLength(1); const download = request(`/api/v2/datasets/canonical/${originalHash}/export`); expect(download.method).toBe('GET'); await flush(() => root!.render(createElement(CanonicalResults, { result: value, fillsOnly: true })) ); expect(download.signal?.aborted).toBe(true); expect(host.textContent).not.toContain('Download retained dataset'); expect(host.textContent).not.toContain('Downloading retained dataset'); expect(host.textContent).toContain('0.12500000'); expect(requests).toHaveLength(1); }); describe('canonical run result download', () => { const blobs: Blob[] = []; const downloads: { href: string; filename: string }[] = []; const revoked: string[] = []; let failure: 'url' | 'click' | undefined; let restore: () => void; const tick = () => new Promise(resolve => setTimeout(resolve, 0)); beforeEach(() => { blobs.length = downloads.length = revoked.length = 0; failure = undefined; const createUrl = spyOn(URL, 'createObjectURL').mockImplementation(blob => { if (failure === 'url') { throw new Error('Browser file creation failed'); } blobs.push(blob as Blob); return `blob:run-${blobs.length}`; }); const revokeUrl = spyOn(URL, 'revokeObjectURL').mockImplementation(url => { revoked.push(url); }); const anchorClick = spyOn(browser.HTMLAnchorElement.prototype, 'click').mockImplementation( () => { if (failure === 'click') { throw new Error('Browser download failed'); } const anchor = browser.document.querySelector('a[download]'); if (!(anchor instanceof browser.HTMLAnchorElement)) { throw new Error('Download anchor was not attached'); } downloads.push({ href: anchor.href, filename: anchor.download }); } ); restore = () => { createUrl.mockRestore(); revokeUrl.mockRestore(); anchorClick.mockRestore(); }; }); afterEach(async () => { await tick(); restore(); }); test('saves the complete original result without rounding, mutation or another request', async () => { const value = report(); const before = structuredClone(value); await mount(createElement(CanonicalResults, { result: value })); expect(downloads).toHaveLength(0); await flush(() => click('Download run result')); expect(downloads).toEqual([{ href: 'blob:run-1', filename: 'run-run.json' }]); expect(blobs[0]!.type.split(';')[0]).toBe('application/json'); expect(JSON.parse(await blobs[0]!.text())).toEqual(before); expect(value).toEqual(before); expect(browser.document.querySelector('a[download]')).toBeNull(); await tick(); expect(revoked).toEqual(['blob:run-1']); const other = report(); other.runId = other.request.runId = 'another-run'; other.request.name = 'Other retained inputs'; await flush(() => root!.render(createElement(CanonicalResults, { result: other }))); await flush(() => click('Download run result')); expect(downloads[1]!.filename).toBe('run-another-run.json'); expect(JSON.parse(await blobs[1]!.text())).toEqual(other); expect(requests).toHaveLength(0); await flush(() => root!.render(createElement(CanonicalResults, { result: other, fillsOnly: true })) ); expect(host.textContent).not.toContain('Download run result'); expect(host.textContent).not.toContain('Retry run result download'); }); for (const stage of ['url', 'click'] as const) { test(`reports ${stage} failure inline and retries the unchanged result with cleanup`, async () => { const value = report(); await mount(createElement(CanonicalResults, { result: value })); failure = stage; await flush(() => click('Download run result')); expect(host.querySelector('[role="alert"]')?.textContent).toBe( stage === 'url' ? 'Browser file creation failed' : 'Browser download failed' ); expect(downloads).toHaveLength(0); expect(browser.document.querySelector('a[download]')).toBeNull(); await tick(); expect(revoked).toEqual(stage === 'url' ? [] : ['blob:run-1']); failure = undefined; await flush(() => click('Retry run result download')); expect(host.querySelector('[role="alert"]')).toBeNull(); expect(downloads).toHaveLength(1); expect(JSON.parse(await blobs.at(-1)!.text())).toEqual(value); expect(requests).toHaveLength(0); await tick(); expect(revoked).toEqual(blobs.map((_, index) => `blob:run-${index + 1}`)); }); } test('a different displayed run clears the earlier local download error', async () => { await mount(createElement(CanonicalResults, { result: report() })); failure = 'click'; await flush(() => click('Download run result')); expect(host.querySelector('[role="alert"]')?.textContent).toBe('Browser download failed'); const other = report(); other.runId = other.request.runId = 'next-run'; await flush(() => root!.render(createElement(CanonicalResults, { result: other }))); expect(host.querySelector('[role="alert"]')).toBeNull(); failure = undefined; await flush(() => click('Download run result')); expect(downloads[0]!.filename).toBe('run-next-run.json'); expect(JSON.parse(await blobs.at(-1)!.text())).toEqual(other); expect(requests).toHaveLength(0); }); }); test('explains a partial-session evaluation horizon alongside the unchanged retained CAGR', async () => { const value = report(); value.financial.reporting.tradeStart = Date.parse('2024-10-01T14:30:00Z'); value.financial.reporting.tradeEnd = Date.parse('2024-10-01T20:00:00Z'); value.financial.reporting.elapsedMs = '19800000'; value.financial.reporting.sessions = value.financial.reporting.sessions.map(session => ({ ...session, periodStart: value.financial.reporting.tradeStart, periodEnd: value.financial.reporting.tradeEnd, partialStart: true, partialEnd: true, })); // Retained metrics are presentation inputs; the view must not recalculate them from balances. value.analytics.metrics.totalReturn = -0.0005457499930000553; value.analytics.metrics.cagr = -0.5808255828609735; const before = structuredClone(value); await mount(createElement(CanonicalResults, { result: value })); const horizon = host.querySelector('[aria-label="Evaluation horizon"]'); expect(horizon?.textContent).toContain('2024-10-01T14:30:00.000Z'); expect(horizon?.textContent).toContain('2024-10-01T20:00:00.000Z'); expect(horizon?.textContent).toContain('5 hours, 30 minutes'); const cagr = [...host.querySelectorAll('dt')].find(el => el.textContent === 'CAGR'); expect(cagr?.nextElementSibling?.textContent).toBe('-58.08%'); expect(cagr?.nextElementSibling?.getAttribute('title')).toBe('-0.5808255828609735'); expect(cagr?.parentElement?.textContent).toContain( 'CAGR extrapolates this evaluation interval to a 365-calendar-day year, including nontrading time. It is not an observed annual return or a forecast.' ); expect(host.textContent).toContain('Annualization for periodic statistics: 252 periods/year'); expect(value).toEqual(before); expect(requests).toHaveLength(0); }); test('shows overnight calendar duration exactly and preserves unavailable CAGR reasons', async () => { const value = report(); // A Friday-to-Monday interval includes the weekend and retains sub-second precision. value.financial.reporting.tradeStart = Date.parse('2024-10-04T14:30:00Z'); value.financial.reporting.tradeEnd = Date.parse('2024-10-07T20:00:01.123Z'); value.financial.reporting.elapsedMs = '279001123'; value.analytics.metrics.cagr = null; value.analytics.unavailable.cagr = 'nonfinite-result'; await mount(createElement(CanonicalResults, { result: value })); const horizon = host.querySelector('[aria-label="Evaluation horizon"]'); expect(horizon?.textContent).toContain('2024-10-04T14:30:00.000Z'); expect(horizon?.textContent).toContain('2024-10-07T20:00:01.123Z'); expect(horizon?.textContent).toContain( '3 days, 5 hours, 30 minutes, 1 second, 123 milliseconds' ); const cagr = [...host.querySelectorAll('dt')].find(el => el.textContent === 'CAGR'); expect(cagr?.nextElementSibling?.textContent).toBe('Unavailable — nonfinite result'); expect(cagr?.parentElement?.textContent).toContain('365-calendar-day year'); value.financial.reporting.tradeEnd = value.financial.reporting.tradeStart; value.financial.reporting.elapsedMs = '0'; value.analytics.unavailable.cagr = 'zero-duration'; await flush(() => root!.render(createElement(CanonicalResults, { result: value }))); expect(host.querySelector('[aria-label="Evaluation horizon"]')?.textContent).toContain( '0 seconds' ); expect( [...host.querySelectorAll('dt')].find(el => el.textContent === 'CAGR')?.nextElementSibling ?.textContent ).toBe('Unavailable — zero duration'); }); test('setup validates explicit policy and saves exact non-midnight daily bounds without legacy policy leakage', async () => { const saves: CreateBacktestRequest[] = []; await mount( createElement(CanonicalSetup, { backtest: { ...definition, config: { commission: 0.9, riskPercentage: 80, speedMultiplier: 50, datasetHash: 'old-v1', }, }, onSave: async value => { saves.push(value); }, }) ); await selected(); expect(field('Canonical dataset').value).toBe(''); expect(button('Save canonical setup').disabled).toBe(true); await flush(() => reply(request('/api/v2/datasets/canonical'), { datasets: [entry] })); await flush(() => edit('Canonical dataset', hash)); expect(button('Save canonical setup').disabled).toBe(true); await flush(() => reply(request(`/api/v2/datasets/canonical/${hash}`), { dataset: entry })); await validateSelected(); await flush(() => { edit('Fee rate', '-0.1'); edit('Annual risk-free rate', '0'); edit('Random seed', '42'); }); expect(button('Save canonical setup').disabled).toBe(true); await flush(() => edit('Fee rate', '0')); expect(button('Save canonical setup').disabled).toBe(false); await flush(() => click('Save canonical setup')); expect(saves).toHaveLength(1); const saved = saves[0]!; expect(saved.symbols).toEqual(['X0.US']); expect(saved.startDate).toBe('2024-01-01T09:00:00.123Z'); expect(saved.endDate).toBe('2024-01-02T09:00:00.456Z'); expect(saved.strategyVersionId).toBe('version-one'); expect(saved.strategyParameters).toEqual(definition.strategyParameters); expect(Object.keys(saved.config!).sort()).toEqual([ 'canonical', 'dataFrequency', 'datasetHash', ]); expect(saved.config!.dataFrequency).toBe('1d'); expect(saved.config!.canonical).toMatchObject({ version: 1, feeRate: '0.00000000', annualRiskFreeRate: 0, seed: 42, ownerBudget: '100000.00000000', }); expect(host.textContent).toContain(saved.startDate); }); test('authoritative setup reset clears stale validation and submits the parameters visible after restore', async () => { const saves: CreateBacktestRequest[] = []; const onSave = async (value: CreateBacktestRequest) => { saves.push(value); }; await mount(createElement(CanonicalSetup, { backtest: definition, onSave })); await selected(); await flush(() => reply(request('/api/v2/datasets/canonical'), { datasets: [entry] })); await flush(() => edit('Canonical dataset', hash)); await flush(() => reply(request(`/api/v2/datasets/canonical/${hash}`), { dataset: entry })); await flush(() => edit('fastPeriod', '3')); await flush(() => click('Validate parameters')); const stale = request('/api/v2/strategy-versions/version-one/validate', 'POST'); await flush(() => root!.render( createElement( router.MemoryRouter, null, createElement(CanonicalSetup, { backtest: { ...definition, archivedAt: '2026-01-02' }, disabled: true, onSave, }) ) ) ); await selected(); await flush(() => reply(request('/api/v2/datasets/canonical'), { datasets: [entry] })); await flush(() => reply(stale, { parameters: { fastPeriod: 3, slowPeriod: 15 }, runnable: false, reason: 'gated', }) ); expect(field('fastPeriod').value).toBe('5'); expect(button('Save canonical setup').disabled).toBe(true); await flush(() => root!.render( createElement( router.MemoryRouter, null, createElement(CanonicalSetup, { backtest: { ...definition }, onSave }) ) ) ); await selected(); await flush(() => reply(request('/api/v2/datasets/canonical'), { datasets: [entry] })); expect(field('fastPeriod').value).toBe('5'); expect(button('Save canonical setup').disabled).toBe(true); await flush(() => edit('Canonical dataset', hash)); await flush(() => reply(request(`/api/v2/datasets/canonical/${hash}`), { dataset: entry })); await validateSelected(); await flush(() => click('Save canonical setup')); expect(saves[0]?.strategyParameters).toEqual({ fastPeriod: 5, slowPeriod: 15 }); }); test('retains missing saved dataset, handles catalog failure, and fences stale selected metadata', async () => { await mount( createElement(CanonicalSetup, { backtest: definition, onSave: async () => { throw new Error('must not save'); }, }) ); await flush(() => reply(request('/api/v2/datasets/canonical'), { error: 'Dataset catalog unavailable' }, 503) ); expect(host.textContent).toContain('Dataset catalog unavailable'); await flush(() => click('Retry canonical datasets')); const other = { ...entry, hash: 'b'.repeat(64), manifest: { ...entry.manifest!, hash: 'b'.repeat(64) }, }; await flush(() => reply(request('/api/v2/datasets/canonical'), { datasets: [entry, other] })); await flush(() => edit('Canonical dataset', hash)); const stale = request(`/api/v2/datasets/canonical/${hash}`); await flush(() => edit('Canonical dataset', other.hash)); await flush(() => reply( request(`/api/v2/datasets/canonical/${other.hash}`), { error: 'Retained dataset missing' }, 404 ) ); await flush(() => reply(stale, { dataset: entry })); expect(field('Canonical dataset').value).toBe(other.hash); expect(host.textContent).toContain('Retained dataset missing'); expect(host.textContent).not.toContain('Trading start (UTC)'); expect(button('Save canonical setup').disabled).toBe(true); }); test('capability late replies cannot enable a changed definition; failed request retries reuse frozen receipt after archive', async () => { await mount(createElement(Hook)); await loadDefinition(); const stale = request('/api/v2/backtests/definition/canonical-capability'); await flush(() => latest.refreshCanonicalCapability()); await flush(() => reply(stale, { available: true, reason: null })); expect(latest.canonicalCapability).toBeNull(); await flush(() => reply( request('/api/v2/backtests/definition/canonical-capability'), { error: 'Engine offline' }, 503 ) ); expect(latest.capabilityError).toBe('Engine offline'); await flush(() => { void latest.createRun(); }); expect(requests.filter(item => item.method === 'POST')).toHaveLength(0); await flush(() => latest.refreshCanonicalCapability()); await flush(() => reply(request('/api/v2/backtests/definition/canonical-capability'), { available: true, reason: null, }) ); await flush(() => { void latest.createRun(7); }); const first = request('/api/v2/backtests/definition/runs', 'POST'); await flush(() => fail(first)); expect(latest.hasPendingSubmission).toBe(true); let archive: Promise; await flush(() => { archive = latest.setBacktestArchived('definition', true); }); await flush(() => reply(request('/api/v2/backtests/definition/archive', 'POST'), { ...definition, archivedAt: '2026-01-02', }) ); await archive!; expect(latest.canonicalCapability).toBeNull(); await flush(() => { void latest.createRun(100); }); const retry = request('/api/v2/backtests/definition/runs', 'POST'); expect(retry.headers.get('Idempotency-Key')).toBe(first.headers.get('Idempotency-Key')); expect(retry.body).toEqual({ speedMultiplier: null }); await flush(() => reply( retry, { id: 'accepted', backtestId: 'definition', runNumber: 1, status: 'pending', progress: 0, createdAt: '2026-01-01', updatedAt: '2026-01-01', speedMultiplier: null, }, 202 ) ); expect(latest.hasPendingSubmission).toBe(false); await flush(() => { void latest.createRun(); }); expect( requests.filter(item => item.method === 'POST' && item.path.endsWith('/runs')) ).toHaveLength(2); }); test('operator review requires authentication and reason and preserves backend failure', async () => { const reviewed: StrategyVersionSummary[] = []; await mount( createElement(BuiltinReview, { version: version('version-one', { reviewStatus: 'pending' }), onReviewed: value => reviewed.push(value), }) ); await flush(() => reply(request('/api/auth/session'), { authenticated: true, role: 'admin' })); expect(button('Approve built-in version').disabled).toBe(true); await flush(() => edit('Review reason', 'Reviewed immutable retained bytes')); await flush(() => click('Approve built-in version')); expect(request('/api/v2/strategy-versions/version-one/reviews', 'POST').body).toEqual({ decision: 'approve', reason: 'Reviewed immutable retained bytes', }); await flush(() => reply( request('/api/v2/strategy-versions/version-one/reviews', 'POST'), { error: 'Review unavailable' }, 503 ) ); expect(host.textContent).toContain('Review unavailable'); expect(field('Review reason').value).toBe('Reviewed immutable retained bytes'); await flush(() => click('Approve built-in version')); await flush(() => reply( request('/api/v2/strategy-versions/version-one/reviews', 'POST'), { version: version(), }, 201 ) ); expect(reviewed).toHaveLength(1); }); for (const role of ['service', 'read', 'anonymous']) { test(`${role} cannot use the built-in approval action`, async () => { await mount( createElement(BuiltinReview, { version: version('version-one', { reviewStatus: 'pending' }), onReviewed: () => { throw new Error('must not approve'); }, }) ); await flush(() => reply(request('/api/auth/session'), { authenticated: role !== 'anonymous', role }) ); expect(host.textContent).toContain('authenticated human operator'); expect( [...host.querySelectorAll('button')].some( el => el.textContent === 'Approve built-in version' ) ).toBe(false); }); } }); const catalogPath = '/api/v2/datasets/canonical'; function catalogEntry( index: number, extra: Partial = {} ): CanonicalDatasetCatalogEntry { const identity = index.toString(16).padStart(64, '0'); return { ...entry, hash: identity, manifest: { ...entry.manifest!, hash: identity }, ...extra, }; } async function setupCatalog(entries: CanonicalDatasetCatalogEntry[]) { const saves: CreateBacktestRequest[] = []; await mount( createElement(CanonicalSetup, { backtest: definition, onSave: async value => { saves.push(value); }, }) ); await selected(); await validateSelected(); await flush(() => reply(request(catalogPath), { datasets: entries })); return saves; } async function useKnownHash(value: string) { await flush(() => edit('Retained dataset hash', value)); await flush(() => click('Use dataset hash')); } function optionHashes() { return [...(field('Canonical dataset') as HTMLSelectElement).options] .map(option => option.value) .filter(Boolean); } describe('retained canonical dataset reuse', () => { test('loads beyond fifty, retries the same failed offset, deduplicates overlaps and saves exact verified bounds', async () => { const entries = Array.from({ length: 53 }, (_, index) => catalogEntry(index + 1)); const saves = await setupCatalog(entries.slice(0, 50)); await flush(() => edit('Canonical dataset', entries[0]!.hash)); await flush(() => reply(request(`${catalogPath}/${entries[0]!.hash}`), { dataset: entries[0] }) ); await flush(() => { click('Load more canonical datasets'); click('Load more canonical datasets'); }); const next = request(catalogPath); expect(next.search).toBe('?limit=50&offset=50'); expect(requests.filter(item => item.path === catalogPath && !item.settled)).toHaveLength(1); await flush(() => fail(next)); expect(optionHashes()).toHaveLength(50); expect(field('Canonical dataset').value).toBe(entries[0]!.hash); expect(button('Save canonical setup').disabled).toBe(false); await flush(() => click('Retry canonical datasets')); expect(request(catalogPath).search).toBe('?limit=50&offset=50'); await flush(() => reply(request(catalogPath), { datasets: entries.slice(49) })); expect(optionHashes()).toHaveLength(53); expect(new Set(optionHashes()).size).toBe(53); expect( [...host.querySelectorAll('button')].some( item => item.textContent === 'Load more canonical datasets' ) ).toBe(false); const chosen = entries[52]!; await flush(() => edit('Canonical dataset', chosen.hash)); expect(button('Save canonical setup').disabled).toBe(true); await flush(() => reply(request(`${catalogPath}/${chosen.hash}`), { dataset: chosen })); await flush(() => click('Save canonical setup')); expect(saves).toHaveLength(1); expect(saves[0]!.config?.datasetHash).toBe(chosen.hash); expect(saves[0]!.startDate).toBe(new Date(chosen.manifest!.bounds.tradeStart).toISOString()); expect(saves[0]!.endDate).toBe(new Date(chosen.manifest!.bounds.tradeEnd).toISOString()); expect(requests.some(item => item.method === 'POST' && item.path.endsWith('/runs'))).toBe( false ); }); test('explicit known-hash lookup accepts converted lineage; typing and Enter never fetch or submit', async () => { const chosen = catalogEntry(100); chosen.manifest = { ...chosen.manifest!, parentDatasetHash: 'e'.repeat(64) }; const saves = await setupCatalog([]); const before = requests.length; await flush(() => edit('Retained dataset hash', chosen.hash)); const enter = new browser.KeyboardEvent('keydown', { key: 'Enter', bubbles: true, cancelable: true, }); await flush(() => { field('Retained dataset hash').dispatchEvent(enter as unknown as Event); }); expect(enter.defaultPrevented).toBe(true); expect(requests).toHaveLength(before); expect(saves).toEqual([]); expect(host.textContent).not.toContain('Unsaved canonical setup'); await flush(() => click('Use dataset hash')); await flush(() => reply(request(`${catalogPath}/${chosen.hash}`), { dataset: chosen })); expect(field('Canonical dataset').value).toBe(chosen.hash); expect(optionHashes()).toEqual([chosen.hash]); expect(button('Save canonical setup').disabled).toBe(false); await flush(() => click('Save canonical setup')); expect(saves[0]!.config?.datasetHash).toBe(chosen.hash); }); test('malformed hash never fetches and invalid, missing, unavailable or wrong detail cannot authorize saving', async () => { const chosen = catalogEntry(100); const saves = await setupCatalog([chosen]); for (const invalid of ['', 'not-a-hash', 'A'.repeat(64)]) { const before = requests.length; await useKnownHash(invalid); expect(requests).toHaveLength(before); expect(host.textContent).toContain('64 lowercase hexadecimal'); expect(button('Save canonical setup').disabled).toBe(true); } const replies = [ { body: { error: 'Dataset not found' }, status: 404 }, { body: { dataset: { ...chosen, available: false, manifest: null, reason: 'Stored bytes invalid' }, }, status: 200, }, { body: { dataset: catalogEntry(101) }, status: 200 }, { body: { dataset: { ...chosen, available: true, manifest: null } }, status: 200 }, { body: { dataset: { ...chosen, manifest: { ...chosen.manifest, executionSeries: null } } }, status: 200, }, { body: { wrongEnvelope: chosen }, status: 200 }, ]; for (const item of replies) { await useKnownHash(chosen.hash); await flush(() => reply(request(`${catalogPath}/${chosen.hash}`), item.body, item.status)); expect(button('Save canonical setup').disabled).toBe(true); expect(host.querySelector('[role="alert"]')).not.toBeNull(); expect(host.textContent).not.toContain('The selected hash is retained'); } await useKnownHash(chosen.hash); await flush(() => reply(request(`${catalogPath}/${chosen.hash}`), { dataset: chosen })); expect(button('Save canonical setup').disabled).toBe(false); await flush(() => edit('Retained dataset hash', 'bad')); await flush(() => { click('Use dataset hash'); click('Save canonical setup'); }); expect(saves).toEqual([]); }); test('late lookups, refresh and unmount cannot replace the current verified hash or authorize a same-event save', async () => { const a = catalogEntry(100), b = catalogEntry(101); const saves = await setupCatalog([]); await useKnownHash(a.hash); const stale = request(`${catalogPath}/${a.hash}`); await useKnownHash(b.hash); expect(stale.signal?.aborted).toBe(true); await flush(() => reply(request(`${catalogPath}/${b.hash}`), { dataset: b })); await flush(() => reply(stale, { dataset: a })); expect(field('Canonical dataset').value).toBe(b.hash); await flush(() => { click('Refresh canonical datasets'); click('Save canonical setup'); }); expect(saves).toEqual([]); expect(button('Save canonical setup').disabled).toBe(true); expect(field('Canonical dataset').value).toBe(b.hash); await flush(() => reply(request(catalogPath), { datasets: [] })); await flush(() => reply(request(`${catalogPath}/${b.hash}`), { dataset: b })); expect(button('Save canonical setup').disabled).toBe(false); await useKnownHash(a.hash); const pending = request(`${catalogPath}/${a.hash}`); await flush(() => root!.unmount()); root = undefined; expect(pending.signal?.aborted).toBe(true); await flush(() => reply(pending, { dataset: a })); expect(saves).toEqual([]); }); test('refresh fences old pages, resets pagination and preserves an off-page selection', async () => { const entries = Array.from({ length: 51 }, (_, index) => catalogEntry(index + 1)); await setupCatalog(entries.slice(0, 50)); const chosen = entries[0]!; await flush(() => edit('Canonical dataset', chosen.hash)); await flush(() => reply(request(`${catalogPath}/${chosen.hash}`), { dataset: chosen })); await flush(() => click('Load more canonical datasets')); const old = request(catalogPath); await flush(() => click('Refresh canonical datasets')); expect(old.signal?.aborted).toBe(true); await flush(() => reply(old, { datasets: entries.slice(50) })); expect(optionHashes()).toEqual([chosen.hash]); expect(request(catalogPath).search).toBe('?limit=50&offset=0'); await flush(() => reply(request(catalogPath), { datasets: entries.slice(1, 51) })); await flush(() => reply(request(`${catalogPath}/${chosen.hash}`), { dataset: chosen })); expect(field('Canonical dataset').value).toBe(chosen.hash); expect(optionHashes()).toHaveLength(51); await flush(() => click('Load more canonical datasets')); expect(request(catalogPath).search).toBe('?limit=50&offset=50'); }); test('malformed catalog is recoverable; valid unavailable entries remain visible and disabled', async () => { await setupCatalog([]); for (const malformed of [ { datasets: null }, { datasets: [null] }, { datasets: [{ ...entry, manifest: {} }] }, { entries: [] }, ]) { await flush(() => click('Refresh canonical datasets')); await flush(() => reply(request(catalogPath), malformed)); expect(host.textContent).toContain('catalog response could not be verified'); expect(button('Save canonical setup').disabled).toBe(true); } await flush(() => click('Retry canonical datasets')); const unavailable = { ...catalogEntry(99), available: false, manifest: null, reason: 'Retained payload cannot be validated', }; await flush(() => reply(request(catalogPath), { datasets: [unavailable] })); const option = [...(field('Canonical dataset') as HTMLSelectElement).options].find( item => item.value === unavailable.hash )!; expect(option.disabled).toBe(true); expect(option.textContent).toContain(unavailable.reason); expect(host.querySelector('[role="alert"]')).toBeNull(); }); test('retention refresh fences an old page and selects newly retained bytes without duplicate choices', async () => { const entries = Array.from({ length: 50 }, (_, index) => catalogEntry(index + 1)); await setupCatalog(entries); await flush(() => click('Load more canonical datasets')); const old = request(catalogPath); const retained = nativeReplayFixture(4).dataset; const { calendars, series, executionSeries, bounds, universe, corporateActions } = retained.manifest; const input = { metadata: { calendars, series, executionSeries, bounds, universe, corporateActions }, bars: retained.bars.map(bar => ({ seriesId: bar.seriesId, timestamp: bar.intervalStart, availableAt: bar.availableAt, sourceSequence: bar.sourceSequence, open: bar.open, high: bar.high, low: bar.low, close: bar.close, volume: bar.volume, })), }; const file = field('Source dataset JSON'); Object.defineProperty(file, 'files', { configurable: true, value: [{ name: 'new.json', text: async () => JSON.stringify(input) }], }); await flush(() => file.dispatchEvent(new browser.Event('change', { bubbles: true }) as unknown as Event) ); await flush(() => click('Preview dataset')); const preparation = { version: 'canonical-dataset-preparation/v1', hash: retained.manifest.hash, manifest: retained.manifest, available: true, reason: null, }; await flush(() => reply(request('/api/v2/datasets/canonical/preview', 'POST'), { preparation }) ); await flush(() => click('Retain dataset')); await flush(() => reply(request('/api/v2/datasets/canonical/retain', 'POST'), { preparation })); expect(old.signal?.aborted).toBe(true); await flush(() => reply(old, { datasets: [catalogEntry(51)] })); const fresh = { hash: retained.manifest.hash, manifest: retained.manifest, available: true, reason: null, createdAt: entry.createdAt, }; expect(request(catalogPath).search).toBe('?limit=50&offset=0'); await flush(() => reply(request(catalogPath), { datasets: [fresh, ...entries.slice(0, 49)] })); await flush(() => reply(request(`${catalogPath}/${fresh.hash}`), { dataset: fresh })); expect(field('Canonical dataset').value).toBe(fresh.hash); expect(optionHashes()).toHaveLength(50); expect(new Set(optionHashes()).size).toBe(50); expect(button('Save canonical setup').disabled).toBe(false); await flush(() => click('Load more canonical datasets')); expect(request(catalogPath).search).toBe('?limit=50&offset=50'); }); test('transport rejects malformed page arguments and exact-hash requests before network access', async () => { const before = requests.length; await expect(backtestApiV2.listCanonicalDatasets(0, 0)).rejects.toThrow('pagination'); await expect(backtestApiV2.listCanonicalDatasets(50, -1)).rejects.toThrow('pagination'); await expect(backtestApiV2.canonicalDataset('bad')).rejects.toThrow('64 lowercase hexadecimal'); expect(requests).toHaveLength(before); }); });