feat(research): prepare stored EOD datasets before canonical admission

This commit is contained in:
Boki 2026-10-24 15:26:38 -04:00
parent 366bee810b
commit 0c6aec4dc6
16 changed files with 1897 additions and 61 deletions

View file

@ -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) {

View file

@ -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();