feat(execution): preserve durable recovery on canonical Rust core
This commit is contained in:
parent
5e9655de0b
commit
c01e96e4dd
27 changed files with 3644 additions and 182 deletions
77
test/fixtures/canonical-paper-crash-owner.ts
vendored
Normal file
77
test/fixtures/canonical-paper-crash-owner.ts
vendored
Normal file
|
|
@ -0,0 +1,77 @@
|
|||
/** Runs only in a disposable schema; the parent kills this process at a durable boundary. */
|
||||
import { Pool } from 'pg';
|
||||
import { PostgreSQLClient } from '@stock-bot/postgres';
|
||||
import type { CanonicalExecutionRepository } 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 { canonicalConfig, counterProgram } from './canonical-paper';
|
||||
import { logger } from './execution';
|
||||
|
||||
const url = process.env.PIPELINE_TEST_DATABASE_URL;
|
||||
const schema = process.env.CANONICAL_CRASH_SCHEMA;
|
||||
const phase = process.env.CANONICAL_CRASH_PHASE;
|
||||
if (
|
||||
!url ||
|
||||
!new URL(url).pathname.startsWith('/stock_bot_safety') ||
|
||||
!schema ||
|
||||
!/^stock_bot_safety_[a-f0-9]+$/.test(schema) ||
|
||||
!['decision', 'checkpoint', 'dispatch', 'fill'].includes(phase ?? '')
|
||||
) {
|
||||
throw new Error('Unsafe canonical crash fixture');
|
||||
}
|
||||
const pool = new Pool({ connectionString: url, options: '-c search_path=' + schema });
|
||||
const postgres = new PostgreSQLClient(
|
||||
{ host: 'unused', port: 5432, database: 'unused', username: 'unused', password: 'unused' },
|
||||
logger
|
||||
);
|
||||
Object.defineProperty(postgres, 'connectionPool', { get: () => pool });
|
||||
const durable = new PostgresCanonicalExecutionRepository(postgres);
|
||||
const block = async () => {
|
||||
process.send?.({ phase });
|
||||
await new Promise<void>(() => {});
|
||||
};
|
||||
const repository: CanonicalExecutionRepository = {
|
||||
initialize: (account, owners) => durable.initialize(account, owners),
|
||||
async transact(accountId, work) {
|
||||
let committedBoundary = false;
|
||||
const result = await durable.transact(accountId, tx =>
|
||||
work({
|
||||
...tx,
|
||||
async putOwner(owner) {
|
||||
// The callback has returned, but neither its next checkpoint nor its
|
||||
// complete batch has committed. Killing here must roll both back.
|
||||
if (phase === 'decision' && owner.diagnostic.nextDecisionSequence > 0) {
|
||||
await block();
|
||||
}
|
||||
await tx.putOwner(owner);
|
||||
},
|
||||
async putBatch(batch) {
|
||||
await tx.putBatch(batch);
|
||||
committedBoundary =
|
||||
(phase === 'checkpoint' && batch.status === 'pending') ||
|
||||
(phase === 'dispatch' && batch.status === 'dispatched');
|
||||
},
|
||||
async putInput(input) {
|
||||
await tx.putInput(input);
|
||||
if (
|
||||
phase === 'fill' &&
|
||||
input.status === 'applied' &&
|
||||
input.input.command.body.kind === 'execute'
|
||||
) {
|
||||
committedBoundary = true;
|
||||
}
|
||||
},
|
||||
})
|
||||
);
|
||||
if (committedBoundary) {
|
||||
// SQL has committed, but drain has not received its acknowledgement and
|
||||
// cannot publish. Restart must use committed state without rerunning it.
|
||||
await block();
|
||||
}
|
||||
return result;
|
||||
},
|
||||
};
|
||||
const execution = new CanonicalPaperExecution({ repository, programs: [counterProgram()] });
|
||||
await execution.initialize(canonicalConfig());
|
||||
await execution.drain();
|
||||
throw new Error('Canonical crash fixture did not reach its requested boundary');
|
||||
137
test/fixtures/canonical-paper.ts
vendored
Normal file
137
test/fixtures/canonical-paper.ts
vendored
Normal file
|
|
@ -0,0 +1,137 @@
|
|||
import { parseFinancialDecimal } from '@stock-bot/types';
|
||||
import type { CanonicalMatchingConfig } from '../../apps/stock/orchestrator/src/contracts/canonical-execution';
|
||||
import type { StrategyProgram } from '../../apps/stock/orchestrator/src/contracts/canonical-strategy';
|
||||
import type { CanonicalPaperInput } from '../../apps/stock/orchestrator/src/execution/canonical-paper';
|
||||
|
||||
export function canonicalConfig(owners = ['A']): CanonicalMatchingConfig {
|
||||
return {
|
||||
risk: {
|
||||
ledger: {
|
||||
version: 1,
|
||||
sessionId: 'canonical-paper-test',
|
||||
accountId: 'canonical-paper-test',
|
||||
baseCurrency: 'USD',
|
||||
reserveOwnerId: 'reserve',
|
||||
ownerIds: owners,
|
||||
initialCapital: '1000',
|
||||
riskSession: {
|
||||
calendarId: 'account',
|
||||
calendarRevision: '1',
|
||||
sessionId: 'risk-1',
|
||||
startsAt: 0,
|
||||
},
|
||||
},
|
||||
feeRate: '0.01',
|
||||
maxOrderQuantity: '100',
|
||||
maxPositionQuantity: '100',
|
||||
maxSymbolExposure: '10000',
|
||||
maxGrossExposure: '10000',
|
||||
maxDailyLoss: '100',
|
||||
maxDrawdownAmount: '1000',
|
||||
maxMarkAgeMs: 1000,
|
||||
},
|
||||
owners: owners.map(ownerId => ({ ownerId, mode: 'Target' })),
|
||||
series: [{ instrumentId: 'X', seriesId: 'X:quote', mode: 'Quote' }],
|
||||
halfSpreadRate: '0',
|
||||
slippageRate: '0',
|
||||
latencyMs: 0,
|
||||
};
|
||||
}
|
||||
export type CounterState = { count: number; samples: number[]; seen: number[] };
|
||||
export function counterProgram(ownerId = 'A'): StrategyProgram<CounterState> {
|
||||
return {
|
||||
ownerId,
|
||||
strategyId: 'counter',
|
||||
strategyVersion: '1',
|
||||
mode: 'target',
|
||||
seed: 7,
|
||||
initialState: { count: 0, samples: [], seen: [] },
|
||||
decide(context) {
|
||||
return {
|
||||
nextState: {
|
||||
count: context.state.count + 1,
|
||||
samples: [...context.state.samples, context.random()],
|
||||
seen: [...context.state.seen, ...context.observations.map(row => row.source_sequence)],
|
||||
},
|
||||
intent: {
|
||||
mode: 'target',
|
||||
targets: [{ instrumentId: 'X', quantity: parseFinancialDecimal('2') }],
|
||||
},
|
||||
};
|
||||
},
|
||||
};
|
||||
}
|
||||
export function openInput(): CanonicalPaperInput {
|
||||
return {
|
||||
command: {
|
||||
commandId: 'open',
|
||||
key: { at: 0, phase: 'Observation', instrumentId: 'X', sourceSequence: 0 },
|
||||
body: { kind: 'openSession', session: { sessionId: 'venue-1', opensAt: 0, closesAt: 10000 } },
|
||||
},
|
||||
observations: [],
|
||||
};
|
||||
}
|
||||
export function markInput(sequence: number, ownerIds = ['A'], price = '10'): CanonicalPaperInput {
|
||||
const at = sequence * 10;
|
||||
return {
|
||||
command: {
|
||||
commandId: `mark-${sequence}`,
|
||||
key: { at, phase: 'Observation', instrumentId: 'X', sourceSequence: sequence },
|
||||
body: { kind: 'mark', seriesId: 'X:quote', price, observedAt: at },
|
||||
},
|
||||
observations: [
|
||||
{
|
||||
series_id: 'X:quote',
|
||||
instrument_id: 'X',
|
||||
interval_start: at - 1,
|
||||
interval_end: at,
|
||||
event_time: at,
|
||||
available_at: at,
|
||||
source_sequence: sequence,
|
||||
open: parseFinancialDecimal(price),
|
||||
high: parseFinancialDecimal(price),
|
||||
low: parseFinancialDecimal(price),
|
||||
close: parseFinancialDecimal(price),
|
||||
volume: parseFinancialDecimal('100'),
|
||||
},
|
||||
],
|
||||
...(ownerIds.length
|
||||
? {
|
||||
decision: {
|
||||
commandId: `decision-${sequence}`,
|
||||
key: { at, phase: 'Decision' as const, instrumentId: 'X', sourceSequence: sequence },
|
||||
barrierId: `barrier-${sequence}`,
|
||||
ownerIds,
|
||||
inputs: [
|
||||
{
|
||||
series_id: 'X:quote',
|
||||
availability: { Fresh: { event_time: at, available_at: at } },
|
||||
},
|
||||
],
|
||||
},
|
||||
}
|
||||
: {}),
|
||||
};
|
||||
}
|
||||
export function quoteInput(sequence: number, capacity = '100', price = '10'): CanonicalPaperInput {
|
||||
const at = sequence * 10 + 1;
|
||||
return {
|
||||
command: {
|
||||
commandId: `quote-${sequence}`,
|
||||
key: { at, phase: 'Execution', instrumentId: 'X', sourceSequence: sequence },
|
||||
body: {
|
||||
kind: 'execute',
|
||||
seriesId: 'X:quote',
|
||||
observation: {
|
||||
kind: 'quote',
|
||||
observedAt: at,
|
||||
bid: price,
|
||||
ask: price,
|
||||
bidSize: capacity,
|
||||
askSize: capacity,
|
||||
},
|
||||
},
|
||||
},
|
||||
observations: [],
|
||||
};
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue