refactor(orchestrator): share pure strategy bookkeeping (CL19)
This commit is contained in:
parent
984dc1a9cc
commit
6055aeeee9
17 changed files with 297 additions and 157 deletions
|
|
@ -2,6 +2,7 @@ import { describe, expect, test } from 'bun:test';
|
|||
import { stageFinancialTransaction } from '@stock-bot/engine';
|
||||
import { parseFinancialDecimal } from '@stock-bot/types';
|
||||
import {
|
||||
compareEventKeys,
|
||||
parseFinancialTransactionResult,
|
||||
type CanonicalMatchingCommand,
|
||||
} from '../../apps/stock/orchestrator/src/contracts/canonical-execution';
|
||||
|
|
@ -145,7 +146,11 @@ describe('trusted canonical paper feed policy', () => {
|
|||
});
|
||||
},
|
||||
value => {
|
||||
value.matching.series.push({ ...value.matching.series[0]!, seriesId: 'other' });
|
||||
value.matching.series.push({
|
||||
...value.matching.series[0]!,
|
||||
seriesId: 'other',
|
||||
mode: 'Quote',
|
||||
});
|
||||
},
|
||||
];
|
||||
for (const change of changes) {
|
||||
|
|
@ -465,3 +470,36 @@ describe('paper frame deterministic native command planning', () => {
|
|||
).toThrow(PaperRuntimeError);
|
||||
});
|
||||
});
|
||||
|
||||
test('paper planning and admission use Rust-compatible phase, UTF-8 and sequence ordering', () => {
|
||||
const instruments = ['𐀀', '\ue000', 'A'];
|
||||
const f = fixture(paperFeedConfiguration(instruments));
|
||||
const frame = paperFeedFrame(1000, instruments);
|
||||
const plan = f.plan(frame);
|
||||
expect(plan.map(input => input.command.key)).toEqual(
|
||||
plan.map(input => input.command.key).sort(compareEventKeys)
|
||||
);
|
||||
expect(
|
||||
plan
|
||||
.filter(input => input.command.body.kind === 'openSession')
|
||||
.map(input => input.command.key.instrumentId)
|
||||
).toEqual(['A', '\ue000', '𐀀']);
|
||||
expect(
|
||||
plan
|
||||
.filter(input => input.command.body.kind === 'execute')
|
||||
.map(input => input.command.key.instrumentId)
|
||||
).toEqual(['A', '\ue000', '𐀀']);
|
||||
for (const input of plan) {
|
||||
f.apply(input.command);
|
||||
}
|
||||
const keys: CanonicalMatchingCommand['key'][] = [
|
||||
{ at: 10, phase: 'SessionClose', instrumentId: 'A', sourceSequence: 0 },
|
||||
{ at: 10, phase: 'Execution', instrumentId: 'A', sourceSequence: 0 },
|
||||
{ at: 10, phase: 'Decision', instrumentId: 'A', sourceSequence: 0 },
|
||||
{ at: 10, phase: 'Observation', instrumentId: '𐀀', sourceSequence: 2 },
|
||||
{ at: 10, phase: 'Observation', instrumentId: '𐀀', sourceSequence: 1 },
|
||||
{ at: 10, phase: 'Observation', instrumentId: '\ue000', sourceSequence: 9 },
|
||||
{ at: 9, phase: 'SessionClose', instrumentId: '𐀀', sourceSequence: 9 },
|
||||
];
|
||||
expect([...keys].sort(compareEventKeys)).toEqual([...keys].reverse());
|
||||
});
|
||||
|
|
|
|||
|
|
@ -1,4 +1,5 @@
|
|||
import { afterEach, describe, expect, test } from 'bun:test';
|
||||
import { canonicalJson as neutralCanonicalJson } from '../../apps/stock/orchestrator/src/canonical-json';
|
||||
import { BacktestExecutionRepository } from '../../apps/stock/orchestrator/src/execution/BacktestExecutionRepository';
|
||||
import { canonicalJson } from '../../apps/stock/orchestrator/src/execution/strategy-recovery';
|
||||
import { config, makeExecution, order, quote, start } from '../fixtures/execution';
|
||||
|
|
@ -167,6 +168,16 @@ describe('transactional strategy recovery', () => {
|
|||
}
|
||||
expect(canonicalJson({ b: 1, a: [2] })).toBe(canonicalJson({ a: [2], b: 1 }));
|
||||
});
|
||||
test('canonical serialization retains historical bytes and the compatibility export', () => {
|
||||
expect(canonicalJson).toBe(neutralCanonicalJson);
|
||||
const value = JSON.parse(
|
||||
'{"z":-0,"𐀀":3,"a":[{"z":2,"a":1},null,true],"\\ue000":4,"__proto__":{"b":2,"a":1},"10":10,"2":2}'
|
||||
);
|
||||
const expected =
|
||||
'{"2":2,"10":10,"__proto__":{"a":1,"b":2},"a":[{"a":1,"z":2},null,true],"z":0,"𐀀":3,"\ue000":4}';
|
||||
expect(canonicalJson(value)).toBe(expected);
|
||||
expect(neutralCanonicalJson(value)).toBe(expected);
|
||||
});
|
||||
test('a callback cannot open a nested repository transaction and deadlock its account', async () => {
|
||||
const f = await fixture();
|
||||
f.strategy.onDecision = async () => {
|
||||
|
|
|
|||
|
|
@ -272,51 +272,60 @@ test('post-native-submit failure never publishes unconfirmed strategy state or r
|
|||
expect(retry.diagnostics).toEqual(baseline.diagnostics);
|
||||
});
|
||||
|
||||
test('malformed second-owner feedback after real native admission cannot partially commit diagnostic state', () => {
|
||||
const f = fixture(['A', 'B']);
|
||||
const programs = ['A', 'B'].map(id =>
|
||||
program(id, context => ({
|
||||
nextState: {
|
||||
count: context.state.count + 1,
|
||||
samples: [...context.state.samples, context.random()],
|
||||
},
|
||||
intent: target(String(context.state.count + 1)),
|
||||
}))
|
||||
);
|
||||
const originalSubmit = NativeReplaySession.prototype.submit;
|
||||
let submissions = 0;
|
||||
let failedSession: NativeReplaySession | undefined;
|
||||
NativeReplaySession.prototype.submit = function (...args) {
|
||||
const output = originalSubmit.apply(this, args);
|
||||
failedSession = this;
|
||||
if (++submissions !== 2) {
|
||||
return output;
|
||||
test.each(['status', 'owner'] as const)(
|
||||
'malformed second-owner %s feedback cannot partially commit diagnostic state',
|
||||
field => {
|
||||
const f = fixture(['A', 'B']);
|
||||
const programs = ['A', 'B'].map(id =>
|
||||
program(id, context => ({
|
||||
nextState: {
|
||||
count: context.state.count + 1,
|
||||
samples: [...context.state.samples, context.random()],
|
||||
},
|
||||
intent: target(String(context.state.count + 1)),
|
||||
}))
|
||||
);
|
||||
const originalSubmit = NativeReplaySession.prototype.submit;
|
||||
let submissions = 0;
|
||||
let failedSession: NativeReplaySession | undefined;
|
||||
NativeReplaySession.prototype.submit = function (...args) {
|
||||
const output = originalSubmit.apply(this, args);
|
||||
failedSession = this;
|
||||
if (++submissions !== 2) {
|
||||
return output;
|
||||
}
|
||||
const malformed = structuredClone(output);
|
||||
const secondOwner = malformed.effects.find(effect => {
|
||||
const order = effect.Order as { order: { decision: { ownerId: string } } } | undefined;
|
||||
return order?.order.decision.ownerId === 'B';
|
||||
});
|
||||
expect(secondOwner).toBeDefined();
|
||||
if (field === 'status') {
|
||||
(secondOwner!.Order as { status: unknown }).status = 'InventedStatus';
|
||||
} else {
|
||||
(
|
||||
secondOwner!.Order as { order: { decision: { ownerId: string } } }
|
||||
).order.decision.ownerId = 'outside-the-barrier';
|
||||
}
|
||||
return malformed;
|
||||
};
|
||||
let failure: StrategyReplayError;
|
||||
try {
|
||||
failure = captureFailure(() => runStrategyReplay(f.load, programs));
|
||||
} finally {
|
||||
NativeReplaySession.prototype.submit = originalSubmit;
|
||||
}
|
||||
const malformed = structuredClone(output);
|
||||
const secondOwner = malformed.effects.find(effect => {
|
||||
const order = effect.Order as { order: { decision: { ownerId: string } } } | undefined;
|
||||
return order?.order.decision.ownerId === 'B';
|
||||
});
|
||||
expect(secondOwner).toBeDefined();
|
||||
(secondOwner!.Order as { status: unknown }).status = 'InventedStatus';
|
||||
return malformed;
|
||||
};
|
||||
let failure: StrategyReplayError;
|
||||
try {
|
||||
failure = captureFailure(() => runStrategyReplay(f.load, programs));
|
||||
} finally {
|
||||
NativeReplaySession.prototype.submit = originalSubmit;
|
||||
expect(submissions).toBe(2);
|
||||
expect(failure.diagnostics.committedBarriers).toBe(1);
|
||||
for (const saved of failure.diagnostics.strategies) {
|
||||
expect(saved.nextDecisionSequence).toBe(1);
|
||||
expect(saved.rng.draws).toBe(1);
|
||||
expect((saved.state as CountState).count).toBe(1);
|
||||
expect(saved.previousAdmission?.decision.sequence).toBe(0);
|
||||
}
|
||||
expect(() => failedSession!.project()).toThrow('disposed');
|
||||
}
|
||||
expect(submissions).toBe(2);
|
||||
expect(failure.diagnostics.committedBarriers).toBe(1);
|
||||
for (const saved of failure.diagnostics.strategies) {
|
||||
expect(saved.nextDecisionSequence).toBe(1);
|
||||
expect(saved.rng.draws).toBe(1);
|
||||
expect((saved.state as CountState).count).toBe(1);
|
||||
expect(saved.previousAdmission?.decision.sequence).toBe(0);
|
||||
}
|
||||
expect(() => failedSession!.project()).toThrow('disposed');
|
||||
});
|
||||
);
|
||||
|
||||
test('risk rejection commits state and cursors and returns the actual rejection at the next decision', () => {
|
||||
const f = fixture();
|
||||
|
|
|
|||
|
|
@ -11,16 +11,18 @@ import {
|
|||
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,
|
||||
import {
|
||||
canonicalPaperInputSchema,
|
||||
type CanonicalExecutionRepository,
|
||||
type CanonicalJournalEntry,
|
||||
type CanonicalPaperInput,
|
||||
type 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 { StrategyController } from '../../apps/stock/orchestrator/src/strategies/strategy-controller';
|
||||
import {
|
||||
canonicalConfig,
|
||||
counterProgram,
|
||||
|
|
@ -175,6 +177,62 @@ function ordersConfig(): CanonicalMatchingConfig {
|
|||
}
|
||||
|
||||
describe.skipIf(!url)('canonical paper custody on real PostgreSQL', () => {
|
||||
test('research and durable paper retain identical owned state, RNG and admission feedback', async () => {
|
||||
const config = canonicalConfig(['A', 'B']);
|
||||
const programs = [counterProgram('B'), counterProgram('A')];
|
||||
const f = await fixture(config, programs);
|
||||
const controller = new StrategyController(
|
||||
{ version: 1, sessionId: config.risk.ledger.sessionId, datasetHash: '0'.repeat(64) },
|
||||
programs,
|
||||
{ matching: config }
|
||||
);
|
||||
const diagnostics = async () => (await f.host.snapshot()).owners.map(owner => owner.diagnostic);
|
||||
const initial = controller.snapshot().strategies;
|
||||
expect(initial).toEqual(await diagnostics());
|
||||
programs[0]!.initialState.samples.push(999);
|
||||
expect(initial).toEqual(await diagnostics());
|
||||
expect(controller.snapshot().strategies).toEqual(initial);
|
||||
let cursor = 0;
|
||||
for (const input of [
|
||||
openInput(),
|
||||
markInput(1, ['A', 'B']),
|
||||
quoteInput(1, '1'),
|
||||
markInput(2, ['A', 'B']),
|
||||
]) {
|
||||
await send(f.host, input);
|
||||
const entries = await f.host.journal(cursor);
|
||||
cursor = entries.at(-1)?.sequence ?? cursor;
|
||||
const context = entries.find(entry => entry.payload.kind === 'decision')?.payload;
|
||||
const admitted = entries.find(
|
||||
entry => entry.payload.kind === 'command' && entry.payload.command.body.kind === 'submit'
|
||||
)?.payload;
|
||||
if (context?.kind === 'decision') {
|
||||
if (
|
||||
admitted?.kind !== 'command' ||
|
||||
admitted.command.body.kind !== 'submit' ||
|
||||
!admitted.outcome
|
||||
) {
|
||||
throw new Error('Missing native decision admission in paper journal');
|
||||
}
|
||||
expect(
|
||||
controller
|
||||
.stage(context.context, canonicalPaperInputSchema.parse(input).observations)
|
||||
.sort((a, b) =>
|
||||
Buffer.compare(Buffer.from(a.decision.ownerId), Buffer.from(b.decision.ownerId))
|
||||
)
|
||||
).toEqual(admitted.command.body.decisions);
|
||||
controller.committed(admitted.outcome);
|
||||
}
|
||||
expect(controller.snapshot().strategies).toEqual(await diagnostics());
|
||||
}
|
||||
for (const owner of controller.snapshot().strategies) {
|
||||
expect(owner.rng.draws).toBe(2);
|
||||
expect(
|
||||
owner.previousAdmission?.orders.every(order => order.decision.ownerId === owner.ownerId)
|
||||
).toBe(true);
|
||||
}
|
||||
});
|
||||
|
||||
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());
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue