stock-bot/test/postgres/migration-runner.test.ts

347 lines
14 KiB
TypeScript

import { randomUUID } from 'node:crypto';
import { readFileSync } from 'node:fs';
import { afterEach, describe, expect, test } from 'bun:test';
import type { PoolClient } from 'pg';
import { Pool } from 'pg';
import { getLogger, setLoggerConfig } from '@stock-bot/logger';
import { PostgreSQLClient } from '@stock-bot/postgres';
import { runMigrations } from '../../apps/stock/web-api/src/migrations/migration-runner';
setLoggerConfig({ logLevel: 'fatal', logConsole: false });
const logger = getLogger('migration-runner-test');
const url = process.env.PIPELINE_TEST_DATABASE_URL;
const migrations = [
'09-backtest-run-contract.sql',
'10-durable-backtest-dispatch.sql',
'11-simulation-execution-ledger.sql',
'12-historical-datasets.sql',
'13-strategy-recovery.sql',
'14-backtest-submission.sql',
'15-canonical-paper-intents.sql',
];
const cleanup: (() => Promise<void>)[] = [];
afterEach(async () => {
for (const close of cleanup.splice(0).reverse()) {
await close();
}
});
type Query = { pid: number; sql: string; values: unknown[] };
type BeforeQuery = (query: Query, client: PoolClient) => Promise<void>;
const isPrecheck = (query: Query) => query.sql.startsWith('SELECT 1 FROM migrations');
const isRecord = (query: Query) => query.sql.startsWith('INSERT INTO migrations');
function gate() {
let release!: () => void;
const promise = new Promise<void>(resolve => {
release = resolve;
});
return { promise, release };
}
async function until(check: () => Promise<boolean>) {
const deadline = Date.now() + 3_000;
while (Date.now() < deadline) {
if (await check()) {
return;
}
await Bun.sleep(10);
}
throw new Error('Timed out waiting for the second PostgreSQL advisory-lock waiter');
}
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,
options: `-c search_path=${schema} -c statement_timeout=5000 -c lock_timeout=5000`,
});
cleanup.push(async () => {
await pool.end();
await admin.query(`DROP SCHEMA ${schema} CASCADE`);
await admin.end();
});
// Real historical bootstrap scripts establish the pre-additive schema only in this fixture.
for (const filename of [
'06-create-backtest-tables.sql',
'07-fix-execution-time-type.sql',
'08-create-runs-table.sql',
]) {
await pool.query(
readFileSync(new URL(`../../database/postgres/init/${filename}`, import.meta.url), 'utf8')
);
}
const startup = (beforeQuery?: BeforeQuery) => {
const queries: Query[] = [];
const postgres = new PostgreSQLClient(
{ host: 'unused', port: 5432, database: 'unused', username: 'unused', password: 'unused' },
logger
);
// Keep the production transaction manager and real PostgreSQL clients. Only observe queries
// and inject test barriers/failures; no production hooks or mocked transaction semantics.
Object.defineProperty(postgres, 'connectionPool', {
get: () => ({
async connect() {
const client = await pool.connect();
const pid = (await client.query('SELECT pg_backend_pid() AS pid')).rows[0].pid as number;
return new Proxy(client, {
get(target, property) {
if (property === 'query') {
return async (sql: string, values: unknown[] = []) => {
const query = { pid, sql, values };
queries.push(query);
await beforeQuery?.(query, client);
return client.query(sql, values);
};
}
const value = Reflect.get(target, property);
return typeof value === 'function' ? value.bind(target) : value;
},
});
},
}),
});
Object.defineProperty(postgres, 'query', {
value: () => {
throw new Error('Migration escaped the pinned transaction client');
},
});
return {
queries,
run: () => runMigrations({ postgres, logger }),
};
};
const recorded = async () =>
(await pool.query('SELECT filename FROM migrations ORDER BY filename')).rows.map(
row => row.filename as string
);
const relations = async () =>
(
await pool.query('SELECT tablename FROM pg_tables WHERE schemaname = $1 ORDER BY tablename', [
schema,
])
).rows.map(row => row.tablename);
return { pool, schema, startup, recorded, relations };
}
describe.skipIf(!url)('startup migrations on real PostgreSQL', () => {
test('submission migration preserves legacy NULL-key runs and enforces complete key records', async () => {
const f = await fixture();
for (const filename of migrations.filter(name => name !== '14-backtest-submission.sql')) {
await f.pool.query(
readFileSync(new URL(`../../database/postgres/init/${filename}`, import.meta.url), 'utf8')
);
}
const backtestId = randomUUID();
const runId = randomUUID();
await f.pool.query(
`INSERT INTO backtests (id,name,strategy,symbols,start_date,end_date,initial_capital)
VALUES ($1,'Legacy','sma-crossover','["A.US"]','2024-01-01','2024-02-01',10000)`,
[backtestId]
);
await f.pool.query(
"INSERT INTO runs (id,backtest_id,run_number,status,request_snapshot) VALUES ($1,$2,1,'completed','{\"legacy\":true}')",
[runId, backtestId]
);
await f.startup().run();
const row = (await f.pool.query('SELECT * FROM runs WHERE id = $1', [runId])).rows[0];
expect(row.request_snapshot).toEqual({ legacy: true });
expect(row.status).toBe('completed');
expect([row.submission_principal, row.submission_key, row.submission_hash]).toEqual([
null,
null,
null,
]);
await expect(
f.pool.query("UPDATE runs SET submission_key = 'incomplete' WHERE id = $1", [runId])
).rejects.toThrow('runs_submission_complete');
await f.startup().run();
expect((await f.pool.query('SELECT * FROM runs')).rows).toHaveLength(1);
});
test('two_concurrent_startups_same_client_lock and precheck_inside_lock', async () => {
const f = await fixture();
const firstAtPrecheck = gate();
const releaseFirst = gate();
const first = f.startup(async query => {
if (isPrecheck(query)) {
firstAtPrecheck.release();
await releaseFirst.promise;
}
});
const second = f.startup();
const firstRun = first.run();
let secondRun: Promise<void> | undefined;
try {
await Promise.race([
firstAtPrecheck.promise,
firstRun.then(() => {
throw new Error('First startup completed without reaching its migration precheck');
}),
]);
secondRun = second.run();
await until(async () => {
const pid = second.queries[0]?.pid;
if (!pid) {
return false;
}
return (
(
await f.pool.query(
"SELECT 1 FROM pg_locks WHERE pid = $1 AND locktype = 'advisory' AND NOT granted",
[pid]
)
).rowCount === 1
);
});
// The waiter must not initialize the table, discover/check migrations or apply SQL yet.
expect(second.queries.map(query => query.sql)).toEqual([
'BEGIN',
'SELECT pg_advisory_xact_lock($1, $2)',
]);
expect(second.queries.some(isPrecheck)).toBe(false);
} finally {
releaseFirst.release();
await Promise.all([firstRun, secondRun]);
}
expect(first.queries[0]?.pid).not.toBe(second.queries[0]?.pid);
for (const startup of [first, second]) {
expect(new Set(startup.queries.map(query => query.pid)).size).toBe(1);
expect(startup.queries.map(query => query.sql).filter(sql => sql === 'BEGIN')).toHaveLength(
1
);
expect(startup.queries[1]?.sql).toContain('pg_advisory_xact_lock');
expect(startup.queries[2]?.sql).toContain('CREATE TABLE IF NOT EXISTS migrations');
expect(startup.queries.at(-1)?.sql).toBe('COMMIT');
expect(startup.queries.filter(isPrecheck)).toHaveLength(migrations.length);
}
expect(first.queries.filter(isRecord).map(query => query.values[0])).toEqual(migrations);
expect(second.queries.filter(isRecord)).toHaveLength(0);
expect(await f.recorded()).toEqual(migrations);
});
test('migration_failure_rollback: late SQL failure rolls back earlier DDL and records, then retries', async () => {
const f = await fixture();
const before = await f.relations();
let injectFailure = true;
const startup = f.startup(async (query, client) => {
if (
injectFailure &&
query.sql.includes('CREATE TABLE IF NOT EXISTS simulation_market_inputs')
) {
injectFailure = false;
await client.query('SELECT 1 / 0');
}
});
await expect(startup.run()).rejects.toThrow('division by zero');
expect(startup.queries.at(-1)?.sql).toBe('ROLLBACK');
expect(await f.relations()).toEqual(before); // Includes rollback of migrations table itself.
expect(
(
await f.pool.query(
"SELECT 1 FROM information_schema.columns WHERE table_schema = $1 AND table_name = 'backtest_results' AND column_name = 'configuration'",
[f.schema]
)
).rowCount
).toBe(0);
await startup.run();
expect(await f.recorded()).toEqual(migrations);
});
test('migration_failure_rollback: record failure rolls back all applications and releases the lock for retry', async () => {
const f = await fixture();
await f.pool.query(`CREATE TABLE migrations (filename text PRIMARY KEY);
INSERT INTO migrations VALUES ('bootstrap-marker');
CREATE FUNCTION reject_migration_record() RETURNS trigger LANGUAGE plpgsql AS $$ BEGIN
IF NEW.filename = '13-strategy-recovery.sql' THEN RAISE EXCEPTION 'injected record failure'; END IF;
RETURN NEW; END $$;
CREATE TRIGGER reject_migration_record BEFORE INSERT ON migrations
FOR EACH ROW EXECUTE FUNCTION reject_migration_record()`);
const before = await f.relations();
await expect(f.startup().run()).rejects.toThrow('injected record failure');
expect(await f.relations()).toEqual(before);
expect(await f.recorded()).toEqual(['bootstrap-marker']);
await f.pool.query('DROP TRIGGER reject_migration_record ON migrations');
await f.startup().run();
expect(await f.recorded()).toEqual([...migrations, 'bootstrap-marker']);
});
test('destructive_init_excluded and current histories survive startup/reapplication', async () => {
const f = await fixture();
await f.startup().run();
const backtestId = randomUUID();
const runId = randomUUID();
const orderId = randomUUID();
const datasetHash = 'a'.repeat(64);
await f.pool.query(
`INSERT INTO backtests (id,name,strategy,symbols,start_date,end_date,initial_capital)
VALUES ($1,'Saved research','sma-crossover','["A"]','2024-01-01','2024-02-01',10000);
`,
[backtestId]
);
await f.pool.query('INSERT INTO backtest_datasets (hash,payload) VALUES ($1,$2)', [
datasetHash,
{ manifest: { hash: datasetHash }, bars: [{ close: 101 }] },
]);
await f.pool.query(
"INSERT INTO runs (id,backtest_id,run_number,status,dataset_hash,request_snapshot) VALUES ($1,$2,1,'completed',$3,$4)",
[runId, backtestId, datasetHash, { strategy: 'sma-crossover', initialCapital: 10000 }]
);
await f.pool.query(
`INSERT INTO backtest_results (run_id,metrics,equity_curve,ohlc_data,trades,positions,analytics,execution_time,configuration,engine)
VALUES ($1,'{"totalReturn":0.01}','[10000,10100]','[]','[{"id":"trade"}]','[]','{}',10,'{"seed":42}','native')`,
[runId]
);
await f.pool.query(
"INSERT INTO simulation_accounts (id,state) VALUES ('paper','{\"cash\":9990}')"
);
await f.pool.query(
"INSERT INTO simulation_orders (id,account_id,client_order_id,status,payload) VALUES ($1,'paper','intent','filled','{\"quantity\":1}')",
[orderId]
);
await f.pool.query("INSERT INTO simulation_fills VALUES ('paper','fill',$1,'{\"fee\":1}')", [
orderId,
]);
await f.pool.query(`INSERT INTO simulation_events VALUES ('paper','quote','fingerprint');
INSERT INTO simulation_market_inputs VALUES ('paper','quote',1,'applied','{"close":100}');
INSERT INTO simulation_strategy_journal VALUES ('paper',1,'{"event":"quote"}');
INSERT INTO simulation_strategy_checkpoints VALUES ('paper','sma','{"cursor":1,"position":1}');
INSERT INTO simulation_strategy_intents VALUES ('paper','intent','sma',1,'dispatched','{"quantity":1}')`);
const tables = (await f.relations()).filter(table => table !== 'migrations');
const snapshot = () =>
Promise.all(
tables.map(
async table =>
(
await f.pool.query(
`SELECT to_jsonb(t) AS row FROM ${table} t ORDER BY to_jsonb(t)::text`
)
).rows
)
);
const before = await snapshot();
// The schema/data may predate migration tracking. Reapplying approved additive SQL is safe.
await f.pool.query('DELETE FROM migrations');
const startup = f.startup();
await startup.run();
expect(await snapshot()).toEqual(before);
expect(startup.queries.filter(isPrecheck).map(query => query.values[0])).toEqual(migrations);
expect(startup.queries.filter(isRecord).map(query => query.values[0])).toEqual(migrations);
expect(await f.recorded()).toEqual(migrations);
// In particular 08 would try renaming a removed column, and 02 drops existing schema objects.
expect((await f.pool.query('SELECT count(*)::int AS count FROM runs')).rows[0].count).toBe(1);
expect(
(await f.pool.query('SELECT count(*)::int AS count FROM simulation_fills')).rows[0].count
).toBe(1);
expect(
(await f.pool.query('SELECT count(*)::int AS count FROM simulation_strategy_checkpoints'))
.rows[0].count
).toBe(1);
});
});