336 lines
13 KiB
TypeScript
336 lines
13 KiB
TypeScript
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(input = source(), scopedReads = false) {
|
|
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);
|
|
},
|
|
});
|
|
let reads = 0;
|
|
const mongodb = {
|
|
async find(_collection: string, filter: { timestamp: { $gte: number; $lt: number } }) {
|
|
reads++;
|
|
return structuredClone(
|
|
scopedReads
|
|
? input.rows.filter(
|
|
row => row.timestamp >= filter.timestamp.$gte && row.timestamp < filter.timestamp.$lt
|
|
)
|
|
: 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('declared sessions retain captured rows across an invalid intervening close marker without further source reads', async () => {
|
|
const input = source();
|
|
const first = input.metadata.bounds.warmupStart;
|
|
const day = 86_400_000;
|
|
const close = first + 180_000;
|
|
const originals = structuredClone(input.rows);
|
|
input.metadata = {
|
|
...input.metadata,
|
|
calendars: input.metadata.calendars.map(calendar => ({
|
|
...calendar,
|
|
endDate: '2024-01-03',
|
|
sessions: [
|
|
{ date: '2024-01-01', open: first, close },
|
|
{ date: '2024-01-02', open: first + day, close: close + day },
|
|
],
|
|
})),
|
|
bounds: { ...input.metadata.bounds, tradeEnd: close + day },
|
|
corporateActions: input.metadata.corporateActions.map(coverage => ({
|
|
...coverage,
|
|
end: close + day,
|
|
})),
|
|
};
|
|
input.rows = [
|
|
...originals,
|
|
{ ...at(originals), timestamp: close / 1000, volume: -1 },
|
|
...originals.map(row => ({ ...row, timestamp: row.timestamp + day / 1000 })),
|
|
];
|
|
const f = await fixture(input, true);
|
|
const before = await f.snapshot();
|
|
expect((await f.post('stored-source', { metadata: input.metadata })).status).toBe(500);
|
|
const response = await f.post('stored-source', {
|
|
metadata: input.metadata,
|
|
selection: 'declared-sessions',
|
|
});
|
|
expect(response.status).toBe(200);
|
|
const captured = (await response.json()) as CanonicalStoredSourcePreparation;
|
|
expect(captured.selection).toBe('declared-sessions');
|
|
expect(captured.input.bars).toHaveLength(6);
|
|
expect(captured.input.bars.map(bar => bar.sourceSequence)).toEqual([0, 1, 2, 3, 4, 5]);
|
|
expect(f.reads).toBe(3);
|
|
expect(await f.snapshot()).toEqual(before);
|
|
const expected = createDatasetV2(captured.input);
|
|
const retainBody = { input: captured.input, expectedHash: expected.manifest.hash };
|
|
input.rows.splice(0);
|
|
for (let attempt = 0; attempt < 2; attempt++) {
|
|
expect((await f.post('retain', retainBody)).status).toBe(200);
|
|
}
|
|
expect(f.reads).toBe(3);
|
|
const rows = (await f.pool.query('SELECT payload FROM backtest_datasets')).rows;
|
|
expect(rows).toHaveLength(1);
|
|
expect(validateDatasetV2(at(rows).payload)).toEqual(expected);
|
|
const { backtest_datasets: _datasets, ...unchangedBefore } = before;
|
|
expect(await f.snapshot(false)).toEqual(unchangedBefore);
|
|
});
|
|
|
|
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);
|
|
});
|
|
});
|