diff --git a/apps/stock/web-api/src/migrations/migration-runner.ts b/apps/stock/web-api/src/migrations/migration-runner.ts index 95dd2f58..a7c29384 100644 --- a/apps/stock/web-api/src/migrations/migration-runner.ts +++ b/apps/stock/web-api/src/migrations/migration-runner.ts @@ -18,67 +18,68 @@ export async function runMigrations(container: IServiceContainer): Promise } try { - // Create migrations table if it doesn't exist - await container.postgres.query(` + await container.postgres.transaction(async client => { + // All startup migrations share one database-scoped lock on this transaction's client. + // PostgreSQL releases it on commit/rollback, including when startup fails. + await client.query('SELECT pg_advisory_xact_lock($1, $2)', [0x53544254, 1]); + + // Create migrations table if it doesn't exist + await client.query(` CREATE TABLE IF NOT EXISTS migrations ( id SERIAL PRIMARY KEY, filename VARCHAR(255) NOT NULL UNIQUE, executed_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW() ) - `); + `); - // Get list of migration files from database/postgres/init - let directory = dirname(fileURLToPath(import.meta.url)); - while (!existsSync(join(directory, 'database', 'postgres', 'init'))) { - const parent = dirname(directory); - if (parent === directory) { - throw new Error('Cannot locate PostgreSQL migrations'); + // Get list of migration files from database/postgres/init while holding the lock. + let directory = dirname(fileURLToPath(import.meta.url)); + while (!existsSync(join(directory, 'database', 'postgres', 'init'))) { + const parent = dirname(directory); + if (parent === directory) { + throw new Error('Cannot locate PostgreSQL migrations'); + } + directory = parent; } - directory = parent; - } - const migrationsDir = join(directory, 'database', 'postgres', 'init'); - logger.info('Looking for migrations', { directory: migrationsDir }); + const migrationsDir = join(directory, 'database', 'postgres', 'init'); + logger.info('Looking for migrations', { directory: migrationsDir }); - const files = readdirSync(migrationsDir) - .filter( - f => - f.endsWith('.sql') && - (f.startsWith('001_') || - f === '09-backtest-run-contract.sql' || - f === '10-durable-backtest-dispatch.sql' || - f === '11-simulation-execution-ledger.sql' || - f === '12-historical-datasets.sql' || - f === '13-strategy-recovery.sql') - ) // Explicit additive migration allowlist; never replay destructive init migrations - .sort(); + const files = readdirSync(migrationsDir) + .filter( + f => + f.endsWith('.sql') && + (f.startsWith('001_') || + f === '09-backtest-run-contract.sql' || + f === '10-durable-backtest-dispatch.sql' || + f === '11-simulation-execution-ledger.sql' || + f === '12-historical-datasets.sql' || + f === '13-strategy-recovery.sql') + ) // Explicit additive migration allowlist; never replay destructive init migrations + .sort(); - logger.info('Found migration files:', files); + logger.info('Found migration files:', files); - for (const file of files) { - // Check if migration has already been run - const result = await container.postgres.query( - 'SELECT 1 FROM migrations WHERE filename = $1', - [file] - ); + for (const file of files) { + // Check and apply using the same locked client, not another pooled connection. + const result = await client.query('SELECT 1 FROM migrations WHERE filename = $1', [file]); - if (result.rows.length === 0) { - logger.info(`Running migration: ${file}`); + if (result.rows.length === 0) { + logger.info(`Running migration: ${file}`); - // Read and execute migration - const sql = readFileSync(join(migrationsDir, file), 'utf8'); - await container.postgres.transaction(async client => { + // Read and execute migration + const sql = readFileSync(join(migrationsDir, file), 'utf8'); await client.query(sql); await client.query( 'INSERT INTO migrations (filename) VALUES ($1) ON CONFLICT (filename) DO NOTHING', [file] ); - }); - logger.info(`Migration completed: ${file}`); - } else { - logger.debug(`Migration already executed: ${file}`); + logger.info(`Migration applied: ${file}`); + } else { + logger.debug(`Migration already executed: ${file}`); + } } - } + }); logger.info('All migrations completed successfully'); } catch (error) { diff --git a/test/postgres/migration-runner.test.ts b/test/postgres/migration-runner.test.ts new file mode 100644 index 00000000..0b451a4b --- /dev/null +++ b/test/postgres/migration-runner.test.ts @@ -0,0 +1,312 @@ +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 type { IServiceContainer } from '@stock-bot/handlers'; +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', +]; +const cleanup: (() => Promise)[] = []; +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; +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(resolve => { + release = resolve; + }); + return { promise, release }; +} + +async function until(check: () => Promise) { + 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 } as IServiceContainer), + }; + }; + 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('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 | 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); + }); +});