refactor: pre-M0 cleanup, core library hardening, and isolated dev/QA Docker stack

- Remove ~44k LOC of dead code, legacy v1 TS simulator/strategy stack, event-bus, analytics FastAPI prototype, legacy calculation archives, and unused deps (data-ingestion provider API handlers untouched)
- Extract @stock-bot/di/http-security and isolate @stock-bot/browser to data-ingestion via ServiceContainerBuilder.withRegistrations()
- Harden @stock-bot/mongodb read-only proxies, flatten @stock-bot/postgres with unified master+research migrations, and fix @stock-bot/config EnvLoader, ServiceApplication worker lifecycle, NamespacedCache.clear(), and BatchProcessor error propagation
- Flatten workspace root (remove apps/stock/package.json) and collapse orchestrator re-export shims
- Pin all Docker image versions, add shm_size/nofile/RAM caps and docker-compose.quant.yml, fix 05-add-visible-column.sql view recreation, and decouple dev/QA Compose project names for side-by-side execution
- Update PLATFORM-PLAN, DATA-CONTRACTS (bars_1m PARTITION BY MONTH, Rust bulk ETL, DuckDB limits), MILESTONES, and servers docs
This commit is contained in:
Boki 2026-11-27 00:11:50 -05:00
parent ce9e2df67c
commit 4cd6038063
432 changed files with 1247 additions and 44469 deletions

View file

@ -11,7 +11,7 @@ import {
type CanonicalRunResult,
} from '@stock-bot/stock-config/canonical-research';
import { BacktestRunner } from '../../apps/stock/orchestrator/src/backtest/BacktestRunner';
import { readCanonicalBuildIdentity } from '../../apps/stock/orchestrator/src/backtest/canonical-build';
import { readCanonicalBuildIdentity } from '@stock-bot/trading-runtime/canonical-build';
import { LegacyBacktestRunWriter } from '../../apps/stock/orchestrator/src/backtest/compatibility/LegacyBacktestRunWriter';
import { BacktestCancelledError } from '../../apps/stock/orchestrator/src/backtest/execution-engine';
import { PostgresBacktestRunRepository } from '../../apps/stock/orchestrator/src/backtest/PostgresBacktestRunRepository';

View file

@ -5,12 +5,12 @@ import { Pool } from 'pg';
import { stageFinancialTransaction } from '@stock-bot/engine';
import { PostgreSQLClient } from '@stock-bot/postgres';
import { parseFinancialDecimal } from '@stock-bot/types';
import { builtinStrategySelectionSchema } from '../../apps/stock/orchestrator/src/contracts/builtin-strategy';
import { builtinStrategySelectionSchema } from '@stock-bot/stock-config/strategy';
import {
parseFinancialTransactionResult,
type CanonicalMatchingConfig,
} from '../../apps/stock/orchestrator/src/contracts/canonical-execution';
import type { StrategyProgram } from '../../apps/stock/orchestrator/src/contracts/canonical-strategy';
} from '@stock-bot/stock-config/canonical-execution';
import type { StrategyProgram } from '@stock-bot/research/strategy-api';
import {
canonicalPaperInputSchema,
type CanonicalExecutionRepository,
@ -20,7 +20,6 @@ import {
} from '../../apps/stock/orchestrator/src/execution/canonical-paper';
import { CanonicalPaperExecution } from '../../apps/stock/orchestrator/src/execution/CanonicalPaperExecution';
import { PostgresCanonicalExecutionRepository } from '../../apps/stock/orchestrator/src/execution/PostgresCanonicalExecutionRepository';
import { PostgresExecutionRepository } from '../../apps/stock/orchestrator/src/execution/PostgresExecutionRepository';
import { createBuiltinStrategy } from '../../apps/stock/orchestrator/src/strategies/canonical-builtins';
import { StrategyController } from '../../apps/stock/orchestrator/src/strategies/strategy-controller';
import {
@ -535,20 +534,10 @@ describe.skipIf(!url)('canonical paper custody on real PostgreSQL', () => {
]) {
await expect(f.make({ programs: [program] })).rejects.toThrow('definition');
}
const legacy = new PostgresExecutionRepository(f.postgres);
await expect(legacy.transact(f.config.risk.ledger.accountId, async () => null)).rejects.toThrow(
'canonical adapter'
);
await expect(legacy.initialize(f.config.risk.ledger.accountId, {} as never)).rejects.toThrow(
'canonical adapter'
);
await f.pool.query(
'UPDATE simulation_accounts SET state = \'{"kind":"canonical-paper","version":99}\''
);
await expect(f.make()).rejects.toThrow('explicit migration');
await expect(legacy.transact(f.config.risk.ledger.accountId, async () => null)).rejects.toThrow(
'canonical adapter'
);
await f.pool.query('UPDATE simulation_accounts SET state = \'{"cash":100}\'');
await expect(f.make()).rejects.toThrow('explicit migration');
});

View file

@ -23,7 +23,7 @@ import { PostgresBacktestRunRepository } from '../../apps/stock/orchestrator/src
import { BacktestLeaseLostError } from '../../apps/stock/orchestrator/src/backtest/run-repository';
import { RustBacktestAdapter } from '../../apps/stock/orchestrator/src/backtest/RustBacktestAdapter';
import { loadDataset } from '../../apps/stock/orchestrator/src/data/historical-dataset';
import { StorageService } from '../../apps/stock/orchestrator/src/services/StorageService';
import { StorageService } from '@stock-bot/trading-runtime/historical-storage';
import { BacktestConfigSchema } from '../../apps/stock/orchestrator/src/types';
import { createBacktestV2Routes } from '../../apps/stock/web-api/src/routes/backtests-v2.routes';
import {

View file

@ -1,235 +0,0 @@
import { randomUUID } from 'node:crypto';
import { readFileSync } from 'node:fs';
import { afterEach, describe, expect, test } from 'bun:test';
import { Pool } from 'pg';
import { PostgreSQLClient } from '@stock-bot/postgres';
import { PostgresExecutionRepository } from '../../apps/stock/orchestrator/src/execution/PostgresExecutionRepository';
import { ExecutionConflictError } from '../../apps/stock/orchestrator/src/execution/repository';
import { config, logger, makeExecution, order, quote, start } from '../fixtures/execution';
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();
});
const sql = readFileSync(
new URL('../../database/postgres/init/11-simulation-execution-ledger.sql', import.meta.url),
'utf8'
);
await pool.query(sql);
await pool.query(sql);
await pool.query(
readFileSync(
new URL('../../database/postgres/init/13-strategy-recovery.sql', 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;
const make = async (
limits = {
maxOrderSize: 100,
maxPositionSize: 100,
maxDailyLoss: 100,
maxGrossExposure: 10000,
maxSymbolExposure: 10000,
}
) => {
const runtime = makeExecution(new PostgresExecutionRepository(postgres), () => now);
await runtime.execution.initialize(
{
mode: 'paper',
accountId: 'fixture',
startingCapital: config.initialCapital,
commission: 0.001,
slippage: 0,
maxQuoteAgeMs: 1000,
riskLimits: limits,
},
runtime.engine
);
cleanup.push(() => runtime.execution.shutdown());
return runtime.execution;
};
const execution = await make();
return {
pool,
postgres,
execution,
make,
setTime(time: number) {
now = time;
},
};
}
describe.skipIf(!url)('paper execution ledger on real PostgreSQL', () => {
test('competing service instances deduplicate the same client ID, fill and account transaction', async () => {
const f = await fixture();
const second = await f.make();
await f.execution.onMarketData(quote('q'));
const reports = await Promise.all([
f.execution.submitOrder(order('id')),
second.submitOrder(order('id')),
]);
expect(reports[0]).toEqual(reports[1]);
expect((await f.pool.query('SELECT * FROM simulation_orders')).rows).toHaveLength(1);
const fills = (await f.pool.query('SELECT payload FROM simulation_fills')).rows;
expect(fills).toHaveLength(1);
expect(fills[0].payload.pnl).toBe(-1);
expect((await second.getAccount()).cash).toBe(8999);
expect((await second.getPositions())[0]?.quantity).toBe(10);
await expect(second.submitOrder(order('id', 'buy', 11))).rejects.toBeInstanceOf(
ExecutionConflictError
);
});
test('a fill-write failure rolls back acceptance and cash/positions together; retry has no phantom fill', async () => {
const f = await fixture();
await f.execution.onMarketData(quote('q'));
let events = 0;
f.execution.on('fill', () => events++);
await f.pool.query(`CREATE FUNCTION reject_fill() RETURNS trigger LANGUAGE plpgsql AS $$ BEGIN
RAISE EXCEPTION 'injected fill failure'; END $$;
CREATE TRIGGER reject_fill BEFORE INSERT ON simulation_fills FOR EACH ROW EXECUTE FUNCTION reject_fill();`);
await expect(f.execution.submitOrder(order('id'))).rejects.toThrow('injected fill failure');
expect((await f.pool.query('SELECT * FROM simulation_orders')).rows).toHaveLength(0);
expect((await f.execution.getAccount()).cash).toBe(10000);
expect(events).toBe(0);
await f.pool.query('DROP TRIGGER reject_fill ON simulation_fills');
expect((await f.execution.submitOrder(order('id'))).status).toBe('filled');
expect(events).toBe(1);
});
test('restart restores partial orders, consumed liquidity, cash and strategy positions without refilling duplicates', async () => {
const f = await fixture();
await f.execution.onMarketData(quote('q1', 100, 3));
const first = await f.execution.submitOrder(order('id'), { strategyId: 'strategy' });
expect(first.status).toBe('partiallyFilled');
await f.execution.shutdown();
const second = await f.make();
expect((await second.getStrategySnapshot('strategy')).positions.A).toBe(3);
expect((await second.getStrategySnapshot('strategy')).orders).toHaveLength(1);
expect(await second.onMarketData(quote('q1', 100, 3))).toBe(false);
f.setTime(start + 1);
await second.onMarketData(quote('q2', 100, 7, start + 1));
expect((await second.getOrderStatus(first.orderId))?.status).toBe('filled');
expect((await second.getAccount()).cash).toBe(8999);
expect((await f.pool.query('SELECT * FROM simulation_fills')).rows).toHaveLength(2);
});
test('account locking serializes projected-risk reservations across producers', async () => {
const f = await fixture();
const limits = {
maxOrderSize: 100,
maxPositionSize: 100,
maxDailyLoss: 100,
maxGrossExposure: 1000,
maxSymbolExposure: 1000,
};
const first = await f.make(limits),
second = await f.make(limits);
await first.onMarketData(quote('q', 100, 0));
const reports = await Promise.all([
first.submitOrder(order('a', 'buy', 7)),
second.submitOrder(order('b', 'buy', 7)),
]);
expect(reports.map(r => r.status).sort()).toEqual(['accepted', 'rejected']);
expect((await f.execution.getAccount()).cash).toBe(10000);
});
test('duplicate and conflicting market IDs cannot reapply fills, even after a restart', async () => {
const f = await fixture();
await f.execution.onMarketData(quote('q', 100, 3));
const report = await f.execution.submitOrder(order('id'));
const second = await f.make();
await expect(second.onMarketData(quote('q', 200, 3))).rejects.toBeInstanceOf(
ExecutionConflictError
);
expect(await second.onMarketData(quote('q', 100, 3))).toBe(false);
expect((await second.getOrderStatus(report.orderId))?.fills).toHaveLength(1);
expect((await second.getAccount()).cash).toBe(9699.7);
});
test('daily P&L uses deltas; loss limit blocks new risk but permits reduction and resets at UTC midnight', async () => {
const f = await fixture();
const e = await f.make({
maxOrderSize: 100,
maxPositionSize: 100,
maxDailyLoss: 1,
maxGrossExposure: 10000,
maxSymbolExposure: 10000,
});
await e.onMarketData(quote('q'));
await e.submitOrder(order('open'));
expect((await e.submitOrder(order('blocked', 'buy', 1))).status).toBe('rejected');
expect((await e.submitOrder(order('close', 'sell', 10))).status).toBe('filled');
expect((await e.getAccount()).dailyPnl).toBe(-2);
f.setTime(start + 86400000);
await e.onMarketData(quote('new-day', 100, 100, start + 86400000));
expect((await e.getAccount()).dailyPnl).toBe(0);
expect((await e.submitOrder(order('new-day-order', 'buy', 1))).status).toBe('filled');
});
test('stale quotes reject submission; day orders expire and unfilled cancellation survives restart', async () => {
const f = await fixture();
await f.execution.onMarketData(quote('q', 100, 0));
const day = await f.execution.submitOrder(order('day'));
const gtc = await f.execution.submitOrder({ ...order('gtc'), timeInForce: 'GTC' });
f.setTime(start + 2000);
expect((await f.execution.submitOrder(order('stale'))).rejectionReason).toContain('stale');
await expect(f.execution.onMarketData(quote('old', 100, 100, start + 1))).rejects.toThrow(
'Stale'
);
f.setTime(start + 86400000);
await f.execution.onMarketData(quote('next', 100, 0, start + 86400000));
expect((await f.execution.getOrderStatus(day.orderId))?.status).toBe('cancelled');
expect(await f.execution.cancelOrder(gtc.orderId)).toBe(true);
const second = await f.make();
expect((await second.getOrderStatus(gtc.orderId))?.status).toBe('cancelled');
});
test('observer exceptions cannot change committed fills into reported failure or trigger another fill', async () => {
const f = await fixture();
await f.execution.onMarketData(quote('q'));
f.execution.setObserver(async () => {
throw new Error('observer disconnected');
});
const report = await f.execution.submitOrder(order('id'));
expect(report.status).toBe('filled');
expect((await f.execution.submitOrder(order('id'))).orderId).toBe(report.orderId);
expect((await f.pool.query('SELECT * FROM simulation_fills')).rows).toHaveLength(1);
});
test('pending orders retain their accepted commission policy after account configuration changes', async () => {
const f = await fixture();
await f.execution.onMarketData(quote('q1', 100, 3));
const original = await f.execution.submitOrder(order('pending'));
const changed = makeExecution(new PostgresExecutionRepository(f.postgres), () => start + 1);
await changed.execution.initialize(
{
mode: 'paper',
accountId: 'fixture',
startingCapital: 10000,
commission: 0.01,
slippage: 0,
},
changed.engine
);
cleanup.push(() => changed.execution.shutdown());
await changed.execution.onMarketData(quote('q2', 100, 10, start + 1));
const report = await changed.execution.getOrderStatus(original.orderId);
expect(report?.fills.reduce((n, fill) => n + fill.commission, 0)).toBe(1);
const next = await changed.execution.submitOrder(order('new', 'buy', 1));
expect(next.fills[0]?.commission).toBe(1);
});
});

View file

@ -13,8 +13,8 @@ import { PostgresCanonicalExecutionRepository } from '../../apps/stock/orchestra
import {
readPaperDeployment,
verifyPaperEvidenceCustody,
} from '../../apps/stock/orchestrator/src/paper/paper-deployment-custody';
import { readPaperHostIdentity } from '../../apps/stock/orchestrator/src/paper/paper-host-identity';
} from '@stock-bot/trading-runtime/paper-deployment-custody';
import { readPaperHostIdentity } from '@stock-bot/trading-runtime/paper-host-identity';
import { PaperDeploymentHost } from '../../apps/stock/orchestrator/src/paper/PaperDeploymentHost';
import { BacktestServiceV2 } from '../../apps/stock/web-api/src/services/backtest-v2.service';
import { ExperimentsService } from '../../apps/stock/web-api/src/services/experiments.service';

View file

@ -5,8 +5,8 @@ import { createHttpSecurity, ServiceContainerBuilder } from '@stock-bot/di';
import { parseFinancialDecimal } from '@stock-bot/types';
import { createPaperRoutes } from '../../apps/stock/orchestrator/src/api/rest/paper';
import { registerOrchestratorServices } from '../../apps/stock/orchestrator/src/container';
import { builtinStrategySelectionSchema } from '../../apps/stock/orchestrator/src/contracts/builtin-strategy';
import type { PaperRuntime } from '../../apps/stock/orchestrator/src/contracts/paper-runtime';
import { builtinStrategySelectionSchema } from '@stock-bot/stock-config/strategy';
import type { PaperRuntime } from '@stock-bot/stock-config/paper-runtime';
import { createBuiltinStrategy } from '../../apps/stock/orchestrator/src/strategies/canonical-builtins';
import type { OrchestratorServices } from '../../apps/stock/orchestrator/src/types';
import { canonicalAdmissionFixture } from '../fixtures/canonical-admission';

View file

@ -1,373 +0,0 @@
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.logger, null, 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,
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);
});
});