feat(execution): preserve durable recovery on canonical Rust core

This commit is contained in:
Boki 2026-10-23 15:58:44 -04:00
parent 5e9655de0b
commit c01e96e4dd
27 changed files with 3644 additions and 182 deletions

View file

@ -4,9 +4,16 @@ import {
BacktestEngine,
FinancialReplaySession,
IncrementalSMA,
stageFinancialTransaction,
TechnicalIndicators,
TradingEngine,
} from '@stock-bot/engine';
import { parseFinancialDecimal } from '@stock-bot/types';
import {
financialTransactionRequestSchema,
parseFinancialTransactionResult,
} from '../../apps/stock/orchestrator/src/contracts/canonical-execution';
import nativeReplayLoad from '../../test/fixtures/native-replay-load.json';
describe('generated native bindings', () => {
it('fill P&L is an incremental delta and native FIFO commissions are allocated once', () => {
@ -72,6 +79,7 @@ describe('generated native bindings', () => {
expect(binding.TechnicalIndicators).toBe(TechnicalIndicators);
expect(binding.IncrementalSMA).toBe(IncrementalSMA);
expect(binding.FinancialReplaySession).toBe(FinancialReplaySession);
expect(binding.stageFinancialTransaction).toBe(stageFinancialTransaction);
expect(typeof FinancialReplaySession.prototype.project).toBe('function');
expect(typeof FinancialReplaySession.prototype.report).toBe('function');
});
@ -122,3 +130,169 @@ describe('generated native bindings', () => {
).toThrow('SMA periods must satisfy');
});
});
describe('stateless native financial transaction contract', () => {
const config = nativeReplayLoad.config.matching;
const identity = {
sessionId: config.risk.ledger.sessionId,
accountId: config.risk.ledger.accountId,
};
function initialized() {
const request = financialTransactionRequestSchema.parse({
version: 1,
kind: 'initialize',
identity,
config,
});
return parseFinancialTransactionResult(
stageFinancialTransaction(JSON.stringify(request)),
identity
);
}
function marked() {
const init = initialized();
const at = config.risk.ledger.riskSession.startsAt;
const command = {
commandId: 'mark',
key: { at, phase: 'Observation', instrumentId: 'X0.US', sourceSequence: 0 },
body: { kind: 'mark', seriesId: 'X0.US:1m', price: '10', observedAt: at },
};
const request = financialTransactionRequestSchema.parse({
version: 1,
kind: 'apply',
identity,
checkpoint: init.checkpoint,
command,
});
if (request.kind !== 'apply') {
throw new Error('Expected an apply request in the mark fixture');
}
const raw = stageFinancialTransaction(JSON.stringify(request));
return { init, request, raw, result: parseFinancialTransactionResult(raw, identity) };
}
it('initializes and applies with strict parsed views, checkpoint and exact journal effects', () => {
const { init, result } = marked();
expect(init.outcome).toBeNull();
expect(init.view.equity).toBe(parseFinancialDecimal('10000.00000000'));
expect(result.checkpoint.revision).toBe(1);
expect(result.journal).toHaveLength(1);
expect(result.journal[0]!.viewAfter.admissionRevision).toBe(0);
expect(result.view.admissionRevision).toBe(1);
expect(result.view.portfolio.cash).toBe(init.view.portfolio.cash);
});
it('returns no journal for an old replay after a later mark', () => {
const { request, result } = marked();
const later = {
...request.command,
commandId: 'later',
key: { ...request.command.key, at: request.command.key.at + 1 },
body: {
kind: 'mark',
seriesId: 'X0.US:1m',
price: '11',
observedAt: request.command.key.at + 1,
},
};
const advanced = parseFinancialTransactionResult(
stageFinancialTransaction(
JSON.stringify({ ...request, checkpoint: result.checkpoint, command: later })
),
identity
);
const replay = parseFinancialTransactionResult(
stageFinancialTransaction(JSON.stringify({ ...request, checkpoint: advanced.checkpoint })),
identity
);
expect(replay.journal).toEqual([]);
expect(replay.view).toEqual(advanced.view);
expect(replay.outcome!.revision).toBe(1);
expect(replay.checkpoint.revision).toBe(2);
expect(replay.checkpoint).toEqual(advanced.checkpoint);
});
it('rejects missing fields, wrong identity/revision and altered effect journals', () => {
const { raw } = marked();
const mutations: Array<(value: any) => void> = [
value => {
delete value.journal[0].effect.Risk.command;
},
value => {
delete value.journal[0].effect.Risk.outcome.financial.effects;
},
value => {
value.identity.accountId = 'wrong';
},
value => {
value.view.admissionRevision = 0;
},
value => {
value.journal[0].viewAfter.admissionRevision = 1;
},
value => {
value.journal[0].index = 2;
},
value => {
value.journal[0].effect.Risk.outcome.disposition = { Rejected: 'Invented' };
},
value => {
value.journal[0].effect.Risk.command.commandId = 'different';
},
];
for (const mutate of mutations) {
const bad = JSON.parse(raw);
mutate(bad);
expect(() => parseFinancialTransactionResult(JSON.stringify(bad), identity)).toThrow();
}
const reordered = JSON.parse(raw);
const command = reordered.journal[0].effect.Risk.command;
reordered.journal[0].effect.Risk.command = Object.fromEntries(
Object.entries(command).reverse()
);
expect(() =>
parseFinancialTransactionResult(JSON.stringify(reordered), identity)
).not.toThrow();
});
it('validates initialized metadata and rejects operator/legacy/malformed native requests', () => {
const result = initialized();
const bad = structuredClone(result);
bad.checkpoint.cursor = {
at: 1,
phase: 'Observation',
instrumentId: 'X0.US',
sourceSequence: 0,
};
expect(() => parseFinancialTransactionResult(JSON.stringify(bad), identity)).toThrow(
'initialized'
);
expect(() =>
stageFinancialTransaction(
JSON.stringify({
version: 1,
kind: 'apply',
identity,
checkpoint: { cash: 1000 },
command: {},
})
)
).toThrow();
expect(() =>
stageFinancialTransaction(JSON.stringify({ version: 1, kind: 'reset', identity }))
).toThrow();
expect(() =>
stageFinancialTransaction(
JSON.stringify({
version: 1,
kind: 'initialize',
identity: { ...identity, accountId: 'other' },
config,
})
)
).toThrow('identity');
const request = {
version: 1,
kind: 'initialize',
identity,
config: { ...config, unexpected: true },
};
expect(() => stageFinancialTransaction(JSON.stringify(request))).toThrow();
});
});