feat(research): prepare and retain explicit source datasets in the web workbench
This commit is contained in:
parent
06039d17ba
commit
366bee810b
21 changed files with 2677 additions and 76 deletions
882
test/integration/dataset-source-preparation-ui.test.tsx
Normal file
882
test/integration/dataset-source-preparation-ui.test.tsx
Normal file
|
|
@ -0,0 +1,882 @@
|
|||
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,
|
||||
} from '@stock-bot/stock-config/canonical-research';
|
||||
import type {
|
||||
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';
|
||||
|
||||
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;
|
||||
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 });
|
||||
}
|
||||
Object.defineProperty(field('Source dataset JSON'), 'files', {
|
||||
configurable: true,
|
||||
value: [file],
|
||||
});
|
||||
field('Source dataset JSON').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 } = 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);
|
||||
});
|
||||
});
|
||||
394
test/integration/dataset-source-preparation.test.ts
Normal file
394
test/integration/dataset-source-preparation.test.ts
Normal file
|
|
@ -0,0 +1,394 @@
|
|||
import { describe, expect, mock, test } from 'bun:test';
|
||||
import { Hono } from 'hono';
|
||||
import { createHttpSecurity } from '@stock-bot/di';
|
||||
import { getLogger, setLoggerConfig } from '@stock-bot/logger';
|
||||
import type { IServiceContainer } from '@stock-bot/services';
|
||||
import type { HistoricalDatasetInputV2 } from '@stock-bot/types';
|
||||
import {
|
||||
NativeReplaySession,
|
||||
prepareReplayLoad,
|
||||
runReplayConformance,
|
||||
} from '../../apps/stock/orchestrator/src/backtest/native-replay';
|
||||
import {
|
||||
createDatasetV2,
|
||||
validateDatasetV2,
|
||||
} from '../../apps/stock/orchestrator/src/data/historical-dataset-v2';
|
||||
import { retainResearchDataset } from '../../apps/stock/orchestrator/src/data/retained-research-dataset';
|
||||
import { createDatasetRoutes } from '../../apps/stock/web-api/src/routes/datasets.routes';
|
||||
import { readCanonicalDataset } from '../../apps/stock/web-api/src/services/canonical-research.service';
|
||||
import {
|
||||
previewDatasetPreparation,
|
||||
retainDatasetPreparation,
|
||||
} from '../../apps/stock/web-api/src/services/dataset-preparation.service';
|
||||
import { retainResearchDataset as cliRetain } from '../../scripts/import-research-dataset';
|
||||
import { datasetInput } from '../fixtures/historical-v2/dataset';
|
||||
import { nativeReplayFixture } from '../fixtures/native-replay';
|
||||
|
||||
setLoggerConfig({ logLevel: 'fatal', logConsole: false });
|
||||
const logger = getLogger('dataset-source-preparation-test');
|
||||
const tokens = {
|
||||
admin: 'source-preparation-admin-fixture-123456789',
|
||||
read: 'source-preparation-read-fixture-1234567890',
|
||||
service: 'source-preparation-service-fixture-12345678',
|
||||
};
|
||||
type Mutable<T> = { -readonly [K in keyof T]: T[K] extends object ? Mutable<T[K]> : T[K] };
|
||||
const source = () => structuredClone(datasetInput()) as Mutable<HistoricalDatasetInputV2>;
|
||||
function at<T>(values: readonly T[], index = 0): T {
|
||||
const value = values[index];
|
||||
if (value === undefined) {
|
||||
throw new Error('Missing fixture item');
|
||||
}
|
||||
return value;
|
||||
}
|
||||
function fixture(
|
||||
query: (
|
||||
sql: string,
|
||||
values?: unknown[]
|
||||
) => Promise<{ rows: Record<string, unknown>[] }> = async () => {
|
||||
throw new Error('Preview/rejected request reached storage');
|
||||
}
|
||||
) {
|
||||
const database = { query: mock(query) };
|
||||
const app = new Hono();
|
||||
createHttpSecurity({
|
||||
adminToken: tokens.admin,
|
||||
serviceToken: tokens.service,
|
||||
readToken: tokens.read,
|
||||
environment: 'test',
|
||||
hostname: '127.0.0.1',
|
||||
browserSessions: true,
|
||||
}).mount(app);
|
||||
app.route(
|
||||
'/',
|
||||
createDatasetRoutes({ postgres: database, logger } as unknown as IServiceContainer)
|
||||
);
|
||||
const request = (
|
||||
operation: 'preview' | 'retain',
|
||||
body: unknown,
|
||||
headers: Record<string, string> = { Authorization: `Bearer ${tokens.admin}` }
|
||||
) =>
|
||||
app.request(`/api/v2/datasets/canonical/${operation}`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json', ...headers },
|
||||
body: JSON.stringify(body),
|
||||
});
|
||||
return { app, database, request };
|
||||
}
|
||||
|
||||
describe('explicit source-export preparation', () => {
|
||||
test('preview is pure, stable under normalized permutation and preserves declared evidence without mutating input', async () => {
|
||||
const f = fixture();
|
||||
const input = source(),
|
||||
before = structuredClone(input);
|
||||
const reply = await f.request('preview', { input });
|
||||
expect(reply.status).toBe(200);
|
||||
expect(reply.headers.get('Cache-Control')).toBe('no-store');
|
||||
const expected = previewDatasetPreparation({ input });
|
||||
expect(await reply.json()).toEqual({ preparation: expected });
|
||||
expect(expected).toMatchObject({
|
||||
version: 'canonical-dataset-preparation/v1',
|
||||
available: true,
|
||||
reason: null,
|
||||
});
|
||||
expect(expected.manifest.series).toEqual(input.metadata.series);
|
||||
expect(expected.manifest.calendars).toEqual(input.metadata.calendars);
|
||||
expect(expected.manifest.universe).toEqual(input.metadata.universe);
|
||||
expect(expected.manifest.corporateActions).toEqual(input.metadata.corporateActions);
|
||||
expect(expected.manifest.parentDatasetHash).toBeNull();
|
||||
expect(expected.manifest.limitations.some(value => value.includes('interval end'))).toBe(true);
|
||||
expect(input).toEqual(before);
|
||||
input.bars.reverse();
|
||||
at(input.metadata.calendars).sessions.reverse();
|
||||
const permuted = structuredClone(input);
|
||||
expect(previewDatasetPreparation({ input })).toEqual(expected);
|
||||
expect(input).toEqual(permuted);
|
||||
expect(f.database.query).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
test('complete strict source validation rejects missing metadata, bad declarations, duplicate/invalid observations with actionable safe diagnostics', async () => {
|
||||
const f = fixture();
|
||||
const invalid: unknown[] = [
|
||||
null,
|
||||
{},
|
||||
{ bars: source().bars },
|
||||
{ metadata: source().metadata },
|
||||
{ ...source(), extra: 'not permitted' },
|
||||
];
|
||||
const mutations: Array<(value: Mutable<HistoricalDatasetInputV2>) => void> = [
|
||||
value => {
|
||||
at(value.metadata.calendars).revision = '';
|
||||
},
|
||||
value => {
|
||||
at(value.metadata.calendars).timeZone = 'private-invalid-timezone';
|
||||
},
|
||||
value => {
|
||||
value.metadata.corporateActions = [];
|
||||
},
|
||||
value => {
|
||||
at(value.metadata.series).source.revision = '';
|
||||
},
|
||||
value => {
|
||||
at(value.metadata.series).availability = 'explicit';
|
||||
},
|
||||
value => {
|
||||
value.bars.push({ ...at(value.bars) });
|
||||
},
|
||||
value => {
|
||||
at(value.bars).high = 1;
|
||||
},
|
||||
value => {
|
||||
at(value.bars).volume = -1;
|
||||
},
|
||||
value => {
|
||||
at(value.bars).timestamp = '2024-03-09';
|
||||
},
|
||||
];
|
||||
for (const change of mutations) {
|
||||
const input = source();
|
||||
change(input);
|
||||
invalid.push(input);
|
||||
}
|
||||
for (const input of invalid) {
|
||||
const response = await f.request('preview', { input });
|
||||
expect(response.status).toBe(400);
|
||||
expect(response.headers.get('Cache-Control')).toBe('no-store');
|
||||
expect(await response.text()).not.toContain('private-invalid-timezone');
|
||||
}
|
||||
const missing = await f.request('preview', { input: { bars: [] } });
|
||||
expect(await missing.text()).toContain('metadata');
|
||||
const duplicate = source();
|
||||
duplicate.bars.push({ ...at(duplicate.bars) });
|
||||
expect(await (await f.request('preview', { input: duplicate })).text()).toContain(
|
||||
'Duplicate or conflicting'
|
||||
);
|
||||
expect(f.database.query).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
test('preview availability exactly matches the existing workbench gate for valid exploratory, adjusted, known-action and multiasset datasets', async () => {
|
||||
const variants: Array<(value: Mutable<HistoricalDatasetInputV2>) => void> = [
|
||||
value => {
|
||||
value.metadata.universe.selection = 'unknown';
|
||||
value.metadata.universe.asOf = null;
|
||||
},
|
||||
value => {
|
||||
at(value.metadata.corporateActions).status = 'unknown';
|
||||
},
|
||||
value => {
|
||||
at(value.metadata.series).adjustment = 'provider-adjusted';
|
||||
},
|
||||
value => {
|
||||
const coverage = at(value.metadata.corporateActions);
|
||||
coverage.status = 'known-actions';
|
||||
coverage.actions.push({
|
||||
effectiveAt: value.metadata.bounds.tradeStart,
|
||||
kind: 'split',
|
||||
reference: 'operator-declared-action',
|
||||
});
|
||||
},
|
||||
value => {
|
||||
value.metadata.series.push({
|
||||
...at(value.metadata.series),
|
||||
id: 'B.US:daily:raw',
|
||||
instrumentId: 'B.US',
|
||||
});
|
||||
value.metadata.executionSeries.push({ instrumentId: 'B.US', seriesId: 'B.US:daily:raw' });
|
||||
value.metadata.universe.instrumentIds.push('B.US');
|
||||
value.metadata.corporateActions.push({
|
||||
...at(value.metadata.corporateActions),
|
||||
instrumentId: 'B.US',
|
||||
});
|
||||
value.bars.push(...value.bars.map(bar => ({ ...bar, seriesId: 'B.US:daily:raw' })));
|
||||
},
|
||||
];
|
||||
for (const mutate of variants) {
|
||||
const input = source();
|
||||
mutate(input);
|
||||
const prepared = previewDatasetPreparation({ input });
|
||||
expect(prepared.available).toBe(false);
|
||||
expect(prepared.manifest).toEqual(createDatasetV2(input).manifest);
|
||||
await expect(
|
||||
readCanonicalDataset(
|
||||
{ query: async () => ({ rows: [{ payload: createDatasetV2(input) }] }) },
|
||||
prepared.hash
|
||||
)
|
||||
).rejects.toThrow(prepared.reason ?? 'missing reason');
|
||||
const stored = new Map<string, unknown>();
|
||||
const retained = await retainDatasetPreparation(
|
||||
{
|
||||
async query(sql, values) {
|
||||
if (sql.startsWith('INSERT')) {
|
||||
stored.set(String(values?.[0]), JSON.parse(String(values?.[1])));
|
||||
return { rows: [] };
|
||||
}
|
||||
return { rows: [{ payload: stored.get(String(values?.[0])) }] };
|
||||
},
|
||||
},
|
||||
{ input, expectedHash: prepared.hash }
|
||||
);
|
||||
expect(retained).toEqual(prepared);
|
||||
}
|
||||
});
|
||||
|
||||
test('retained explicit delay and missing VWAP survive normalization; native decisions cannot observe unpublished bars', async () => {
|
||||
const f = nativeReplayFixture(5),
|
||||
manifest = f.dataset.manifest;
|
||||
const delayedAt = f.start + 2.5 * f.minute;
|
||||
const input: HistoricalDatasetInputV2 = {
|
||||
metadata: {
|
||||
calendars: manifest.calendars,
|
||||
series: manifest.series,
|
||||
executionSeries: manifest.executionSeries,
|
||||
bounds: manifest.bounds,
|
||||
universe: manifest.universe,
|
||||
corporateActions: manifest.corporateActions,
|
||||
},
|
||||
bars: f.dataset.bars.map(bar => ({
|
||||
seriesId: bar.seriesId,
|
||||
timestamp: bar.intervalStart,
|
||||
sourceSequence: bar.sourceSequence,
|
||||
availableAt: bar.sourceSequence === 0 ? delayedAt : bar.availableAt,
|
||||
open: bar.open,
|
||||
high: bar.high,
|
||||
low: bar.low,
|
||||
close: bar.close,
|
||||
volume: bar.volume,
|
||||
})),
|
||||
};
|
||||
let stored: unknown;
|
||||
const prepared = previewDatasetPreparation({ input });
|
||||
await retainDatasetPreparation(
|
||||
{
|
||||
async query(sql, values) {
|
||||
if (sql.startsWith('INSERT')) {
|
||||
stored = JSON.parse(String(values?.[1]));
|
||||
return { rows: [] };
|
||||
}
|
||||
return { rows: [{ payload: stored }] };
|
||||
},
|
||||
},
|
||||
{ input, expectedHash: prepared.hash }
|
||||
);
|
||||
const retained = validateDatasetV2(stored);
|
||||
expect(retained.bars.find(bar => bar.sourceSequence === 0)?.availableAt).toBe(delayedAt);
|
||||
expect(retained.bars.every(bar => bar.vwap === null)).toBe(true);
|
||||
expect(retained.manifest.series).toEqual(manifest.series);
|
||||
const decisions: Array<{ at: number; sequence: number[] }> = [];
|
||||
runReplayConformance(
|
||||
new NativeReplaySession(prepareReplayLoad(retained, f.config)),
|
||||
(_owner, context, observations) => {
|
||||
expect(observations.every(bar => bar.available_at <= context.barrier.at)).toBe(true);
|
||||
decisions.push({
|
||||
at: context.barrier.at,
|
||||
sequence: observations.map(bar => bar.source_sequence),
|
||||
});
|
||||
return { mode: 'target', targets: [] };
|
||||
}
|
||||
);
|
||||
expect(decisions.some(decision => decision.at < delayedAt)).toBe(true);
|
||||
expect(
|
||||
decisions
|
||||
.filter(decision => decision.at < delayedAt)
|
||||
.every(decision => !decision.sequence.includes(0))
|
||||
).toBe(true);
|
||||
expect(
|
||||
decisions.some(decision => decision.at >= delayedAt && decision.sequence.includes(0))
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
test('strict bodies, malformed JSON and hash drift reject before any write; errors are not cacheable', async () => {
|
||||
const f = fixture(),
|
||||
input = source(),
|
||||
expectedHash = previewDatasetPreparation({ input }).hash;
|
||||
for (const [operation, body] of [
|
||||
['preview', {}],
|
||||
['preview', { input, extra: true }],
|
||||
['preview', { input, expectedHash }],
|
||||
['retain', { input }],
|
||||
['retain', { input, expectedHash: expectedHash.toUpperCase() }],
|
||||
['retain', { input, expectedHash, extra: true }],
|
||||
['retain', { input: null, expectedHash }],
|
||||
] as const) {
|
||||
const response = await f.request(operation, body);
|
||||
expect(response.status).toBe(400);
|
||||
expect(response.headers.get('Cache-Control')).toBe('no-store');
|
||||
}
|
||||
const mismatch = await f.request('retain', { input, expectedHash: '0'.repeat(64) });
|
||||
expect(mismatch.status).toBe(409);
|
||||
expect(mismatch.headers.get('Cache-Control')).toBe('no-store');
|
||||
const malformed = await f.app.request('/api/v2/datasets/canonical/preview', {
|
||||
method: 'POST',
|
||||
headers: { Authorization: `Bearer ${tokens.admin}`, 'Content-Type': 'application/json' },
|
||||
body: '{',
|
||||
});
|
||||
expect(malformed.status).toBe(400);
|
||||
expect(f.database.query).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
test('storage exceptions and corrupt conflicting content fail as sanitized 500, never input errors or success', async () => {
|
||||
const input = source(),
|
||||
expectedHash = previewDatasetPreparation({ input }).hash;
|
||||
for (const query of [
|
||||
async () => {
|
||||
throw new Error('private-storage-details');
|
||||
},
|
||||
async () => ({ rows: [{ payload: { private: 'private-storage-details' } }] }),
|
||||
async () => ({ rows: [] }),
|
||||
]) {
|
||||
const response = await fixture(query).request('retain', { input, expectedHash });
|
||||
expect(response.status).toBe(500);
|
||||
expect(response.headers.get('Cache-Control')).toBe('no-store');
|
||||
expect(await response.text()).not.toContain('private-storage-details');
|
||||
}
|
||||
});
|
||||
|
||||
test('existing mounted global auth rejects read tokens and protects browser mutations with trusted Origin', async () => {
|
||||
const input = source(),
|
||||
expectedHash = previewDatasetPreparation({ input }).hash;
|
||||
const stored = createDatasetV2(input);
|
||||
const f = fixture(async () => ({ rows: [{ payload: stored }] }));
|
||||
for (const operation of ['preview', 'retain'] as const) {
|
||||
const body = operation === 'preview' ? { input } : { input, expectedHash };
|
||||
expect((await f.request(operation, body, {})).status).toBe(401);
|
||||
expect(
|
||||
(await f.request(operation, body, { Authorization: `Bearer ${tokens.read}` })).status
|
||||
).toBe(403);
|
||||
}
|
||||
const login = await f.app.request('/api/auth/session', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json', Origin: 'http://localhost' },
|
||||
body: JSON.stringify({ token: tokens.admin }),
|
||||
});
|
||||
expect(login.status).toBe(200);
|
||||
const cookie = login.headers.get('Set-Cookie')?.split(';')[0];
|
||||
if (!cookie) {
|
||||
throw new Error('Missing authenticated browser session');
|
||||
}
|
||||
for (const operation of ['preview', 'retain'] as const) {
|
||||
const body = operation === 'preview' ? { input } : { input, expectedHash };
|
||||
expect((await f.request(operation, body, { Cookie: cookie })).status).toBe(403);
|
||||
expect(
|
||||
(await f.request(operation, body, { Cookie: cookie, Origin: 'https://foreign.invalid' }))
|
||||
.status
|
||||
).toBe(403);
|
||||
}
|
||||
expect(f.database.query).not.toHaveBeenCalled();
|
||||
expect(
|
||||
(await f.request('preview', { input }, { Cookie: cookie, Origin: 'http://localhost' })).status
|
||||
).toBe(200);
|
||||
expect(f.database.query).not.toHaveBeenCalled();
|
||||
expect(
|
||||
(
|
||||
await f.request(
|
||||
'retain',
|
||||
{ input, expectedHash },
|
||||
{ Cookie: cookie, Origin: 'http://localhost' }
|
||||
)
|
||||
).status
|
||||
).toBe(200);
|
||||
expect(f.database.query).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
|
||||
test('existing CLI imports reexport the same retained custody helper without executing the CLI', () => {
|
||||
expect(cliRetain).toBe(retainResearchDataset);
|
||||
});
|
||||
});
|
||||
Loading…
Add table
Add a link
Reference in a new issue