feat(research): prepare stored EOD datasets before canonical admission
This commit is contained in:
parent
366bee810b
commit
0c6aec4dc6
16 changed files with 1897 additions and 61 deletions
|
|
@ -39,6 +39,17 @@ import { seedBuiltinCatalog } from '../../scripts/seed-builtin-strategies';
|
|||
|
||||
setLoggerConfig({ logLevel: 'fatal', logConsole: false });
|
||||
const logger = getLogger('browser-fixture');
|
||||
interface StoredEodBar {
|
||||
eodSearchCode: string;
|
||||
symbol: string;
|
||||
exchange: string;
|
||||
timestamp: number;
|
||||
open: number;
|
||||
high: number;
|
||||
low: number;
|
||||
close: number;
|
||||
volume: number;
|
||||
}
|
||||
export function gate() {
|
||||
let resolve!: () => void;
|
||||
const promise = new Promise<void>(done => {
|
||||
|
|
@ -395,7 +406,35 @@ export async function fixture(browser: Browser, native = false) {
|
|||
}
|
||||
});
|
||||
cleanup.push(() => dispatcher.shutdown());
|
||||
const container = { postgres, logger } as IServiceContainer;
|
||||
// Replace only Mongo transport; HTTP preparation exercises the real EOD
|
||||
// StorageService adapter, while retained execution must never read it.
|
||||
const storedEodBars = new Map<string, StoredEodBar[]>();
|
||||
const storedSourceReads: {
|
||||
collection: string;
|
||||
filter: { eodSearchCode: string; timestamp: { $gte: number; $lt: number } };
|
||||
}[] = [];
|
||||
const mongodb = {
|
||||
async find(
|
||||
collection: string,
|
||||
filter: { eodSearchCode: string; timestamp: { $gte: number; $lt: number } }
|
||||
) {
|
||||
if (!['eodIntraday1M', 'eodIntraday5M', 'eodIntraday1H'].includes(collection)) {
|
||||
throw new Error('Unexpected stored-source collection');
|
||||
}
|
||||
storedSourceReads.push({ collection, filter: structuredClone(filter) });
|
||||
return structuredClone(
|
||||
(storedEodBars.get(collection) ?? [])
|
||||
.filter(
|
||||
bar =>
|
||||
bar.eodSearchCode === filter.eodSearchCode &&
|
||||
bar.timestamp >= filter.timestamp.$gte &&
|
||||
bar.timestamp < filter.timestamp.$lt
|
||||
)
|
||||
.sort((a, b) => a.timestamp - b.timestamp)
|
||||
);
|
||||
},
|
||||
} as unknown as NonNullable<IServiceContainer['mongodb']>;
|
||||
const container = { postgres, mongodb, logger } as IServiceContainer;
|
||||
const token = randomUUID() + randomUUID();
|
||||
const security = createHttpSecurity({
|
||||
adminToken: token,
|
||||
|
|
@ -602,6 +641,10 @@ export async function fixture(browser: Browser, native = false) {
|
|||
close,
|
||||
unexpectedNetwork,
|
||||
historicalDataReads,
|
||||
storedSourceReads,
|
||||
setStoredEodBars: (collection: string, bars: StoredEodBar[]) => {
|
||||
storedEodBars.set(collection, structuredClone(bars));
|
||||
},
|
||||
seedCatalog: () => seedBuiltinCatalog(new StrategyCatalogService(container)),
|
||||
};
|
||||
} catch (error) {
|
||||
|
|
|
|||
|
|
@ -5,6 +5,7 @@ import {
|
|||
canonicalResearchSettingsSchema,
|
||||
type CanonicalDatasetPreparation,
|
||||
type CanonicalRunResult,
|
||||
type CanonicalStoredSourcePreparation,
|
||||
} from '@stock-bot/stock-config/canonical-research';
|
||||
import type {
|
||||
ChronologicalValidationActionResult,
|
||||
|
|
@ -34,6 +35,7 @@ import type {
|
|||
ResearchArtifact,
|
||||
ResearchFindingSource,
|
||||
} from '@stock-bot/types';
|
||||
import { createDatasetV2 } from '../../apps/stock/orchestrator/src/data/historical-dataset-v2';
|
||||
import { retainResearchDataset } from '../../scripts/import-research-dataset';
|
||||
import { canonicalSettings } from '../fixtures/canonical-research';
|
||||
import { canonicalSmaFixture } from '../fixtures/canonical-sma';
|
||||
|
|
@ -2114,7 +2116,7 @@ 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 = oracle.dataset.manifest;
|
||||
let 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.
|
||||
|
|
@ -2326,6 +2328,107 @@ test('research_project_to_finding_browser_with_canonical_strategy_setup_run_and_
|
|||
expect(await f.page.getByLabel('Initial capital (USD)', { exact: true }).inputValue()).toBe(
|
||||
'10000'
|
||||
);
|
||||
// Materialize an actual stored EOD source through the same panel, then edit
|
||||
// the mutable store. Retention and execution must keep the displayed bytes.
|
||||
const storedMetadata = {
|
||||
...source.metadata,
|
||||
series: source.metadata.series.map(series => ({
|
||||
...series,
|
||||
source: { provider: 'eod', revision: 'declared-browser-source-v1' },
|
||||
availability: 'interval-end-assumption' as const,
|
||||
})),
|
||||
};
|
||||
const storedRows = oracle.dataset.bars.map(bar => ({
|
||||
eodSearchCode: 'X0.US',
|
||||
symbol: 'X0',
|
||||
exchange: 'US',
|
||||
timestamp: bar.intervalStart / 1000,
|
||||
open: bar.open,
|
||||
high: bar.high,
|
||||
low: bar.low,
|
||||
close: bar.close,
|
||||
volume: bar.volume,
|
||||
}));
|
||||
f.setStoredEodBars('eodIntraday1M', storedRows);
|
||||
await f.page.getByLabel('Dataset input', { exact: true }).selectOption('stored-eod');
|
||||
await f.page.getByLabel('Source metadata JSON', { exact: true }).setInputFiles({
|
||||
name: 'declared-stored-eod-metadata.json',
|
||||
mimeType: 'application/json',
|
||||
buffer: Buffer.from(JSON.stringify(storedMetadata)),
|
||||
});
|
||||
const loadingStored = f.page.waitForResponse(response =>
|
||||
response.url().endsWith('/api/v2/datasets/canonical/stored-source')
|
||||
);
|
||||
await f.page.getByRole('button', { name: 'Preview dataset', exact: true }).click();
|
||||
const storedResponse = await loadingStored;
|
||||
expect(storedResponse.status()).toBe(200);
|
||||
expect(storedResponse.headers()['cache-control']).toBe('no-store');
|
||||
expect(storedResponse.request().postDataJSON()).toEqual({ metadata: storedMetadata });
|
||||
const materialized = (await storedResponse.json()) as CanonicalStoredSourcePreparation;
|
||||
expect(materialized.input.metadata).toEqual(storedMetadata);
|
||||
expect(materialized.input.bars).toHaveLength(oracle.dataset.bars.length);
|
||||
expect(materialized.input.bars.every(bar => bar.availableAt === undefined)).toBe(true);
|
||||
const expectedStored = createDatasetV2(materialized.input);
|
||||
expect(materialized.preparation.manifest).toEqual(expectedStored.manifest);
|
||||
expect(expectedStored.bars).toEqual(oracle.dataset.bars);
|
||||
expect(materialized.preparation.hash).not.toBe(retained.hash);
|
||||
expect(f.storedSourceReads).toEqual([
|
||||
{
|
||||
collection: 'eodIntraday1M',
|
||||
filter: {
|
||||
eodSearchCode: 'X0.US',
|
||||
timestamp: { $gte: bounds.warmupStart / 1000, $lt: bounds.tradeEnd / 1000 },
|
||||
},
|
||||
},
|
||||
]);
|
||||
await visible(f.page, `Dataset hash: ${materialized.preparation.hash}`);
|
||||
await visible(f.page, /Availability is explicitly assumed at interval end/);
|
||||
expect(await preparationCounts()).toEqual({ datasets: 1, runs: 0, dispatch: 0 });
|
||||
// A fresh preview observes corrected provider history; the current UI
|
||||
// preview and its retention payload must remain the previously captured one.
|
||||
f.setStoredEodBars(
|
||||
'eodIntraday1M',
|
||||
storedRows.map(row => ({
|
||||
...row,
|
||||
open: row.open + 100,
|
||||
high: row.high + 100,
|
||||
low: row.low + 100,
|
||||
close: row.close + 100,
|
||||
}))
|
||||
);
|
||||
const refreshedSource = (await f.request('/api/v2/datasets/canonical/stored-source', 'POST', {
|
||||
metadata: storedMetadata,
|
||||
})) as CanonicalStoredSourcePreparation;
|
||||
expect(refreshedSource.preparation.hash).not.toBe(materialized.preparation.hash);
|
||||
expect(f.storedSourceReads).toHaveLength(2);
|
||||
const retainingStored = f.page.waitForResponse(response =>
|
||||
response.url().endsWith('/api/v2/datasets/canonical/retain')
|
||||
);
|
||||
await f.page.getByRole('button', { name: 'Retain dataset', exact: true }).click();
|
||||
const storedRetention = await retainingStored;
|
||||
expect(storedRetention.status()).toBe(200);
|
||||
const capturedRequest = storedRetention.request().postDataJSON();
|
||||
expect(capturedRequest).toEqual({
|
||||
input: materialized.input,
|
||||
expectedHash: materialized.preparation.hash,
|
||||
});
|
||||
expect(await storedRetention.json()).toEqual({ preparation: materialized.preparation });
|
||||
expect(await f.request('/api/v2/datasets/canonical/retain', 'POST', capturedRequest)).toEqual({
|
||||
preparation: materialized.preparation,
|
||||
});
|
||||
expect(f.storedSourceReads).toHaveLength(2);
|
||||
expect(await preparationCounts()).toEqual({ datasets: 2, runs: 0, dispatch: 0 });
|
||||
expect(await f.request(`/api/v2/backtests/${backtestId}`)).toEqual(templateBeforePreparation);
|
||||
retained = expectedStored.manifest;
|
||||
await until(
|
||||
async () =>
|
||||
(await f.page.getByLabel('Canonical dataset', { exact: true }).inputValue()) ===
|
||||
retained.hash,
|
||||
'captured stored source selected for canonical execution'
|
||||
);
|
||||
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');
|
||||
|
|
@ -2662,6 +2765,7 @@ test('research_project_to_finding_browser_with_canonical_strategy_setup_run_and_
|
|||
).toBe(run.id);
|
||||
expect((await f.pool.query('SELECT * FROM backtest_results')).rowCount).toBe(3);
|
||||
expect(f.historicalDataReads).toEqual([]);
|
||||
expect(f.storedSourceReads).toHaveLength(2);
|
||||
expect(f.unexpectedNetwork).toEqual([]);
|
||||
} finally {
|
||||
await f.close();
|
||||
|
|
|
|||
|
|
@ -5,8 +5,10 @@ import type { Root } from 'react-dom/client';
|
|||
import type {
|
||||
CanonicalDatasetCatalogEntry,
|
||||
CanonicalDatasetPreparation,
|
||||
CanonicalStoredSourcePreparation,
|
||||
} from '@stock-bot/stock-config/canonical-research';
|
||||
import type {
|
||||
HistoricalDatasetMetadataV2,
|
||||
StrategyParameterSchema,
|
||||
StrategyRecord,
|
||||
StrategyVersionPackage,
|
||||
|
|
@ -15,6 +17,7 @@ import type {
|
|||
import { createDatasetV2 } from '../../apps/stock/orchestrator/src/data/historical-dataset-v2';
|
||||
import type { CreateBacktestRequest } from '../../apps/stock/web-app/src/features/backtest/services/backtestApiV2';
|
||||
import { datasetInput } from '../fixtures/historical-v2/dataset';
|
||||
import { metadata as intradayMetadata, intradayResponse } from '../fixtures/intraday/eod';
|
||||
|
||||
const browser = new GlobalWindow({ url: 'http://localhost:5173' });
|
||||
const keys = ['window', 'document', 'IS_REACT_ACT_ENVIRONMENT', 'ResizeObserver'] as const;
|
||||
|
|
@ -24,6 +27,7 @@ let router: typeof import('react-router-dom');
|
|||
let CanonicalSetup: typeof import('../../apps/stock/web-app/src/features/backtest/components/CanonicalSetup').CanonicalSetup;
|
||||
let DatasetPreparation: typeof import('../../apps/stock/web-app/src/features/backtest/components/DatasetPreparation').DatasetPreparation;
|
||||
let parseDatasetPreparation: typeof import('../../apps/stock/web-app/src/features/backtest/services/backtestApiV2').parseDatasetPreparation;
|
||||
let parseStoredDatasetPreparation: typeof import('../../apps/stock/web-app/src/features/backtest/services/backtestApiV2').parseStoredDatasetPreparation;
|
||||
function confirmWith(value: () => boolean) {
|
||||
Object.defineProperty(browser, 'confirm', { configurable: true, writable: true, value });
|
||||
}
|
||||
|
|
@ -114,13 +118,13 @@ function upload(value: unknown = datasetInput(), name = 'source.json', read?: Pr
|
|||
if (read) {
|
||||
Object.defineProperty(file, 'text', { value: () => read });
|
||||
}
|
||||
Object.defineProperty(field('Source dataset JSON'), 'files', {
|
||||
const label =
|
||||
field('Dataset input').value === 'stored-eod' ? 'Source metadata JSON' : 'Source dataset JSON';
|
||||
Object.defineProperty(field(label), 'files', {
|
||||
configurable: true,
|
||||
value: [file],
|
||||
});
|
||||
field('Source dataset JSON').dispatchEvent(
|
||||
new browser.Event('change', { bubbles: true }) as unknown as Event
|
||||
);
|
||||
field(label).dispatchEvent(new browser.Event('change', { bubbles: true }) as unknown as Event);
|
||||
}
|
||||
async function mount(element: ReactElement) {
|
||||
root = createRoot(host);
|
||||
|
|
@ -271,7 +275,7 @@ beforeAll(async () => {
|
|||
({ DatasetPreparation } = await import(
|
||||
'../../apps/stock/web-app/src/features/backtest/components/DatasetPreparation'
|
||||
));
|
||||
({ parseDatasetPreparation } = await import(
|
||||
({ parseDatasetPreparation, parseStoredDatasetPreparation } = await import(
|
||||
'../../apps/stock/web-app/src/features/backtest/services/backtestApiV2'
|
||||
));
|
||||
});
|
||||
|
|
@ -880,3 +884,445 @@ describe('canonical setup coordination', () => {
|
|||
expect(button('Save canonical setup').disabled).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
const storedPath = '/api/v2/datasets/canonical/stored-source';
|
||||
function storedFixture(
|
||||
metadata: HistoricalDatasetMetadataV2 = intradayMetadata()
|
||||
): CanonicalStoredSourcePreparation {
|
||||
const input = {
|
||||
metadata,
|
||||
bars: intradayResponse().map((bar, sourceSequence) => ({
|
||||
seriesId: metadata.series[0]!.id,
|
||||
timestamp: bar.timestamp * 1000,
|
||||
sourceSequence,
|
||||
open: bar.open,
|
||||
high: bar.high,
|
||||
low: bar.low,
|
||||
close: bar.close,
|
||||
volume: bar.volume,
|
||||
})),
|
||||
};
|
||||
const normalized = createDatasetV2(input);
|
||||
const { calendars, series, executionSeries, bounds, universe, corporateActions } =
|
||||
normalized.manifest;
|
||||
return {
|
||||
input: {
|
||||
...input,
|
||||
metadata: { calendars, series, executionSeries, bounds, universe, corporateActions },
|
||||
},
|
||||
preparation: {
|
||||
version: 'canonical-dataset-preparation/v1',
|
||||
hash: normalized.manifest.hash,
|
||||
manifest: normalized.manifest,
|
||||
available: normalized.manifest.eligibility === 'eligible',
|
||||
reason:
|
||||
normalized.manifest.eligibility === 'eligible'
|
||||
? null
|
||||
: 'Declared coverage is unavailable for execution',
|
||||
},
|
||||
};
|
||||
}
|
||||
const storedMetadata: HistoricalDatasetMetadataV2 = {
|
||||
...intradayMetadata(),
|
||||
universe: {
|
||||
...intradayMetadata().universe,
|
||||
selection: 'point-in-time',
|
||||
asOf: intradayMetadata().bounds.warmupStart,
|
||||
},
|
||||
corporateActions: intradayMetadata().corporateActions.map(item => ({
|
||||
...item,
|
||||
status: 'action-free',
|
||||
})),
|
||||
};
|
||||
const stored = storedFixture(storedMetadata);
|
||||
async function storedPreview(value: CanonicalStoredSourcePreparation = stored) {
|
||||
await flush(() => edit('Dataset input', 'stored-eod'));
|
||||
await flush(() => upload(value.input.metadata, 'metadata.json'));
|
||||
await flush(() => click('Preview dataset'));
|
||||
await flush(() => reply(request(storedPath), value));
|
||||
}
|
||||
|
||||
describe('stored source response contract', () => {
|
||||
test('validates the captured complete input without inventing optional VWAP or availability', () => {
|
||||
const result = parseStoredDatasetPreparation(stored, storedMetadata);
|
||||
expect(result).toEqual(stored);
|
||||
expect(result.input.bars.every(bar => !('vwap' in bar) && !('availableAt' in bar))).toBe(true);
|
||||
});
|
||||
test('accepts the normalizer collection order while preserving all declared values', () => {
|
||||
const base = intradayMetadata();
|
||||
const calendar = base.calendars[0]!;
|
||||
const metadata: HistoricalDatasetMetadataV2 = {
|
||||
...base,
|
||||
calendars: [
|
||||
{
|
||||
...calendar,
|
||||
id: 'z-extra',
|
||||
startDate: '2024-03-10',
|
||||
sessions: [
|
||||
calendar.sessions[0]!,
|
||||
{
|
||||
date: '2024-03-10',
|
||||
open: calendar.sessions[0]!.open - 86400000,
|
||||
close: calendar.sessions[0]!.close - 86400000,
|
||||
},
|
||||
],
|
||||
},
|
||||
calendar,
|
||||
],
|
||||
corporateActions: base.corporateActions.map(item => ({
|
||||
...item,
|
||||
status: 'known-actions',
|
||||
actions: [
|
||||
{ effectiveAt: item.start + 1, kind: 'dividend', reference: 'z-later' },
|
||||
{ effectiveAt: item.start, kind: 'split', reference: 'a-earlier' },
|
||||
],
|
||||
})),
|
||||
};
|
||||
const result = storedFixture(metadata);
|
||||
expect(result.input.metadata.calendars[0]!.id).toBe(calendar.id);
|
||||
expect(parseStoredDatasetPreparation(result, metadata)).toEqual(result);
|
||||
expect(metadata.calendars[0]!.id).toBe('z-extra');
|
||||
expect(metadata.corporateActions[0]!.actions[0]!.reference).toBe('z-later');
|
||||
});
|
||||
type Mutable<T> = { -readonly [K in keyof T]: T[K] extends object ? Mutable<T[K]> : T[K] };
|
||||
const changes: {
|
||||
name: string;
|
||||
change: (value: Mutable<CanonicalStoredSourcePreparation>) => unknown;
|
||||
}[] = [
|
||||
{ name: 'unknown envelope property', change: v => Object.assign(v, { certified: true }) },
|
||||
{ name: 'unknown input property', change: v => Object.assign(v.input, { requestId: 'other' }) },
|
||||
{
|
||||
name: 'unknown metadata property',
|
||||
change: v => Object.assign(v.input.metadata, { certified: true }),
|
||||
},
|
||||
{
|
||||
name: 'unknown bar property',
|
||||
change: v => Object.assign(v.input.bars[0]!, { instrumentId: 'wrong' }),
|
||||
},
|
||||
{
|
||||
name: 'invented availability',
|
||||
change: v => Object.assign(v.input.bars[0]!, { availableAt: v.input.bars[0]!.timestamp }),
|
||||
},
|
||||
{ name: 'wrong preparation hash', change: v => (v.preparation.hash = 'a'.repeat(64)) },
|
||||
{ name: 'wrong bar count', change: v => v.preparation.manifest.barCount++ },
|
||||
{ name: 'wrong series identity', change: v => (v.input.bars[0]!.seriesId = 'another-series') },
|
||||
{ name: 'wrong row ordinal', change: v => (v.input.bars[1]!.sourceSequence = 15) },
|
||||
{
|
||||
name: 'duplicate timestamp',
|
||||
change: v => (v.input.bars[1]!.timestamp = v.input.bars[0]!.timestamp),
|
||||
},
|
||||
{
|
||||
name: 'out-of-range timestamp',
|
||||
change: v => (v.input.bars[0]!.timestamp = v.input.metadata.bounds.tradeEnd),
|
||||
},
|
||||
{ name: 'non-finite price', change: v => (v.input.bars[0]!.open = Infinity) },
|
||||
{ name: 'malformed VWAP', change: v => (v.input.bars[0]!.vwap = -1) },
|
||||
{ name: 'empty bars', change: v => (v.input.bars = []) },
|
||||
{
|
||||
name: 'changed source revision',
|
||||
change: v => (v.input.metadata.series[0]!.source.revision = 'unexpected revision'),
|
||||
},
|
||||
{
|
||||
name: 'changed manifest revision',
|
||||
change: v => (v.preparation.manifest.calendars[0]!.revision = 'changed-calendar'),
|
||||
},
|
||||
{
|
||||
name: 'changed source provider',
|
||||
change: v => (v.input.metadata.series[0]!.source.provider = 'questdb'),
|
||||
},
|
||||
{
|
||||
name: 'unsupported daily interval',
|
||||
change: v => (v.input.metadata.series[0]!.interval = '1d'),
|
||||
},
|
||||
{
|
||||
name: 'unsupported adjusted prices',
|
||||
change: v => (v.input.metadata.series[0]!.adjustment = 'provider-adjusted'),
|
||||
},
|
||||
{
|
||||
name: 'unsupported explicit availability',
|
||||
change: v => (v.input.metadata.series[0]!.availability = 'explicit'),
|
||||
},
|
||||
];
|
||||
for (const { name, change } of changes) {
|
||||
test(`rejects ${name}`, () => {
|
||||
const value = structuredClone(stored) as Mutable<CanonicalStoredSourcePreparation>;
|
||||
change(value);
|
||||
expect(() => parseStoredDatasetPreparation(value, storedMetadata)).toThrow();
|
||||
});
|
||||
}
|
||||
test('rejects a valid response bound to different caller metadata', () => {
|
||||
expect(() =>
|
||||
parseStoredDatasetPreparation(stored, {
|
||||
...storedMetadata,
|
||||
bounds: { ...storedMetadata.bounds, tradeStart: storedMetadata.bounds.tradeStart + 1 },
|
||||
})
|
||||
).toThrow();
|
||||
});
|
||||
});
|
||||
|
||||
describe('stored source panel', () => {
|
||||
test('defaults to the existing export mode and selecting stored mode performs no IO', async () => {
|
||||
await mountPanel();
|
||||
expect(field('Dataset input').value).toBe('export');
|
||||
await flush(() => edit('Dataset input', 'stored-eod'));
|
||||
expect(field('Source metadata JSON')).toBeDefined();
|
||||
expect(host.textContent).toContain('No source metadata selected.');
|
||||
expect(host.textContent).toContain('not a vendor sequence');
|
||||
expect(host.textContent).toContain('not independently certified');
|
||||
expect(requests).toHaveLength(0);
|
||||
expect(button('Preview dataset').disabled).toBe(true);
|
||||
});
|
||||
test('stored preview sends only declared metadata, displays snapshot and retains returned full input without requery', async () => {
|
||||
await mountPanel();
|
||||
await storedPreview();
|
||||
expect(requests.filter(item => item.path === storedPath)).toHaveLength(1);
|
||||
expect(requests.find(item => item.path === storedPath)!.body).toEqual({
|
||||
metadata: stored.input.metadata,
|
||||
});
|
||||
expect(host.textContent).toContain('Stored source: EOD');
|
||||
expect(host.textContent).toContain('FIXTURE.TEST / 5m');
|
||||
expect(host.textContent).toContain('2024-03-11T13:30:00.000Z');
|
||||
expect(host.textContent).toContain('2024-03-11T20:00:00.000Z');
|
||||
expect(host.textContent).toContain('Availability: interval-end-assumption');
|
||||
await flush(() => {
|
||||
click('Retain dataset');
|
||||
click('Retain dataset');
|
||||
});
|
||||
const first = request(retainPath);
|
||||
expect(first.body).toEqual({ input: stored.input, expectedHash: stored.preparation.hash });
|
||||
await flush(() => fail(first));
|
||||
expect(field('Dataset input').disabled).toBe(true);
|
||||
expect(field('Source metadata JSON').disabled).toBe(true);
|
||||
await flush(() => {
|
||||
edit('Dataset input', 'export');
|
||||
upload({ replacement: true });
|
||||
});
|
||||
expect(field('Dataset input').value).toBe('stored-eod');
|
||||
expect(host.textContent).toContain('Selected metadata: metadata.json');
|
||||
await flush(() => click('Retry retaining same dataset'));
|
||||
expect(request(retainPath).body).toEqual(first.body);
|
||||
expect(requests.filter(item => item.path === storedPath)).toHaveLength(1);
|
||||
expect(requests.filter(item => item.path === previewPath)).toHaveLength(0);
|
||||
await flush(() => reply(request(retainPath), { preparation: stored.preparation }));
|
||||
expect(retained).toEqual([{ hash: stored.preparation.hash, available: true }]);
|
||||
expect(states.at(-1)).toEqual({ busy: false, blocking: false });
|
||||
});
|
||||
test('same-event retain then mode change cannot discard or retarget the captured snapshot', async () => {
|
||||
await mountPanel();
|
||||
await storedPreview();
|
||||
await flush(() => {
|
||||
click('Retain dataset');
|
||||
edit('Dataset input', 'export');
|
||||
click('Clear source preparation');
|
||||
});
|
||||
expect(request(retainPath).body).toEqual({
|
||||
input: stored.input,
|
||||
expectedHash: stored.preparation.hash,
|
||||
});
|
||||
expect(field('Dataset input').value).toBe('stored-eod');
|
||||
await flush(() => fail(request(retainPath)));
|
||||
expect(button('Retry retaining same dataset').disabled).toBe(false);
|
||||
confirmWith(() => false);
|
||||
await flush(() => click('Clear source preparation'));
|
||||
expect(field('Dataset input').disabled).toBe(true);
|
||||
confirmWith(() => true);
|
||||
await flush(() => click('Clear source preparation'));
|
||||
await flush(() => edit('Dataset input', 'export'));
|
||||
expect(field('Dataset input').value).toBe('export');
|
||||
expect(host.textContent).toContain('No source export selected.');
|
||||
});
|
||||
test('same-event mode change invalidates old retain and preview handlers', async () => {
|
||||
await mountPanel();
|
||||
await storedPreview();
|
||||
await flush(() => {
|
||||
edit('Dataset input', 'export');
|
||||
click('Retain dataset');
|
||||
click('Preview dataset');
|
||||
});
|
||||
expect(requests.filter(item => item.path === retainPath)).toHaveLength(0);
|
||||
expect(requests.filter(item => item.path === previewPath)).toHaveLength(0);
|
||||
expect(host.querySelector('[aria-label="Prepared dataset metadata"]')).toBeNull();
|
||||
});
|
||||
test('mode switching fences a late stored response and a late export response', async () => {
|
||||
await mountPanel();
|
||||
await flush(() => edit('Dataset input', 'stored-eod'));
|
||||
await flush(() => upload(storedMetadata));
|
||||
await flush(() => click('Preview dataset'));
|
||||
const oldStored = request(storedPath);
|
||||
await flush(() => edit('Dataset input', 'export'));
|
||||
expect(oldStored.signal?.aborted).toBe(true);
|
||||
await flush(() => reply(oldStored, stored));
|
||||
expect(host.querySelector('[aria-label="Prepared dataset metadata"]')).toBeNull();
|
||||
await flush(() => upload());
|
||||
await flush(() => click('Preview dataset'));
|
||||
const oldExport = request(previewPath);
|
||||
await flush(() => edit('Dataset input', 'stored-eod'));
|
||||
await flush(() => reply(oldExport, { preparation }));
|
||||
expect(host.textContent).toContain('No source metadata selected.');
|
||||
expect(host.querySelector('[aria-label="Prepared dataset metadata"]')).toBeNull();
|
||||
});
|
||||
test('mode switching fences a late file read', async () => {
|
||||
await mountPanel();
|
||||
const read = deferred<string>();
|
||||
await flush(() => upload({}, 'old-export.json', read.promise));
|
||||
await flush(() => edit('Dataset input', 'stored-eod'));
|
||||
await flush(() => read.resolve(JSON.stringify(datasetInput())));
|
||||
expect(host.textContent).toContain('No source metadata selected.');
|
||||
expect(button('Preview dataset').disabled).toBe(true);
|
||||
});
|
||||
test('file replacement fences the previous stored read without discarding the new file', async () => {
|
||||
await mountPanel();
|
||||
await flush(() => edit('Dataset input', 'stored-eod'));
|
||||
await flush(() => upload(storedMetadata));
|
||||
await flush(() => click('Preview dataset'));
|
||||
const old = request(storedPath);
|
||||
const next = {
|
||||
...storedMetadata,
|
||||
universe: { ...storedMetadata.universe, revision: 'next declaration' },
|
||||
};
|
||||
await flush(() => upload(next, 'next.json'));
|
||||
await flush(() => reply(old, stored));
|
||||
expect(host.textContent).toContain('Selected metadata: next.json');
|
||||
expect(button('Retain dataset').disabled).toBe(true);
|
||||
await flush(() => click('Preview dataset'));
|
||||
expect(request(storedPath).body).toEqual({ metadata: next });
|
||||
});
|
||||
test('explicit fresh preview replaces materialized data only after its response', async () => {
|
||||
await mountPanel();
|
||||
await storedPreview();
|
||||
await flush(() => click('Preview dataset'));
|
||||
expect(button('Retain dataset').disabled).toBe(true);
|
||||
expect(host.querySelector('[aria-label="Prepared dataset metadata"]')).toBeNull();
|
||||
const input = {
|
||||
...stored.input,
|
||||
bars: stored.input.bars.map(bar => ({ ...bar, volume: bar.volume + 1 })),
|
||||
};
|
||||
const nextDataset = createDatasetV2(input);
|
||||
const next = {
|
||||
input,
|
||||
preparation: {
|
||||
...stored.preparation,
|
||||
hash: nextDataset.manifest.hash,
|
||||
manifest: nextDataset.manifest,
|
||||
},
|
||||
};
|
||||
await flush(() => reply(request(storedPath), next));
|
||||
await flush(() => click('Retain dataset'));
|
||||
expect(request(retainPath).body).toEqual({
|
||||
input: next.input,
|
||||
expectedHash: next.preparation.hash,
|
||||
});
|
||||
expect(requests.filter(item => item.path === storedPath)).toHaveLength(2);
|
||||
});
|
||||
for (const [status, message] of [
|
||||
[400, 'Unsupported metadata'],
|
||||
[404, 'No stored bars'],
|
||||
[503, 'EOD store unavailable'],
|
||||
[500, 'Stored source unavailable'],
|
||||
] as const) {
|
||||
test(`stored ${status} exposes repair or retry without retention`, async () => {
|
||||
await mountPanel();
|
||||
await flush(() => edit('Dataset input', 'stored-eod'));
|
||||
await flush(() => upload(storedMetadata));
|
||||
await flush(() => click('Preview dataset'));
|
||||
await flush(() => reply(request(storedPath), { error: message }, status));
|
||||
expect(host.textContent).toContain(message);
|
||||
expect(button('Preview dataset').disabled).toBe(false);
|
||||
expect(button('Retain dataset').disabled).toBe(true);
|
||||
expect(field('Source metadata JSON').disabled).toBe(false);
|
||||
expect(retained).toHaveLength(0);
|
||||
});
|
||||
}
|
||||
test('malformed stored success fails closed and keeps the metadata draft available for retry', async () => {
|
||||
await mountPanel();
|
||||
await flush(() => edit('Dataset input', 'stored-eod'));
|
||||
await flush(() => upload(storedMetadata));
|
||||
await flush(() => click('Preview dataset'));
|
||||
await flush(() =>
|
||||
reply(request(storedPath), {
|
||||
input: { metadata: storedMetadata, bars: [] },
|
||||
preparation: stored.preparation,
|
||||
})
|
||||
);
|
||||
expect(host.textContent).toContain('stored source response could not be verified');
|
||||
expect(host.textContent).toContain('Selected metadata: source.json');
|
||||
expect(button('Retain dataset').disabled).toBe(true);
|
||||
expect(button('Preview dataset').disabled).toBe(false);
|
||||
});
|
||||
test('stored exploratory evidence remains visible and retainable without canonical selection', async () => {
|
||||
await mountPanel();
|
||||
const exploratory = storedFixture();
|
||||
await storedPreview(exploratory);
|
||||
expect(host.textContent).toContain('Unavailable for canonical setup');
|
||||
expect(host.textContent).toContain('Universe: unknown');
|
||||
await flush(() => click('Retain dataset'));
|
||||
await flush(() => reply(request(retainPath), { preparation: exploratory.preparation }));
|
||||
expect(retained).toEqual([{ hash: exploratory.preparation.hash, available: false }]);
|
||||
expect(states.at(-1)).toEqual({ busy: false, blocking: true });
|
||||
});
|
||||
test('unmount ignores stored materialization that completes after an aborted request', async () => {
|
||||
await mountPanel();
|
||||
await flush(() => edit('Dataset input', 'stored-eod'));
|
||||
await flush(() => upload(storedMetadata));
|
||||
await flush(() => click('Preview dataset'));
|
||||
const old = request(storedPath);
|
||||
await flush(() => root!.unmount());
|
||||
root = undefined;
|
||||
await flush(() => reply(old, stored));
|
||||
expect(old.signal?.aborted).toBe(true);
|
||||
expect(retained).toHaveLength(0);
|
||||
expect(states.at(-1)).toEqual({ busy: false, blocking: false });
|
||||
});
|
||||
test('parent saves are synchronously blocked while stored source is pending; drafts remain intact', async () => {
|
||||
let saves = 0;
|
||||
await readySetup(async () => {
|
||||
saves++;
|
||||
});
|
||||
await flush(() => {
|
||||
edit('Backtest name', 'Stored draft');
|
||||
edit('Fee rate', '0.02');
|
||||
edit('Dataset input', 'stored-eod');
|
||||
});
|
||||
await flush(() => {
|
||||
upload(storedMetadata);
|
||||
host
|
||||
.querySelector('form')!
|
||||
.dispatchEvent(
|
||||
new browser.Event('submit', { bubbles: true, cancelable: true }) as unknown as Event
|
||||
);
|
||||
});
|
||||
expect(saves).toBe(0);
|
||||
expect(button('Save canonical setup').disabled).toBe(true);
|
||||
await flush(() => click('Preview dataset'));
|
||||
await flush(() => reply(request(storedPath), stored));
|
||||
expect(field('Backtest name').value).toBe('Stored draft');
|
||||
expect(field('Fee rate').value).toBe('0.02');
|
||||
expect(field('Canonical dataset').value).toBe(entry.hash);
|
||||
await flush(() => click('Retain dataset'));
|
||||
await flush(() => reply(request(retainPath), { preparation: stored.preparation }));
|
||||
expect(field('Canonical dataset').value).toBe(stored.preparation.hash);
|
||||
expect(saves).toBe(0);
|
||||
expect(field('Fee rate').value).toBe('0.02');
|
||||
});
|
||||
test('authoritative parent reset fences late stored response and restores export mode', async () => {
|
||||
const onSave = async () => {};
|
||||
await readySetup(onSave);
|
||||
await flush(() => edit('Dataset input', 'stored-eod'));
|
||||
await flush(() => upload(storedMetadata));
|
||||
await flush(() => click('Preview dataset'));
|
||||
const old = request(storedPath);
|
||||
await flush(() =>
|
||||
root!.render(
|
||||
createElement(
|
||||
router.MemoryRouter,
|
||||
null,
|
||||
createElement(CanonicalSetup, { backtest: { ...definition, name: 'Reset' }, onSave })
|
||||
)
|
||||
)
|
||||
);
|
||||
await flush(() => reply(old, stored));
|
||||
expect(field('Dataset input').value).toBe('export');
|
||||
expect(field('Backtest name').value).toBe('Reset');
|
||||
expect(host.querySelector('[aria-label="Prepared dataset metadata"]')).toBeNull();
|
||||
});
|
||||
});
|
||||
|
|
|
|||
472
test/integration/stored-dataset-preparation.test.ts
Normal file
472
test/integration/stored-dataset-preparation.test.ts
Normal file
|
|
@ -0,0 +1,472 @@
|
|||
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, MongoDBClient, QuestDBClient } from '@stock-bot/services';
|
||||
import { parseFinancialDecimal, type HistoricalDatasetMetadataV2 } from '@stock-bot/types';
|
||||
import {
|
||||
NativeReplaySession,
|
||||
prepareReplayLoad,
|
||||
runReplayConformance,
|
||||
} from '../../apps/stock/orchestrator/src/backtest/native-replay';
|
||||
import { createDatasetV2 } from '../../apps/stock/orchestrator/src/data/historical-dataset-v2';
|
||||
import {
|
||||
StorageService,
|
||||
type HistoricalBar,
|
||||
} from '../../apps/stock/orchestrator/src/services/StorageService';
|
||||
import { createDatasetRoutes } from '../../apps/stock/web-api/src/routes/datasets.routes';
|
||||
import { previewDatasetPreparation } from '../../apps/stock/web-api/src/services/dataset-preparation.service';
|
||||
import { prepareStoredDataset } from '../../apps/stock/web-api/src/services/stored-dataset-preparation';
|
||||
import { nativeReplayFixture } from '../fixtures/native-replay';
|
||||
|
||||
setLoggerConfig({ logLevel: 'fatal', logConsole: false });
|
||||
const logger = getLogger('stored-source-test');
|
||||
const token = 'stored-source-admin-fixture-not-a-real-secret';
|
||||
type Mutable<T> = { -readonly [K in keyof T]: T[K] extends object ? Mutable<T[K]> : T[K] };
|
||||
type Row = {
|
||||
symbol: string;
|
||||
exchange: string;
|
||||
eodSearchCode: string;
|
||||
timestamp: number;
|
||||
open: number;
|
||||
high: number;
|
||||
low: number;
|
||||
close: number;
|
||||
volume: number;
|
||||
};
|
||||
function at<T>(values: readonly T[], index = 0): T {
|
||||
const value = values[index];
|
||||
if (value === undefined) {
|
||||
throw new Error('Missing fixture row');
|
||||
}
|
||||
return value;
|
||||
}
|
||||
function source(interval: '1m' | '5m' | '1h' = '1m') {
|
||||
const f = nativeReplayFixture(3),
|
||||
duration = { '1m': 60000, '5m': 300000, '1h': 3600000 }[interval];
|
||||
const { calendars, series, executionSeries, bounds, universe, corporateActions } =
|
||||
f.dataset.manifest;
|
||||
const metadata = structuredClone({
|
||||
calendars,
|
||||
series,
|
||||
executionSeries,
|
||||
bounds,
|
||||
universe,
|
||||
corporateActions,
|
||||
}) as Mutable<HistoricalDatasetMetadataV2>;
|
||||
const declared = at(metadata.series);
|
||||
declared.interval = interval;
|
||||
declared.source = { provider: 'eod', revision: 'operator-declared-source-v1' };
|
||||
declared.availability = 'interval-end-assumption';
|
||||
metadata.bounds.tradeStart = f.start + duration;
|
||||
metadata.bounds.tradeEnd = f.start + 3 * duration;
|
||||
at(metadata.corporateActions).end = metadata.bounds.tradeEnd;
|
||||
const rows: Row[] = f.dataset.bars.map((bar, index) => ({
|
||||
symbol: 'X0',
|
||||
exchange: 'US',
|
||||
eodSearchCode: 'X0.US',
|
||||
timestamp: (f.start + index * duration) / 1000,
|
||||
open: bar.open,
|
||||
high: bar.high,
|
||||
low: bar.low,
|
||||
close: bar.close,
|
||||
volume: bar.volume,
|
||||
}));
|
||||
return { metadata, rows, f, duration };
|
||||
}
|
||||
function fixture(
|
||||
find: (
|
||||
collection: string,
|
||||
filter: Record<string, unknown>,
|
||||
options: Record<string, unknown>
|
||||
) => Promise<Row[]> = async () => source().rows,
|
||||
mongoAvailable = true
|
||||
) {
|
||||
const query = mock(async () => {
|
||||
throw new Error('Preparation must not reach PostgreSQL');
|
||||
});
|
||||
const read = mock(find);
|
||||
const mongodb = mongoAvailable ? ({ find: read } as unknown as MongoDBClient) : undefined;
|
||||
const questdb = {
|
||||
query: mock(async () => {
|
||||
throw new Error('Unexpected provider fallback');
|
||||
}),
|
||||
} as unknown as QuestDBClient;
|
||||
const container = {
|
||||
logger,
|
||||
mongodb,
|
||||
questdb,
|
||||
postgres: { query },
|
||||
} as unknown as IServiceContainer;
|
||||
const app = new Hono();
|
||||
createHttpSecurity({
|
||||
adminToken: token,
|
||||
serviceToken: 'stored-source-service-fixture-not-a-real-secret',
|
||||
readToken: 'stored-source-read-fixture-not-a-real-secret',
|
||||
environment: 'test',
|
||||
browserSessions: true,
|
||||
}).mount(app);
|
||||
app.route('/', createDatasetRoutes(container));
|
||||
const request = (body: unknown, signal?: AbortSignal) =>
|
||||
app.request('/api/v2/datasets/canonical/stored-source', {
|
||||
method: 'POST',
|
||||
headers: { Authorization: `Bearer ${token}`, 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(body),
|
||||
signal,
|
||||
});
|
||||
return {
|
||||
request,
|
||||
app,
|
||||
read,
|
||||
query,
|
||||
questdb,
|
||||
storage: new StorageService(container, mongodb, null, questdb),
|
||||
container,
|
||||
};
|
||||
}
|
||||
|
||||
describe('stored EOD preparation', () => {
|
||||
test('all supported intraday intervals use the actual strict EOD adapter once, exact UTC query bounds and unchanged raw observations', async () => {
|
||||
for (const interval of ['1m', '5m', '1h'] as const) {
|
||||
const input = source(interval);
|
||||
const f = fixture(async () => [...input.rows].reverse());
|
||||
const reply = await f.request({ metadata: input.metadata });
|
||||
expect(reply.status).toBe(200);
|
||||
expect(reply.headers.get('Cache-Control')).toBe('no-store');
|
||||
const body = await reply.json();
|
||||
expect(f.read).toHaveBeenCalledTimes(1);
|
||||
expect(f.read.mock.calls[0]).toEqual([
|
||||
{ '1m': 'eodIntraday1M', '5m': 'eodIntraday5M', '1h': 'eodIntraday1H' }[interval],
|
||||
{
|
||||
eodSearchCode: 'X0.US',
|
||||
timestamp: {
|
||||
$gte: input.metadata.bounds.warmupStart / 1000,
|
||||
$lt: input.metadata.bounds.tradeEnd / 1000,
|
||||
},
|
||||
},
|
||||
{
|
||||
sort: { timestamp: 1 },
|
||||
projection: {
|
||||
symbol: 1,
|
||||
exchange: 1,
|
||||
eodSearchCode: 1,
|
||||
timestamp: 1,
|
||||
open: 1,
|
||||
high: 1,
|
||||
low: 1,
|
||||
close: 1,
|
||||
volume: 1,
|
||||
},
|
||||
},
|
||||
]);
|
||||
expect(body.input.metadata).toEqual(input.metadata);
|
||||
expect(body.input.bars.map((bar: { sourceSequence: number }) => bar.sourceSequence)).toEqual([
|
||||
0, 1, 2,
|
||||
]);
|
||||
expect(body.input.bars.map((bar: { timestamp: number }) => bar.timestamp)).toEqual(
|
||||
input.rows.map(row => row.timestamp * 1000)
|
||||
);
|
||||
expect(
|
||||
body.input.bars.every(
|
||||
(bar: Record<string, unknown>) =>
|
||||
!Object.hasOwn(bar, 'vwap') && !Object.hasOwn(bar, 'availableAt')
|
||||
)
|
||||
).toBe(true);
|
||||
expect(body.preparation).toEqual(previewDatasetPreparation({ input: body.input }));
|
||||
const normalized = createDatasetV2(body.input);
|
||||
expect(
|
||||
normalized.bars.every(bar => bar.vwap === null && bar.availableAt === bar.intervalEnd)
|
||||
).toBe(true);
|
||||
expect(normalized.manifest.parentDatasetHash).toBeNull();
|
||||
expect(f.query).not.toHaveBeenCalled();
|
||||
expect(f.questdb.query).not.toHaveBeenCalled();
|
||||
}
|
||||
});
|
||||
|
||||
test('complete metadata and supported scope reject before every provider read', async () => {
|
||||
const f = fixture();
|
||||
const bodies: unknown[] = [
|
||||
null,
|
||||
{},
|
||||
{ metadata: {} },
|
||||
{ metadata: source().metadata, extra: true },
|
||||
];
|
||||
const changes: Array<(metadata: Mutable<HistoricalDatasetMetadataV2>) => void> = [
|
||||
metadata => {
|
||||
at(metadata.series).source.provider = 'auto';
|
||||
},
|
||||
metadata => {
|
||||
at(metadata.series).source.provider = 'questdb';
|
||||
},
|
||||
metadata => {
|
||||
at(metadata.series).source.revision = '';
|
||||
},
|
||||
metadata => {
|
||||
at(metadata.series).interval = '15m';
|
||||
},
|
||||
metadata => {
|
||||
at(metadata.series).interval = '1d';
|
||||
at(metadata.series).timestamp = 'session-date';
|
||||
},
|
||||
metadata => {
|
||||
at(metadata.series).adjustment = 'provider-adjusted';
|
||||
},
|
||||
metadata => {
|
||||
at(metadata.series).timestamp = 'interval-end';
|
||||
},
|
||||
metadata => {
|
||||
at(metadata.series).availability = 'explicit';
|
||||
},
|
||||
metadata => {
|
||||
metadata.corporateActions = [];
|
||||
},
|
||||
metadata => {
|
||||
at(metadata.calendars).timeZone = 'private-invalid-timezone';
|
||||
},
|
||||
metadata => {
|
||||
metadata.bounds.tradeStart = metadata.bounds.tradeEnd;
|
||||
},
|
||||
metadata => {
|
||||
metadata.series.push({ ...at(metadata.series), id: 'X1.US:1m', instrumentId: 'X1.US' });
|
||||
metadata.executionSeries.push({ instrumentId: 'X1.US', seriesId: 'X1.US:1m' });
|
||||
metadata.universe.instrumentIds.push('X1.US');
|
||||
metadata.corporateActions.push({ ...at(metadata.corporateActions), instrumentId: 'X1.US' });
|
||||
},
|
||||
];
|
||||
for (const change of changes) {
|
||||
const { metadata } = source();
|
||||
change(metadata);
|
||||
bodies.push({ metadata });
|
||||
}
|
||||
for (const body of bodies) {
|
||||
const reply = await f.request(body);
|
||||
expect(reply.status).toBe(400);
|
||||
expect(reply.headers.get('Cache-Control')).toBe('no-store');
|
||||
expect(await reply.text()).not.toContain('private-invalid-timezone');
|
||||
}
|
||||
expect(f.read).not.toHaveBeenCalled();
|
||||
expect(f.query).not.toHaveBeenCalled();
|
||||
expect(f.questdb.query).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
test('empty, unavailable, corrupt and transport failure cases stay distinct without fallback or private errors', async () => {
|
||||
const body = { metadata: source().metadata };
|
||||
const cases: Array<[ReturnType<typeof fixture>, number]> = [
|
||||
[fixture(async () => []), 404],
|
||||
[fixture(undefined, false), 503],
|
||||
[
|
||||
fixture(async () => {
|
||||
throw new Error('private database connection details');
|
||||
}),
|
||||
500,
|
||||
],
|
||||
[
|
||||
fixture(async () =>
|
||||
source().rows.map((row, index) => (index === 0 ? { ...row, high: 0 } : row))
|
||||
),
|
||||
500,
|
||||
],
|
||||
[fixture(async () => source().rows.map(row => ({ ...row, exchange: 'WRONG' }))), 500],
|
||||
[fixture(async () => [...source().rows, at(source().rows)]), 500],
|
||||
];
|
||||
for (const [f, status] of cases) {
|
||||
const reply = await f.request(body);
|
||||
expect(reply.status).toBe(status);
|
||||
expect(reply.headers.get('Cache-Control')).toBe('no-store');
|
||||
expect(await reply.text()).not.toContain('private database connection details');
|
||||
expect(f.query).not.toHaveBeenCalled();
|
||||
expect(f.questdb.query).not.toHaveBeenCalled();
|
||||
}
|
||||
});
|
||||
|
||||
test('valid unavailable declarations remain inspectable; partial intervals and declared session mismatches fail422', async () => {
|
||||
const input = source();
|
||||
input.metadata.universe.selection = 'unknown';
|
||||
input.metadata.universe.asOf = null;
|
||||
const reply = await fixture().request({ metadata: input.metadata });
|
||||
expect(reply.status).toBe(200);
|
||||
expect((await reply.json()).preparation).toMatchObject({
|
||||
available: false,
|
||||
manifest: { eligibility: 'exploratory' },
|
||||
});
|
||||
const partial = source();
|
||||
partial.metadata.bounds.tradeEnd -= 30000;
|
||||
const partialReply = await fixture().request({ metadata: partial.metadata });
|
||||
expect(partialReply.status).toBe(422);
|
||||
const wrongSession = source();
|
||||
at(at(wrongSession.metadata.calendars).sessions).open += 30000;
|
||||
const sessionReply = await fixture().request({ metadata: wrongSession.metadata });
|
||||
expect(sessionReply.status).toBe(422);
|
||||
expect(await sessionReply.text()).toContain('declared complete dataset metadata');
|
||||
});
|
||||
|
||||
test('metadata is detached and deeply frozen before await; later caller/store mutations cannot alter returned captured bytes', async () => {
|
||||
const initial = source(),
|
||||
expectedMetadata = structuredClone(initial.metadata);
|
||||
let release: (() => void) | undefined;
|
||||
const gate = new Promise<void>(resolve => {
|
||||
release = resolve;
|
||||
});
|
||||
const f = fixture(async () => {
|
||||
await gate;
|
||||
return initial.rows;
|
||||
});
|
||||
const promise = prepareStoredDataset(
|
||||
{ metadata: initial.metadata },
|
||||
f.storage,
|
||||
new AbortController().signal
|
||||
);
|
||||
expect(f.read).toHaveBeenCalledTimes(1);
|
||||
at(initial.metadata.series).source.revision = 'later source revision';
|
||||
initial.metadata.bounds.tradeEnd += initial.duration;
|
||||
if (!release) {
|
||||
throw new Error('Missing fixture barrier');
|
||||
}
|
||||
release();
|
||||
const prepared = await promise;
|
||||
expect(prepared.input.metadata).toEqual(expectedMetadata);
|
||||
expect(Object.isFrozen(prepared)).toBe(true);
|
||||
expect(Object.isFrozen(prepared.input.metadata.calendars[0]?.sessions)).toBe(true);
|
||||
expect(Object.isFrozen(prepared.input.bars[0])).toBe(true);
|
||||
at(initial.rows).close = 10.5;
|
||||
expect(prepared.input.bars[0]?.close).toBe(11);
|
||||
expect(prepared.preparation).toEqual(previewDatasetPreparation({ input: prepared.input }));
|
||||
});
|
||||
|
||||
test('initial and late cancellation return499 even when underlying Mongo finishes; cancelled calls write nothing', async () => {
|
||||
const initial = new AbortController();
|
||||
initial.abort(new Error('private abort reason'));
|
||||
const f = fixture();
|
||||
const early = await f.request({ metadata: source().metadata }, initial.signal);
|
||||
expect(early.status).toBe(499);
|
||||
expect(early.headers.get('Cache-Control')).toBe('no-store');
|
||||
expect(f.read).not.toHaveBeenCalled();
|
||||
const controller = new AbortController();
|
||||
let release: (() => void) | undefined;
|
||||
const gate = new Promise<void>(resolve => {
|
||||
release = resolve;
|
||||
});
|
||||
let entered: (() => void) | undefined;
|
||||
const started = new Promise<void>(resolve => {
|
||||
entered = resolve;
|
||||
});
|
||||
const slow = fixture(async () => {
|
||||
entered?.();
|
||||
await gate;
|
||||
return source().rows;
|
||||
});
|
||||
const pending = slow.request({ metadata: source().metadata }, controller.signal);
|
||||
await started;
|
||||
controller.abort(new Error('private abort reason'));
|
||||
if (!release) {
|
||||
throw new Error('Missing fixture barrier');
|
||||
}
|
||||
release();
|
||||
const late = await pending;
|
||||
expect(late.status).toBe(499);
|
||||
expect(late.headers.get('Cache-Control')).toBe('no-store');
|
||||
expect(await late.text()).not.toContain('private abort reason');
|
||||
expect(slow.read).toHaveBeenCalledTimes(1);
|
||||
expect(slow.query).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
test('the focused adapter independently refuses wrong source, symbol, interpolation and out-of-range rows', async () => {
|
||||
const input = source();
|
||||
const f = fixture();
|
||||
const baseline = await f.storage.getHistoricalBars(
|
||||
'X0.US',
|
||||
new Date(input.metadata.bounds.warmupStart),
|
||||
new Date(input.metadata.bounds.tradeEnd),
|
||||
'1m',
|
||||
{ adjustment: 'raw', timestamp: 'utc-instant' },
|
||||
undefined,
|
||||
'eod'
|
||||
);
|
||||
const changes: Array<(row: HistoricalBar) => HistoricalBar> = [
|
||||
row => ({ ...row, source: 'questdb' }),
|
||||
row => ({ ...row, symbol: 'WRONG.US' }),
|
||||
row => ({ ...row, interpolated: true }),
|
||||
row => ({ ...row, timestamp: new Date(input.metadata.bounds.tradeEnd) }),
|
||||
];
|
||||
for (const change of changes) {
|
||||
await expect(
|
||||
prepareStoredDataset(
|
||||
{ metadata: input.metadata },
|
||||
{ getHistoricalBars: async () => [change(at(baseline))] },
|
||||
new AbortController().signal
|
||||
)
|
||||
).rejects.toThrow('inconsistent bar identity or range');
|
||||
}
|
||||
});
|
||||
|
||||
test('actual stored adapter output preserves native next-open costs/equity and never reveals observations before interval end', async () => {
|
||||
const input = source(),
|
||||
f = fixture(async () => input.rows);
|
||||
const captured = await prepareStoredDataset(
|
||||
{ metadata: input.metadata },
|
||||
f.storage,
|
||||
new AbortController().signal
|
||||
);
|
||||
const dataset = createDatasetV2(captured.input);
|
||||
let decisions = 0;
|
||||
const { result } = runReplayConformance(
|
||||
new NativeReplaySession(prepareReplayLoad(dataset, input.f.config)),
|
||||
(_owner, context, observations) => {
|
||||
decisions++;
|
||||
expect(
|
||||
observations.every(
|
||||
bar => bar.available_at === bar.interval_end && bar.available_at <= context.barrier.at
|
||||
)
|
||||
).toBe(true);
|
||||
return context.barrier.at === input.f.start + input.f.minute
|
||||
? {
|
||||
mode: 'target',
|
||||
targets: [{ instrumentId: 'X0.US', quantity: parseFinancialDecimal('2') }],
|
||||
}
|
||||
: { mode: 'target', targets: [] };
|
||||
}
|
||||
);
|
||||
expect(decisions).toBe(2);
|
||||
expect(String(result.view.portfolio.cash)).toBe('9975.76000000');
|
||||
expect(String(result.view.equity)).toBe('10005.76000000');
|
||||
expect<unknown>(result.view.portfolio.fees).toEqual([{ ownerId: 'A', amount: '0.24000000' }]);
|
||||
});
|
||||
|
||||
test('mounted security denies read-token writes and untrusted browser origins', async () => {
|
||||
const f = fixture();
|
||||
const payload = JSON.stringify({ metadata: source().metadata });
|
||||
const denied = await f.app.request('/api/v2/datasets/canonical/stored-source', {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
Authorization: 'Bearer stored-source-read-fixture-not-a-real-secret',
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
body: payload,
|
||||
});
|
||||
expect(denied.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 }),
|
||||
});
|
||||
const cookie = login.headers.get('Set-Cookie')?.split(';')[0];
|
||||
if (!cookie) {
|
||||
throw new Error('Missing authenticated session');
|
||||
}
|
||||
const browser = (origin?: string) =>
|
||||
f.app.request('/api/v2/datasets/canonical/stored-source', {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
Cookie: cookie,
|
||||
'Content-Type': 'application/json',
|
||||
...(origin ? { Origin: origin } : {}),
|
||||
},
|
||||
body: payload,
|
||||
});
|
||||
expect((await browser()).status).toBe(403);
|
||||
expect((await browser('https://foreign.invalid')).status).toBe(403);
|
||||
expect(f.read).not.toHaveBeenCalled();
|
||||
expect((await browser('http://localhost')).status).toBe(200);
|
||||
expect(f.read).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
});
|
||||
276
test/postgres/stored-dataset-preparation.test.ts
Normal file
276
test/postgres/stored-dataset-preparation.test.ts
Normal file
|
|
@ -0,0 +1,276 @@
|
|||
import { randomUUID } from 'node:crypto';
|
||||
import { readFileSync } from 'node:fs';
|
||||
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 type { MongoDBClient } from '@stock-bot/services';
|
||||
import type { CanonicalStoredSourcePreparation } from '@stock-bot/stock-config/canonical-research';
|
||||
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 { nativeReplayFixture } from '../fixtures/native-replay';
|
||||
|
||||
setLoggerConfig({ logLevel: 'fatal', logConsole: false });
|
||||
const logger = getLogger('stored-source-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;
|
||||
}
|
||||
function source() {
|
||||
const { dataset } = nativeReplayFixture(3);
|
||||
const { calendars, series, executionSeries, bounds, universe, corporateActions } =
|
||||
dataset.manifest;
|
||||
const metadata = {
|
||||
calendars,
|
||||
series: series.map(value => ({
|
||||
...value,
|
||||
source: { provider: 'eod', revision: 'operator-declared-v1' },
|
||||
availability: 'interval-end-assumption' as const,
|
||||
})),
|
||||
executionSeries,
|
||||
bounds,
|
||||
universe,
|
||||
corporateActions,
|
||||
};
|
||||
const rows = dataset.bars.map(bar => ({
|
||||
symbol: 'X0',
|
||||
exchange: 'US',
|
||||
eodSearchCode: 'X0.US',
|
||||
timestamp: bar.intervalStart / 1000,
|
||||
open: bar.open,
|
||||
high: bar.high,
|
||||
low: bar.low,
|
||||
close: bar.close,
|
||||
volume: bar.volume,
|
||||
}));
|
||||
return { metadata, rows };
|
||||
}
|
||||
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 input = source();
|
||||
let reads = 0;
|
||||
const mongodb = {
|
||||
async find() {
|
||||
reads++;
|
||||
return structuredClone(input.rows);
|
||||
},
|
||||
} as unknown as MongoDBClient;
|
||||
const routes = new Hono().route('/', createDatasetRoutes({ postgres, mongodb, logger }));
|
||||
const post = (operation: 'stored-source' | '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 {
|
||||
input,
|
||||
get reads() {
|
||||
return reads;
|
||||
},
|
||||
pool,
|
||||
schema,
|
||||
post,
|
||||
routes,
|
||||
snapshot,
|
||||
defaults,
|
||||
get queryCount() {
|
||||
return queryCount;
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
describe.skipIf(!url)('stored source materialization and immutable retention on PostgreSQL', () => {
|
||||
test('source read writes nothing; edits after capture cannot change exact retention/retry, and a fresh read has a different identity', async () => {
|
||||
const f = await fixture();
|
||||
const before = await f.snapshot(),
|
||||
defaults = await f.defaults();
|
||||
const initial = await f.post('stored-source', { metadata: f.input.metadata });
|
||||
expect(initial.status).toBe(200);
|
||||
expect(initial.headers.get('Cache-Control')).toBe('no-store');
|
||||
const captured = (await initial.json()) as CanonicalStoredSourcePreparation;
|
||||
expect(f.reads).toBe(1);
|
||||
expect(f.queryCount).toBe(0);
|
||||
expect(await f.snapshot()).toEqual(before);
|
||||
expect(captured.preparation.hash).toBe(createDatasetV2(captured.input).manifest.hash);
|
||||
at(f.input.rows).close = 10.5;
|
||||
const newer = await f.post('stored-source', { metadata: f.input.metadata });
|
||||
expect(newer.status).toBe(200);
|
||||
const refreshed = (await newer.json()) as CanonicalStoredSourcePreparation;
|
||||
expect(f.reads).toBe(2);
|
||||
expect(refreshed.preparation.hash).not.toBe(captured.preparation.hash);
|
||||
expect(at(refreshed.input.bars).close).toBe(10.5);
|
||||
expect(at(captured.input.bars).close).toBe(11);
|
||||
expect(await f.snapshot()).toEqual(before);
|
||||
const retainBody = { input: captured.input, expectedHash: captured.preparation.hash };
|
||||
for (const response of await Promise.all([
|
||||
f.post('retain', retainBody),
|
||||
f.post('retain', retainBody),
|
||||
])) {
|
||||
expect(response.status).toBe(200);
|
||||
expect(await response.json()).toEqual({ preparation: captured.preparation });
|
||||
}
|
||||
const rows = (await f.pool.query('SELECT * FROM backtest_datasets')).rows;
|
||||
expect(rows).toHaveLength(1);
|
||||
const saved = validateDatasetV2(at(rows).payload);
|
||||
expect(saved).toEqual(createDatasetV2(captured.input));
|
||||
expect(saved.manifest.hash).toBe(captured.preparation.hash);
|
||||
expect(saved.bars.every(bar => bar.vwap === null && bar.availableAt === bar.intervalEnd)).toBe(
|
||||
true
|
||||
);
|
||||
expect(f.reads).toBe(2);
|
||||
const retry = await f.post('retain', retainBody);
|
||||
expect(retry.status).toBe(200);
|
||||
expect((await f.pool.query('SELECT * FROM backtest_datasets')).rows).toEqual(rows);
|
||||
expect(f.reads).toBe(2);
|
||||
const lookup = await f.routes.request(
|
||||
`/api/v2/datasets/canonical/${captured.preparation.hash}`
|
||||
);
|
||||
expect((await lookup.json()).dataset).toMatchObject({
|
||||
available: true,
|
||||
hash: captured.preparation.hash,
|
||||
manifest: captured.preparation.manifest,
|
||||
});
|
||||
expect(await readCanonicalDataset(f.pool, captured.preparation.hash)).toEqual(saved);
|
||||
const { backtest_datasets: _datasets, ...untouched } = before;
|
||||
expect(await f.snapshot(false)).toEqual(untouched);
|
||||
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' },
|
||||
]);
|
||||
});
|
||||
|
||||
test('stored previews cannot bypass scope/hash validation or overwrite corrupt retained custody', async () => {
|
||||
const f = await fixture();
|
||||
const initial = await f.post('stored-source', { metadata: f.input.metadata });
|
||||
const captured = (await initial.json()) as CanonicalStoredSourcePreparation;
|
||||
const before = await f.snapshot();
|
||||
const wrong = {
|
||||
...f.input.metadata,
|
||||
series: f.input.metadata.series.map(value => ({
|
||||
...value,
|
||||
source: { ...value.source, provider: 'auto' },
|
||||
})),
|
||||
};
|
||||
expect((await f.post('stored-source', { metadata: wrong })).status).toBe(400);
|
||||
expect(f.reads).toBe(1);
|
||||
expect(
|
||||
(await f.post('retain', { input: captured.input, expectedHash: '0'.repeat(64) })).status
|
||||
).toBe(409);
|
||||
expect(await f.snapshot()).toEqual(before);
|
||||
const dataset = createDatasetV2(captured.input);
|
||||
const corrupt = {
|
||||
...dataset,
|
||||
bars: dataset.bars.map((bar, index) => (index === 0 ? { ...bar, close: 10.5 } : bar)),
|
||||
};
|
||||
expect(corrupt).not.toEqual(dataset);
|
||||
await f.pool.query('INSERT INTO backtest_datasets(hash,payload) VALUES($1,$2)', [
|
||||
dataset.manifest.hash,
|
||||
corrupt,
|
||||
]);
|
||||
const damaged = await f.snapshot();
|
||||
const response = await f.post('retain', {
|
||||
input: captured.input,
|
||||
expectedHash: captured.preparation.hash,
|
||||
});
|
||||
expect(response.status).toBe(500);
|
||||
expect(await response.json()).toEqual({ error: 'Source dataset retention unavailable' });
|
||||
expect(await f.snapshot()).toEqual(damaged);
|
||||
expect(f.reads).toBe(1);
|
||||
});
|
||||
});
|
||||
Loading…
Add table
Add a link
Reference in a new issue