feat(research): prepare and retain explicit source datasets in the web workbench

This commit is contained in:
Boki 2026-10-24 15:06:52 -04:00
parent 06039d17ba
commit 366bee810b
21 changed files with 2677 additions and 76 deletions

View file

@ -21,7 +21,10 @@ import {
} from '../../apps/stock/orchestrator/src/data/historical-dataset';
import type { StorageService } from '../../apps/stock/orchestrator/src/services/StorageService';
import type { BacktestConfig } from '../../apps/stock/orchestrator/src/types';
import { createRoutes } from '../../apps/stock/web-api/src/routes/create-routes';
import {
createRoutes,
WEB_API_MAX_REQUEST_BODY_SIZE,
} from '../../apps/stock/web-api/src/routes/create-routes';
import {
createWebSocketRoute,
handleWebSocketConnection,
@ -420,6 +423,7 @@ export async function fixture(browser: Browser, native = false) {
const server = Bun.serve<RunSocketData, {}>({
hostname: '127.0.0.1',
port: 0,
maxRequestBodySize: WEB_API_MAX_REQUEST_BODY_SIZE,
async fetch(request, server) {
const pathname = new URL(request.url).pathname;
if (pathname === '/ws' && request.headers.get('upgrade') === 'websocket') {

View file

@ -3,6 +3,7 @@ import { afterAll, beforeAll, expect, test } from 'bun:test';
import { chromium, type Browser, type Request } from 'playwright';
import {
canonicalResearchSettingsSchema,
type CanonicalDatasetPreparation,
type CanonicalRunResult,
} from '@stock-bot/stock-config/canonical-research';
import type {
@ -28,7 +29,11 @@ import type {
WalkForwardDetail,
WalkForwardPreview,
} from '@stock-bot/stock-config/walk-forward';
import type { ResearchArtifact, ResearchFindingSource } from '@stock-bot/types';
import type {
HistoricalDatasetInputV2,
ResearchArtifact,
ResearchFindingSource,
} from '@stock-bot/types';
import { retainResearchDataset } from '../../scripts/import-research-dataset';
import { canonicalSettings } from '../fixtures/canonical-research';
import { canonicalSmaFixture } from '../fixtures/canonical-sma';
@ -2109,7 +2114,25 @@ test('research_project_to_finding_browser_with_canonical_strategy_setup_run_and_
f.page.on('dialog', dialog => void dialog.accept());
try {
const oracle = canonicalSmaFixture();
const retained = await retainResearchDataset(f.pool, oracle.dataset);
const retained = oracle.dataset.manifest;
const { calendars, series, executionSeries, bounds, universe, corporateActions } = retained;
// Explicit synthetic source export, with the same reviewed next-open oracle.
// The browser submits raw source rows; only the server normalizes/hashes them.
const source: HistoricalDatasetInputV2 = {
metadata: { calendars, series, executionSeries, bounds, universe, corporateActions },
bars: oracle.dataset.bars.map(bar => ({
seriesId: bar.seriesId,
timestamp: bar.intervalStart,
availableAt: bar.availableAt,
sourceSequence: bar.sourceSequence,
open: bar.open,
high: bar.high,
low: bar.low,
close: bar.close,
volume: bar.volume,
vwap: bar.vwap,
})),
};
const seeded = await f.seedCatalog();
const selected = seeded.find(item => item.package.program.strategyId === 'sma_crossover')!;
expect(selected.reviewStatus).toBe('pending');
@ -2216,7 +2239,93 @@ test('research_project_to_finding_browser_with_canonical_strategy_setup_run_and_
);
await f.page.getByRole('button', { name: 'Settings', exact: true }).click();
await f.page.getByRole('button', { name: 'Configure canonical research', exact: true }).click();
await f.page.getByLabel('Canonical dataset', { exact: true }).selectOption(retained.hash);
await f.page.getByLabel('Initial capital (USD)', { exact: true }).fill('10000');
const templateBeforePreparation = await f.request(`/api/v2/backtests/${backtestId}`);
const preparationCounts = async () =>
(
await f.pool.query(`SELECT
(SELECT count(*)::int FROM backtest_datasets) AS datasets,
(SELECT count(*)::int FROM runs) AS runs,
(SELECT count(*)::int FROM backtest_dispatch) AS dispatch`)
).rows[0];
expect(await preparationCounts()).toEqual({ datasets: 0, runs: 0, dispatch: 0 });
await f.page.getByText('Prepare dataset from source export', { exact: true }).click();
await f.page.getByLabel('Source dataset JSON', { exact: true }).setInputFiles({
name: 'reviewed-synthetic-source.json',
mimeType: 'application/json',
buffer: Buffer.from(JSON.stringify(source)),
});
const previewingDataset = f.page.waitForResponse(response =>
response.url().endsWith('/api/v2/datasets/canonical/preview')
);
await f.page.getByRole('button', { name: 'Preview dataset', exact: true }).click();
const previewedDataset = await previewingDataset;
expect(previewedDataset.status()).toBe(200);
expect(previewedDataset.request().postDataJSON()).toEqual({ input: source });
const preview = (await previewedDataset.json()) as {
preparation: CanonicalDatasetPreparation;
};
expect(preview.preparation.manifest).toEqual(retained);
expect(preview.preparation.hash).toBe(retained.hash);
expect(preview.preparation.available).toBe(true);
// Exercise real HTTP JSON consumption above the former web-server 1 MiB cap.
// Whitespace changes transport size without changing the economic oracle.
const largePreview = await f.page.evaluate(async input => {
const body = JSON.stringify({ input }) + ' '.repeat(1_048_576);
const response = await fetch('/api/v2/datasets/canonical/preview', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body,
});
return {
bytes: new TextEncoder().encode(body).byteLength,
status: response.status,
cacheControl: response.headers.get('Cache-Control'),
result: await response.json(),
};
}, source);
expect(largePreview.bytes).toBeGreaterThan(1_048_576);
expect(largePreview.status).toBe(200);
expect(largePreview.cacheControl).toBe('no-store');
expect(largePreview.result).toEqual(preview);
await visible(f.page, `Dataset hash: ${retained.hash}`);
const calendarDetails = f.page
.getByRole('region', { name: 'Prepared dataset metadata', exact: true })
.getByText(/^Calendar:/);
await calendarDetails.waitFor();
expect(await calendarDetails.textContent()).toContain(
`Revision: ${retained.calendars[0]!.revision}`
);
expect(await preparationCounts()).toEqual({ datasets: 0, runs: 0, dispatch: 0 });
expect(await f.request(`/api/v2/backtests/${backtestId}`)).toEqual(templateBeforePreparation);
const retainingDataset = f.page.waitForResponse(response =>
response.url().endsWith('/api/v2/datasets/canonical/retain')
);
await f.page.getByRole('button', { name: 'Retain dataset', exact: true }).click();
const retainedDataset = await retainingDataset;
expect(retainedDataset.status()).toBe(200);
const retainedRequest = retainedDataset.request().postDataJSON();
expect(retainedRequest).toEqual({ input: source, expectedHash: retained.hash });
expect(await retainedDataset.json()).toEqual(preview);
// Exact replay is safe after a lost response: one immutable row, no new jobs.
expect(await f.request('/api/v2/datasets/canonical/retain', 'POST', retainedRequest)).toEqual(
preview
);
expect(await preparationCounts()).toEqual({ datasets: 1, runs: 0, dispatch: 0 });
expect(await f.request(`/api/v2/backtests/${backtestId}`)).toEqual(templateBeforePreparation);
expect(
(await f.pool.query('SELECT payload FROM backtest_datasets WHERE hash=$1', [retained.hash]))
.rows[0].payload
).toEqual(oracle.dataset);
await until(
async () =>
(await f.page.getByLabel('Canonical dataset', { exact: true }).inputValue()) ===
retained.hash,
'retained source dataset selected in canonical setup'
);
expect(await f.page.getByLabel('Initial capital (USD)', { exact: true }).inputValue()).toBe(
'10000'
);
await visible(f.page, new Date(retained.bounds.tradeStart).toISOString());
await visible(f.page, new Date(retained.bounds.tradeEnd).toISOString());
await f.page.getByLabel('Initial capital (USD)', { exact: true }).fill('10000');

View 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);
});
});

View 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);
});
});

View file

@ -0,0 +1,307 @@
import { randomUUID } from 'node:crypto';
import { readFileSync } from 'node:fs';
import { mkdtemp, rm, writeFile } from 'node:fs/promises';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { afterEach, describe, expect, test } from 'bun:test';
import { Hono } from 'hono';
import { Pool } from 'pg';
import { getLogger, setLoggerConfig } from '@stock-bot/logger';
import { PostgreSQLClient } from '@stock-bot/postgres';
import {
createDatasetV2,
validateDatasetV2,
} from '../../apps/stock/orchestrator/src/data/historical-dataset-v2';
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 } from '../../apps/stock/web-api/src/services/dataset-preparation.service';
import { datasetInput } from '../fixtures/historical-v2/dataset';
setLoggerConfig({ logLevel: 'fatal', logConsole: false });
const logger = getLogger('source-preparation-postgres');
const url = process.env.PIPELINE_TEST_DATABASE_URL;
const cleanup: Array<() => Promise<void>> = [];
afterEach(async () => {
for (const close of cleanup.splice(0).reverse()) {
await close();
}
});
function at<T>(values: readonly T[], index = 0): T {
const value = values[index];
if (value === undefined) {
throw new Error('Missing fixture item');
}
return value;
}
async function fixture() {
if (!url || !new URL(url).pathname.startsWith('/stock_bot_safety')) {
throw new Error('Dedicated stock_bot_safety database required');
}
const schema = `stock_bot_safety_${randomUUID().replaceAll('-', '')}`;
const admin = new Pool({ connectionString: url });
await admin.query(`CREATE SCHEMA ${schema}`);
const pool = new Pool({
connectionString: url,
max: 4,
application_name: schema,
options: `-c search_path=${schema} -c statement_timeout=10000`,
});
cleanup.push(async () => {
await pool.end();
await admin.query(`DROP SCHEMA ${schema} CASCADE`);
await admin.end();
});
for (const name of [
'06-create-backtest-tables.sql',
'08-create-runs-table.sql',
'09-backtest-run-contract.sql',
'10-durable-backtest-dispatch.sql',
'12-historical-datasets.sql',
'14-backtest-submission.sql',
'16-strategy-catalog.sql',
'17-research-retention.sql',
'18-backtest-strategy-versions.sql',
'19-canonical-research.sql',
'20-research-workspace.sql',
'21-run-reproduction.sql',
'22-experiments.sql',
'23-experiment-retries.sql',
'24-chronological-validation.sql',
'25-walk-forward.sql',
'26-cost-sensitivity.sql',
'27-research-evidence-sources.sql',
]) {
await pool.query(
readFileSync(new URL(`../../database/postgres/init/${name}`, import.meta.url), 'utf8')
);
}
await pool.query(`INSERT INTO backtests(name,strategy,symbols,start_date,end_date,initial_capital,config)
VALUES('untouched legacy draft','sma-crossover','["A.US"]','2024-03-01','2024-04-01',1000,'{"fastPeriod":2,"slowPeriod":3}')`);
const postgres = new PostgreSQLClient(
{ host: 'unused', port: 5432, database: 'unused', username: 'unused', password: 'unused' },
logger
);
let queryCount = 0;
Object.defineProperty(postgres, 'connectionPool', { get: () => pool });
Object.defineProperty(postgres, 'query', {
value: async (sql: string, values?: unknown[]) => {
queryCount++;
return pool.query(sql, values);
},
});
const routes = new Hono().route('/', createDatasetRoutes({ postgres, logger }));
const post = (operation: 'preview' | 'retain', body: unknown) =>
routes.request(`/api/v2/datasets/canonical/${operation}`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(body),
});
const snapshot = async (includeDatasets = true) => {
const tables = (
await pool.query<{ tablename: string }>(
'SELECT tablename FROM pg_tables WHERE schemaname=$1 ORDER BY tablename',
[schema]
)
).rows;
const rows: Record<string, unknown> = {};
for (const { tablename } of tables) {
if (includeDatasets || tablename !== 'backtest_datasets') {
rows[tablename] = (
await pool.query(
`SELECT to_jsonb(t) AS row FROM "${tablename}" t ORDER BY to_jsonb(t)::text`
)
).rows;
}
}
return rows;
};
const defaults = async () =>
(
await pool.query(
`SELECT table_name,column_name,column_default FROM information_schema.columns WHERE table_schema=$1 ORDER BY table_name,column_name`,
[schema]
)
).rows;
return {
pool,
schema,
post,
routes,
snapshot,
defaults,
get queryCount() {
return queryCount;
},
};
}
describe.skipIf(!url)('source-export preparation with retained PostgreSQL custody', () => {
test('preview, invalid input and drift write nothing; retain only adds exact normalized dataset, leaving runs/outbox/templates/schema defaults untouched', async () => {
const f = await fixture(),
input = datasetInput();
const before = await f.snapshot(),
defaults = await f.defaults();
const preview = await f.post('preview', { input });
expect(preview.status).toBe(200);
expect(f.queryCount).toBe(0);
const prepared = previewDatasetPreparation({ input });
expect(await preview.json()).toEqual({ preparation: prepared });
expect((await f.post('retain', { input, expectedHash: '0'.repeat(64) })).status).toBe(409);
expect((await f.post('retain', { input: {}, expectedHash: prepared.hash })).status).toBe(400);
expect(f.queryCount).toBe(0);
expect(await f.snapshot()).toEqual(before);
const retained = await f.post('retain', { input, expectedHash: prepared.hash });
expect(retained.status).toBe(200);
expect(await retained.json()).toEqual({ preparation: prepared });
const stored = at((await f.pool.query('SELECT hash,payload FROM backtest_datasets')).rows);
expect(stored.hash).toBe(prepared.hash);
expect(stored.payload).toEqual(createDatasetV2(input));
expect(validateDatasetV2(stored.payload).bars.map(bar => bar.vwap)).toEqual([null, 101, null]);
const { backtest_datasets: _datasets, ...unchanged } = before;
expect(await f.snapshot(false)).toEqual(unchanged);
expect(await f.defaults()).toEqual(defaults);
expect((await f.pool.query('SELECT count(*) AS n FROM runs')).rows).toEqual([{ n: '0' }]);
expect((await f.pool.query('SELECT count(*) AS n FROM backtest_dispatch')).rows).toEqual([
{ n: '0' },
]);
const found = await f.routes.request(`/api/v2/datasets/canonical/${prepared.hash}`);
expect(found.status).toBe(200);
expect((await found.json()).dataset).toMatchObject({
hash: prepared.hash,
manifest: prepared.manifest,
available: true,
reason: null,
});
});
test('concurrent and repeated exact retention is content idempotent with one frozen row and unchanged created_at', async () => {
const f = await fixture(),
input = datasetInput();
const expected = previewDatasetPreparation({ input });
const body = { input, expectedHash: expected.hash };
const replies = await Promise.all(Array.from({ length: 6 }, () => f.post('retain', body)));
for (const reply of replies) {
expect(reply.status).toBe(200);
expect(await reply.json()).toEqual({ preparation: expected });
}
const before = (await f.pool.query('SELECT * FROM backtest_datasets')).rows;
expect(before).toHaveLength(1);
const repeat = await f.post('retain', body);
expect(repeat.status).toBe(200);
expect(await repeat.json()).toEqual({ preparation: expected });
const permuted = { ...input, bars: [...input.bars].reverse() };
expect((await f.post('retain', { input: permuted, expectedHash: expected.hash })).status).toBe(
200
);
expect((await f.pool.query('SELECT * FROM backtest_datasets')).rows).toEqual(before);
await expect(
f.pool.query('UPDATE backtest_datasets SET payload=$1 WHERE hash=$2', [
{ corrupt: true },
expected.hash,
])
).rejects.toThrow();
expect((await f.pool.query('SELECT * FROM backtest_datasets')).rows).toEqual(before);
});
test('valid unavailable source evidence may be retained but remains rejected by the existing picker and execution gate', async () => {
const f = await fixture(),
original = datasetInput();
const input = {
...original,
metadata: {
...original.metadata,
universe: { ...original.metadata.universe, selection: 'unknown' as const, asOf: null },
},
};
const prepared = previewDatasetPreparation({ input });
expect(prepared.available).toBe(false);
expect(prepared.manifest.eligibility).toBe('exploratory');
expect((await f.post('retain', { input, expectedHash: prepared.hash })).status).toBe(200);
expect(
validateDatasetV2(
at((await f.pool.query('SELECT payload FROM backtest_datasets')).rows).payload
).manifest
).toEqual(prepared.manifest);
const lookup = await f.routes.request(`/api/v2/datasets/canonical/${prepared.hash}`);
expect((await lookup.json()).dataset).toMatchObject({
available: false,
reason: prepared.reason,
});
await expect(readCanonicalDataset(f.pool, prepared.hash)).rejects.toThrow(
prepared.reason ?? 'missing reason'
);
expect((await f.pool.query('SELECT count(*) AS n FROM runs')).rows).toEqual([{ n: '0' }]);
});
test('a conflicting retained row with structurally valid but hash-corrupted bars fails full readback as sanitized500 and is never overwritten', async () => {
const f = await fixture(),
input = datasetInput(),
dataset = createDatasetV2(input);
const corrupt = {
...dataset,
bars: dataset.bars.map((bar, index) => (index === 0 ? { ...bar, close: 106 } : bar)),
};
expect(corrupt).not.toEqual(dataset);
await f.pool.query('INSERT INTO backtest_datasets(hash,payload) VALUES($1,$2)', [
dataset.manifest.hash,
corrupt,
]);
const before = await f.snapshot();
const response = await f.post('retain', { input, expectedHash: dataset.manifest.hash });
expect(response.status).toBe(500);
expect(response.headers.get('Cache-Control')).toBe('no-store');
expect(await response.json()).toEqual({ error: 'Source dataset retention unavailable' });
expect(await f.snapshot()).toEqual(before);
await expect(readCanonicalDataset(f.pool, dataset.manifest.hash)).rejects.toThrow(
'content validation'
);
});
test('existing --file CLI retains the same v2 identity and safely repeats against the web-prepared row', async () => {
const f = await fixture(),
input = datasetInput(),
dataset = createDatasetV2(input);
const directory = await mkdtemp(join(tmpdir(), 'source-preparation-cli-'));
cleanup.push(() => rm(directory, { recursive: true, force: true }));
const file = join(directory, 'dataset.json');
await writeFile(file, JSON.stringify(dataset));
const connection = new URL(url ?? '');
connection.searchParams.set('options', `-c search_path=${f.schema}`);
const execute = async (args: string[]) => {
const child = Bun.spawn(
[process.execPath, 'run', 'scripts/import-research-dataset.ts', ...args],
{
cwd: new URL('../../', import.meta.url).pathname,
env: { ...process.env, RESEARCH_DATASET_DATABASE_URL: connection.toString() },
stdout: 'pipe',
stderr: 'pipe',
}
);
const [code, out, err] = await Promise.all([
child.exited,
new Response(child.stdout).text(),
new Response(child.stderr).text(),
]);
return { code, out, err };
};
expect((await f.post('retain', { input, expectedHash: dataset.manifest.hash })).status).toBe(
200
);
const before = await f.snapshot();
const cli = await execute(['--file', file]);
expect(cli.code).toBe(0);
expect(JSON.parse(cli.out)).toEqual({
hash: dataset.manifest.hash,
barCount: dataset.manifest.barCount,
eligibility: dataset.manifest.eligibility,
limitations: dataset.manifest.limitations,
});
expect(await f.snapshot()).toEqual(before);
const flags = await execute(['--source-hash', dataset.manifest.hash]);
expect(flags.code).toBe(1);
expect(flags.err).toContain('Usage:');
await writeFile(file, JSON.stringify(input));
expect((await execute(['--file', file])).code).toBe(1);
expect(await f.snapshot()).toEqual(before);
});
});