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: [],
|
||||
};
|
||||
}
|
||||
165
test/postgres/canonical-paper-crash.test.ts
Normal file
165
test/postgres/canonical-paper-crash.test.ts
Normal file
|
|
@ -0,0 +1,165 @@
|
|||
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 { parseFinancialDecimal } from '@stock-bot/types';
|
||||
import { CanonicalPaperExecution } from '../../apps/stock/orchestrator/src/execution/CanonicalPaperExecution';
|
||||
import { PostgresCanonicalExecutionRepository } from '../../apps/stock/orchestrator/src/execution/PostgresCanonicalExecutionRepository';
|
||||
import {
|
||||
canonicalConfig,
|
||||
counterProgram,
|
||||
markInput,
|
||||
openInput,
|
||||
quoteInput,
|
||||
} from '../fixtures/canonical-paper';
|
||||
import { logger } 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();
|
||||
});
|
||||
for (const migration of [
|
||||
'11-simulation-execution-ledger.sql',
|
||||
'13-strategy-recovery.sql',
|
||||
'15-canonical-paper-intents.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', username: 'unused', password: 'unused' },
|
||||
logger
|
||||
);
|
||||
Object.defineProperty(postgres, 'connectionPool', { get: () => pool });
|
||||
const make = async (onDecision = () => {}) => {
|
||||
const program = counterProgram();
|
||||
const observed: typeof program = {
|
||||
...program,
|
||||
decide(context) {
|
||||
onDecision();
|
||||
return program.decide(context);
|
||||
},
|
||||
};
|
||||
const execution = new CanonicalPaperExecution({
|
||||
repository: new PostgresCanonicalExecutionRepository(postgres),
|
||||
programs: [observed],
|
||||
});
|
||||
await execution.initialize(canonicalConfig());
|
||||
return execution;
|
||||
};
|
||||
return { schema, pool, make };
|
||||
}
|
||||
|
||||
describe.skipIf(!url)('canonical paper process recovery on real PostgreSQL', () => {
|
||||
test.each(['decision', 'checkpoint', 'dispatch', 'fill'] as const)(
|
||||
'hard kill at %s matches uninterrupted state, effects and fees',
|
||||
async phase => {
|
||||
const baselineFixture = await fixture();
|
||||
const baseline = await baselineFixture.make();
|
||||
const interruptedFixture = await fixture();
|
||||
const interrupted = await interruptedFixture.make();
|
||||
for (const input of [openInput(), markInput(1), quoteInput(2)]) {
|
||||
await baseline.enqueue(input);
|
||||
await interrupted.enqueue(input);
|
||||
}
|
||||
await baseline.drain();
|
||||
const expected = await baseline.snapshot();
|
||||
const expectedJournal = await baseline.journal();
|
||||
expect(expected.account.checkpoint.orders).toHaveLength(1);
|
||||
expect(expected.account.checkpoint.orders[0]?.status).toBe('Filled');
|
||||
expect(expected.account.view.portfolio.cash).toBe(parseFinancialDecimal('979.80000000'));
|
||||
expect(expected.account.view.equity).toBe(parseFinancialDecimal('999.80000000'));
|
||||
const child = fork(
|
||||
fileURLToPath(new URL('../fixtures/canonical-paper-crash-owner.ts', import.meta.url)),
|
||||
[],
|
||||
{
|
||||
execPath: process.execPath,
|
||||
execArgv: [],
|
||||
stdio: ['ignore', 'ignore', 'pipe', 'ipc'],
|
||||
env: {
|
||||
...process.env,
|
||||
CANONICAL_CRASH_SCHEMA: interruptedFixture.schema,
|
||||
CANONICAL_CRASH_PHASE: phase,
|
||||
},
|
||||
}
|
||||
);
|
||||
let childError = '';
|
||||
child.stderr?.on('data', chunk => {
|
||||
childError += String(chunk);
|
||||
});
|
||||
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 timer = setTimeout(
|
||||
() => reject(new Error('Canonical crash boundary timeout: ' + childError)),
|
||||
10000
|
||||
);
|
||||
child.once('message', message => {
|
||||
clearTimeout(timer);
|
||||
if ((message as { phase?: string }).phase === phase) {
|
||||
resolve();
|
||||
} else {
|
||||
reject(new Error('Unexpected canonical crash boundary'));
|
||||
}
|
||||
});
|
||||
child.once('error', error => {
|
||||
clearTimeout(timer);
|
||||
reject(error);
|
||||
});
|
||||
child.once('exit', () => {
|
||||
clearTimeout(timer);
|
||||
reject(new Error('Canonical child exited before boundary: ' + childError));
|
||||
});
|
||||
});
|
||||
child.kill('SIGKILL');
|
||||
await exited;
|
||||
let recoveredDecisions = 0;
|
||||
const recovered = await interruptedFixture.make(() => {
|
||||
recoveredDecisions++;
|
||||
});
|
||||
await recovered.drain();
|
||||
expect(recoveredDecisions).toBe(phase === 'decision' ? 1 : 0);
|
||||
expect(await recovered.snapshot()).toEqual(expected);
|
||||
expect(await recovered.journal()).toEqual(expectedJournal);
|
||||
expect(await recovered.getRecoveryStatus()).toMatchObject({
|
||||
status: 'Running',
|
||||
pendingDecisionSequence: null,
|
||||
pendingBatch: null,
|
||||
pendingInput: null,
|
||||
});
|
||||
const batches = await interruptedFixture.pool.query(
|
||||
'SELECT status FROM simulation_canonical_intents'
|
||||
);
|
||||
expect(batches.rows).toEqual([{ status: 'dispatched' }]);
|
||||
expect(await recovered.enqueue(markInput(1))).toBe(false);
|
||||
await recovered.drain();
|
||||
expect(await recovered.snapshot()).toEqual(expected);
|
||||
expect(await recovered.journal()).toEqual(expectedJournal);
|
||||
},
|
||||
20000
|
||||
);
|
||||
});
|
||||
887
test/postgres/canonical-paper.test.ts
Normal file
887
test/postgres/canonical-paper.test.ts
Normal file
|
|
@ -0,0 +1,887 @@
|
|||
import { randomUUID } from 'node:crypto';
|
||||
import { readFileSync } from 'node:fs';
|
||||
import { afterEach, describe, expect, test } from 'bun:test';
|
||||
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 {
|
||||
parseFinancialTransactionResult,
|
||||
type CanonicalMatchingConfig,
|
||||
} from '../../apps/stock/orchestrator/src/contracts/canonical-execution';
|
||||
import type { StrategyProgram } from '../../apps/stock/orchestrator/src/contracts/canonical-strategy';
|
||||
import type {
|
||||
CanonicalExecutionRepository,
|
||||
CanonicalJournalEntry,
|
||||
CanonicalPaperInput,
|
||||
CanonicalTransaction,
|
||||
} 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-sma';
|
||||
import {
|
||||
canonicalConfig,
|
||||
counterProgram,
|
||||
markInput,
|
||||
openInput,
|
||||
quoteInput,
|
||||
type CounterState,
|
||||
} from '../fixtures/canonical-paper';
|
||||
import { logger } 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(
|
||||
config = canonicalConfig(),
|
||||
programs: readonly StrategyProgram[] = [counterProgram()]
|
||||
) {
|
||||
if (!url || !new URL(url).pathname.startsWith('/stock_bot_safety')) {
|
||||
throw new Error('Dedicated stock_bot_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} -c statement_timeout=10000`,
|
||||
});
|
||||
cleanup.push(async () => {
|
||||
await pool.end();
|
||||
await admin.query(`DROP SCHEMA ${schema} CASCADE`);
|
||||
await admin.end();
|
||||
});
|
||||
for (const filename of [
|
||||
'11-simulation-execution-ledger.sql',
|
||||
'13-strategy-recovery.sql',
|
||||
'15-canonical-paper-intents.sql',
|
||||
]) {
|
||||
const sql = readFileSync(
|
||||
new URL(`../../database/postgres/init/${filename}`, import.meta.url),
|
||||
'utf8'
|
||||
);
|
||||
await pool.query(sql);
|
||||
await pool.query(sql);
|
||||
}
|
||||
const postgres = new PostgreSQLClient(
|
||||
{ host: 'unused', port: 5432, database: 'unused', username: 'unused', password: 'unused' },
|
||||
logger
|
||||
);
|
||||
Object.defineProperty(postgres, 'connectionPool', { get: () => pool });
|
||||
const repository = new PostgresCanonicalExecutionRepository(postgres);
|
||||
const make = async (
|
||||
options: {
|
||||
repository?: CanonicalExecutionRepository;
|
||||
programs?: readonly StrategyProgram[];
|
||||
publish?: (entries: readonly CanonicalJournalEntry[]) => void | Promise<void>;
|
||||
} = {}
|
||||
) => {
|
||||
const host = new CanonicalPaperExecution({ repository, programs, ...options });
|
||||
await host.initialize(config);
|
||||
return host;
|
||||
};
|
||||
return { pool, postgres, repository, make, host: await make(), config };
|
||||
}
|
||||
async function send(host: CanonicalPaperExecution, input: CanonicalPaperInput) {
|
||||
await host.enqueue(input);
|
||||
await host.drain();
|
||||
}
|
||||
function failOnce(
|
||||
delegate: CanonicalExecutionRepository,
|
||||
method: keyof CanonicalTransaction,
|
||||
stage: 'before' | 'after' | 'commit',
|
||||
matches: (value: unknown) => boolean = () => true
|
||||
): CanonicalExecutionRepository {
|
||||
let armed = true;
|
||||
return {
|
||||
initialize: (account, owners) => delegate.initialize(account, owners),
|
||||
async transact<T>(accountId: string, work: (tx: CanonicalTransaction) => Promise<T>) {
|
||||
let hit = false;
|
||||
const result = await delegate.transact(accountId, tx =>
|
||||
work(
|
||||
new Proxy(tx, {
|
||||
get(target, key: keyof CanonicalTransaction) {
|
||||
const value = target[key];
|
||||
if (typeof value !== 'function') {
|
||||
return value;
|
||||
}
|
||||
return async (...args: unknown[]) => {
|
||||
if (armed && key === method && matches(args[0])) {
|
||||
armed = false;
|
||||
hit = true;
|
||||
}
|
||||
if (hit && stage === 'before') {
|
||||
throw new Error('injected before commit');
|
||||
}
|
||||
const result = await Reflect.apply(value, target, args);
|
||||
if (hit && stage === 'after') {
|
||||
throw new Error('injected before commit');
|
||||
}
|
||||
return result;
|
||||
};
|
||||
},
|
||||
})
|
||||
)
|
||||
);
|
||||
if (hit && stage === 'commit') {
|
||||
throw new Error('lost commit acknowledgement');
|
||||
}
|
||||
return result;
|
||||
},
|
||||
};
|
||||
}
|
||||
const isPending = (value: unknown) => (value as { status?: string })?.status === 'pending';
|
||||
const isDispatched = (value: unknown) => (value as { status?: string })?.status === 'dispatched';
|
||||
|
||||
function explicitProgram(
|
||||
tif: 'DAY' | 'GTC' | 'IOC' | 'FOK',
|
||||
quantity = '2'
|
||||
): StrategyProgram<CounterState> {
|
||||
return {
|
||||
...counterProgram(),
|
||||
mode: 'orders',
|
||||
decide: context => ({
|
||||
nextState: { count: context.state.count + 1, samples: [context.random()], seen: [] },
|
||||
intent: {
|
||||
mode: 'orders',
|
||||
orders:
|
||||
context.state.count === 0
|
||||
? [
|
||||
{
|
||||
kind: 'market',
|
||||
orderId: 'explicit-order',
|
||||
instrumentId: 'X',
|
||||
side: 'buy',
|
||||
quantity: parseFinancialDecimal(quantity),
|
||||
timeInForce: tif,
|
||||
},
|
||||
]
|
||||
: [],
|
||||
},
|
||||
}),
|
||||
};
|
||||
}
|
||||
function ordersConfig(): CanonicalMatchingConfig {
|
||||
const config = canonicalConfig();
|
||||
config.owners[0]!.mode = 'Orders';
|
||||
return config;
|
||||
}
|
||||
|
||||
describe.skipIf(!url)('canonical paper custody on real PostgreSQL', () => {
|
||||
test('real strategy state/RNG and economic postings match uninterrupted replacement and the direct Rust command tape', async () => {
|
||||
const f = await fixture();
|
||||
await send(f.host, openInput());
|
||||
await send(f.host, markInput(1));
|
||||
await send(f.host, quoteInput(1, '1'));
|
||||
const restored = await f.make();
|
||||
await send(restored, quoteInput(2));
|
||||
await send(restored, markInput(3));
|
||||
const snapshot = await restored.snapshot();
|
||||
expect(snapshot.owners[0]!.diagnostic.nextDecisionSequence).toBe(2);
|
||||
expect(snapshot.owners[0]!.diagnostic.rng.draws).toBe(2);
|
||||
expect(snapshot.account.view.portfolio.positions[0]!.quantity).toBe(
|
||||
parseFinancialDecimal('2.00000000')
|
||||
);
|
||||
const entries = await restored.journal();
|
||||
const identity = snapshot.account.identity;
|
||||
let native = parseFinancialTransactionResult(
|
||||
stageFinancialTransaction(
|
||||
JSON.stringify({ version: 1, kind: 'initialize', identity, config: f.config })
|
||||
),
|
||||
identity
|
||||
);
|
||||
for (const row of entries) {
|
||||
if (row.payload.kind === 'command') {
|
||||
const commandId = row.payload.command.commandId;
|
||||
native = parseFinancialTransactionResult(
|
||||
stageFinancialTransaction(
|
||||
JSON.stringify({
|
||||
version: 1,
|
||||
kind: 'apply',
|
||||
identity,
|
||||
checkpoint: native.checkpoint,
|
||||
command: row.payload.command,
|
||||
})
|
||||
),
|
||||
identity
|
||||
);
|
||||
expect(native.outcome).toEqual(row.payload.outcome);
|
||||
expect(native.view).toEqual(row.payload.view);
|
||||
expect(
|
||||
entries
|
||||
.filter(
|
||||
entry => entry.payload.kind === 'effect' && entry.payload.commandId === commandId
|
||||
)
|
||||
.map(entry => (entry.payload.kind === 'effect' ? entry.payload.fact : null))
|
||||
).toEqual(native.journal);
|
||||
}
|
||||
}
|
||||
expect(native.checkpoint).toEqual(snapshot.account.checkpoint);
|
||||
const baseline = await fixture();
|
||||
for (const input of [
|
||||
openInput(),
|
||||
markInput(1),
|
||||
quoteInput(1, '1'),
|
||||
quoteInput(2),
|
||||
markInput(3),
|
||||
]) {
|
||||
await send(baseline.host, input);
|
||||
}
|
||||
expect(await baseline.host.snapshot()).toEqual(snapshot);
|
||||
expect(await baseline.host.journal()).toEqual(entries);
|
||||
expect((await f.pool.query('SELECT * FROM simulation_orders')).rows).toHaveLength(0);
|
||||
expect((await f.pool.query('SELECT * FROM simulation_fills')).rows).toHaveLength(0);
|
||||
});
|
||||
|
||||
test('competing hosts restore locked owner checkpoints and share one revision without duplicate fills or fees', async () => {
|
||||
const f = await fixture(canonicalConfig(['A', 'B']), [
|
||||
counterProgram('A'),
|
||||
counterProgram('B'),
|
||||
]);
|
||||
const second = await f.make();
|
||||
await send(f.host, openInput());
|
||||
expect(
|
||||
await Promise.all([
|
||||
f.host.enqueue(markInput(1, ['B', 'A'])),
|
||||
second.enqueue(markInput(1, ['B', 'A'])),
|
||||
])
|
||||
).toEqual([true, false]);
|
||||
await Promise.all([f.host.drain(), second.drain()]);
|
||||
await Promise.all([f.host.enqueue(quoteInput(1)), second.enqueue(quoteInput(1))]);
|
||||
await Promise.all([f.host.drain(), second.drain()]);
|
||||
const snapshot = await second.snapshot();
|
||||
expect(snapshot.owners.map(owner => owner.diagnostic.nextDecisionSequence)).toEqual([1, 1]);
|
||||
expect(snapshot.account.view.portfolio.positions.map(position => position.quantity)).toEqual([
|
||||
parseFinancialDecimal('2.00000000'),
|
||||
parseFinancialDecimal('2.00000000'),
|
||||
]);
|
||||
const batches = (await f.pool.query('SELECT payload FROM simulation_canonical_intents')).rows;
|
||||
expect(batches).toHaveLength(1);
|
||||
const decisions = batches[0]!.payload.command.body.decisions;
|
||||
expect(decisions[0].revision).toBe(decisions[1].revision);
|
||||
expect(snapshot.account.view.portfolio.cash).toBe(parseFinancialDecimal('959.60000000'));
|
||||
const conflict = markInput(1, ['A', 'B'], '12');
|
||||
await expect(second.enqueue(conflict)).rejects.toThrow('Conflicting');
|
||||
});
|
||||
|
||||
test('mixed-cadence restart retains every slow owner observation and scoped RNG prefix', async () => {
|
||||
const config = canonicalConfig(['A', 'B']);
|
||||
const programs = [counterProgram('A'), counterProgram('B')];
|
||||
const f = await fixture(config, programs);
|
||||
await send(f.host, openInput());
|
||||
await send(f.host, markInput(1, ['A']));
|
||||
await send(f.host, markInput(2, ['A']));
|
||||
const before = await f.host.snapshot();
|
||||
expect(before.owners[1]!.pendingObservations.map(row => row.source_sequence)).toEqual([1, 2]);
|
||||
const restored = await f.make();
|
||||
await send(restored, markInput(3, ['A', 'B']));
|
||||
const after = await restored.snapshot();
|
||||
expect(after.owners[1]!.diagnostic.state).toEqual({
|
||||
count: 1,
|
||||
samples: [1025555898 / 4294967296],
|
||||
seen: [1, 2, 3],
|
||||
});
|
||||
expect(after.account.observed).toBe(3);
|
||||
expect(after.owners[1]!.diagnostic.observationCount).toBe(3);
|
||||
expect(after.owners[1]!.pendingObservations).toEqual([]);
|
||||
});
|
||||
|
||||
test('checkpoint and complete batch SQL failure rolls back every owner decision/RNG and resumes before later input', async () => {
|
||||
const config = canonicalConfig(['A', 'B']);
|
||||
const programs = [counterProgram('A'), counterProgram('B')];
|
||||
const f = await fixture(config, programs);
|
||||
await send(f.host, openInput());
|
||||
await f.pool
|
||||
.query(`CREATE FUNCTION reject_batch() RETURNS trigger LANGUAGE plpgsql AS $$ BEGIN RAISE EXCEPTION 'batch write failed'; END $$;
|
||||
CREATE TRIGGER reject_batch BEFORE INSERT ON simulation_canonical_intents FOR EACH ROW EXECUTE FUNCTION reject_batch()`);
|
||||
await f.host.enqueue(markInput(1, ['A', 'B']));
|
||||
await f.host.enqueue(quoteInput(1));
|
||||
await expect(f.host.drain()).rejects.toThrow('batch write failed');
|
||||
const failed = await f.host.snapshot();
|
||||
expect(
|
||||
failed.owners.map(owner => [
|
||||
owner.diagnostic.nextDecisionSequence,
|
||||
owner.diagnostic.rng.draws,
|
||||
])
|
||||
).toEqual([
|
||||
[0, 0],
|
||||
[0, 0],
|
||||
]);
|
||||
expect(failed.owners.map(owner => owner.pendingObservations.length)).toEqual([1, 1]);
|
||||
expect((await f.host.getRecoveryStatus()).pendingInput).toBe('quote-1');
|
||||
await f.pool.query('DROP TRIGGER reject_batch ON simulation_canonical_intents');
|
||||
const restored = await f.make();
|
||||
await restored.drain();
|
||||
expect((await restored.snapshot()).account.view.portfolio.positions).toHaveLength(2);
|
||||
});
|
||||
|
||||
test('effect journal failure rolls back native fills, account and input; no phantom publication', async () => {
|
||||
const f = await fixture();
|
||||
await send(f.host, openInput());
|
||||
await send(f.host, markInput(1));
|
||||
const before = await f.host.snapshot();
|
||||
const publications: CanonicalJournalEntry[] = [];
|
||||
const host = await f.make({
|
||||
publish: entries => {
|
||||
publications.push(...entries);
|
||||
},
|
||||
});
|
||||
await host.enqueue(quoteInput(1));
|
||||
await f.pool.query(`CREATE FUNCTION reject_effect() RETURNS trigger LANGUAGE plpgsql AS $$ BEGIN
|
||||
IF NEW.payload->>'kind' = 'effect' THEN RAISE EXCEPTION 'effect write failed'; END IF; RETURN NEW; END $$;
|
||||
CREATE TRIGGER reject_effect BEFORE INSERT ON simulation_strategy_journal FOR EACH ROW EXECUTE FUNCTION reject_effect()`);
|
||||
await expect(host.drain()).rejects.toThrow('effect write failed');
|
||||
expect((await host.snapshot()).account.checkpoint).toEqual(before.account.checkpoint);
|
||||
expect(publications).toEqual([]);
|
||||
expect((await host.getRecoveryStatus()).pendingInput).toBe('quote-1');
|
||||
await f.pool.query('DROP TRIGGER reject_effect ON simulation_strategy_journal');
|
||||
const restored = await f.make();
|
||||
await restored.drain();
|
||||
expect((await restored.snapshot()).account.view.portfolio.positions[0]!.quantity).toBe(
|
||||
parseFinancialDecimal('2.00000000')
|
||||
);
|
||||
});
|
||||
|
||||
test('lost checkpoint/dispatch commit acknowledgement and throwing publication cannot duplicate decisions, costs or effects', async () => {
|
||||
for (const [method, matches] of [
|
||||
['putBatch', isPending],
|
||||
['putBatch', isDispatched],
|
||||
] as const) {
|
||||
const f = await fixture();
|
||||
await send(f.host, openInput());
|
||||
const host = await f.make({
|
||||
repository: failOnce(f.repository, method, 'commit', matches),
|
||||
publish: () => {
|
||||
throw new Error('observer failed');
|
||||
},
|
||||
});
|
||||
await host.enqueue(markInput(1));
|
||||
await host.enqueue(quoteInput(1));
|
||||
await expect(host.drain()).rejects.toThrow('lost commit acknowledgement');
|
||||
const restored = await f.make({
|
||||
publish: () => {
|
||||
throw new Error('observer failed');
|
||||
},
|
||||
});
|
||||
await restored.drain();
|
||||
const before = await restored.snapshot();
|
||||
const journal = await restored.journal();
|
||||
await restored.enqueue(markInput(1));
|
||||
await restored.enqueue(quoteInput(1));
|
||||
await restored.drain();
|
||||
expect(await restored.snapshot()).toEqual(before);
|
||||
expect(await restored.journal()).toEqual(journal);
|
||||
expect(before.owners[0]!.diagnostic.nextDecisionSequence).toBe(1);
|
||||
expect(before.account.view.portfolio.cash).toBe(parseFinancialDecimal('979.80000000'));
|
||||
expect(await restored.journal(journal.at(-2)!.sequence)).toEqual(journal.slice(-1));
|
||||
}
|
||||
});
|
||||
|
||||
test('failed owner callback rolls back earlier owner state/RNG, nested inputs cannot mutate another owner', async () => {
|
||||
let fail = true;
|
||||
let retained: unknown;
|
||||
const first: StrategyProgram<CounterState> = {
|
||||
...counterProgram('A'),
|
||||
decide(context) {
|
||||
retained = context;
|
||||
expect(Object.isFrozen(context.portfolio.portfolio)).toBe(true);
|
||||
expect(Object.isFrozen(context.observations[0])).toBe(true);
|
||||
expect(Object.isFrozen(context.state.samples)).toBe(true);
|
||||
expect(() => Object.assign(context.observations[0]!, { close: '900' })).toThrow();
|
||||
return counterProgram('A').decide(context);
|
||||
},
|
||||
};
|
||||
const second: StrategyProgram<CounterState> = {
|
||||
...counterProgram('B'),
|
||||
decide(context) {
|
||||
expect(context.observations[0]!.close).toBe(parseFinancialDecimal('10.00000000'));
|
||||
if (fail) {
|
||||
throw new Error('second owner failed');
|
||||
}
|
||||
return counterProgram('B').decide(context);
|
||||
},
|
||||
};
|
||||
const f = await fixture(canonicalConfig(['A', 'B']), [first, second]);
|
||||
await send(f.host, openInput());
|
||||
await f.host.enqueue(markInput(1, ['A', 'B']));
|
||||
await expect(f.host.drain()).rejects.toThrow('second owner failed');
|
||||
expect((await f.host.snapshot()).owners.map(owner => owner.diagnostic.rng.draws)).toEqual([
|
||||
0, 0,
|
||||
]);
|
||||
expect(() => (retained as { random(): number }).random()).toThrow('only valid');
|
||||
fail = false;
|
||||
await f.host.drain();
|
||||
expect((await f.host.snapshot()).owners.map(owner => owner.diagnostic.rng.draws)).toEqual([
|
||||
1, 1,
|
||||
]);
|
||||
});
|
||||
|
||||
test('alias receipts after later fills do not append observations, decisions or old effect journals', async () => {
|
||||
const f = await fixture();
|
||||
await send(f.host, openInput());
|
||||
const quote = quoteInput(1);
|
||||
quote.observations = markInput(1).observations;
|
||||
quote.decision = { ...markInput(1).decision!, key: quote.command.key };
|
||||
await send(f.host, quote);
|
||||
await send(f.host, quoteInput(2));
|
||||
const before = await f.host.snapshot();
|
||||
const journal = await f.host.journal();
|
||||
const alias = structuredClone(quote);
|
||||
alias.command.commandId = 'old-quote-alias';
|
||||
await send(f.host, alias);
|
||||
const after = await f.host.snapshot();
|
||||
expect(after.owners).toEqual(before.owners);
|
||||
expect(after.account.observed).toBe(before.account.observed);
|
||||
expect(after.account.view).toEqual(before.account.view);
|
||||
expect(await f.host.journal()).toEqual(journal);
|
||||
expect(after.account.checkpoint.receipts.length).toBe(
|
||||
before.account.checkpoint.receipts.length + 1
|
||||
);
|
||||
});
|
||||
|
||||
test('exact quote cursor decisions never consume the same quote twice; only a later eligible quote fills', async () => {
|
||||
const f = await fixture();
|
||||
await send(f.host, openInput());
|
||||
const quote = quoteInput(1);
|
||||
quote.observations = markInput(1).observations;
|
||||
quote.decision = { ...markInput(1).decision!, key: quote.command.key };
|
||||
await send(f.host, quote);
|
||||
expect((await f.host.snapshot()).account.view.portfolio.positions).toHaveLength(0);
|
||||
const alias = structuredClone(quote);
|
||||
alias.command.commandId = 'quote-alias';
|
||||
await send(f.host, alias);
|
||||
expect((await f.host.snapshot()).owners[0]!.diagnostic.nextDecisionSequence).toBe(1);
|
||||
expect((await f.host.snapshot()).account.view.portfolio.positions).toHaveLength(0);
|
||||
await send(f.host, quoteInput(2));
|
||||
expect((await f.host.snapshot()).account.view.portfolio.positions[0]!.quantity).toBe(
|
||||
parseFinancialDecimal('2.00000000')
|
||||
);
|
||||
});
|
||||
|
||||
test('version/config/seed/initial-state changes and legacy accounts explicitly refuse reinterpretation', async () => {
|
||||
const f = await fixture();
|
||||
const changed = canonicalConfig();
|
||||
changed.risk.feeRate = '0.1';
|
||||
await expect(f.host.initialize(changed)).rejects.toThrow('configuration');
|
||||
for (const program of [
|
||||
{ ...counterProgram(), seed: 8 },
|
||||
{ ...counterProgram(), strategyVersion: '2' },
|
||||
{ ...counterProgram(), initialState: { count: 1, samples: [], seen: [] } },
|
||||
]) {
|
||||
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');
|
||||
});
|
||||
|
||||
test('future observations, wrong availability, direct submissions and out-of-order new commands cannot reach a callback', async () => {
|
||||
let called = 0;
|
||||
const program: StrategyProgram<CounterState> = {
|
||||
...counterProgram(),
|
||||
decide(context) {
|
||||
called++;
|
||||
return counterProgram().decide(context);
|
||||
},
|
||||
};
|
||||
const f = await fixture(canonicalConfig(), [program]);
|
||||
await send(f.host, openInput());
|
||||
const future = markInput(1);
|
||||
future.observations[0]!.available_at = 20;
|
||||
expect(() => f.host.enqueue(future)).toThrow('unavailable');
|
||||
const submit: CanonicalPaperInput = {
|
||||
command: {
|
||||
commandId: 'bypass',
|
||||
key: markInput(1).command.key,
|
||||
body: { kind: 'submit', decisions: [] },
|
||||
},
|
||||
observations: [],
|
||||
};
|
||||
expect(() => f.host.enqueue(submit)).toThrow('durable');
|
||||
const wrong = markInput(1);
|
||||
wrong.decision!.inputs[0]!.availability = 'Missing';
|
||||
await f.host.enqueue(wrong);
|
||||
await expect(f.host.drain()).rejects.toThrow('observation prefix');
|
||||
expect(called).toBe(0);
|
||||
expect((await f.host.getRecoveryStatus()).pendingInput).toBe('mark-1');
|
||||
// Invalid trusted queued inputs are retained for diagnostics; correction requires an explicit new account/tape.
|
||||
const g = await fixture();
|
||||
await send(g.host, openInput());
|
||||
await send(g.host, markInput(2));
|
||||
await g.host.enqueue(markInput(1));
|
||||
await expect(g.host.drain()).rejects.toThrow();
|
||||
expect((await g.host.snapshot()).owners[0]!.diagnostic.nextDecisionSequence).toBe(1);
|
||||
});
|
||||
|
||||
test('corrupt envelope/context identities fail before callback or financial changes', async () => {
|
||||
const f = await fixture();
|
||||
await send(f.host, openInput());
|
||||
const host = await f.make({ repository: failOnce(f.repository, 'putOwner', 'before') });
|
||||
await host.enqueue(markInput(1));
|
||||
await expect(host.drain()).rejects.toThrow('injected');
|
||||
// Stop after the input transaction, before the actual callback.
|
||||
const g = await fixture();
|
||||
await send(g.host, openInput());
|
||||
const stop = await g.make({
|
||||
repository: failOnce(
|
||||
g.repository,
|
||||
'appendJournal',
|
||||
'commit',
|
||||
value => (value as { kind: string }).kind === 'decision'
|
||||
),
|
||||
});
|
||||
await stop.enqueue(markInput(1));
|
||||
await expect(stop.drain()).rejects.toThrow('lost commit');
|
||||
const before = (await g.pool.query('SELECT state FROM simulation_accounts')).rows[0]!.state;
|
||||
await g.pool.query(
|
||||
`UPDATE simulation_strategy_journal SET payload = jsonb_set(payload, '{context,barrier,revision}', '999') WHERE payload->>'kind' = 'decision'`
|
||||
);
|
||||
await expect(g.host.drain()).rejects.toThrow('no longer matches');
|
||||
expect((await g.pool.query('SELECT state FROM simulation_accounts')).rows[0]!.state).toEqual(
|
||||
before
|
||||
);
|
||||
await g.pool.query(
|
||||
`UPDATE simulation_accounts SET state = jsonb_set(state, '{identity,sessionId}', '"corrupt"')`
|
||||
);
|
||||
await expect(g.host.snapshot()).rejects.toThrow('identity or revision');
|
||||
});
|
||||
|
||||
test('GTC partial fill, DAY expiry and IOC/FOK policies survive restarts under next-event timing', async () => {
|
||||
for (const tif of ['GTC', 'DAY', 'IOC', 'FOK'] as const) {
|
||||
const f = await fixture(ordersConfig(), [explicitProgram(tif)]);
|
||||
await send(f.host, openInput());
|
||||
await send(f.host, markInput(1));
|
||||
const restored = await f.make();
|
||||
await send(restored, quoteInput(1, '1'));
|
||||
let snapshot = await restored.snapshot();
|
||||
const order = snapshot.account.checkpoint.orders[0]!;
|
||||
expect(order.filled).toBe(parseFinancialDecimal(tif === 'FOK' ? '0.00000000' : '1.00000000'));
|
||||
expect(order.status).toBe(tif === 'IOC' || tif === 'FOK' ? 'Cancelled' : 'Open');
|
||||
if (tif === 'GTC') {
|
||||
const again = await f.make();
|
||||
await send(again, quoteInput(2));
|
||||
expect((await again.snapshot()).account.checkpoint.orders[0]!.status).toBe('Filled');
|
||||
} else if (tif === 'DAY') {
|
||||
await send(restored, {
|
||||
command: {
|
||||
commandId: 'close',
|
||||
key: { at: 10000, phase: 'SessionClose', instrumentId: 'X', sourceSequence: 0 },
|
||||
body: { kind: 'closeSession', sessionId: 'venue-1' },
|
||||
},
|
||||
observations: [],
|
||||
});
|
||||
snapshot = await (await f.make()).snapshot();
|
||||
expect(snapshot.account.checkpoint.orders[0]!.status).toBe('Expired');
|
||||
}
|
||||
}
|
||||
});
|
||||
test('portfolio reservations enforce shared cash across owners before matching', async () => {
|
||||
const config = canonicalConfig(['A', 'B']);
|
||||
config.risk.ledger.initialCapital = '30';
|
||||
const f = await fixture(config, [counterProgram('A'), counterProgram('B')]);
|
||||
await send(f.host, openInput());
|
||||
await send(f.host, markInput(1, ['A', 'B']));
|
||||
const admitted = await f.host.snapshot();
|
||||
expect(admitted.account.checkpoint.orders.map(order => order.status)).toEqual([
|
||||
'Open',
|
||||
{ Rejected: 'InsufficientCash' },
|
||||
]);
|
||||
await send(await f.make(), quoteInput(1));
|
||||
const snapshot = await f.host.snapshot();
|
||||
expect(snapshot.account.view.portfolio.cash).toBe(parseFinancialDecimal('9.80000000'));
|
||||
expect(snapshot.account.view.portfolio.positions.map(position => position.ownerId)).toEqual([
|
||||
'A',
|
||||
]);
|
||||
});
|
||||
|
||||
test('daily loss survives restart, allows reductions, and requires explicit risk-session rollover', async () => {
|
||||
const config = canonicalConfig();
|
||||
config.risk.maxDailyLoss = '10';
|
||||
const program: StrategyProgram<CounterState> = {
|
||||
...counterProgram(),
|
||||
decide(context) {
|
||||
const next = counterProgram().decide(context);
|
||||
return {
|
||||
...next,
|
||||
intent: {
|
||||
mode: 'target',
|
||||
targets: [
|
||||
{
|
||||
instrumentId: 'X',
|
||||
quantity: parseFinancialDecimal(context.state.count === 1 ? '0' : '2'),
|
||||
},
|
||||
],
|
||||
},
|
||||
};
|
||||
},
|
||||
};
|
||||
const f = await fixture(config, [program]);
|
||||
await send(f.host, openInput());
|
||||
await send(f.host, markInput(1));
|
||||
await send(f.host, quoteInput(1));
|
||||
await send(f.host, markInput(2, ['A'], '1'));
|
||||
expect((await f.host.snapshot()).account.view.risk.dailyHalted).toBe(true);
|
||||
const restored = await f.make();
|
||||
await send(restored, quoteInput(2, '100', '1'));
|
||||
await send(restored, markInput(3, ['A'], '1'));
|
||||
expect((await restored.snapshot()).account.checkpoint.orders.at(-1)!.status).toEqual({
|
||||
Rejected: 'DailyLoss',
|
||||
});
|
||||
await send(restored, {
|
||||
command: {
|
||||
commandId: 'risk-rollover',
|
||||
key: { at: 40, phase: 'Observation', instrumentId: 'X', sourceSequence: 4 },
|
||||
body: {
|
||||
kind: 'riskSessionBoundary',
|
||||
riskSession: {
|
||||
calendarId: 'account',
|
||||
calendarRevision: '1',
|
||||
sessionId: 'risk-2',
|
||||
startsAt: 40,
|
||||
},
|
||||
},
|
||||
},
|
||||
observations: [],
|
||||
});
|
||||
await send(await f.make(), markInput(5, ['A'], '1'));
|
||||
expect((await restored.snapshot()).account.checkpoint.orders.at(-1)!.status).toBe('Open');
|
||||
});
|
||||
|
||||
test('stale quotes never fill restored orders; GTC cancellation releases reservations durably', async () => {
|
||||
const f = await fixture();
|
||||
await send(f.host, openInput());
|
||||
await send(f.host, markInput(1));
|
||||
const stale = quoteInput(201);
|
||||
if (stale.command.body.kind !== 'execute' || stale.command.body.observation.kind !== 'quote') {
|
||||
throw new Error('fixture');
|
||||
}
|
||||
stale.command.body.observation.observedAt = 10;
|
||||
await send(await f.make(), stale);
|
||||
expect((await f.host.snapshot()).account.view.portfolio.positions).toHaveLength(0);
|
||||
expect((await f.host.snapshot()).account.checkpoint.orders[0]!.status).toEqual({
|
||||
Rejected: 'StaleMark',
|
||||
});
|
||||
await send(await f.make(), markInput(202));
|
||||
await send(await f.make(), quoteInput(202));
|
||||
expect((await f.host.snapshot()).account.view.portfolio.positions[0]!.quantity).toBe(
|
||||
parseFinancialDecimal('2.00000000')
|
||||
);
|
||||
const program: StrategyProgram<CounterState> = {
|
||||
...explicitProgram('GTC'),
|
||||
decide(context) {
|
||||
if (context.state.count === 0) {
|
||||
return explicitProgram('GTC').decide(context);
|
||||
}
|
||||
return {
|
||||
nextState: { count: context.state.count + 1, samples: [], seen: [] },
|
||||
intent: { mode: 'orders', orders: [{ kind: 'cancel', orderId: 'explicit-order' }] },
|
||||
};
|
||||
},
|
||||
};
|
||||
const g = await fixture(ordersConfig(), [program]);
|
||||
await send(g.host, openInput());
|
||||
await send(g.host, markInput(1));
|
||||
await send(g.host, quoteInput(1, '1'));
|
||||
const restart = await g.make();
|
||||
await send(restart, markInput(2));
|
||||
expect((await restart.snapshot()).account.checkpoint.orders[0]!.status).toBe('Cancelled');
|
||||
expect((await restart.snapshot()).account.view.reservations).toEqual([]);
|
||||
await send(restart, quoteInput(2));
|
||||
expect((await restart.snapshot()).account.view.portfolio.positions[0]!.quantity).toBe(
|
||||
parseFinancialDecimal('1.00000000')
|
||||
);
|
||||
});
|
||||
|
||||
test('returned native Failed prefix commits exact fees/effects once and remains terminal across restart', async () => {
|
||||
const max = '792281625142643375935.43950335';
|
||||
const config = canonicalConfig(['A', 'B']);
|
||||
config.owners.forEach(owner => {
|
||||
owner.mode = 'Orders';
|
||||
});
|
||||
config.risk.ledger.initialCapital = '100000000000000000000';
|
||||
for (const field of [
|
||||
'maxOrderQuantity',
|
||||
'maxPositionQuantity',
|
||||
'maxSymbolExposure',
|
||||
'maxGrossExposure',
|
||||
] as const) {
|
||||
config.risk[field] = max;
|
||||
}
|
||||
const programs: StrategyProgram<CounterState>[] = ['A', 'B'].map(ownerId => ({
|
||||
...counterProgram(ownerId),
|
||||
mode: 'orders',
|
||||
decide(context) {
|
||||
const order = (orderId: string, side: 'buy' | 'sell', quantity: string) => ({
|
||||
kind: 'market' as const,
|
||||
orderId,
|
||||
instrumentId: 'X',
|
||||
side,
|
||||
quantity: parseFinancialDecimal(quantity),
|
||||
timeInForce: 'GTC' as const,
|
||||
});
|
||||
return {
|
||||
nextState: { count: context.state.count + 1, samples: [context.random()], seen: [] },
|
||||
intent: {
|
||||
mode: 'orders',
|
||||
orders:
|
||||
context.state.count === 0
|
||||
? ownerId === 'A'
|
||||
? [order('seed', 'buy', '1')]
|
||||
: []
|
||||
: [
|
||||
ownerId === 'A'
|
||||
? order('sell', 'sell', '1')
|
||||
: order('overflow', 'buy', '396140812571321687967'),
|
||||
],
|
||||
},
|
||||
};
|
||||
},
|
||||
}));
|
||||
const f = await fixture(config, programs);
|
||||
await send(f.host, openInput());
|
||||
await send(f.host, markInput(1, ['A', 'B'], '0.00000001'));
|
||||
await send(f.host, quoteInput(1, '1', '0.00000001'));
|
||||
await send(f.host, markInput(2, ['A', 'B'], '0.00000001'));
|
||||
const failure = quoteInput(2, max, '3');
|
||||
await f.host.enqueue(failure);
|
||||
await expect(f.host.drain()).rejects.toThrow('Canonical account failed');
|
||||
const snapshot = await f.host.snapshot();
|
||||
const journal = await f.host.journal();
|
||||
expect(typeof snapshot.account.checkpoint.status).toBe('object');
|
||||
expect(
|
||||
snapshot.account.checkpoint.orders.find(order => order.order.orderId === 'sell')!.status
|
||||
).toBe('Filled');
|
||||
expect(snapshot.account.view.portfolio.fees).toEqual([
|
||||
{ ownerId: 'A', amount: parseFinancialDecimal('0.03000000') },
|
||||
{ ownerId: 'B', amount: parseFinancialDecimal('0.00000000') },
|
||||
]);
|
||||
expect(
|
||||
(await f.pool.query("SELECT status FROM simulation_market_inputs WHERE id = 'quote-2'"))
|
||||
.rows[0]!.status
|
||||
).toBe('applied');
|
||||
const restored = await f.make();
|
||||
await expect(restored.drain()).rejects.toThrow('Canonical account failed');
|
||||
expect(await restored.enqueue(failure)).toBe(false);
|
||||
await expect(restored.enqueue(quoteInput(3))).rejects.toThrow('terminal');
|
||||
expect(await restored.snapshot()).toEqual(snapshot);
|
||||
expect(await restored.journal()).toEqual(journal);
|
||||
// Native can return an old successful receipt while the authoritative current checkpoint is Failed.
|
||||
const old = openInput().command;
|
||||
const replay = parseFinancialTransactionResult(
|
||||
stageFinancialTransaction(
|
||||
JSON.stringify({
|
||||
version: 1,
|
||||
kind: 'apply',
|
||||
identity: snapshot.account.identity,
|
||||
checkpoint: snapshot.account.checkpoint,
|
||||
command: old,
|
||||
})
|
||||
),
|
||||
snapshot.account.identity
|
||||
);
|
||||
expect(replay.outcome!.status).toBe('Running');
|
||||
expect(replay.checkpoint.status).toEqual(snapshot.account.checkpoint.status);
|
||||
expect(replay.journal).toEqual([]);
|
||||
});
|
||||
test('canonical SMA checkpoint and buy/sell fills exactly match uninterrupted execution after replacement', async () => {
|
||||
const selection = builtinStrategySelectionSchema.parse({
|
||||
ownerId: 'A',
|
||||
strategyId: 'sma_crossover',
|
||||
strategyVersion: 'sma-crossover-long-only/v1',
|
||||
seed: 7,
|
||||
instrumentId: 'X',
|
||||
seriesId: 'X:quote',
|
||||
ownerBudget: '20',
|
||||
parameters: { fastPeriod: 2, slowPeriod: 3 },
|
||||
});
|
||||
const run = async (restart: boolean) => {
|
||||
const f = await fixture(canonicalConfig(), [createBuiltinStrategy(selection)]);
|
||||
let host = f.host;
|
||||
await send(host, openInput());
|
||||
for (const [index, price] of ['3', '2', '1', '4', '5', '1', '1'].entries()) {
|
||||
await send(host, markInput(index + 1, ['A'], price));
|
||||
if (restart) {
|
||||
host = await f.make({ programs: [createBuiltinStrategy(selection)] });
|
||||
}
|
||||
await send(host, quoteInput(index + 1, '100', price));
|
||||
}
|
||||
return { snapshot: await host.snapshot(), journal: await host.journal() };
|
||||
};
|
||||
const uninterrupted = await run(false);
|
||||
expect(await run(true)).toEqual(uninterrupted);
|
||||
const filled = uninterrupted.snapshot.account.checkpoint.orders.filter(
|
||||
order => order.status === 'Filled'
|
||||
);
|
||||
expect(filled.some(order => order.order.side === 'buy')).toBe(true);
|
||||
expect(filled.some(order => order.order.side === 'sell')).toBe(true);
|
||||
});
|
||||
test('a native failed admission prefix atomically makes its durable batch terminal', async () => {
|
||||
const max = '792281625142643375935.43950335';
|
||||
const config = ordersConfig();
|
||||
config.risk.ledger.initialCapital = max;
|
||||
for (const field of [
|
||||
'maxOrderQuantity',
|
||||
'maxPositionQuantity',
|
||||
'maxSymbolExposure',
|
||||
'maxGrossExposure',
|
||||
] as const) {
|
||||
config.risk[field] = max;
|
||||
}
|
||||
const program: StrategyProgram<CounterState> = {
|
||||
...explicitProgram('GTC'),
|
||||
decide(context) {
|
||||
return {
|
||||
nextState: { count: context.state.count + 1, samples: [context.random()], seen: [] },
|
||||
intent: {
|
||||
mode: 'orders',
|
||||
orders: ['1', max].map((quantity, index) => ({
|
||||
kind: 'market',
|
||||
orderId: `order-${index}`,
|
||||
instrumentId: 'X',
|
||||
side: 'buy',
|
||||
quantity: parseFinancialDecimal(quantity),
|
||||
timeInForce: 'GTC',
|
||||
})),
|
||||
},
|
||||
};
|
||||
},
|
||||
};
|
||||
const f = await fixture(config, [program]);
|
||||
await send(f.host, openInput());
|
||||
await f.host.enqueue(markInput(1));
|
||||
await expect(f.host.drain()).rejects.toThrow('Canonical account failed');
|
||||
const before = await f.host.snapshot();
|
||||
const journal = await f.host.journal();
|
||||
expect(typeof before.account.checkpoint.status).toBe('object');
|
||||
expect(before.owners[0]!.diagnostic.nextDecisionSequence).toBe(1);
|
||||
expect(
|
||||
(await f.pool.query('SELECT status FROM simulation_canonical_intents')).rows.map(
|
||||
row => row.status
|
||||
)
|
||||
).toEqual(['failed']);
|
||||
const restored = await f.make();
|
||||
await expect(restored.drain()).rejects.toThrow('Canonical account failed');
|
||||
expect(await restored.snapshot()).toEqual(before);
|
||||
expect(await restored.journal()).toEqual(journal);
|
||||
});
|
||||
});
|
||||
|
|
@ -3,7 +3,6 @@ import { readFileSync } from 'node:fs';
|
|||
import { afterEach, describe, expect, test } from 'bun:test';
|
||||
import type { PoolClient } from 'pg';
|
||||
import { Pool } from 'pg';
|
||||
import type { IServiceContainer } from '@stock-bot/handlers';
|
||||
import { getLogger, setLoggerConfig } from '@stock-bot/logger';
|
||||
import { PostgreSQLClient } from '@stock-bot/postgres';
|
||||
import { runMigrations } from '../../apps/stock/web-api/src/migrations/migration-runner';
|
||||
|
|
@ -18,6 +17,7 @@ const migrations = [
|
|||
'12-historical-datasets.sql',
|
||||
'13-strategy-recovery.sql',
|
||||
'14-backtest-submission.sql',
|
||||
'15-canonical-paper-intents.sql',
|
||||
];
|
||||
const cleanup: (() => Promise<void>)[] = [];
|
||||
afterEach(async () => {
|
||||
|
|
@ -114,7 +114,7 @@ async function fixture() {
|
|||
});
|
||||
return {
|
||||
queries,
|
||||
run: () => runMigrations({ postgres } as IServiceContainer),
|
||||
run: () => runMigrations({ postgres, logger }),
|
||||
};
|
||||
};
|
||||
const recorded = async () =>
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue