Refactor execution boundaries and add durable strategy recovery

This commit is contained in:
Boki 2026-10-21 12:23:43 -04:00
parent d6b09eb635
commit 694c48bbdb
36 changed files with 3077 additions and 491 deletions

View file

@ -0,0 +1,47 @@
/** Local, deterministic workload; no native engine, database, network or trading credentials. */
import { defaultRiskLimits, type Account } from '../apps/stock/orchestrator/src/execution/model';
import { BacktestExecutionRepository } from '../apps/stock/orchestrator/src/execution/BacktestExecutionRepository';
const account: Account = {
initialCapital: 10000,
cash: 10000,
realizedPnl: 0,
dailyPnl: 0,
day: '2024-01-01',
commission: 0.001,
slippage: 0,
limits: { ...defaultRiskLimits },
maxQuoteAgeMs: 60000,
positions: {},
quotes: {},
strategyPositions: {},
};
for (const history of [0, 1000, 10000]) {
const repository = new BacktestExecutionRepository();
await repository.initialize('benchmark', account);
await repository.transact('benchmark', async tx => {
for (let i = 0; i < history; i++) {
await tx.appendJournal({
kind: 'market',
market: {
type: 'trade',
eventId: String(i),
data: { symbol: 'A.US', price: 100, size: 1, side: 'buy', timestamp: i },
},
recipients: [],
account,
});
}
});
const start = performance.now();
for (let i = 0; i < 200; i++) {
await repository.transact('benchmark', async tx => ({
cash: tx.account.cash,
next: await tx.nextJournal(history),
}));
}
process.stdout.write(
`${history} journal events: ${((performance.now() - start) / 200).toFixed(3)} ms/transaction\n`
);
}

View file

@ -0,0 +1,101 @@
import { existsSync, readFileSync } from 'node:fs';
import { dirname, join, relative, resolve } from 'node:path';
import { fileURLToPath } from 'node:url';
import { describe, expect, it } from 'bun:test';
import ts from 'typescript';
const root = fileURLToPath(new URL('../../apps/stock/orchestrator/src/', import.meta.url));
const files = [...new Bun.Glob('**/*.ts').scanSync({ cwd: root })].map(file => join(root, file));
/** Include static imports/re-exports and lazy imports; type-only edges do not load code. */
function runtimeImports(file: string): string[] {
const source = ts.createSourceFile(file, readFileSync(file, 'utf8'), ts.ScriptTarget.Latest, true);
const imports = new Set<string>();
function visit(node: ts.Node) {
if (ts.isImportDeclaration(node) && ts.isStringLiteral(node.moduleSpecifier)) {
const clause = node.importClause;
const bindings = clause?.namedBindings;
const typesOnly = clause?.isTypeOnly ||
(clause && !clause.name && bindings && ts.isNamedImports(bindings) &&
bindings.elements.length > 0 && bindings.elements.every(item => item.isTypeOnly));
if (!typesOnly) imports.add(node.moduleSpecifier.text);
}
if (ts.isExportDeclaration(node) && !node.isTypeOnly && node.moduleSpecifier && ts.isStringLiteral(node.moduleSpecifier)) {
const clause = node.exportClause;
if (!clause || !ts.isNamedExports(clause) || !clause.elements.length || clause.elements.some(item => !item.isTypeOnly)) {
imports.add(node.moduleSpecifier.text);
}
}
if (ts.isCallExpression(node) && node.expression.kind === ts.SyntaxKind.ImportKeyword && node.arguments[0] && ts.isStringLiteral(node.arguments[0])) {
imports.add(node.arguments[0].text);
}
ts.forEachChild(node, visit);
}
visit(source);
return [...imports];
}
const imports = new Map(files.map(file => [file, runtimeImports(file)]));
function localFile(from: string, specifier: string): string | undefined {
if (!specifier.startsWith('.')) return undefined;
const path = resolve(dirname(from), specifier);
const target = [path, `${path}.ts`, join(path, 'index.ts')].find(file => existsSync(file) && imports.has(file));
if (!target) throw new Error(`Unresolved local runtime import: ${relative(root, from)} -> ${specifier}`);
return target;
}
const graph = new Map([...imports].map(([file, dependencies]) => [file,
dependencies.map(specifier => localFile(file, specifier)).filter((file): file is string => !!file),
]));
function reachable(file: string, seen = new Set<string>()): Set<string> {
if (seen.has(file)) return seen;
seen.add(file);
for (const next of graph.get(file) ?? []) reachable(next, seen);
return seen;
}
describe('orchestrator architecture boundaries', () => {
it('local runtime dependencies are acyclic', () => {
const done = new Set<string>();
function visit(file: string, stack: string[]) {
if (stack.includes(file)) throw new Error(`Runtime dependency cycle: ${[...stack, file].map(file => relative(root, file)).join(' -> ')}`);
if (done.has(file)) return;
for (const next of graph.get(file) ?? []) visit(next, [...stack, file]);
done.add(file);
}
for (const file of files) visit(file, []);
});
it('contracts and native worker protocol cannot load services, storage or server adapters', () => {
const contracts = files.filter(file => file.startsWith(join(root, 'contracts/')));
for (const entry of [...contracts, join(root, 'types.ts'), join(root, 'backtest/native-worker-protocol.ts')]) {
for (const file of reachable(entry)) {
const path = relative(root, file);
expect(path === 'types.ts' || path.startsWith('contracts/') || path === 'backtest/native-worker-protocol.ts').toBe(true);
for (const specifier of imports.get(file) ?? []) {
expect(specifier.startsWith('.') || ['zod', '@stock-bot/types'].includes(specifier)).toBe(true);
}
}
}
});
it('recovery and the ledger port do not depend on concrete adapters, strategies or the service container', () => {
for (const entry of ['execution/SimulationExecution.ts', 'execution/StrategyRecovery.ts', 'execution/repository.ts', 'execution/strategy-recovery.ts', 'execution/model.ts']) {
for (const file of reachable(join(root, entry))) {
expect(relative(root, file)).not.toMatch(/^(services|strategies|core|data)\//);
expect(relative(root, file)).not.toMatch(/(Postgres|Backtest)ExecutionRepository/);
for (const specifier of imports.get(file) ?? []) {
expect(['@stock-bot/services', '@stock-bot/di', '@stock-bot/engine', 'awilix'].includes(specifier)).toBe(false);
}
}
}
expect(imports.get(join(root, 'execution/repository.ts'))).toEqual([]);
});
it('the strategy manager cannot select or directly import concrete strategies', () => {
const file = join(root, 'strategies/StrategyManager.ts');
expect(imports.get(file)?.some(specifier => specifier.includes('/examples/'))).toBe(false);
expect(readFileSync(file, 'utf8')).not.toMatch(/switch\s*\(\s*config\.name/);
expect(imports.get(join(root, 'strategies/StrategyRegistry.ts'))).toEqual([]);
});
});