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

@ -1,8 +1,6 @@
/** Trusted synchronous programs on the canonical financial engine. Fresh
* attempts recompute from original inputs; diagnostics are not resume tokens. */
import { types } from 'node:util';
import { z } from 'zod';
import { parseFinancialStrategyDecision, type FinancialStrategyDecision } from '@stock-bot/types';
import type { FinancialStrategyDecision } from '@stock-bot/types';
import type {
DeepReadonly,
StrategyAdmissionFeedback,
@ -23,6 +21,14 @@ import {
type ReplayResult,
type ReplaySubmissionOutcome,
} from '../contracts/native-replay';
import {
freeze,
increment,
metadataSchema,
stageStrategyDecision,
stateCopy,
type Metadata,
} from '../strategies/strategy-decision';
import {
NativeReplaySession,
runReplaySession,
@ -51,92 +57,11 @@ export class StrategyReplayError extends Error {
}
}
function freeze<T>(value: T): DeepReadonly<T> {
if (value && typeof value === 'object' && !Object.isFrozen(value)) {
for (const child of Object.values(value)) {
freeze(child);
}
Object.freeze(value);
}
return value as DeepReadonly<T>;
}
/** Check descriptors before reading values: JSON.stringify would silently lose
* symbols/custom array keys, invoke accessors, or rewrite non-JSON objects. */
function stateCopy(input: unknown, ancestors = new Set<object>()): unknown {
if (input === null || typeof input === 'string' || typeof input === 'boolean') {
return input;
}
if (typeof input === 'number' && Number.isFinite(input)) {
if (Object.is(input, -0)) {
throw new Error('Strategy state cannot contain negative zero');
}
return input;
}
const invalid = () => new Error('Strategy state requires finite plain JSON data properties');
if (!input || typeof input !== 'object' || ancestors.has(input)) {
throw invalid();
}
const array = Array.isArray(input);
if (Object.getPrototypeOf(input) !== (array ? Array.prototype : Object.prototype)) {
throw invalid();
}
const descriptors = Object.getOwnPropertyDescriptors(input);
const keys = Reflect.ownKeys(input);
if (keys.some(key => typeof key !== 'string')) {
throw invalid();
}
ancestors.add(input);
try {
const data = (key: string): unknown => {
const descriptor = descriptors[key];
if (!descriptor?.enumerable || !('value' in descriptor)) {
throw invalid();
}
return stateCopy(descriptor.value, ancestors);
};
if (array) {
if (keys.length !== input.length + 1) {
throw invalid();
}
return Array.from({ length: input.length }, (_, index) => data(String(index)));
}
// fromEntries preserves an own '__proto__' key without changing prototype.
return Object.fromEntries((keys as string[]).sort().map(key => [key, data(key)]));
} finally {
ancestors.delete(input);
}
}
const id = z
.string()
.min(1)
.refine(value =>
[...value].every(char => char.charCodeAt(0) >= 32 && char.charCodeAt(0) !== 127)
);
const metadataSchema = z
.object({
ownerId: id,
strategyId: id,
strategyVersion: id,
mode: z.enum(['target', 'orders']),
seed: z.number().int().min(0).max(0xffff_ffff),
})
.strict();
type Metadata = z.infer<typeof metadataSchema>;
interface Slot {
program: Metadata & { decide: StrategyProgram['decide'] };
diagnostic: DeepReadonly<StrategyDiagnostic>;
pendingObservations: PublishedObservation[];
}
function increment(value: number, amount = 1): number {
const next = value + amount;
if (!Number.isSafeInteger(next) || next < 0) {
throw new Error('Strategy counter exhausted');
}
return next;
}
class StrategyController implements ReplayController {
private slots: Map<string, Slot>;
private committedBarriers = 0;
@ -229,90 +154,15 @@ class StrategyController implements ReplayController {
if (!due.has(slot.program.ownerId)) {
continue;
}
const { program, diagnostic } = slot;
let active = true,
rngState = diagnostic.rng.state,
draws = diagnostic.rng.draws;
const random = () => {
if (!active) {
throw new Error('Strategy random is only valid during its decision');
}
draws = increment(draws);
rngState = (Math.imul(rngState, 1664525) + 1013904223) >>> 0;
return rngState / 4294967296;
};
let output: ReturnType<StrategyProgram['decide']>;
try {
const decide = program.decide;
output = decide(
Object.freeze({
ownerId: program.ownerId,
strategyId: program.strategyId,
strategyVersion: program.strategyVersion,
decisionSequence: diagnostic.nextDecisionSequence,
now: context.barrier.at,
barrier: context.barrier,
portfolio: context.view,
positions: Object.freeze(
context.view.portfolio.positions.filter(
position => position.ownerId === program.ownerId
)
),
observations: Object.freeze([...slot.pendingObservations]),
previousAdmission: diagnostic.previousAdmission,
state: diagnostic.state,
random,
})
);
} finally {
active = false;
}
if (types.isPromise(output)) {
// Reject async strategies synchronously, but observe their actual
// Promise rejection so failed attempts cannot leak unhandled errors.
// Do not await it or call arbitrary thenable methods.
Promise.prototype.then.call(output, undefined, () => {});
throw new Error('Strategy decide must synchronously return nextState and intent');
}
if (!output || typeof output !== 'object' || 'then' in output) {
throw new Error('Strategy decide must synchronously return nextState and intent');
}
const state = freeze(stateCopy(output.nextState));
const decision = parseFinancialStrategyDecision({
version: 1,
sessionId: this.identity.sessionId,
barrierId: context.barrier.barrier_id,
revision: context.barrier.revision,
decision: {
ownerId: program.ownerId,
decisionId: JSON.stringify([
'strategy',
program.ownerId,
program.strategyId,
program.strategyVersion,
diagnostic.nextDecisionSequence,
]),
sequence: diagnostic.nextDecisionSequence,
},
intent: output.intent,
});
if (decision.intent.mode !== program.mode) {
throw new Error('Strategy intent mode differs from its configured mode');
}
staged.owners.push({
ownerId: program.ownerId,
decision,
diagnostic: {
ownerId: program.ownerId,
strategyId: program.strategyId,
strategyVersion: program.strategyVersion,
state,
nextDecisionSequence: increment(diagnostic.nextDecisionSequence),
rng: { algorithm: 'lcg32-v1', seed: program.seed, state: rngState, draws },
observationCount: increment(diagnostic.observationCount, slot.pendingObservations.length),
previousAdmission: null,
},
});
staged.owners.push(
stageStrategyDecision(
this.identity.sessionId,
slot.program,
slot.diagnostic,
slot.pendingObservations,
context
)
);
}
this.staged = staged;
return staged.owners.map(owner => owner.decision);