stock-bot/test/postgres/dataset-catalog.test.ts

364 lines
15 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 { HistoricalDatasetManifest } from '@stock-bot/types';
import { createDatasetRoutes } from '../../apps/stock/web-api/src/routes/datasets.routes';
import {
BacktestServiceV2,
type BacktestRequest,
} from '../../apps/stock/web-api/src/services/backtest-v2.service';
import { DatasetCatalogService } from '../../apps/stock/web-api/src/services/dataset-catalog.service';
setLoggerConfig({ logLevel: 'fatal', logConsole: false });
const logger = getLogger('dataset-catalog-test');
const url = process.env.PIPELINE_TEST_DATABASE_URL;
const cleanup: (() => Promise<void>)[] = [];
afterEach(async () => {
for (const close of cleanup.splice(0).reverse()) {
await close();
}
});
const hash = '1'.repeat(64);
const manifest = (key = hash): HistoricalDatasetManifest => ({
version: 1,
hash: key,
instruments: [{ id: 'FIXTURE.TEST', symbol: 'FIXTURE', exchange: 'TEST' }],
startDate: '2024-01-01T00:00:00.000Z',
endDate: '2024-01-03T00:00:00.000Z',
interval: '1d',
policy: { adjustment: 'raw', timestamp: 'utc-session-date' },
volumePolicy: 'reported',
qualityPolicy: 'reject-invalid-no-interpolation',
sources: [{ instrumentId: 'FIXTURE.TEST', provider: 'eod', revision: 'fixture-v1' }],
barCount: 1,
});
const request = (): BacktestRequest => ({
name: 'Dataset choice',
strategy: 'sma-crossover',
symbols: ['FIXTURE.TEST'],
startDate: manifest().startDate,
endDate: manifest().endDate,
initialCapital: 1000,
config: { fastPeriod: 2, slowPeriod: 3, datasetHash: hash, dataFrequency: '1d' },
});
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,
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',
'21-run-reproduction.sql',
'22-experiments.sql',
]) {
await pool.query(
readFileSync(new URL(`../../database/postgres/init/${name}`, import.meta.url), 'utf8')
);
}
const postgres = new PostgreSQLClient(
{ host: 'unused', port: 5432, database: 'unused', username: 'unused', password: 'unused' },
logger
);
Object.defineProperty(postgres, 'connectionPool', { get: () => pool });
Object.defineProperty(postgres, 'query', { value: pool.query.bind(pool) });
const insert = async (key: string, payload: unknown) =>
pool.query(
"INSERT INTO backtest_datasets(hash,payload,created_at) VALUES($1,$2::jsonb,'2024-02-01T00:00:00Z')",
[key, JSON.stringify(payload)]
);
const api = new BacktestServiceV2({ postgres, logger }, async () => {
throw new Error('Catalog must not fetch source data');
});
return {
pool,
schema,
postgres,
api,
insert,
catalog: new DatasetCatalogService(postgres),
routes: new Hono().route('/', createDatasetRoutes({ postgres, logger })),
};
}
describe.skipIf(!url)('dataset catalog and selected-run submission on real PostgreSQL', () => {
test('dataset_list_metadata_only projects no bars and diagnoses malformed shapes without SQL errors', async () => {
const f = await fixture();
await f.insert(hash, {
manifest: manifest(),
bars: [{ payloadMustStayInPostgres: 'SECRET_BAR_CONTENT' }],
});
const cases = [
null,
[],
'malformed',
{ manifest: manifest('2'.repeat(64)), bars: {} },
{ manifest: manifest('3'.repeat(64)), bars: [] },
{ manifest: manifest('4'.repeat(64)), bars: [1], extra: true },
{ manifest: { version: 2 }, bars: [] },
];
for (let index = 0; index < cases.length; index++) {
await f.insert(String(index + 2).repeat(64), cases[index]);
}
const result = await f.routes.request('/api/v2/datasets');
expect(result.status).toBe(200);
const body = await result.json();
expect(body.datasets).toHaveLength(8);
expect(body.datasets[0]).toMatchObject({
hash,
status: 'available',
coverage: 'unknown',
integrity: 'not-verified',
manifest: { barCount: 1 },
});
expect(body.datasets.at(-1)).toMatchObject({
version: 2,
status: 'unsupported',
manifest: null,
});
expect(body.datasets.at(-1).reason).toContain('R05');
expect(JSON.stringify(body)).not.toContain('SECRET_BAR_CONTENT');
expect(JSON.stringify(body)).not.toContain('"bars"');
for (const item of body.datasets.slice(1, -1)) {
expect(item.status).toBe('invalid');
}
const queries: string[] = [];
const projected = new DatasetCatalogService({
async query(text, values) {
queries.push(text);
const rows = await f.pool.query(text, values);
expect(rows.rows[0]).not.toHaveProperty('payload');
expect(rows.rows[0]).not.toHaveProperty('bars');
expect(rows.rows[0].bar_count).toBe(1);
return rows;
},
});
await projected.get(hash);
expect(queries[0]).not.toContain('SELECT *');
expect(queries[0]).toContain("payload->'manifest' AS manifest");
expect((await f.routes.request('/api/v2/datasets?limit=1&offset=1')).status).toBe(200);
expect((await f.routes.request(`/api/v2/datasets/${'f'.repeat(64)}`)).status).toBe(404);
expect((await f.routes.request('/api/v2/datasets/not-a-hash')).status).toBe(400);
});
test('select_hash_compatibility validates exact assets, interval, range, policy and explicit source on create and update', async () => {
const f = await fixture();
await f.insert(hash, { manifest: manifest(), bars: [{}] });
const saved = await f.api.createBacktest(request(), { autoStart: false });
for (const changed of [
{ symbols: ['OTHER.TEST'] },
{ startDate: '2024-01-02T00:00:00.000Z' },
{ endDate: '2024-01-04T00:00:00.000Z' },
{ config: { ...request().config, dataFrequency: '1h' } },
{
config: {
...request().config,
dataPolicy: { adjustment: 'provider-adjusted', timestamp: 'utc-session-date' },
},
},
{ config: { ...request().config, dataSource: 'questdb' } },
]) {
await expect(
f.api.createBacktest({ ...request(), ...changed }, { autoStart: false })
).rejects.toThrow('does not match');
await expect(f.api.updateBacktest(saved.id, changed)).rejects.toThrow('does not match');
}
expect((await f.api.getBacktest(saved.id))!.config).toEqual(request().config!);
expect((await f.pool.query('SELECT count(*)::int AS n FROM backtests')).rows[0].n).toBe(1);
for (const dataSource of ['eod', 'auto']) {
await expect(
f.api.updateBacktest(saved.id, { config: { ...request().config, dataSource } })
).resolves.not.toBeNull();
}
});
test('missing, inconsistent, malformed and unsupported selected snapshots reject before any run/outbox is inserted', async () => {
const f = await fixture();
const saved = await f.api.createBacktest(
{ ...request(), config: { fastPeriod: 2, slowPeriod: 3 } },
{ autoStart: false }
);
const payloads = [
{ manifest: manifest('f'.repeat(64)), bars: [{}] },
{ manifest: { ...manifest(), barCount: 2 }, bars: [{}] },
{ manifest: { ...manifest(), sources: [] }, bars: [{}] },
{ manifest: { version: 2 }, bars: [] },
];
for (const [index, payload] of payloads.entries()) {
const key = String(index + 1).repeat(64);
const row = structuredClone(payload);
// Preserve each malformed shape while matching the storage key except in the identity-mismatch case.
if (index > 0 && 'hash' in row.manifest) {
row.manifest.hash = key;
}
await f.insert(key, row);
await f.pool.query('UPDATE backtests SET config=$2 WHERE id=$1', [
saved.id,
JSON.stringify({ ...request().config, datasetHash: key }),
]);
await expect(f.api.createRun({ backtestId: saved.id })).rejects.toThrow();
}
await f.pool.query('UPDATE backtests SET config=$2 WHERE id=$1', [
saved.id,
{ ...request().config, datasetHash: 'e'.repeat(64) },
]);
await expect(f.api.createRun({ backtestId: saved.id })).rejects.toThrow('not found');
expect((await f.pool.query('SELECT count(*)::int AS n FROM runs')).rows[0].n).toBe(0);
expect((await f.pool.query('SELECT count(*)::int AS n FROM backtest_dispatch')).rows[0].n).toBe(
0
);
});
test('concurrent partial definition edits lock, merge and validate one committed definition', async () => {
const f = await fixture();
await f.insert(hash, { manifest: manifest(), bars: [{}] });
const saved = await f.api.createBacktest({ ...request(), config: {} }, { autoStart: false });
const blocker = await f.pool.connect();
await blocker.query('BEGIN');
await blocker.query('LOCK TABLE backtest_datasets IN ACCESS EXCLUSIVE MODE');
const selected = f.api.updateBacktest(saved.id, { config: request().config }).then(
value => ({ value, error: null }),
error => ({ value: null, error })
);
const isWaiting = async (pattern: string) => {
for (let attempt = 0; attempt < 100; attempt++) {
const result = await f.pool.query(
"SELECT 1 FROM pg_stat_activity WHERE application_name=$1 AND wait_event_type='Lock' AND query LIKE $2",
[f.schema, pattern]
);
if (result.rowCount) {
return true;
}
await new Promise(resolve => setTimeout(resolve, 5));
}
return false;
};
let catalogWait = false;
let definitionWait = false;
let changed: typeof selected | undefined;
try {
catalogWait = await isWaiting('%FROM backtest_datasets%');
changed = f.api.updateBacktest(saved.id, { endDate: '2024-01-04T00:00:00.000Z' }).then(
value => ({ value, error: null }),
error => ({ value: null, error })
);
definitionWait = await isWaiting('SELECT * FROM backtests WHERE id = $1 FOR UPDATE');
} finally {
await blocker.query('COMMIT');
blocker.release();
}
const winner = await selected;
if (!changed) {
throw new Error('Concurrent edit was not started');
}
const loser = await changed;
expect(catalogWait).toBe(true);
expect(definitionWait).toBe(true);
expect(winner.error).toBeNull();
expect(loser.error).toBeInstanceOf(Error);
expect(loser.error!.message).toContain('does not match');
const retained = await f.api.getBacktest(saved.id);
expect(retained!.endDate.toISOString()).toBe(manifest().endDate);
expect(retained!.config.datasetHash).toBe(hash);
expect((await f.api.createRun({ backtestId: saved.id })).dataset.requestedHash).toBe(hash);
});
test('selected run snapshots commit atomically and same-key retry returns its original receipt before mutable definition validation', async () => {
const f = await fixture();
await f.insert(hash, { manifest: manifest(), bars: [{}] });
const saved = await f.api.createBacktest(request(), { autoStart: false });
await f.pool.query(
`CREATE FUNCTION reject_dataset_outbox() RETURNS trigger LANGUAGE plpgsql AS $$ BEGIN RAISE EXCEPTION 'injected outbox failure'; END $$; CREATE TRIGGER reject_dataset_outbox BEFORE INSERT ON backtest_dispatch FOR EACH ROW EXECUTE FUNCTION reject_dataset_outbox()`
);
await expect(f.api.createRun({ backtestId: saved.id })).rejects.toThrow(
'injected outbox failure'
);
expect((await f.pool.query('SELECT count(*)::int AS n FROM runs')).rows[0].n).toBe(0);
await f.pool.query('DROP TRIGGER reject_dataset_outbox ON backtest_dispatch');
const submission = { principal: 'operator' as const, key: 'dataset-retry' };
const first = await f.api.createRun({ backtestId: saved.id }, submission);
expect(first.dataset).toEqual({
requestedHash: hash,
pinnedHash: null,
source: 'auto',
state: 'requested',
});
await f.pool.query(
'UPDATE backtests SET symbols=\'["OTHER.TEST"]\',config=\'{"datasetHash":"bad"}\' WHERE id=$1',
[saved.id]
);
await expect(f.pool.query('DELETE FROM backtest_datasets')).rejects.toThrow();
const retried = await f.api.createRun({ backtestId: saved.id }, submission);
expect(retried.id).toBe(first.id);
expect(retried.dataset).toEqual(first.dataset);
expect((await f.pool.query('SELECT count(*)::int AS n FROM backtest_dispatch')).rows[0].n).toBe(
1
);
await expect(
f.api.createRun({ backtestId: saved.id }, { ...submission, key: 'different' })
).rejects.toThrow();
});
test('source_request_freeze_status exposes immutable request and binding independently of run success or later template edits', async () => {
const f = await fixture();
await f.insert(hash, { manifest: manifest(), bars: [{}] });
const saved = await f.api.createBacktest(
{ ...request(), config: { dataSource: 'eod' } },
{ autoStart: false }
);
const run = await f.api.createRun({ backtestId: saved.id });
expect(run.dataset).toEqual({
requestedHash: null,
pinnedHash: null,
source: 'eod',
state: 'requested',
});
await f.pool.query("UPDATE runs SET status='running' WHERE id=$1", [run.id]);
expect((await f.api.getRun(run.id))!.dataset.state).toBe('preparing');
await f.pool.query("UPDATE runs SET status='failed' WHERE id=$1", [run.id]);
expect((await f.api.getRun(run.id))!.dataset.state).toBe('unavailable');
await f.pool.query('UPDATE runs SET dataset_hash=$2 WHERE id=$1', [run.id, hash]);
await f.pool.query('UPDATE backtests SET config=\'{"dataSource":"questdb"}\' WHERE id=$1', [
saved.id,
]);
expect(await f.api.getRun(run.id)).toMatchObject({
status: 'failed',
dataset: { requestedHash: null, pinnedHash: hash, source: 'eod', state: 'pinned' },
});
const legacyRunId = randomUUID();
await f.pool.query(
"INSERT INTO runs(id,backtest_id,run_number,status,dataset_hash) VALUES ($1,$2,2,'completed',$3)",
[legacyRunId, saved.id, hash]
);
expect((await f.api.getRun(legacyRunId))!.dataset).toEqual({
requestedHash: null,
pinnedHash: hash,
source: null,
state: 'unknown',
});
});
});