Refactor execution boundaries and add durable strategy recovery
This commit is contained in:
parent
d6b09eb635
commit
694c48bbdb
36 changed files with 3077 additions and 491 deletions
56
test/fixtures/strategy-crash-owner.ts
vendored
Normal file
56
test/fixtures/strategy-crash-owner.ts
vendored
Normal file
|
|
@ -0,0 +1,56 @@
|
|||
/** Disposable process used only against an isolated stock_bot_safety schema. */
|
||||
import { Pool } from 'pg';
|
||||
import { PostgreSQLClient } from '@stock-bot/postgres';
|
||||
import { PostgresExecutionRepository } from '../../apps/stock/orchestrator/src/execution/PostgresExecutionRepository';
|
||||
import { logger, makeExecution, start } from './execution';
|
||||
import { attachCounter, CounterStrategy, FaultRepository } from './strategy-recovery';
|
||||
|
||||
const url = process.env.PIPELINE_TEST_DATABASE_URL,
|
||||
schema = process.env.STRATEGY_FIXTURE_SCHEMA,
|
||||
phase = process.env.STRATEGY_FIXTURE_PHASE;
|
||||
if (
|
||||
!url ||
|
||||
!new URL(url).pathname.startsWith('/stock_bot_safety') ||
|
||||
!schema ||
|
||||
!/^stock_bot_safety_[a-f0-9]+$/.test(schema) ||
|
||||
!['decision', 'checkpoint', 'dispatch'].includes(phase ?? '')
|
||||
) {
|
||||
throw new Error('Unsafe strategy crash fixture');
|
||||
}
|
||||
const pool = new Pool({ connectionString: url, options: '-c search_path=' + schema });
|
||||
const postgres = new PostgreSQLClient(
|
||||
{ host: 'unused', port: 5432, database: 'unused', user: 'unused', password: 'unused' },
|
||||
logger
|
||||
);
|
||||
Object.defineProperty(postgres, 'connectionPool', { get: () => pool });
|
||||
const repository = new FaultRepository(new PostgresExecutionRepository(postgres));
|
||||
const { execution, engine } = makeExecution(repository, () => start + 100);
|
||||
await execution.initialize(
|
||||
{
|
||||
mode: 'paper',
|
||||
accountId: 'fixture',
|
||||
startingCapital: 10000,
|
||||
commission: 0.001,
|
||||
slippage: 0,
|
||||
maxQuoteAgeMs: 1000,
|
||||
},
|
||||
engine
|
||||
);
|
||||
const blocked = async () => {
|
||||
process.send?.({ phase });
|
||||
await new Promise<void>(() => {});
|
||||
};
|
||||
const strategy = new CounterStrategy(execution);
|
||||
if (phase === 'decision') {
|
||||
strategy.onDecision = blocked;
|
||||
} else {
|
||||
repository.fault = {
|
||||
method: 'putIntent',
|
||||
stage: 'commit',
|
||||
matches: value =>
|
||||
(value as { status: string }).status === (phase === 'checkpoint' ? 'pending' : 'dispatched'),
|
||||
hook: blocked,
|
||||
};
|
||||
}
|
||||
await attachCounter(execution, strategy);
|
||||
throw new Error('Crash fixture did not reach its requested boundary');
|
||||
126
test/fixtures/strategy-recovery.ts
vendored
Normal file
126
test/fixtures/strategy-recovery.ts
vendored
Normal file
|
|
@ -0,0 +1,126 @@
|
|||
import { z } from 'zod';
|
||||
import type { ModeManager } from '../../apps/stock/orchestrator/src/core/ModeManager';
|
||||
import type {
|
||||
ExecutionRepository,
|
||||
ExecutionTransaction,
|
||||
} from '../../apps/stock/orchestrator/src/execution/repository';
|
||||
import type {
|
||||
ExecutionService,
|
||||
StrategyFill,
|
||||
} from '../../apps/stock/orchestrator/src/services/ExecutionService';
|
||||
import {
|
||||
BaseStrategy,
|
||||
type Signal,
|
||||
} from '../../apps/stock/orchestrator/src/strategies/BaseStrategy';
|
||||
import { StrategyManager } from '../../apps/stock/orchestrator/src/strategies/StrategyManager';
|
||||
import type { MarketData, StrategyConfig } from '../../apps/stock/orchestrator/src/types';
|
||||
import { logger } from './execution';
|
||||
|
||||
export const recoveryConfig: StrategyConfig = {
|
||||
id: 'counter',
|
||||
name: 'fixture',
|
||||
symbols: ['A'],
|
||||
parameters: {},
|
||||
allocation: 1,
|
||||
enabled: true,
|
||||
};
|
||||
export class CounterStrategy extends BaseStrategy {
|
||||
count = 0;
|
||||
equities: number[] = [];
|
||||
failDecision = false;
|
||||
failFill = false;
|
||||
onDecision?: () => Promise<void>;
|
||||
version = 'counter/v1';
|
||||
constructor(execution: ExecutionService, config = recoveryConfig) {
|
||||
super(config, {} as ModeManager, execution);
|
||||
}
|
||||
override getCheckpointVersion() {
|
||||
return this.version;
|
||||
}
|
||||
protected override captureIndicators() {
|
||||
return { count: this.count, equities: this.equities };
|
||||
}
|
||||
protected override restoreIndicators(input: unknown) {
|
||||
const state = z
|
||||
.object({ count: z.number().int().nonnegative(), equities: z.array(z.number().finite()) })
|
||||
.parse(input);
|
||||
this.count = state.count;
|
||||
this.equities = state.equities;
|
||||
}
|
||||
protected updateIndicators() {
|
||||
this.count++;
|
||||
}
|
||||
protected async generateSignal(data: MarketData): Promise<Signal | null> {
|
||||
this.equities.push((await this.executionService.getAccount()).equity);
|
||||
await this.onDecision?.();
|
||||
if (this.failDecision) {
|
||||
throw new Error('injected decision failure');
|
||||
}
|
||||
return { type: 'buy', symbol: data.data.symbol, strength: 1, metadata: { quantity: 1 } };
|
||||
}
|
||||
override async onFill(fill: StrategyFill) {
|
||||
await super.onFill(fill);
|
||||
if (this.failFill) {
|
||||
throw new Error('injected fill callback failure');
|
||||
}
|
||||
}
|
||||
}
|
||||
export async function attachCounter(
|
||||
execution: ExecutionService,
|
||||
strategy = new CounterStrategy(execution)
|
||||
) {
|
||||
const manager = new StrategyManager({ logger, custom: { ExecutionService: execution } });
|
||||
await manager.attachStrategy(strategy);
|
||||
return { manager, strategy };
|
||||
}
|
||||
|
||||
export class FaultRepository implements ExecutionRepository {
|
||||
fault?: {
|
||||
method: keyof ExecutionTransaction;
|
||||
matches: (argument: unknown) => boolean;
|
||||
stage: 'before' | 'after' | 'commit';
|
||||
hook?: () => Promise<void>;
|
||||
};
|
||||
constructor(private readonly delegate: ExecutionRepository) {}
|
||||
initialize(...args: Parameters<ExecutionRepository['initialize']>) {
|
||||
return this.delegate.initialize(...args);
|
||||
}
|
||||
async transact<T>(account: string, work: (tx: ExecutionTransaction) => Promise<T>): Promise<T> {
|
||||
let matched: typeof this.fault;
|
||||
const result = await this.delegate.transact(account, tx =>
|
||||
work(
|
||||
new Proxy(tx, {
|
||||
get: (target, key: keyof ExecutionTransaction) => {
|
||||
const value = target[key];
|
||||
if (typeof value !== 'function') {
|
||||
return value;
|
||||
}
|
||||
return async (...args: unknown[]) => {
|
||||
const fault = this.fault;
|
||||
const hit = fault && key === fault.method && fault.matches(args[0]);
|
||||
if (hit) {
|
||||
this.fault = undefined;
|
||||
matched = fault;
|
||||
}
|
||||
if (hit && fault.stage === 'before') {
|
||||
throw new Error('injected transaction failure');
|
||||
}
|
||||
const answer = await Reflect.apply(value, target, args);
|
||||
if (hit && fault.stage === 'after') {
|
||||
throw new Error('injected transaction failure');
|
||||
}
|
||||
return answer;
|
||||
};
|
||||
},
|
||||
})
|
||||
)
|
||||
);
|
||||
if (matched?.stage === 'commit') {
|
||||
if (matched.hook) {
|
||||
await matched.hook();
|
||||
}
|
||||
throw new Error('injected lost commit acknowledgement');
|
||||
}
|
||||
return result;
|
||||
}
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue