refactor(orchestrator): share pure strategy bookkeeping (CL19)

This commit is contained in:
Boki 2026-10-26 20:33:56 -04:00
parent 984dc1a9cc
commit 6055aeeee9
17 changed files with 297 additions and 157 deletions

View file

@ -0,0 +1,23 @@
/** Only JSON values are checkpointable; reject lossy JSON.stringify conversions. */
export function canonicalJson(value: unknown): string {
const visit = (input: unknown): unknown => {
if (input === null || typeof input === 'string' || typeof input === 'boolean') {
return input;
}
if (typeof input === 'number' && Number.isFinite(input)) {
return input;
}
if (Array.isArray(input)) {
return Array.from(input, visit);
}
if (input && typeof input === 'object' && Object.getPrototypeOf(input) === Object.prototype) {
return Object.fromEntries(
Object.entries(input)
.sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0))
.map(([key, item]) => [key, visit(item)])
);
}
throw new Error('Strategy checkpoints require finite, plain JSON values');
};
return JSON.stringify(visit(value));
}

View file

@ -94,6 +94,20 @@ export const matchingCommandSchema = z
.strict();
export type CanonicalMatchingCommand = z.input<typeof matchingCommandSchema>;
/** Event ordering must agree with Rust, including UTF-8 instrument identity ties. */
export function compareEventKeys(
a: CanonicalMatchingCommand['key'],
b: CanonicalMatchingCommand['key']
): number {
const phases = { Observation: 0, Decision: 1, Execution: 2, SessionClose: 3 };
return (
a.at - b.at ||
phases[a.phase] - phases[b.phase] ||
Buffer.compare(Buffer.from(a.instrumentId), Buffer.from(b.instrumentId)) ||
a.sourceSequence - b.sourceSequence
);
}
/** Metadata and shapes only. Rust restores and validates all nested receipts,
* reservations, accounting and indexes before any transition. */
export const canonicalExecutionCheckpointSchema = z

View file

@ -1,6 +1,7 @@
import { AsyncLocalStorage } from 'node:async_hooks';
import { createHash } from 'node:crypto';
import { stageFinancialTransaction } from '@stock-bot/engine';
import { canonicalJson } from '../canonical-json';
import {
canonicalMatchingConfigSchema,
financialTransactionRequestSchema,
@ -15,7 +16,9 @@ import { nativeAdmissionOrders, type DecisionContext } from '../contracts/native
import {
freeze,
increment,
initialStrategyDiagnostic,
metadataSchema,
ownerAdmissionFeedback,
stageStrategyDecision,
stateCopy,
type Metadata,
@ -32,7 +35,6 @@ import {
type CanonicalTransaction,
} from './canonical-paper';
import { ExecutionConflictError } from './repository';
import { canonicalJson } from './strategy-recovery';
const callback = new AsyncLocalStorage<boolean>();
function outsideCallback() {
@ -85,16 +87,7 @@ export class CanonicalPaperExecution {
version: 1,
definition: { ...metadata, initialState },
cursor: 0,
diagnostic: {
ownerId,
strategyId,
strategyVersion,
nextDecisionSequence: 0,
state: stateCopy(initialState),
rng: { algorithm: 'lcg32-v1', seed, state: seed, draws: 0 },
observationCount: 0,
previousAdmission: null,
},
diagnostic: initialStrategyDiagnostic(metadata, initialState),
pendingObservations: [],
};
})
@ -327,18 +320,11 @@ export class CanonicalPaperExecution {
if (!decision) {
continue;
}
owner.diagnostic.previousAdmission = {
decision: decision.decision,
revision: result.outcome.revision,
orders: orders
.filter(order => order.order.decision.ownerId === owner.definition.ownerId)
.map(order => ({
orderId: order.order.orderId,
instrumentId: order.order.instrumentId,
decision: order.order.decision,
status: order.status,
})),
};
owner.diagnostic.previousAdmission = ownerAdmissionFeedback(
decision.decision,
result.outcome.revision,
orders
);
await tx.putOwner(owner);
}
}

View file

@ -1,3 +1,4 @@
import { canonicalJson } from '../canonical-json';
import { increment } from '../strategies/strategy-decision';
import {
canonicalAccountSchema,
@ -12,7 +13,6 @@ import {
type CanonicalTransaction,
} from './canonical-paper';
import { ExecutionConflictError } from './repository';
import { canonicalJson } from './strategy-recovery';
function accountState(raw: unknown): CanonicalAccount {
const result = canonicalAccountSchema.safeParse(raw);

View file

@ -6,7 +6,6 @@ import {
canonicalExecutionCheckpointSchema,
financialTransactionResultSchema,
matchingCommandSchema,
type CanonicalMatchingCommand,
} from '../contracts/canonical-execution';
import {
nativeFinancialViewSchema,
@ -196,18 +195,7 @@ export interface CanonicalExecutionRepository {
transact<T>(accountId: string, work: (tx: CanonicalTransaction) => Promise<T>): Promise<T>;
}
export type CanonicalPostgres = Pick<PostgresClient, 'transaction'>;
export function compareEventKeys(
a: CanonicalMatchingCommand['key'],
b: CanonicalMatchingCommand['key']
): number {
const phases = { Observation: 0, Decision: 1, Execution: 2, SessionClose: 3 };
return (
a.at - b.at ||
phases[a.phase] - phases[b.phase] ||
Buffer.compare(Buffer.from(a.instrumentId), Buffer.from(b.instrumentId)) ||
a.sourceSequence - b.sourceSequence
);
}
export { compareEventKeys } from '../contracts/canonical-execution';
/** Legacy callers must never reinterpret any version of a canonical envelope. */
export function refuseCanonicalAccount(state: unknown): void {
if (state && typeof state === 'object' && 'kind' in state) {

View file

@ -1,30 +1,9 @@
import { createHash } from 'node:crypto';
import { canonicalJson } from '../canonical-json';
import type { MarketData, OrderRequest, StrategyConfig } from '../types';
import type { Account, ExecutionReport, Fill } from './model';
/** Only JSON values are checkpointable; reject lossy JSON.stringify conversions. */
export function canonicalJson(value: unknown): string {
const visit = (input: unknown): unknown => {
if (input === null || typeof input === 'string' || typeof input === 'boolean') {
return input;
}
if (typeof input === 'number' && Number.isFinite(input)) {
return input;
}
if (Array.isArray(input)) {
return Array.from(input, visit);
}
if (input && typeof input === 'object' && Object.getPrototypeOf(input) === Object.prototype) {
return Object.fromEntries(
Object.entries(input)
.sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0))
.map(([key, item]) => [key, visit(item)])
);
}
throw new Error('Strategy checkpoints require finite, plain JSON values');
};
return JSON.stringify(visit(value));
}
export { canonicalJson } from '../canonical-json';
export function strategyConfigHash(config: StrategyConfig, version: string): string {
const { enabled: _enabled, ...definition } = config;
return createHash('sha256').update(canonicalJson({ definition, version })).digest('hex');

View file

@ -1,5 +1,6 @@
import { createHash, randomUUID } from 'node:crypto';
import type { PaperDeploymentBinding } from '@stock-bot/stock-config/paper-deployments';
import { canonicalJson } from '../canonical-json';
import type { StrategyProgram } from '../contracts/canonical-strategy';
import {
paperActivationSchema,
@ -21,7 +22,6 @@ import type {
CanonicalTransaction,
} from '../execution/canonical-paper';
import { CanonicalPaperExecution } from '../execution/CanonicalPaperExecution';
import { canonicalJson } from '../execution/strategy-recovery';
import { planPaperFrame, validatePaperConfiguration, validatePaperFrame } from './feed';
const fingerprint = (value: unknown) =>

View file

@ -3,6 +3,7 @@
import { isDeepStrictEqual } from 'node:util';
import { ZodError } from 'zod';
import {
compareEventKeys,
matchingCommandSchema,
type CanonicalMatchingCommand,
} from '../contracts/canonical-execution';
@ -45,15 +46,6 @@ function unique(values: readonly string[], label: string): void {
invalid(`Duplicate paper ${label}`);
}
}
function keyCompare(a: Key, b: Key): number {
const phase = { Observation: 0, Decision: 1, Execution: 2, SessionClose: 3 };
return (
a.at - b.at ||
phase[a.phase] - phase[b.phase] ||
compareText(a.instrumentId, b.instrumentId) ||
a.sourceSequence - b.sourceSequence
);
}
const observationId = (row: Observation) =>
JSON.stringify([row.series_id, row.event_time, row.source_sequence]);
const physicalQuote = (instrumentId: string, observedAt: number, sourceSequence: number) =>
@ -231,7 +223,7 @@ export function validatePaperFrame(
invalid('Paper quote identity, time, price or size is invalid');
}
}
frame.quotes.sort((a, b) => keyCompare(quoteKey(frame, a), quoteKey(frame, b)));
frame.quotes.sort((a, b) => compareEventKeys(quoteKey(frame, a), quoteKey(frame, b)));
for (let index = 1; index < frame.quotes.length; index++) {
const prior = frame.quotes[index - 1];
const current = frame.quotes[index];
@ -350,7 +342,7 @@ export function planPaperFrame(
const add = (command: CanonicalMatchingCommand) => {
if (
command.key.at <= frame.availableAt &&
(!checkpoint.cursor || keyCompare(command.key, checkpoint.cursor) > 0)
(!checkpoint.cursor || compareEventKeys(command.key, checkpoint.cursor) > 0)
) {
commands.push(command);
}
@ -409,7 +401,7 @@ export function planPaperFrame(
});
}
const active = new Map(checkpoint.sessions);
commands.sort((a, b) => keyCompare(a.key, b.key));
commands.sort((a, b) => compareEventKeys(a.key, b.key));
for (const command of commands) {
if (command.body.kind === 'openSession') {
if (active.has(command.key.instrumentId)) {
@ -424,12 +416,12 @@ export function planPaperFrame(
}
}
const quotes = [...frame.quotes].sort((a, b) =>
keyCompare(quoteKey(frame, a), quoteKey(frame, b))
compareEventKeys(quoteKey(frame, a), quoteKey(frame, b))
);
for (const quote of quotes) {
const key = quoteKey(frame, quote);
if (
(checkpoint.cursor && keyCompare(key, checkpoint.cursor) <= 0) ||
(checkpoint.cursor && compareEventKeys(key, checkpoint.cursor) <= 0) ||
!isDeepStrictEqual(
active.get(quote.instrumentId),
activeSession(config, quote.instrumentId, frame.availableAt)

View file

@ -3,7 +3,6 @@
import type { FinancialStrategyDecision } from '@stock-bot/types';
import type {
DeepReadonly,
StrategyAdmissionFeedback,
StrategyDiagnostic,
StrategyDiagnosticSnapshot,
StrategyProgram,
@ -18,9 +17,10 @@ import {
import {
freeze,
increment,
initialStrategyDiagnostic,
metadataSchema,
ownerAdmissionFeedback,
stageStrategyDecision,
stateCopy,
type Metadata,
} from '../strategies/strategy-decision';
@ -64,16 +64,7 @@ export class StrategyController {
if (typeof decide !== 'function') {
throw new Error('Strategy decide must be synchronous callable code');
}
const diagnostic = freeze({
ownerId,
strategyId,
strategyVersion,
nextDecisionSequence: 0,
state: stateCopy(program.initialState),
rng: { algorithm: 'lcg32-v1' as const, seed, state: seed, draws: 0 },
observationCount: 0,
previousAdmission: null,
});
const diagnostic = freeze(initialStrategyDiagnostic(metadata, program.initialState));
return [ownerId, { program: { ...metadata, decide }, diagnostic, pendingObservations: [] }];
})
);
@ -183,18 +174,11 @@ export class StrategyController {
if (!slot) {
throw new Error('Staged strategy owner is missing');
}
const previousAdmission: StrategyAdmissionFeedback = {
decision: owner.decision.decision,
revision: outcome.revision,
orders: orders
.filter(order => order.order.decision.ownerId === owner.ownerId)
.map(order => ({
orderId: order.order.orderId,
instrumentId: order.order.instrumentId,
decision: order.order.decision,
status: order.status,
})),
};
const previousAdmission = ownerAdmissionFeedback(
owner.decision.decision,
outcome.revision,
orders
);
next.set(owner.ownerId, {
program: slot.program,
diagnostic: freeze({ ...owner.diagnostic, previousAdmission }),

View file

@ -4,10 +4,15 @@ import { z } from 'zod';
import { parseFinancialStrategyDecision, type FinancialStrategyDecision } from '@stock-bot/types';
import type {
DeepReadonly,
StrategyAdmissionFeedback,
StrategyDiagnostic,
StrategyProgram,
} from '../contracts/canonical-strategy';
import type { DecisionContext, PublishedObservation } from '../contracts/native-replay';
import type {
DecisionContext,
nativeAdmissionOrders,
PublishedObservation,
} from '../contracts/native-replay';
export function freeze<T>(value: T): DeepReadonly<T> {
if (value && typeof value === 'object' && !Object.isFrozen(value)) {
@ -83,6 +88,43 @@ export const metadataSchema = z
.strict();
export type Metadata = z.infer<typeof metadataSchema>;
/** Fresh detached diagnostics; each host retains its own commit/freeze boundary. */
export function initialStrategyDiagnostic(
{ ownerId, strategyId, strategyVersion, seed }: Metadata,
initialState: unknown
): StrategyDiagnostic {
return {
ownerId,
strategyId,
strategyVersion,
nextDecisionSequence: 0,
state: stateCopy(initialState),
rng: { algorithm: 'lcg32-v1', seed, state: seed, draws: 0 },
observationCount: 0,
previousAdmission: null,
};
}
/** Project already-validated batch admission into this decision owner's feedback. */
export function ownerAdmissionFeedback(
decision: FinancialStrategyDecision['decision'],
revision: number,
orders: ReturnType<typeof nativeAdmissionOrders>
): StrategyAdmissionFeedback {
return {
decision,
revision,
orders: orders
.filter(order => order.order.decision.ownerId === decision.ownerId)
.map(order => ({
orderId: order.order.orderId,
instrumentId: order.order.instrumentId,
decision: order.order.decision,
status: order.status,
})),
};
}
export function increment(value: number, amount = 1): number {
const next = value + amount;
if (!Number.isSafeInteger(next) || next < 0) {