stock-bot/test/postgres/dataset-source-preparation.test.ts

307 lines
12 KiB
TypeScript

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