1328 lines
52 KiB
TypeScript
1328 lines
52 KiB
TypeScript
import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, test } from 'bun:test';
|
|
import { GlobalWindow } from 'happy-dom';
|
|
import { act, createElement, type ReactElement } from 'react';
|
|
import type { Root } from 'react-dom/client';
|
|
import type {
|
|
CanonicalDatasetCatalogEntry,
|
|
CanonicalDatasetPreparation,
|
|
CanonicalStoredSourcePreparation,
|
|
} from '@stock-bot/stock-config/canonical-research';
|
|
import type {
|
|
HistoricalDatasetMetadataV2,
|
|
StrategyParameterSchema,
|
|
StrategyRecord,
|
|
StrategyVersionPackage,
|
|
StrategyVersionSummary,
|
|
} from '@stock-bot/types';
|
|
import { createDatasetV2 } from '../../apps/stock/orchestrator/src/data/historical-dataset-v2';
|
|
import type { CreateBacktestRequest } from '../../apps/stock/web-app/src/features/backtest/services/backtestApiV2';
|
|
import { datasetInput } from '../fixtures/historical-v2/dataset';
|
|
import { metadata as intradayMetadata, intradayResponse } from '../fixtures/intraday/eod';
|
|
|
|
const browser = new GlobalWindow({ url: 'http://localhost:5173' });
|
|
const keys = ['window', 'document', 'IS_REACT_ACT_ENVIRONMENT', 'ResizeObserver'] 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 CanonicalSetup: typeof import('../../apps/stock/web-app/src/features/backtest/components/CanonicalSetup').CanonicalSetup;
|
|
let DatasetPreparation: typeof import('../../apps/stock/web-app/src/features/backtest/components/DatasetPreparation').DatasetPreparation;
|
|
let parseDatasetPreparation: typeof import('../../apps/stock/web-app/src/features/backtest/services/backtestApiV2').parseDatasetPreparation;
|
|
let parseStoredDatasetPreparation: typeof import('../../apps/stock/web-app/src/features/backtest/services/backtestApiV2').parseStoredDatasetPreparation;
|
|
function confirmWith(value: () => boolean) {
|
|
Object.defineProperty(browser, 'confirm', { configurable: true, writable: true, value });
|
|
}
|
|
let root: Root | undefined;
|
|
let host: HTMLDivElement;
|
|
function deferred<T>() {
|
|
let resolve!: (value: T) => void;
|
|
let reject!: (error: Error) => void;
|
|
const promise = new Promise<T>((yes, no) => {
|
|
resolve = yes;
|
|
reject = no;
|
|
});
|
|
return { promise, resolve, reject };
|
|
}
|
|
type Pending = ReturnType<typeof deferred<Response>> & {
|
|
path: string;
|
|
method: string;
|
|
body: unknown;
|
|
signal: AbortSignal | null | undefined;
|
|
settled: boolean;
|
|
};
|
|
const requests: Pending[] = [];
|
|
function request(path: string, method = 'POST') {
|
|
const found = requests.find(
|
|
item => item.path === path && item.method === method && !item.settled
|
|
);
|
|
if (!found) {
|
|
throw new Error(
|
|
`No pending ${method} ${path}: ${JSON.stringify(requests.map(item => [item.path, item.method, item.settled]))}`
|
|
);
|
|
}
|
|
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
|
|
);
|
|
if (!found) {
|
|
throw new Error(`Missing ${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
|
|
| null;
|
|
if (!found) {
|
|
throw new Error(`Missing ${label}`);
|
|
}
|
|
return found;
|
|
}
|
|
function edit(label: string, value: string) {
|
|
const input = field(label);
|
|
Object.getOwnPropertyDescriptor(
|
|
input.tagName === 'SELECT'
|
|
? browser.HTMLSelectElement.prototype
|
|
: browser.HTMLInputElement.prototype,
|
|
'value'
|
|
)!.set!.call(input, value);
|
|
input.dispatchEvent(
|
|
new browser.Event(input.tagName === 'SELECT' ? 'change' : 'input', {
|
|
bubbles: true,
|
|
}) as unknown as Event
|
|
);
|
|
}
|
|
function upload(value: unknown = datasetInput(), name = 'source.json', read?: Promise<string>) {
|
|
const file = new browser.File([typeof value === 'string' ? value : JSON.stringify(value)], name, {
|
|
type: 'application/json',
|
|
});
|
|
if (read) {
|
|
Object.defineProperty(file, 'text', { value: () => read });
|
|
}
|
|
const label =
|
|
field('Dataset input').value === 'stored-eod' ? 'Source metadata JSON' : 'Source dataset JSON';
|
|
Object.defineProperty(field(label), 'files', {
|
|
configurable: true,
|
|
value: [file],
|
|
});
|
|
field(label).dispatchEvent(new browser.Event('change', { bubbles: true }) as unknown as Event);
|
|
}
|
|
async function mount(element: ReactElement) {
|
|
root = createRoot(host);
|
|
await flush(() => root!.render(createElement(router.MemoryRouter, null, element)));
|
|
}
|
|
const previewPath = '/api/v2/datasets/canonical/preview';
|
|
const retainPath = '/api/v2/datasets/canonical/retain';
|
|
const dataset = createDatasetV2(datasetInput());
|
|
const preparation: CanonicalDatasetPreparation = {
|
|
version: 'canonical-dataset-preparation/v1',
|
|
hash: dataset.manifest.hash,
|
|
manifest: dataset.manifest,
|
|
available: true,
|
|
reason: null,
|
|
};
|
|
const entry: CanonicalDatasetCatalogEntry = {
|
|
hash: preparation.hash,
|
|
manifest: preparation.manifest,
|
|
available: true,
|
|
reason: null,
|
|
createdAt: '2026-01-01T00:00:00Z',
|
|
};
|
|
let retained: { hash: string; available: boolean }[] = [];
|
|
let states: { busy: boolean; blocking: boolean }[] = [];
|
|
const panelProps = () => ({
|
|
disabled: false,
|
|
begin: () => true,
|
|
onRetained: (hash: string, available: boolean) => retained.push({ hash, available }),
|
|
onStateChange: (value: { busy: boolean; blocking: boolean }) => states.push(value),
|
|
});
|
|
async function mountPanel() {
|
|
await mount(createElement(DatasetPreparation, panelProps()));
|
|
}
|
|
async function preview(value: CanonicalDatasetPreparation = preparation) {
|
|
await flush(() => upload());
|
|
await flush(() => click('Preview dataset'));
|
|
await flush(() => reply(request(previewPath), { preparation: value }));
|
|
}
|
|
|
|
const family = (id = 'family', extra: Partial<StrategyRecord> = {}): 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; <img src=x onerror=alert(1)>'
|
|
): 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> = {}
|
|
): 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', 'GET'), { strategies: [family('family', { archived })] });
|
|
reply(request('/api/v2/strategy-versions/version-one', 'GET'), {
|
|
version: version(),
|
|
reviews: [],
|
|
});
|
|
});
|
|
await flush(() =>
|
|
reply(request('/api/v2/strategies/family', 'GET'), { strategy: family('family', { archived }) })
|
|
);
|
|
await flush(() =>
|
|
reply(request('/api/v2/strategies/family/versions', 'GET'), { versions: [version()] })
|
|
);
|
|
}
|
|
beforeAll(async () => {
|
|
for (const [key, value] of Object.entries({
|
|
window: browser,
|
|
document: browser.document,
|
|
IS_REACT_ACT_ENVIRONMENT: true,
|
|
ResizeObserver: browser.ResizeObserver,
|
|
})) {
|
|
Object.defineProperty(globalThis, key, { configurable: true, writable: true, value });
|
|
}
|
|
({ createRoot } = await import('react-dom/client'));
|
|
router = await import('react-router-dom');
|
|
({ CanonicalSetup } = await import(
|
|
'../../apps/stock/web-app/src/features/backtest/components/CanonicalSetup'
|
|
));
|
|
({ DatasetPreparation } = await import(
|
|
'../../apps/stock/web-app/src/features/backtest/components/DatasetPreparation'
|
|
));
|
|
({ parseDatasetPreparation, parseStoredDatasetPreparation } = await import(
|
|
'../../apps/stock/web-app/src/features/backtest/services/backtestApiV2'
|
|
));
|
|
});
|
|
beforeEach(() => {
|
|
requests.length = 0;
|
|
retained = [];
|
|
states = [];
|
|
host = browser.document.createElement('div') as unknown as HTMLDivElement;
|
|
browser.document.body.append(host as never);
|
|
confirmWith(() => true);
|
|
browser.fetch = ((url: RequestInfo | URL, init?: RequestInit) => {
|
|
const item: Pending = {
|
|
...deferred<Response>(),
|
|
path: new URL(String(url)).pathname,
|
|
method: init?.method ?? 'GET',
|
|
body: typeof init?.body === 'string' ? JSON.parse(init.body) : undefined,
|
|
signal: init?.signal,
|
|
settled: false,
|
|
};
|
|
requests.push(item);
|
|
return item.promise;
|
|
}) 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 value = originals.get(key);
|
|
if (value) {
|
|
Object.defineProperty(globalThis, key, value);
|
|
} else {
|
|
delete (globalThis as Record<string, unknown>)[key];
|
|
}
|
|
}
|
|
});
|
|
async function readySetup(
|
|
onSave: (value: CreateBacktestRequest) => Promise<void>,
|
|
onClose?: () => void
|
|
) {
|
|
await mount(createElement(CanonicalSetup, { backtest: definition, onSave, onClose }));
|
|
await selected();
|
|
await flush(() => reply(request('/api/v2/datasets/canonical', 'GET'), { datasets: [entry] }));
|
|
await flush(() => edit('Canonical dataset', entry.hash));
|
|
await flush(() =>
|
|
reply(request(`/api/v2/datasets/canonical/${entry.hash}`, 'GET'), { dataset: entry })
|
|
);
|
|
await flush(() => click('Validate parameters'));
|
|
await flush(() =>
|
|
reply(request('/api/v2/strategy-versions/version-one/validate'), {
|
|
parameters: definition.strategyParameters,
|
|
runnable: false,
|
|
reason: 'Execution gated',
|
|
})
|
|
);
|
|
expect(button('Save canonical setup').disabled).toBe(false);
|
|
}
|
|
|
|
describe('source preparation decoder', () => {
|
|
test('accepts complete declared metadata unchanged and direct null lineage', () => {
|
|
expect(parseDatasetPreparation(preparation)).toEqual(preparation);
|
|
});
|
|
type Mutable<T> = { -readonly [K in keyof T]: T[K] extends object ? Mutable<T[K]> : T[K] };
|
|
const mutations: {
|
|
name: string;
|
|
change: (value: Mutable<CanonicalDatasetPreparation>) => unknown;
|
|
}[] = [
|
|
{ name: 'wrong version', change: v => Object.assign(v, { version: 'future' }) },
|
|
{ name: 'hash differs', change: v => (v.hash = 'b'.repeat(64)) },
|
|
{
|
|
name: 'invalid hash',
|
|
change: v => {
|
|
v.hash = 'invalid';
|
|
v.manifest.hash = 'invalid';
|
|
},
|
|
},
|
|
{ name: 'unknown descriptor field', change: v => Object.assign(v, { attested: true }) },
|
|
{
|
|
name: 'unknown manifest field',
|
|
change: v => Object.assign(v.manifest, { certificate: 'not retained' }),
|
|
},
|
|
{
|
|
name: 'unknown nested field',
|
|
change: v => Object.assign(v.manifest.series[0]!, { certificate: true }),
|
|
},
|
|
{ name: 'non-source lineage', change: v => (v.manifest.parentDatasetHash = 'a'.repeat(64)) },
|
|
{
|
|
name: 'missing session revision',
|
|
change: v => Reflect.deleteProperty(v.manifest.calendars[0]!, 'revision'),
|
|
},
|
|
{ name: 'invalid date', change: v => (v.manifest.calendars[0]!.startDate = '2024-02-31') },
|
|
{
|
|
name: 'out of Date range',
|
|
change: v => (v.manifest.bounds.tradeEnd = 8_640_000_000_000_001),
|
|
},
|
|
{ name: 'empty session', change: v => (v.manifest.calendars[0]!.sessions = []) },
|
|
{ name: 'unmatched calendar', change: v => (v.manifest.series[0]!.calendarId = 'other') },
|
|
{
|
|
name: 'unmatched execution series',
|
|
change: v => (v.manifest.executionSeries[0]!.seriesId = 'other'),
|
|
},
|
|
{
|
|
name: 'eligible disabled contradiction',
|
|
change: v => {
|
|
v.available = false;
|
|
v.reason = 'No';
|
|
},
|
|
},
|
|
{
|
|
name: 'exploratory enabled contradiction',
|
|
change: v => (v.manifest.eligibility = 'exploratory'),
|
|
},
|
|
{ name: 'available reason contradiction', change: v => (v.reason = 'No') },
|
|
{ name: 'zero bar count', change: v => (v.manifest.barCount = 0) },
|
|
];
|
|
for (const { name, change } of mutations) {
|
|
test(`rejects ${name}`, () => {
|
|
const value = structuredClone(preparation) as Mutable<CanonicalDatasetPreparation>;
|
|
change(value);
|
|
expect(() => parseDatasetPreparation(value)).toThrow();
|
|
});
|
|
}
|
|
test('rejects retained identity different from captured hash', () =>
|
|
expect(() => parseDatasetPreparation(preparation, 'c'.repeat(64))).toThrow());
|
|
});
|
|
|
|
describe('explicit source preparation', () => {
|
|
test('initial render is lazy and empty; all actions are non-submit buttons', async () => {
|
|
await mountPanel();
|
|
expect(requests).toHaveLength(0);
|
|
expect(host.textContent).toContain('No source export selected.');
|
|
expect(button('Preview dataset').disabled).toBe(true);
|
|
expect(button('Retain dataset').disabled).toBe(true);
|
|
expect(host.querySelector('form')).toBeNull();
|
|
expect([...host.querySelectorAll('button')].every(item => item.type === 'button')).toBe(true);
|
|
});
|
|
test('previews only explicit source, renders declared metadata and preserves unknown publication delay limitation', async () => {
|
|
await mountPanel();
|
|
await flush(() => upload());
|
|
await flush(() => {
|
|
click('Preview dataset');
|
|
click('Preview dataset');
|
|
});
|
|
expect(requests).toHaveLength(1);
|
|
expect(request(previewPath).body).toEqual({ input: datasetInput() });
|
|
expect(host.textContent).toContain('Previewing dataset...');
|
|
expect(retained).toHaveLength(0);
|
|
await flush(() => reply(request(previewPath), { preparation }));
|
|
for (const text of [
|
|
preparation.hash,
|
|
'A.US / 1d',
|
|
'Adjustment: raw',
|
|
'Timestamp: session-date',
|
|
'Availability: interval-end-assumption',
|
|
'actual publication delay is not verified',
|
|
'America/New_York',
|
|
'test-sessions-2024-v1',
|
|
'test-action-coverage-v1',
|
|
'test-universe-v1',
|
|
'Sessions: 3',
|
|
'3 bars',
|
|
'2024-03-11T13:30:00.000Z',
|
|
'not independent provider certification',
|
|
]) {
|
|
expect(host.textContent).toContain(text);
|
|
}
|
|
expect(JSON.parse(host.querySelector('pre')!.textContent!)).toEqual(preparation.manifest);
|
|
expect(requests.some(item => item.path === retainPath)).toBe(false);
|
|
expect(states.at(-1)).toEqual({ busy: false, blocking: true });
|
|
});
|
|
test('invalid JSON is recoverable without POST or invented metadata', async () => {
|
|
await mountPanel();
|
|
await flush(() => upload('{invalid'));
|
|
expect(host.textContent).toContain('Could not read source JSON');
|
|
expect(requests).toHaveLength(0);
|
|
expect(button('Preview dataset').disabled).toBe(true);
|
|
await flush(() => upload());
|
|
await flush(() => click('Preview dataset'));
|
|
expect(request(previewPath).body).toEqual({ input: datasetInput() });
|
|
});
|
|
test('unreadable file leaves actionable error', async () => {
|
|
await mountPanel();
|
|
const reading = deferred<string>();
|
|
await flush(() => upload({}, 'bad.json', reading.promise));
|
|
expect(host.textContent).toContain('Reading source JSON...');
|
|
await flush(() => reading.reject(new Error('read denied')));
|
|
expect(host.textContent).toContain('read denied');
|
|
expect(button('Retain dataset').disabled).toBe(true);
|
|
});
|
|
test('latest file read wins even when older read completes late', async () => {
|
|
await mountPanel();
|
|
const reading = deferred<string>();
|
|
await flush(() => upload({}, 'old.json', reading.promise));
|
|
await flush(() => upload(datasetInput(), 'new.json'));
|
|
await flush(() => reading.resolve('{"wrong":"source"}'));
|
|
expect(host.textContent).toContain('new.json');
|
|
expect(host.textContent).not.toContain('old.json');
|
|
await flush(() => click('Preview dataset'));
|
|
expect(request(previewPath).body).toEqual({ input: datasetInput() });
|
|
});
|
|
test('file replacement invalidates preview and fences ignored abort response', async () => {
|
|
await mountPanel();
|
|
await flush(() => upload());
|
|
await flush(() => click('Preview dataset'));
|
|
const old = request(previewPath);
|
|
await flush(() => upload({ metadata: 'different' }, 'next.json'));
|
|
expect(old.signal?.aborted).toBe(true);
|
|
await flush(() => reply(old, { preparation }));
|
|
expect(host.querySelector('[aria-label="Prepared dataset metadata"]')).toBeNull();
|
|
expect(button('Retain dataset').disabled).toBe(true);
|
|
await flush(() => click('Preview dataset'));
|
|
expect(request(previewPath).body).toEqual({ input: { metadata: 'different' } });
|
|
});
|
|
test('clear cancels pending preview and same-event stale Retain cannot submit', async () => {
|
|
await mountPanel();
|
|
await preview();
|
|
await flush(() => {
|
|
click('Clear source preparation');
|
|
click('Retain dataset');
|
|
});
|
|
expect(requests.filter(item => item.path === retainPath)).toHaveLength(0);
|
|
expect(host.textContent).toContain('No source export selected.');
|
|
await flush(() => upload());
|
|
await flush(() => click('Preview dataset'));
|
|
const old = request(previewPath);
|
|
await flush(() => click('Clear source preparation'));
|
|
await flush(() => reply(old, { preparation }));
|
|
expect(host.querySelector('[aria-label="Prepared dataset metadata"]')).toBeNull();
|
|
expect(states.at(-1)).toEqual({ busy: false, blocking: false });
|
|
});
|
|
test('preview errors and malformed envelopes never enable retention', async () => {
|
|
await mountPanel();
|
|
await flush(() => upload());
|
|
await flush(() => click('Preview dataset'));
|
|
await flush(() => reply(request(previewPath), { error: 'Metadata incomplete' }, 400));
|
|
expect(host.textContent).toContain('Metadata incomplete');
|
|
await flush(() => click('Preview dataset'));
|
|
await flush(() =>
|
|
reply(request(previewPath), { preparation: { ...preparation, manifest: null } })
|
|
);
|
|
expect(host.textContent).toContain('could not be verified');
|
|
expect(button('Retain dataset').disabled).toBe(true);
|
|
});
|
|
test('lost retain response keeps exact input/hash; duplicate clicks and synchronous clear cannot discard intent', async () => {
|
|
await mountPanel();
|
|
await preview();
|
|
let prompts = 0;
|
|
confirmWith(() => {
|
|
prompts++;
|
|
return true;
|
|
});
|
|
await flush(() => {
|
|
click('Retain dataset');
|
|
click('Retain dataset');
|
|
click('Clear source preparation');
|
|
});
|
|
expect(prompts).toBe(0);
|
|
const first = request(retainPath);
|
|
expect(first.body).toEqual({ input: datasetInput(), expectedHash: preparation.hash });
|
|
expect(requests.filter(item => item.path === retainPath)).toHaveLength(1);
|
|
expect(field('Source dataset JSON').disabled).toBe(true);
|
|
await flush(() => fail(first));
|
|
expect(host.textContent).toContain('exact original input and hash are preserved');
|
|
confirmWith(() => false);
|
|
await flush(() => click('Clear source preparation'));
|
|
await flush(() => upload({ not: 'the original' }));
|
|
await flush(() => click('Retry retaining same dataset'));
|
|
expect(request(retainPath).body).toEqual(first.body);
|
|
await flush(() => reply(request(retainPath), { preparation }));
|
|
expect(retained).toEqual([{ hash: preparation.hash, available: true }]);
|
|
expect(states.at(-1)).toEqual({ busy: false, blocking: false });
|
|
expect(button('Retain dataset').disabled).toBe(true);
|
|
});
|
|
for (const status of [400, 409]) {
|
|
test(`definitive ${status} rejects without ambiguous retry and preserves input for new preview`, async () => {
|
|
await mountPanel();
|
|
await preview();
|
|
await flush(() => click('Retain dataset'));
|
|
await flush(() => reply(request(retainPath), { error: 'Hash or input rejected' }, status));
|
|
expect(host.textContent).toContain('Preview again or choose a corrected source export.');
|
|
expect(host.textContent).not.toContain('may already have succeeded');
|
|
expect(button('Preview dataset').disabled).toBe(false);
|
|
expect(button('Retain dataset').disabled).toBe(true);
|
|
expect(field('Source dataset JSON').disabled).toBe(false);
|
|
await flush(() => click('Preview dataset'));
|
|
expect(request(previewPath).body).toEqual({ input: datasetInput() });
|
|
expect(retained).toHaveLength(0);
|
|
});
|
|
}
|
|
for (const mode of [
|
|
'server error',
|
|
'wrong hash',
|
|
'changed metadata',
|
|
'unknown metadata',
|
|
] as const) {
|
|
test(`retention ${mode} remains unconfirmed with same retry`, async () => {
|
|
await mountPanel();
|
|
await preview();
|
|
await flush(() => click('Retain dataset'));
|
|
const first = request(retainPath);
|
|
const changed = structuredClone(preparation);
|
|
if (mode === 'wrong hash') {
|
|
Object.assign(changed, {
|
|
hash: 'b'.repeat(64),
|
|
manifest: { ...changed.manifest, hash: 'b'.repeat(64) },
|
|
});
|
|
}
|
|
if (mode === 'changed metadata') {
|
|
Object.assign(changed.manifest, { limitations: ['changed'] });
|
|
}
|
|
await flush(() =>
|
|
reply(
|
|
first,
|
|
mode === 'server error'
|
|
? { error: 'Storage unavailable' }
|
|
: {
|
|
preparation: mode === 'unknown metadata' ? { ...changed, unknown: true } : changed,
|
|
},
|
|
mode === 'server error' ? 503 : 200
|
|
)
|
|
);
|
|
expect(retained).toHaveLength(0);
|
|
expect(host.textContent).toContain('may already have succeeded');
|
|
await flush(() => click('Retry retaining same dataset'));
|
|
expect(request(retainPath).body).toEqual(first.body);
|
|
});
|
|
}
|
|
test('valid unavailable data can be retained without selection and remains clearly unavailable', async () => {
|
|
await mountPanel();
|
|
const value: CanonicalDatasetPreparation = {
|
|
...preparation,
|
|
manifest: {
|
|
...preparation.manifest,
|
|
eligibility: 'exploratory',
|
|
limitations: ['Source coverage unknown'],
|
|
universe: { ...preparation.manifest.universe, selection: 'unknown', asOf: null },
|
|
},
|
|
available: false,
|
|
reason: 'Requires point-in-time universe',
|
|
};
|
|
await preview(value);
|
|
expect(button('Retain dataset').disabled).toBe(false);
|
|
expect(host.textContent).toContain('As of: Unknown');
|
|
await flush(() => click('Retain dataset'));
|
|
await flush(() => reply(request(retainPath), { preparation: value }));
|
|
expect(retained).toEqual([{ hash: preparation.hash, available: false }]);
|
|
expect(host.textContent).toContain('existing selection is unchanged');
|
|
expect(states.at(-1)).toEqual({ busy: false, blocking: true });
|
|
});
|
|
test('unmount fences late retain and file reads without callbacks', async () => {
|
|
await mountPanel();
|
|
await preview();
|
|
await flush(() => click('Retain dataset'));
|
|
const old = request(retainPath);
|
|
await flush(() => root!.unmount());
|
|
root = undefined;
|
|
await flush(() => reply(old, { preparation }));
|
|
expect(old.signal?.aborted).toBe(true);
|
|
expect(retained).toHaveLength(0);
|
|
});
|
|
test('unmount while reading a file ignores late content', async () => {
|
|
await mountPanel();
|
|
const reading = deferred<string>();
|
|
await flush(() => upload({}, 'late.json', reading.promise));
|
|
await flush(() => root!.unmount());
|
|
root = undefined;
|
|
await flush(() => reading.resolve(JSON.stringify(datasetInput())));
|
|
expect(requests).toHaveLength(0);
|
|
expect(retained).toHaveLength(0);
|
|
expect(states.at(-1)).toEqual({ busy: false, blocking: false });
|
|
});
|
|
test('preserves explicit delayed availability and renders known corporate actions as unavailable evidence', async () => {
|
|
const sourceInput = datasetInput();
|
|
const source = {
|
|
...sourceInput,
|
|
metadata: {
|
|
...sourceInput.metadata,
|
|
series: sourceInput.metadata.series.map(item => ({
|
|
...item,
|
|
availability: 'explicit' as const,
|
|
})),
|
|
corporateActions: sourceInput.metadata.corporateActions.map(item => ({
|
|
...item,
|
|
status: 'known-actions' as const,
|
|
actions: [
|
|
{
|
|
kind: 'split' as const,
|
|
reference: 'declared-split-17',
|
|
effectiveAt: sourceInput.metadata.bounds.tradeStart,
|
|
},
|
|
],
|
|
})),
|
|
},
|
|
bars: sourceInput.bars.map((bar, index) => ({
|
|
...bar,
|
|
availableAt: sourceInput.metadata.calendars[0]!.sessions[index]!.close + 30_000,
|
|
})),
|
|
};
|
|
const preparedDataset = createDatasetV2(source);
|
|
const value = {
|
|
...preparation,
|
|
hash: preparedDataset.manifest.hash,
|
|
manifest: preparedDataset.manifest,
|
|
available: false,
|
|
reason: 'Known actions are unsupported for execution',
|
|
};
|
|
await mountPanel();
|
|
await flush(() => upload(source));
|
|
await flush(() => click('Preview dataset'));
|
|
expect(request(previewPath).body).toEqual({ input: source });
|
|
await flush(() => reply(request(previewPath), { preparation: value }));
|
|
expect(host.textContent).toContain('Availability: explicit');
|
|
expect(host.textContent).toContain('declared-split-17');
|
|
expect(host.textContent).toContain('known-actions');
|
|
expect(host.textContent).toContain('Unavailable for canonical setup');
|
|
expect(host.textContent).not.toContain('Availability is explicitly assumed');
|
|
await flush(() => click('Retain dataset'));
|
|
expect(request(retainPath).body).toEqual({ input: source, expectedHash: value.hash });
|
|
});
|
|
test('disabled panel cannot read source or issue requests', async () => {
|
|
await mount(createElement(DatasetPreparation, { ...panelProps(), disabled: true }));
|
|
await flush(() => upload());
|
|
expect(requests).toHaveLength(0);
|
|
expect(host.textContent).not.toContain('Selected export');
|
|
expect(button('Preview dataset').disabled).toBe(true);
|
|
});
|
|
});
|
|
|
|
describe('canonical setup coordination', () => {
|
|
test('source workflow has no nested form, preserves all settings, selects only after retention/lookup, and never autosaves', async () => {
|
|
const sourceInput = datasetInput();
|
|
const replacementInput = {
|
|
...sourceInput,
|
|
metadata: {
|
|
...sourceInput.metadata,
|
|
series: sourceInput.metadata.series.map(series => ({
|
|
...series,
|
|
source: { ...series.source, revision: 'corrected-export-v2' },
|
|
})),
|
|
},
|
|
};
|
|
const replacementDataset = createDatasetV2(replacementInput);
|
|
const replacement = {
|
|
...preparation,
|
|
hash: replacementDataset.manifest.hash,
|
|
manifest: replacementDataset.manifest,
|
|
};
|
|
const replacementEntry = { ...entry, hash: replacement.hash, manifest: replacement.manifest };
|
|
const saves: CreateBacktestRequest[] = [];
|
|
await readySetup(async value => {
|
|
saves.push(value);
|
|
});
|
|
await flush(() => {
|
|
edit('Backtest name', 'My edited draft');
|
|
edit('Initial capital (USD)', '12345');
|
|
edit('Fee rate', '0.002');
|
|
edit('fastPeriod', '3');
|
|
});
|
|
await flush(() => click('Validate parameters'));
|
|
await flush(() =>
|
|
reply(request('/api/v2/strategy-versions/version-one/validate'), {
|
|
parameters: { fastPeriod: 3, slowPeriod: 15 },
|
|
runnable: false,
|
|
reason: 'gated',
|
|
})
|
|
);
|
|
expect(host.querySelectorAll('form')).toHaveLength(1);
|
|
await flush(() => upload(replacementInput));
|
|
expect(button('Save canonical setup').disabled).toBe(true);
|
|
await flush(() => click('Preview dataset'));
|
|
await flush(() => reply(request(previewPath), { preparation: replacement }));
|
|
expect(field('Canonical dataset').value).toBe(entry.hash);
|
|
expect(saves).toHaveLength(0);
|
|
await flush(() => click('Retain dataset'));
|
|
expect(field('Canonical dataset').value).toBe(entry.hash);
|
|
await flush(() => reply(request(retainPath), { preparation: replacement }));
|
|
expect(field('Canonical dataset').value).toBe(replacement.hash);
|
|
expect(field('Backtest name').value).toBe('My edited draft');
|
|
expect(field('Initial capital (USD)').value).toBe('12345');
|
|
expect(field('Fee rate').value).toBe('0.002');
|
|
expect(field('fastPeriod').value).toBe('3');
|
|
expect(saves).toHaveLength(0);
|
|
expect(button('Save canonical setup').disabled).toBe(true);
|
|
await flush(() => {
|
|
reply(request('/api/v2/datasets/canonical', 'GET'), { datasets: [entry, replacementEntry] });
|
|
reply(request(`/api/v2/datasets/canonical/${replacement.hash}`, 'GET'), {
|
|
dataset: replacementEntry,
|
|
});
|
|
});
|
|
expect(button('Save canonical setup').disabled).toBe(false);
|
|
await flush(() => click('Save canonical setup'));
|
|
expect(saves).toHaveLength(1);
|
|
expect(saves[0]).toMatchObject({
|
|
name: 'My edited draft',
|
|
initialCapital: 12345,
|
|
strategyParameters: { fastPeriod: 3, slowPeriod: 15 },
|
|
config: { datasetHash: replacement.hash, canonical: { feeRate: '0.00200000' } },
|
|
});
|
|
});
|
|
test('same-event file read then submit cannot save or close while preparation is active', async () => {
|
|
let saves = 0,
|
|
closes = 0;
|
|
await readySetup(
|
|
async () => {
|
|
saves++;
|
|
},
|
|
() => {
|
|
closes++;
|
|
}
|
|
);
|
|
const reading = deferred<string>();
|
|
await flush(() => {
|
|
upload({}, 'pending.json', reading.promise);
|
|
host
|
|
.querySelector('form')!
|
|
.dispatchEvent(
|
|
new browser.Event('submit', { bubbles: true, cancelable: true }) as unknown as Event
|
|
);
|
|
click('Back to draft settings');
|
|
});
|
|
expect(saves).toBe(0);
|
|
expect(closes).toBe(0);
|
|
await flush(() => reading.resolve(JSON.stringify(datasetInput())));
|
|
expect(button('Save canonical setup').disabled).toBe(true);
|
|
confirmWith(() => false);
|
|
await flush(() => click('Back to draft settings'));
|
|
expect(closes).toBe(0);
|
|
await flush(() => click('Clear source preparation'));
|
|
expect(button('Save canonical setup').disabled).toBe(false);
|
|
});
|
|
test('same-event parent save blocks file loading until save completes', async () => {
|
|
const saving = deferred<void>();
|
|
let saves = 0;
|
|
await readySetup(async () => {
|
|
saves++;
|
|
await saving.promise;
|
|
});
|
|
await flush(() => {
|
|
click('Save canonical setup');
|
|
upload();
|
|
});
|
|
expect(saves).toBe(1);
|
|
expect(host.textContent).not.toContain('Selected export');
|
|
expect(field('Source dataset JSON').disabled).toBe(true);
|
|
await flush(() => saving.resolve());
|
|
expect(field('Source dataset JSON').disabled).toBe(false);
|
|
});
|
|
for (const newId of [definition.id, 'other-backtest']) {
|
|
test(`parent ${newId} change fences retained result and resets preparation`, async () => {
|
|
const onSave = async () => {};
|
|
await readySetup(onSave);
|
|
await preview();
|
|
await flush(() => click('Retain dataset'));
|
|
const old = request(retainPath);
|
|
await flush(() =>
|
|
root!.render(
|
|
createElement(
|
|
router.MemoryRouter,
|
|
null,
|
|
createElement(CanonicalSetup, {
|
|
backtest: { ...definition, id: newId, name: 'Restored source' },
|
|
onSave,
|
|
})
|
|
)
|
|
)
|
|
);
|
|
await flush(() => reply(old, { preparation }));
|
|
expect(field('Backtest name').value).toBe('Restored source');
|
|
expect(field('Canonical dataset').value).toBe('');
|
|
expect(host.textContent).toContain('No source export selected.');
|
|
expect(host.textContent).not.toContain('Dataset retained.');
|
|
expect(
|
|
requests.filter(item => item.path === `/api/v2/datasets/canonical/${entry.hash}`)
|
|
).toHaveLength(1);
|
|
});
|
|
}
|
|
test('unavailable retention preserves previous selected hash and disabled Save until explicit clear', async () => {
|
|
await readySetup(async () => {});
|
|
const unavailable = {
|
|
...preparation,
|
|
hash: 'd'.repeat(64),
|
|
manifest: {
|
|
...preparation.manifest,
|
|
hash: 'd'.repeat(64),
|
|
eligibility: 'ineligible' as const,
|
|
},
|
|
available: false,
|
|
reason: 'Execution unsupported',
|
|
};
|
|
await preview(unavailable);
|
|
await flush(() => click('Retain dataset'));
|
|
await flush(() => reply(request(retainPath), { preparation: unavailable }));
|
|
expect(field('Canonical dataset').value).toBe(entry.hash);
|
|
expect(button('Save canonical setup').disabled).toBe(true);
|
|
await flush(() => {
|
|
reply(request('/api/v2/datasets/canonical', 'GET'), { datasets: [entry] });
|
|
reply(request(`/api/v2/datasets/canonical/${entry.hash}`, 'GET'), { dataset: entry });
|
|
});
|
|
expect(button('Save canonical setup').disabled).toBe(true);
|
|
await flush(() => click('Clear source preparation'));
|
|
expect(button('Save canonical setup').disabled).toBe(false);
|
|
});
|
|
});
|
|
|
|
const storedPath = '/api/v2/datasets/canonical/stored-source';
|
|
function storedFixture(
|
|
metadata: HistoricalDatasetMetadataV2 = intradayMetadata()
|
|
): CanonicalStoredSourcePreparation {
|
|
const input = {
|
|
metadata,
|
|
bars: intradayResponse().map((bar, sourceSequence) => ({
|
|
seriesId: metadata.series[0]!.id,
|
|
timestamp: bar.timestamp * 1000,
|
|
sourceSequence,
|
|
open: bar.open,
|
|
high: bar.high,
|
|
low: bar.low,
|
|
close: bar.close,
|
|
volume: bar.volume,
|
|
})),
|
|
};
|
|
const normalized = createDatasetV2(input);
|
|
const { calendars, series, executionSeries, bounds, universe, corporateActions } =
|
|
normalized.manifest;
|
|
return {
|
|
input: {
|
|
...input,
|
|
metadata: { calendars, series, executionSeries, bounds, universe, corporateActions },
|
|
},
|
|
preparation: {
|
|
version: 'canonical-dataset-preparation/v1',
|
|
hash: normalized.manifest.hash,
|
|
manifest: normalized.manifest,
|
|
available: normalized.manifest.eligibility === 'eligible',
|
|
reason:
|
|
normalized.manifest.eligibility === 'eligible'
|
|
? null
|
|
: 'Declared coverage is unavailable for execution',
|
|
},
|
|
};
|
|
}
|
|
const storedMetadata: HistoricalDatasetMetadataV2 = {
|
|
...intradayMetadata(),
|
|
universe: {
|
|
...intradayMetadata().universe,
|
|
selection: 'point-in-time',
|
|
asOf: intradayMetadata().bounds.warmupStart,
|
|
},
|
|
corporateActions: intradayMetadata().corporateActions.map(item => ({
|
|
...item,
|
|
status: 'action-free',
|
|
})),
|
|
};
|
|
const stored = storedFixture(storedMetadata);
|
|
async function storedPreview(value: CanonicalStoredSourcePreparation = stored) {
|
|
await flush(() => edit('Dataset input', 'stored-eod'));
|
|
await flush(() => upload(value.input.metadata, 'metadata.json'));
|
|
await flush(() => click('Preview dataset'));
|
|
await flush(() => reply(request(storedPath), value));
|
|
}
|
|
|
|
describe('stored source response contract', () => {
|
|
test('validates the captured complete input without inventing optional VWAP or availability', () => {
|
|
const result = parseStoredDatasetPreparation(stored, storedMetadata);
|
|
expect(result).toEqual(stored);
|
|
expect(result.input.bars.every(bar => !('vwap' in bar) && !('availableAt' in bar))).toBe(true);
|
|
});
|
|
test('accepts the normalizer collection order while preserving all declared values', () => {
|
|
const base = intradayMetadata();
|
|
const calendar = base.calendars[0]!;
|
|
const metadata: HistoricalDatasetMetadataV2 = {
|
|
...base,
|
|
calendars: [
|
|
{
|
|
...calendar,
|
|
id: 'z-extra',
|
|
startDate: '2024-03-10',
|
|
sessions: [
|
|
calendar.sessions[0]!,
|
|
{
|
|
date: '2024-03-10',
|
|
open: calendar.sessions[0]!.open - 86400000,
|
|
close: calendar.sessions[0]!.close - 86400000,
|
|
},
|
|
],
|
|
},
|
|
calendar,
|
|
],
|
|
corporateActions: base.corporateActions.map(item => ({
|
|
...item,
|
|
status: 'known-actions',
|
|
actions: [
|
|
{ effectiveAt: item.start + 1, kind: 'dividend', reference: 'z-later' },
|
|
{ effectiveAt: item.start, kind: 'split', reference: 'a-earlier' },
|
|
],
|
|
})),
|
|
};
|
|
const result = storedFixture(metadata);
|
|
expect(result.input.metadata.calendars[0]!.id).toBe(calendar.id);
|
|
expect(parseStoredDatasetPreparation(result, metadata)).toEqual(result);
|
|
expect(metadata.calendars[0]!.id).toBe('z-extra');
|
|
expect(metadata.corporateActions[0]!.actions[0]!.reference).toBe('z-later');
|
|
});
|
|
type Mutable<T> = { -readonly [K in keyof T]: T[K] extends object ? Mutable<T[K]> : T[K] };
|
|
const changes: {
|
|
name: string;
|
|
change: (value: Mutable<CanonicalStoredSourcePreparation>) => unknown;
|
|
}[] = [
|
|
{ name: 'unknown envelope property', change: v => Object.assign(v, { certified: true }) },
|
|
{ name: 'unknown input property', change: v => Object.assign(v.input, { requestId: 'other' }) },
|
|
{
|
|
name: 'unknown metadata property',
|
|
change: v => Object.assign(v.input.metadata, { certified: true }),
|
|
},
|
|
{
|
|
name: 'unknown bar property',
|
|
change: v => Object.assign(v.input.bars[0]!, { instrumentId: 'wrong' }),
|
|
},
|
|
{
|
|
name: 'invented availability',
|
|
change: v => Object.assign(v.input.bars[0]!, { availableAt: v.input.bars[0]!.timestamp }),
|
|
},
|
|
{ name: 'wrong preparation hash', change: v => (v.preparation.hash = 'a'.repeat(64)) },
|
|
{ name: 'wrong bar count', change: v => v.preparation.manifest.barCount++ },
|
|
{ name: 'wrong series identity', change: v => (v.input.bars[0]!.seriesId = 'another-series') },
|
|
{ name: 'wrong row ordinal', change: v => (v.input.bars[1]!.sourceSequence = 15) },
|
|
{
|
|
name: 'duplicate timestamp',
|
|
change: v => (v.input.bars[1]!.timestamp = v.input.bars[0]!.timestamp),
|
|
},
|
|
{
|
|
name: 'out-of-range timestamp',
|
|
change: v => (v.input.bars[0]!.timestamp = v.input.metadata.bounds.tradeEnd),
|
|
},
|
|
{ name: 'non-finite price', change: v => (v.input.bars[0]!.open = Infinity) },
|
|
{ name: 'malformed VWAP', change: v => (v.input.bars[0]!.vwap = -1) },
|
|
{ name: 'empty bars', change: v => (v.input.bars = []) },
|
|
{
|
|
name: 'changed source revision',
|
|
change: v => (v.input.metadata.series[0]!.source.revision = 'unexpected revision'),
|
|
},
|
|
{
|
|
name: 'changed manifest revision',
|
|
change: v => (v.preparation.manifest.calendars[0]!.revision = 'changed-calendar'),
|
|
},
|
|
{
|
|
name: 'changed source provider',
|
|
change: v => (v.input.metadata.series[0]!.source.provider = 'questdb'),
|
|
},
|
|
{
|
|
name: 'unsupported daily interval',
|
|
change: v => (v.input.metadata.series[0]!.interval = '1d'),
|
|
},
|
|
{
|
|
name: 'unsupported adjusted prices',
|
|
change: v => (v.input.metadata.series[0]!.adjustment = 'provider-adjusted'),
|
|
},
|
|
{
|
|
name: 'unsupported explicit availability',
|
|
change: v => (v.input.metadata.series[0]!.availability = 'explicit'),
|
|
},
|
|
];
|
|
for (const { name, change } of changes) {
|
|
test(`rejects ${name}`, () => {
|
|
const value = structuredClone(stored) as Mutable<CanonicalStoredSourcePreparation>;
|
|
change(value);
|
|
expect(() => parseStoredDatasetPreparation(value, storedMetadata)).toThrow();
|
|
});
|
|
}
|
|
test('rejects a valid response bound to different caller metadata', () => {
|
|
expect(() =>
|
|
parseStoredDatasetPreparation(stored, {
|
|
...storedMetadata,
|
|
bounds: { ...storedMetadata.bounds, tradeStart: storedMetadata.bounds.tradeStart + 1 },
|
|
})
|
|
).toThrow();
|
|
});
|
|
});
|
|
|
|
describe('stored source panel', () => {
|
|
test('defaults to the existing export mode and selecting stored mode performs no IO', async () => {
|
|
await mountPanel();
|
|
expect(field('Dataset input').value).toBe('export');
|
|
await flush(() => edit('Dataset input', 'stored-eod'));
|
|
expect(field('Source metadata JSON')).toBeDefined();
|
|
expect(host.textContent).toContain('No source metadata selected.');
|
|
expect(host.textContent).toContain('not a vendor sequence');
|
|
expect(host.textContent).toContain('not independently certified');
|
|
expect(requests).toHaveLength(0);
|
|
expect(button('Preview dataset').disabled).toBe(true);
|
|
});
|
|
test('stored preview sends only declared metadata, displays snapshot and retains returned full input without requery', async () => {
|
|
await mountPanel();
|
|
await storedPreview();
|
|
expect(requests.filter(item => item.path === storedPath)).toHaveLength(1);
|
|
expect(requests.find(item => item.path === storedPath)!.body).toEqual({
|
|
metadata: stored.input.metadata,
|
|
});
|
|
expect(host.textContent).toContain('Stored source: EOD');
|
|
expect(host.textContent).toContain('FIXTURE.TEST / 5m');
|
|
expect(host.textContent).toContain('2024-03-11T13:30:00.000Z');
|
|
expect(host.textContent).toContain('2024-03-11T20:00:00.000Z');
|
|
expect(host.textContent).toContain('Availability: interval-end-assumption');
|
|
await flush(() => {
|
|
click('Retain dataset');
|
|
click('Retain dataset');
|
|
});
|
|
const first = request(retainPath);
|
|
expect(first.body).toEqual({ input: stored.input, expectedHash: stored.preparation.hash });
|
|
await flush(() => fail(first));
|
|
expect(field('Dataset input').disabled).toBe(true);
|
|
expect(field('Source metadata JSON').disabled).toBe(true);
|
|
await flush(() => {
|
|
edit('Dataset input', 'export');
|
|
upload({ replacement: true });
|
|
});
|
|
expect(field('Dataset input').value).toBe('stored-eod');
|
|
expect(host.textContent).toContain('Selected metadata: metadata.json');
|
|
await flush(() => click('Retry retaining same dataset'));
|
|
expect(request(retainPath).body).toEqual(first.body);
|
|
expect(requests.filter(item => item.path === storedPath)).toHaveLength(1);
|
|
expect(requests.filter(item => item.path === previewPath)).toHaveLength(0);
|
|
await flush(() => reply(request(retainPath), { preparation: stored.preparation }));
|
|
expect(retained).toEqual([{ hash: stored.preparation.hash, available: true }]);
|
|
expect(states.at(-1)).toEqual({ busy: false, blocking: false });
|
|
});
|
|
test('same-event retain then mode change cannot discard or retarget the captured snapshot', async () => {
|
|
await mountPanel();
|
|
await storedPreview();
|
|
await flush(() => {
|
|
click('Retain dataset');
|
|
edit('Dataset input', 'export');
|
|
click('Clear source preparation');
|
|
});
|
|
expect(request(retainPath).body).toEqual({
|
|
input: stored.input,
|
|
expectedHash: stored.preparation.hash,
|
|
});
|
|
expect(field('Dataset input').value).toBe('stored-eod');
|
|
await flush(() => fail(request(retainPath)));
|
|
expect(button('Retry retaining same dataset').disabled).toBe(false);
|
|
confirmWith(() => false);
|
|
await flush(() => click('Clear source preparation'));
|
|
expect(field('Dataset input').disabled).toBe(true);
|
|
confirmWith(() => true);
|
|
await flush(() => click('Clear source preparation'));
|
|
await flush(() => edit('Dataset input', 'export'));
|
|
expect(field('Dataset input').value).toBe('export');
|
|
expect(host.textContent).toContain('No source export selected.');
|
|
});
|
|
test('same-event mode change invalidates old retain and preview handlers', async () => {
|
|
await mountPanel();
|
|
await storedPreview();
|
|
await flush(() => {
|
|
edit('Dataset input', 'export');
|
|
click('Retain dataset');
|
|
click('Preview dataset');
|
|
});
|
|
expect(requests.filter(item => item.path === retainPath)).toHaveLength(0);
|
|
expect(requests.filter(item => item.path === previewPath)).toHaveLength(0);
|
|
expect(host.querySelector('[aria-label="Prepared dataset metadata"]')).toBeNull();
|
|
});
|
|
test('mode switching fences a late stored response and a late export response', async () => {
|
|
await mountPanel();
|
|
await flush(() => edit('Dataset input', 'stored-eod'));
|
|
await flush(() => upload(storedMetadata));
|
|
await flush(() => click('Preview dataset'));
|
|
const oldStored = request(storedPath);
|
|
await flush(() => edit('Dataset input', 'export'));
|
|
expect(oldStored.signal?.aborted).toBe(true);
|
|
await flush(() => reply(oldStored, stored));
|
|
expect(host.querySelector('[aria-label="Prepared dataset metadata"]')).toBeNull();
|
|
await flush(() => upload());
|
|
await flush(() => click('Preview dataset'));
|
|
const oldExport = request(previewPath);
|
|
await flush(() => edit('Dataset input', 'stored-eod'));
|
|
await flush(() => reply(oldExport, { preparation }));
|
|
expect(host.textContent).toContain('No source metadata selected.');
|
|
expect(host.querySelector('[aria-label="Prepared dataset metadata"]')).toBeNull();
|
|
});
|
|
test('mode switching fences a late file read', async () => {
|
|
await mountPanel();
|
|
const read = deferred<string>();
|
|
await flush(() => upload({}, 'old-export.json', read.promise));
|
|
await flush(() => edit('Dataset input', 'stored-eod'));
|
|
await flush(() => read.resolve(JSON.stringify(datasetInput())));
|
|
expect(host.textContent).toContain('No source metadata selected.');
|
|
expect(button('Preview dataset').disabled).toBe(true);
|
|
});
|
|
test('file replacement fences the previous stored read without discarding the new file', async () => {
|
|
await mountPanel();
|
|
await flush(() => edit('Dataset input', 'stored-eod'));
|
|
await flush(() => upload(storedMetadata));
|
|
await flush(() => click('Preview dataset'));
|
|
const old = request(storedPath);
|
|
const next = {
|
|
...storedMetadata,
|
|
universe: { ...storedMetadata.universe, revision: 'next declaration' },
|
|
};
|
|
await flush(() => upload(next, 'next.json'));
|
|
await flush(() => reply(old, stored));
|
|
expect(host.textContent).toContain('Selected metadata: next.json');
|
|
expect(button('Retain dataset').disabled).toBe(true);
|
|
await flush(() => click('Preview dataset'));
|
|
expect(request(storedPath).body).toEqual({ metadata: next });
|
|
});
|
|
test('explicit fresh preview replaces materialized data only after its response', async () => {
|
|
await mountPanel();
|
|
await storedPreview();
|
|
await flush(() => click('Preview dataset'));
|
|
expect(button('Retain dataset').disabled).toBe(true);
|
|
expect(host.querySelector('[aria-label="Prepared dataset metadata"]')).toBeNull();
|
|
const input = {
|
|
...stored.input,
|
|
bars: stored.input.bars.map(bar => ({ ...bar, volume: bar.volume + 1 })),
|
|
};
|
|
const nextDataset = createDatasetV2(input);
|
|
const next = {
|
|
input,
|
|
preparation: {
|
|
...stored.preparation,
|
|
hash: nextDataset.manifest.hash,
|
|
manifest: nextDataset.manifest,
|
|
},
|
|
};
|
|
await flush(() => reply(request(storedPath), next));
|
|
await flush(() => click('Retain dataset'));
|
|
expect(request(retainPath).body).toEqual({
|
|
input: next.input,
|
|
expectedHash: next.preparation.hash,
|
|
});
|
|
expect(requests.filter(item => item.path === storedPath)).toHaveLength(2);
|
|
});
|
|
for (const [status, message] of [
|
|
[400, 'Unsupported metadata'],
|
|
[404, 'No stored bars'],
|
|
[503, 'EOD store unavailable'],
|
|
[500, 'Stored source unavailable'],
|
|
] as const) {
|
|
test(`stored ${status} exposes repair or retry without retention`, async () => {
|
|
await mountPanel();
|
|
await flush(() => edit('Dataset input', 'stored-eod'));
|
|
await flush(() => upload(storedMetadata));
|
|
await flush(() => click('Preview dataset'));
|
|
await flush(() => reply(request(storedPath), { error: message }, status));
|
|
expect(host.textContent).toContain(message);
|
|
expect(button('Preview dataset').disabled).toBe(false);
|
|
expect(button('Retain dataset').disabled).toBe(true);
|
|
expect(field('Source metadata JSON').disabled).toBe(false);
|
|
expect(retained).toHaveLength(0);
|
|
});
|
|
}
|
|
test('malformed stored success fails closed and keeps the metadata draft available for retry', async () => {
|
|
await mountPanel();
|
|
await flush(() => edit('Dataset input', 'stored-eod'));
|
|
await flush(() => upload(storedMetadata));
|
|
await flush(() => click('Preview dataset'));
|
|
await flush(() =>
|
|
reply(request(storedPath), {
|
|
input: { metadata: storedMetadata, bars: [] },
|
|
preparation: stored.preparation,
|
|
})
|
|
);
|
|
expect(host.textContent).toContain('stored source response could not be verified');
|
|
expect(host.textContent).toContain('Selected metadata: source.json');
|
|
expect(button('Retain dataset').disabled).toBe(true);
|
|
expect(button('Preview dataset').disabled).toBe(false);
|
|
});
|
|
test('stored exploratory evidence remains visible and retainable without canonical selection', async () => {
|
|
await mountPanel();
|
|
const exploratory = storedFixture();
|
|
await storedPreview(exploratory);
|
|
expect(host.textContent).toContain('Unavailable for canonical setup');
|
|
expect(host.textContent).toContain('Universe: unknown');
|
|
await flush(() => click('Retain dataset'));
|
|
await flush(() => reply(request(retainPath), { preparation: exploratory.preparation }));
|
|
expect(retained).toEqual([{ hash: exploratory.preparation.hash, available: false }]);
|
|
expect(states.at(-1)).toEqual({ busy: false, blocking: true });
|
|
});
|
|
test('unmount ignores stored materialization that completes after an aborted request', async () => {
|
|
await mountPanel();
|
|
await flush(() => edit('Dataset input', 'stored-eod'));
|
|
await flush(() => upload(storedMetadata));
|
|
await flush(() => click('Preview dataset'));
|
|
const old = request(storedPath);
|
|
await flush(() => root!.unmount());
|
|
root = undefined;
|
|
await flush(() => reply(old, stored));
|
|
expect(old.signal?.aborted).toBe(true);
|
|
expect(retained).toHaveLength(0);
|
|
expect(states.at(-1)).toEqual({ busy: false, blocking: false });
|
|
});
|
|
test('parent saves are synchronously blocked while stored source is pending; drafts remain intact', async () => {
|
|
let saves = 0;
|
|
await readySetup(async () => {
|
|
saves++;
|
|
});
|
|
await flush(() => {
|
|
edit('Backtest name', 'Stored draft');
|
|
edit('Fee rate', '0.02');
|
|
edit('Dataset input', 'stored-eod');
|
|
});
|
|
await flush(() => {
|
|
upload(storedMetadata);
|
|
host
|
|
.querySelector('form')!
|
|
.dispatchEvent(
|
|
new browser.Event('submit', { bubbles: true, cancelable: true }) as unknown as Event
|
|
);
|
|
});
|
|
expect(saves).toBe(0);
|
|
expect(button('Save canonical setup').disabled).toBe(true);
|
|
await flush(() => click('Preview dataset'));
|
|
await flush(() => reply(request(storedPath), stored));
|
|
expect(field('Backtest name').value).toBe('Stored draft');
|
|
expect(field('Fee rate').value).toBe('0.02');
|
|
expect(field('Canonical dataset').value).toBe(entry.hash);
|
|
await flush(() => click('Retain dataset'));
|
|
await flush(() => reply(request(retainPath), { preparation: stored.preparation }));
|
|
expect(field('Canonical dataset').value).toBe(stored.preparation.hash);
|
|
expect(saves).toBe(0);
|
|
expect(field('Fee rate').value).toBe('0.02');
|
|
});
|
|
test('authoritative parent reset fences late stored response and restores export mode', async () => {
|
|
const onSave = async () => {};
|
|
await readySetup(onSave);
|
|
await flush(() => edit('Dataset input', 'stored-eod'));
|
|
await flush(() => upload(storedMetadata));
|
|
await flush(() => click('Preview dataset'));
|
|
const old = request(storedPath);
|
|
await flush(() =>
|
|
root!.render(
|
|
createElement(
|
|
router.MemoryRouter,
|
|
null,
|
|
createElement(CanonicalSetup, { backtest: { ...definition, name: 'Reset' }, onSave })
|
|
)
|
|
)
|
|
);
|
|
await flush(() => reply(old, stored));
|
|
expect(field('Dataset input').value).toBe('export');
|
|
expect(field('Backtest name').value).toBe('Reset');
|
|
expect(host.querySelector('[aria-label="Prepared dataset metadata"]')).toBeNull();
|
|
});
|
|
});
|