feat(research): cut over canonical runtime and enforce agent budgets

This commit is contained in:
Boki 2026-10-24 16:47:19 -04:00
parent ab08db82fd
commit bbf0dd4453
103 changed files with 6138 additions and 3112 deletions

View file

@ -1,91 +1,28 @@
import { createHash, randomUUID } from 'node:crypto';
import { readFileSync } from 'node:fs';
import { asValue } from 'awilix';
import { afterEach, describe, expect, spyOn, test } from 'bun:test';
import { Pool } from 'pg';
import { afterEach, describe, expect, test } from 'bun:test';
import { ServiceContainerBuilder } from '@stock-bot/di';
import { PostgreSQLClient } from '@stock-bot/postgres';
import { BacktestCancelledError } from '../../apps/stock/orchestrator/src/backtest/execution-engine';
import { registerOrchestratorServices } from '../../apps/stock/orchestrator/src/container';
import { canonicalJson } from '../../apps/stock/orchestrator/src/execution/strategy-recovery';
import {
BacktestConfigSchema,
type OrchestratorServices,
} from '../../apps/stock/orchestrator/src/types';
import { logger, quote } from '../fixtures/execution';
import { CounterStrategy } from '../fixtures/strategy-recovery';
import type { OrchestratorServices } from '../../apps/stock/orchestrator/src/types';
import { canonicalAdmissionFixture } from '../fixtures/canonical-admission';
import { logger } from '../fixtures/execution';
import { paperFixture, paperFrame } from '../fixtures/paper-runtime';
const url = process.env.PIPELINE_TEST_DATABASE_URL;
const cleanup: (() => Promise<void>)[] = [];
afterEach(async () => {
for (const close of cleanup.splice(0).reverse()) await close();
for (const close of cleanup.splice(0).reverse()) {
await close();
}
});
const research = BacktestConfigSchema.parse({
mode: 'backtest',
strategy: 'sma-crossover',
symbols: ['RESEARCH.TEST'],
startDate: '2024-01-01T00:00:00.000Z',
endDate: '2024-03-15T00:00:00.000Z',
initialCapital: 100000,
dataFrequency: '1d',
commission: 0,
slippage: 0,
config: { fastPeriod: 3, slowPeriod: 7 },
});
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();
});
await pool.query(`CREATE TYPE run_status AS ENUM ('pending','running','completed','failed','cancelled','paused');
CREATE TABLE backtests (id uuid PRIMARY KEY, name text, strategy text, symbols jsonb,
start_date timestamptz, end_date timestamptz, initial_capital numeric, config jsonb,
created_at timestamptz DEFAULT NOW(), updated_at timestamptz DEFAULT NOW());
CREATE TABLE runs (id uuid PRIMARY KEY, backtest_id uuid REFERENCES backtests(id), run_number integer,
status run_status DEFAULT 'pending', speed_multiplier numeric, progress numeric DEFAULT 0, error text,
started_at timestamptz, completed_at timestamptz, paused_at timestamptz, current_simulation_date timestamptz,
created_at timestamptz DEFAULT NOW(), updated_at timestamptz DEFAULT NOW(), UNIQUE(backtest_id, run_number));
CREATE TABLE backtest_results (run_id uuid REFERENCES runs(id), completed_at timestamptz,
metrics jsonb, equity_curve jsonb, ohlc_data jsonb, trades jsonb, positions jsonb, analytics jsonb,
execution_time numeric);`);
for (const filename of [
'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',
'16-strategy-catalog.sql',
'17-research-retention.sql',
'18-backtest-strategy-versions.sql',
'19-canonical-research.sql',
'21-run-reproduction.sql',
'22-experiments.sql',
'23-experiment-retries.sql',
'24-chronological-validation.sql',
'25-walk-forward.sql',
'26-cost-sensitivity.sql',
]) {
await pool.query(
readFileSync(new URL(`../../database/postgres/init/${filename}`, 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) });
const paper = await paperFixture();
cleanup.push(paper.close);
await paper.runtime.connect({ sourceId: 'fixture', connectionId: 'one' });
await paper.runtime.ingest(paperFrame(1));
await paper.runtime.activate({ recoverPending: false });
paper.clock(20);
await paper.runtime.ingest(paperFrame(2));
const admitted = await canonicalAdmissionFixture(paper.pool, paper.postgres);
const container = await new ServiceContainerBuilder()
.withOptions({
enableCache: false,
@ -97,187 +34,109 @@ async function fixture() {
enableProxy: false,
})
.build();
const services: OrchestratorServices = { logger, postgres };
const services: OrchestratorServices = { logger, postgres: paper.postgres };
container.register({ serviceContainer: asValue(services) });
await registerOrchestratorServices(container, {
initializeMode: false,
nativeExecutionTimeoutMs: 5000,
});
const runtime = services.custom!;
const mode = runtime.ModeManager!;
const runner = runtime.BacktestRunner!;
const market = runtime.MarketDataService!;
const storage = runtime.StorageService!;
const execution = runtime.ExecutionService!;
const strategies = runtime.StrategyManager!;
const feed = { connected: false };
// Only the external transport is offline; real admission, ledger, checkpoints and replay run.
const feedStart = spyOn(market, 'initialize').mockImplementation(async () => {
feed.connected = true;
});
const originalShutdown = market.shutdown.bind(market);
const feedStop = spyOn(market, 'shutdown').mockImplementation(async () => {
feed.connected = false;
await originalShutdown();
});
const lifecycle = [
feedStart,
feedStop,
spyOn(execution, 'initialize'),
spyOn(execution, 'shutdown'),
spyOn(storage, 'initialize'),
spyOn(storage, 'shutdown'),
spyOn(strategies, 'restoreStrategies'),
spyOn(strategies, 'shutdown'),
];
await registerOrchestratorServices(container);
const runtime = services.custom!,
runner = runtime.BacktestRunner!,
engine = runtime.BacktestEngine!;
cleanup.push(async () => {
try {
await runner.shutdown();
await mode.shutdown();
await strategies.shutdown();
await container.dispose();
} finally {
for (const method of lifecycle) method.mockRestore();
}
await runner.shutdown();
await paper.runtime.shutdown();
await container.dispose();
});
await mode.initializeMode({
mode: 'paper',
accountId: 'paper-fixture',
startingCapital: 10000,
commission: 0.001,
slippage: 0,
});
const strategy = new CounterStrategy(execution);
await strategies.attachStrategy(strategy);
await market.subscribeToSymbol('A');
market.ingest(quote('paper-one', 100, 100, Date.now()));
await market.flush();
expect(strategy.count).toBe(1);
expect((await execution.getAccount()).cash).toBe(9899.9);
let failedRead = false;
storage.getHistoricalBars = async () => {
if (failedRead) throw new Error('Injected research history failure');
return Array.from({ length: 70 }, (_, i) => {
const close = 100 + Math.sin((i * Math.PI) / 6) * 8;
return {
symbol: research.symbols[0]!,
source: 'eod' as const,
timestamp: new Date(Date.parse(research.startDate) + i * 86400000),
open: close,
high: close + 1,
low: close - 1,
close,
volume: 1000000,
};
});
};
const stateHash = async () => {
const state: unknown[] = [];
for (const [table, columns] of [
['simulation_accounts', 'id,state'],
['simulation_orders', 'id,payload'],
['simulation_fills', 'id,payload'],
['simulation_events', 'id,fingerprint'],
['simulation_market_inputs', 'id,payload'],
['simulation_strategy_journal', 'sequence,payload'],
['simulation_strategy_checkpoints', 'strategy_id,payload'],
['simulation_strategy_intents', 'client_order_id,payload'],
]) {
const rows = (await pool.query(`SELECT ${columns} FROM ${table}`)).rows;
state.push([table, rows.map(row => canonicalJson(row)).sort()]);
}
return createHash('sha256').update(canonicalJson(state)).digest('hex');
};
return {
services,
pool,
runner,
mode,
execution,
market,
strategies,
strategy,
feed,
stateHash,
lifecycleCounts: () => lifecycle.map(method => method.mock.calls.length),
failHistory: (fail: boolean) => {
failedRead = fail;
},
};
return { paper, ...admitted, container, services, runtime, runner, engine };
}
describe.skipIf(!url)('research isolation from a real paper ledger', () => {
test('legacy_paper_combination_rejected_before_prepare preserves an active paper graph', async () => {
const f = await fixture();
const engine = f.mode.getTradingEngine();
const before = await f.stateHash();
const lifecycle = f.lifecycleCounts();
await expect(f.mode.initializeMode(research)).rejects.toThrow('only permits paper');
await expect(f.mode.transitionMode('paper', 'backtest', research)).rejects.toThrow(
'only permits paper'
);
await expect(f.execution.initialize(research, engine)).rejects.toThrow('only permits paper');
expect(f.mode.getTradingEngine()).toBe(engine);
expect(f.mode.isPaperMode()).toBe(true);
expect(f.feed.connected).toBe(true);
expect(f.lifecycleCounts()).toEqual(
lifecycle.map((count, index) => count + (index === 2 ? 1 : 0))
);
expect(await f.stateHash()).toBe(before);
});
test('native_paper_isolation across successful, cancelled and failed durable jobs', async () => {
const f = await fixture();
const engine = f.mode.getTradingEngine();
const paperConfig = f.mode.getConfig();
const before = await f.stateHash();
const lifecycle = f.lifecycleCounts();
const unchanged = async () => {
expect(await f.stateHash()).toBe(before);
expect(f.mode.getTradingEngine()).toBe(engine);
expect(f.mode.getConfig()).toEqual(paperConfig);
expect(f.lifecycleCounts()).toEqual(lifecycle);
expect(f.market.listenerCount('marketDataBatch')).toBe(1);
expect(f.strategies.getActiveStrategies()).toEqual(['counter']);
expect(f.feed.connected).toBe(true);
};
expect((await f.runner.runBacktest(research)).status).toBe('completed');
await unchanged();
for (let i = 0; i < 2; i++) {
let stopped: Promise<void> | undefined;
f.runner.once('progress', () => {
stopped = f.runner.stopBacktest();
});
const outcome = await f.runner.runBacktest(research).catch(error => error);
await stopped;
expect(stopped).toBeDefined();
expect(outcome).toBeInstanceOf(BacktestCancelledError);
await unchanged();
f.failHistory(true);
await expect(f.runner.runBacktest(research)).rejects.toThrow(
'Injected research history failure'
describe.skipIf(!process.env.PIPELINE_TEST_DATABASE_URL)(
'canonical research isolation from durable paper custody',
() => {
test('default research composition cannot activate, reset or overlay the existing paper account', async () => {
const f = await fixture(),
before = await f.paper.snapshot();
for (const key of [
'ModeManager',
'ExecutionService',
'MarketDataService',
'StrategyManager',
'PaperTradingManager',
'CanonicalPaperRuntime',
]) {
expect(f.runtime).not.toHaveProperty(key);
}
await expect(registerOrchestratorServices(f.container, { role: 'paper' })).rejects.toThrow(
'explicit canonicalPaper'
);
f.failHistory(false);
await expect(
registerOrchestratorServices(f.container, { useRustEngine: false })
).rejects.toThrow('Legacy financial execution is retired');
await expect(
registerOrchestratorServices(f.container, {
role: 'paper',
canonicalPaper: f.paper.configuration,
})
).rejects.toThrow('fresh runtime composition');
expect(await f.paper.snapshot()).toEqual(before);
expect((await f.paper.runtime.status()).active).toBe(true);
});
test('real native success, cancellation and failed durable research leave paper ledger/checkpoint/decisions unchanged', async () => {
const f = await fixture(),
before = await f.paper.snapshot();
const unchanged = async () => {
expect(await f.paper.snapshot()).toEqual(before);
expect((await f.paper.runtime.status()).active).toBe(true);
};
const accept = () => f.api.createRun({ backtestId: f.draft.id });
const completed = await accept();
expect((await f.runner.runQueued(completed.id)).status).toBe('completed');
await unchanged();
}
expect((await f.runner.runBacktest(research)).status).toBe('completed');
await unchanged();
expect(
(
await f.pool.query(
'SELECT status, count(*)::int AS count FROM runs GROUP BY status ORDER BY status::text'
)
).rows
).toEqual([
{ status: 'cancelled', count: 2 },
{ status: 'completed', count: 2 },
{ status: 'failed', count: 2 },
]);
// The existing feed still makes exactly one new durable paper decision after research.
f.market.ingest(quote('paper-two', 101, 100, Date.now()));
await f.market.flush();
expect(f.strategy.count).toBe(2);
expect((await f.execution.getAccount()).strategyPositions.counter?.A).toBe(2);
}, 15000);
});
const result = await f.api.getRunResults(completed.id);
expect(result).not.toBeNull();
expect(result).toHaveProperty('kind', 'canonical-result/v1');
for (let index = 0; index < 2; index++) {
const run = await accept();
let stopped: Promise<void> | undefined;
f.runner.once('progress', () => {
stopped = f.runner.stopBacktest();
});
const cancelled = await f.runner.runQueued(run.id).catch(error => error);
await stopped;
expect(stopped).toBeDefined();
expect(cancelled).toBeInstanceOf(BacktestCancelledError);
await unchanged();
const failed = await accept(),
original = f.engine.runCanonical;
f.engine.runCanonical = async () => {
throw new Error('Injected canonical execution failure');
};
try {
await expect(f.runner.runQueued(failed.id)).rejects.toThrow(
'Injected canonical execution failure'
);
} finally {
f.engine.runCanonical = original;
}
await unchanged();
}
expect((await f.runner.runQueued((await accept()).id)).status).toBe('completed');
await unchanged();
expect(
(
await f.paper.pool.query(
'SELECT status,count(*)::int AS count FROM runs GROUP BY status ORDER BY status::text'
)
).rows
).toEqual([
{ status: 'cancelled', count: 2 },
{ status: 'completed', count: 2 },
{ status: 'failed', count: 2 },
]);
f.paper.clock(30);
await f.paper.runtime.ingest(paperFrame(3));
const continued = await f.paper.snapshot();
expect(continued.owners[0]!.diagnostic.nextDecisionSequence).toBe(
before.owners[0]!.diagnostic.nextDecisionSequence + 1
);
expect(continued.account.view.portfolio.positions).toHaveLength(1);
}, 15000);
}
);