374 lines
15 KiB
TypeScript
374 lines
15 KiB
TypeScript
import { fork } from 'node:child_process';
|
|
import { randomUUID } from 'node:crypto';
|
|
import { readFileSync } from 'node:fs';
|
|
import { fileURLToPath } from 'node:url';
|
|
import { afterEach, describe, expect, test } from 'bun:test';
|
|
import { Pool } from 'pg';
|
|
import { PostgreSQLClient } from '@stock-bot/postgres';
|
|
import { ModeManager } from '../../apps/stock/orchestrator/src/core/ModeManager';
|
|
import { PostgresExecutionRepository } from '../../apps/stock/orchestrator/src/execution/PostgresExecutionRepository';
|
|
import type { ExecutionRepository } from '../../apps/stock/orchestrator/src/execution/repository';
|
|
import { ExecutionService } from '../../apps/stock/orchestrator/src/services/ExecutionService';
|
|
import { MarketDataService } from '../../apps/stock/orchestrator/src/services/MarketDataService';
|
|
import { StorageService } from '../../apps/stock/orchestrator/src/services/StorageService';
|
|
import { createBuiltinStrategyRegistry } from '../../apps/stock/orchestrator/src/strategies/builtin-strategies';
|
|
import { StrategyManager } from '../../apps/stock/orchestrator/src/strategies/StrategyManager';
|
|
import type { OrchestratorServices } from '../../apps/stock/orchestrator/src/types';
|
|
import { logger, makeExecution, quote, start } from '../fixtures/execution';
|
|
import {
|
|
attachCounter,
|
|
CounterStrategy,
|
|
makeStrategyManager,
|
|
recoveryConfig,
|
|
} from '../fixtures/strategy-recovery';
|
|
|
|
const url = process.env.PIPELINE_TEST_DATABASE_URL;
|
|
const cleanup: (() => Promise<void>)[] = [];
|
|
afterEach(async () => {
|
|
for (const close of cleanup.splice(0).reverse()) {
|
|
await close();
|
|
}
|
|
});
|
|
async function fixture() {
|
|
if (!url || !new URL(url).pathname.startsWith('/stock_bot_safety')) {
|
|
throw new Error('Dedicated 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 });
|
|
cleanup.push(async () => {
|
|
await pool.end();
|
|
await admin.query('DROP SCHEMA ' + schema + ' CASCADE');
|
|
await admin.end();
|
|
});
|
|
for (const migration of ['11-simulation-execution-ledger.sql', '13-strategy-recovery.sql']) {
|
|
await pool.query(
|
|
readFileSync(new URL('../../database/postgres/init/' + migration, import.meta.url), 'utf8')
|
|
);
|
|
}
|
|
const postgres = new PostgreSQLClient(
|
|
{ host: 'unused', port: 5432, database: 'unused', user: 'unused', password: 'unused' },
|
|
logger
|
|
);
|
|
Object.defineProperty(postgres, 'connectionPool', { get: () => pool });
|
|
Object.defineProperty(postgres, 'query', { value: pool.query.bind(pool) });
|
|
let now = start + 100;
|
|
const make = async (
|
|
accountId = 'fixture',
|
|
repository: ExecutionRepository = new PostgresExecutionRepository(postgres)
|
|
) => {
|
|
const runtime = makeExecution(repository, () => now);
|
|
await runtime.execution.initialize(
|
|
{
|
|
mode: 'paper',
|
|
accountId,
|
|
startingCapital: 10000,
|
|
commission: 0.001,
|
|
slippage: 0,
|
|
maxQuoteAgeMs: 1000,
|
|
},
|
|
runtime.engine
|
|
);
|
|
cleanup.push(() => runtime.execution.shutdown());
|
|
return runtime;
|
|
};
|
|
return {
|
|
pool,
|
|
postgres,
|
|
schema,
|
|
make,
|
|
setTime: (time: number) => {
|
|
now = time;
|
|
},
|
|
getTime: () => now,
|
|
};
|
|
}
|
|
|
|
describe.skipIf(!url)('strategy recovery on real PostgreSQL', () => {
|
|
test('paper mode restores registered strategies and drains their inbox before starting the feed', async () => {
|
|
const f = await fixture();
|
|
const original = await f.make();
|
|
const config = {
|
|
...recoveryConfig,
|
|
id: 'sma',
|
|
name: 'sma-crossover',
|
|
parameters: { initialCapital: 10000 },
|
|
};
|
|
const prior = makeStrategyManager({
|
|
execution: original.execution,
|
|
modeManager: { getTradingEngine: () => original.engine } as ModeManager,
|
|
});
|
|
await prior.initializeStrategies([config]);
|
|
await prior.onMarketData(quote('one'));
|
|
await prior.shutdown();
|
|
await original.execution.enqueueMarketData(quote('two', 100, 100, start + 1));
|
|
const services: OrchestratorServices = { logger, postgres: f.postgres };
|
|
const storage = new StorageService(services, null, f.postgres, null);
|
|
const execution = new ExecutionService(services, storage, { clock: f.getTime });
|
|
let feedStarted = false;
|
|
class OfflineMarket extends MarketDataService {
|
|
override async initialize() {
|
|
feedStarted = true;
|
|
expect((await execution.getRecoveryStatus()).pendingInputs).toBe(false);
|
|
expect((await execution.getRecoveryStatus()).strategies[0]?.lag).toBe(0);
|
|
}
|
|
}
|
|
const market: MarketDataService = new OfflineMarket({
|
|
logger,
|
|
storage,
|
|
drainStrategies: () => manager.drain(),
|
|
});
|
|
const registry = createBuiltinStrategyRegistry();
|
|
const manager: StrategyManager = new StrategyManager({
|
|
logger,
|
|
execution,
|
|
marketData: market,
|
|
createStrategy: config => registry.create(config, { execution, modeManager: mode }),
|
|
});
|
|
const mode: ModeManager = new ModeManager({
|
|
logger,
|
|
marketData: market,
|
|
execution,
|
|
storage,
|
|
strategies: manager,
|
|
});
|
|
cleanup.push(() => mode.shutdown());
|
|
await mode.initializeMode({
|
|
mode: 'paper',
|
|
accountId: 'fixture',
|
|
startingCapital: 10000,
|
|
commission: 0.001,
|
|
slippage: 0,
|
|
maxQuoteAgeMs: 1000,
|
|
});
|
|
expect(feedStarted).toBe(true);
|
|
expect(manager.getActiveStrategies()).toEqual(['sma']);
|
|
});
|
|
test.each(['decision', 'checkpoint', 'dispatch'] as const)(
|
|
'hard kill at %s resumes without skipped decisions or duplicate fills',
|
|
async phase => {
|
|
const f = await fixture();
|
|
const { execution } = await f.make();
|
|
const initial = await attachCounter(execution);
|
|
await initial.manager.shutdown();
|
|
await execution.enqueueMarketData(quote('one'));
|
|
const child = fork(
|
|
fileURLToPath(new URL('../fixtures/strategy-crash-owner.ts', import.meta.url)),
|
|
[],
|
|
{
|
|
execPath: process.execPath,
|
|
execArgv: [],
|
|
stdio: ['ignore', 'ignore', 'ignore', 'ipc'],
|
|
env: { ...process.env, STRATEGY_FIXTURE_SCHEMA: f.schema, STRATEGY_FIXTURE_PHASE: phase },
|
|
}
|
|
);
|
|
const exited = new Promise<void>(resolve => child.once('exit', () => resolve()));
|
|
cleanup.push(async () => {
|
|
child.kill('SIGKILL');
|
|
await exited;
|
|
});
|
|
await new Promise<void>((resolve, reject) => {
|
|
const timeout = setTimeout(() => reject(new Error('Crash fixture boundary timeout')), 5000);
|
|
child.once('message', message => {
|
|
clearTimeout(timeout);
|
|
if ((message as { phase: string }).phase === phase) {
|
|
resolve();
|
|
} else {
|
|
reject(new Error('Wrong crash boundary'));
|
|
}
|
|
});
|
|
child.once('exit', () => {
|
|
clearTimeout(timeout);
|
|
reject(new Error('Crash fixture exited before its boundary'));
|
|
});
|
|
});
|
|
child.kill('SIGKILL');
|
|
await exited;
|
|
const restarted = await f.make();
|
|
const resumed = await attachCounter(restarted.execution);
|
|
cleanup.push(() => resumed.manager.shutdown());
|
|
expect(resumed.strategy.count).toBe(1);
|
|
expect(resumed.strategy.getPosition('A')).toBe(1);
|
|
expect(resumed.strategy.getPerformance().trades).toBe(1);
|
|
expect((await f.pool.query('SELECT * FROM simulation_orders')).rows).toHaveLength(1);
|
|
expect((await f.pool.query('SELECT * FROM simulation_fills')).rows).toHaveLength(1);
|
|
await resumed.manager.onMarketData(quote('one'));
|
|
expect(resumed.strategy.count).toBe(1);
|
|
expect((await restarted.execution.getRecoveryStatus()).strategies[0]?.lag).toBe(0);
|
|
}
|
|
);
|
|
|
|
test('checkpoint and order-intent SQL writes roll back together on an injected trigger failure', async () => {
|
|
const f = await fixture();
|
|
const { execution } = await f.make();
|
|
const { manager, strategy } = await attachCounter(execution);
|
|
cleanup.push(() => manager.shutdown());
|
|
await f.pool
|
|
.query(`CREATE FUNCTION reject_intent() RETURNS trigger LANGUAGE plpgsql AS $$ BEGIN RAISE EXCEPTION 'injected intent failure'; END $$;
|
|
CREATE TRIGGER reject_intent BEFORE INSERT ON simulation_strategy_intents FOR EACH ROW EXECUTE FUNCTION reject_intent()`);
|
|
await expect(manager.onMarketData(quote('one'))).rejects.toThrow('intent failure');
|
|
expect(strategy.count).toBe(0);
|
|
expect(
|
|
(await f.pool.query('SELECT payload FROM simulation_strategy_checkpoints')).rows[0].payload
|
|
.cursor
|
|
).toBe(0);
|
|
expect((await f.pool.query('SELECT * FROM simulation_strategy_intents')).rows).toHaveLength(0);
|
|
await f.pool.query('DROP TRIGGER reject_intent ON simulation_strategy_intents');
|
|
await manager.recover();
|
|
expect(strategy.count).toBe(1);
|
|
expect(strategy.getPosition('A')).toBe(1);
|
|
});
|
|
|
|
test('input admission survives a rollback before quote application and journal creation', async () => {
|
|
const f = await fixture();
|
|
const { execution } = await f.make();
|
|
const { manager } = await attachCounter(execution);
|
|
cleanup.push(() => manager.shutdown());
|
|
await f.pool
|
|
.query(`CREATE FUNCTION reject_input_apply() RETURNS trigger LANGUAGE plpgsql AS $$ BEGIN RAISE EXCEPTION 'injected application failure'; END $$;
|
|
CREATE TRIGGER reject_input_apply BEFORE UPDATE ON simulation_market_inputs FOR EACH ROW EXECUTE FUNCTION reject_input_apply()`);
|
|
await expect(manager.onMarketData(quote('one'))).rejects.toThrow('application failure');
|
|
expect((await execution.getAccount()).quotes.A).toBeUndefined();
|
|
expect((await f.pool.query('SELECT * FROM simulation_strategy_journal')).rows).toHaveLength(0);
|
|
expect((await execution.getRecoveryStatus()).pendingInputs).toBe(true);
|
|
await manager.shutdown();
|
|
await f.pool.query('DROP TRIGGER reject_input_apply ON simulation_market_inputs');
|
|
const restarted = await f.make();
|
|
const resumed = await attachCounter(restarted.execution);
|
|
cleanup.push(() => resumed.manager.shutdown());
|
|
expect(resumed.strategy.count).toBe(1);
|
|
expect(resumed.strategy.getPosition('A')).toBe(1);
|
|
});
|
|
|
|
test('competing owners restore the locked checkpoint before every decision and consume one intent', async () => {
|
|
const f = await fixture();
|
|
const one = await f.make(),
|
|
two = await f.make();
|
|
const first = await attachCounter(one.execution),
|
|
second = await attachCounter(two.execution);
|
|
cleanup.push(
|
|
() => first.manager.shutdown(),
|
|
() => second.manager.shutdown()
|
|
);
|
|
await one.execution.enqueueMarketData(quote('one'));
|
|
await Promise.all([first.manager.recover(), second.manager.recover()]);
|
|
await Promise.all([first.manager.recover(), second.manager.recover()]);
|
|
expect(first.strategy.count).toBe(1);
|
|
expect(second.strategy.count).toBe(1);
|
|
expect(first.strategy.getPosition('A')).toBe(1);
|
|
expect(second.strategy.getPosition('A')).toBe(1);
|
|
expect((await f.pool.query('SELECT * FROM simulation_fills')).rows).toHaveLength(1);
|
|
});
|
|
|
|
test('stale admitted inputs restore indicators but never fabricate stale paper fills', async () => {
|
|
const f = await fixture();
|
|
const { execution } = await f.make();
|
|
const { manager, strategy } = await attachCounter(execution);
|
|
cleanup.push(() => manager.shutdown());
|
|
await execution.enqueueMarketData(quote('one'));
|
|
f.setTime(start + 5000);
|
|
await manager.recover();
|
|
expect(strategy.count).toBe(1);
|
|
expect(strategy.getPosition('A')).toBe(0);
|
|
const orders = (await f.pool.query('SELECT payload FROM simulation_orders')).rows;
|
|
expect(orders[0].payload.report.status).toBe('rejected');
|
|
expect((await f.pool.query('SELECT * FROM simulation_fills')).rows).toHaveLength(0);
|
|
});
|
|
|
|
test('real SMA indicator checkpoints reproduce an uninterrupted run across process replacement', async () => {
|
|
const f = await fixture();
|
|
const smaConfig = {
|
|
...recoveryConfig,
|
|
id: 'sma',
|
|
name: 'sma-crossover',
|
|
parameters: { initialCapital: 10000 },
|
|
};
|
|
const makeManager = async (account: string) => {
|
|
const runtime = await f.make(account);
|
|
const manager = makeStrategyManager({
|
|
execution: runtime.execution,
|
|
modeManager: { getTradingEngine: () => runtime.engine } as ModeManager,
|
|
});
|
|
await manager.initializeStrategies([smaConfig]);
|
|
cleanup.push(() => manager.shutdown());
|
|
return { ...runtime, manager };
|
|
};
|
|
const bars = Array.from({ length: 45 }, (_, index) => {
|
|
const price = 100 + Math.sin(index / 3) * 8;
|
|
return {
|
|
type: 'bar' as const,
|
|
eventId: 'bar-' + index,
|
|
data: {
|
|
symbol: 'A',
|
|
timestamp: start + index * 86400000,
|
|
open: price,
|
|
high: price + 1,
|
|
low: price - 1,
|
|
close: price,
|
|
volume: 100000,
|
|
},
|
|
};
|
|
});
|
|
const baseline = await makeManager('baseline');
|
|
for (const bar of bars) {
|
|
f.setTime(bar.data.timestamp);
|
|
await baseline.manager.onMarketData(bar);
|
|
}
|
|
f.setTime(start);
|
|
const interrupted = await makeManager('interrupted');
|
|
for (const bar of bars.slice(0, 22)) {
|
|
f.setTime(bar.data.timestamp);
|
|
await interrupted.manager.onMarketData(bar);
|
|
}
|
|
await interrupted.manager.shutdown();
|
|
const restarted = await makeManager('interrupted');
|
|
for (const bar of bars.slice(22)) {
|
|
f.setTime(bar.data.timestamp);
|
|
await restarted.manager.onMarketData(bar);
|
|
}
|
|
const meaningfulState = (manager: StrategyManager) => {
|
|
const {
|
|
seenFills: _seenFills,
|
|
pendingOrders: _pendingOrders,
|
|
...state
|
|
} = manager.getStrategy('sma')!.captureCheckpoint() as Record<string, unknown>;
|
|
return state;
|
|
};
|
|
expect(meaningfulState(restarted.manager)).toEqual(meaningfulState(baseline.manager));
|
|
expect((await restarted.execution.getAccount()).cash).toBe(
|
|
(await baseline.execution.getAccount()).cash
|
|
);
|
|
expect(
|
|
(await f.pool.query("SELECT * FROM simulation_fills WHERE account_id = 'baseline'")).rows
|
|
.length
|
|
).toBeGreaterThan(0);
|
|
});
|
|
|
|
test('uncheckpointed ML paper strategies fail before model startup and migration replay preserves history', async () => {
|
|
const f = await fixture();
|
|
const { execution, engine } = await f.make();
|
|
const manager = makeStrategyManager({
|
|
execution,
|
|
modeManager: { getTradingEngine: () => engine } as ModeManager,
|
|
});
|
|
cleanup.push(() => manager.shutdown());
|
|
await expect(
|
|
manager.initializeStrategies([{ ...recoveryConfig, name: 'ml-enhanced' }])
|
|
).rejects.toThrow('versioned checkpoint');
|
|
expect((await f.pool.query('SELECT * FROM simulation_strategy_checkpoints')).rows).toHaveLength(
|
|
0
|
|
);
|
|
const active = await attachCounter(execution);
|
|
cleanup.push(() => active.manager.shutdown());
|
|
await active.manager.onMarketData(quote('one'));
|
|
await f.pool.query(
|
|
readFileSync(
|
|
new URL('../../database/postgres/init/13-strategy-recovery.sql', import.meta.url),
|
|
'utf8'
|
|
)
|
|
);
|
|
expect((await f.pool.query('SELECT * FROM simulation_fills')).rows).toHaveLength(1);
|
|
expect((await execution.getRecoveryStatus()).strategies[0]?.lag).toBe(0);
|
|
});
|
|
});
|