stock-bot/test/postgres/canonical-paper.test.ts

949 lines
38 KiB
TypeScript

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-builtins';
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('canonical regime strategy retains fractional entry cancellation and exit through every durable restart', async () => {
const selection = builtinStrategySelectionSchema.parse({
ownerId: 'A',
strategyId: 'mean_reversion',
strategyVersion: 'mean-reversion-regime-long-only/v1',
seed: 7,
instrumentId: 'X',
seriesId: 'X:quote',
ownerBudget: '80',
parameters: {
lookbackPeriod: 2,
trendPeriod: 3,
momentumPeriod: 1,
volatilityPeriod: 2,
entryZScore: 1,
exitZScore: 0,
minTrendReturn: -0.5,
minMomentumReturn: -0.5,
maxVolatility: 1,
minNotionalVolume: '1',
regimeFilter: 'volatility',
},
});
const run = async (restart: boolean) => {
const f = await fixture(canonicalConfig(), [createBuiltinStrategy(selection)]);
let host = f.host;
await send(host, openInput());
for (const [index, close] of ['10', '10', '8', '7', '10', '10'].entries()) {
const mark = markInput(index + 1, ['A'], close);
if (index >= 3) {
mark.observations[0]!.volume = parseFinancialDecimal('0');
}
await send(host, mark);
if (restart) {
host = await f.make({ programs: [createBuiltinStrategy(selection)] });
}
if (index === 3) {
expect((await host.snapshot()).owners[0]!.diagnostic.state).toMatchObject({
targetQuantity: parseFinancialDecimal('0.5'),
});
}
const price = ['10', '10', '7', '9', '11', '10'][index]!;
await send(host, quoteInput(index + 1, index === 2 ? '0.5' : '100', price));
if (restart) {
host = await f.make({ programs: [createBuiltinStrategy(selection)] });
}
}
return { snapshot: await host.snapshot(), journal: await host.journal() };
};
const uninterrupted = await run(false);
expect(await run(true)).toEqual(uninterrupted);
const view = uninterrupted.snapshot.account.view;
expect(view.portfolio.cash).toBe(parseFinancialDecimal('1001.91'));
expect(view.equity).toBe(parseFinancialDecimal('1001.91'));
const position = view.portfolio.positions.find(position => position.ownerId === 'A')!;
expect(position.quantity).toBe(parseFinancialDecimal('0'));
expect(position.remainingCost).toBe(parseFinancialDecimal('0'));
expect(position.realizedGrossPnl).toBe(parseFinancialDecimal('2'));
expect(view.portfolio.fees.find(fee => fee.ownerId === 'A')!.amount).toBe(
parseFinancialDecimal('0.09')
);
});
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);
});
});