265 lines
9 KiB
TypeScript
265 lines
9 KiB
TypeScript
/** Trusted synchronous programs on the canonical financial engine. Fresh
|
|
* attempts recompute from original inputs; diagnostics are not resume tokens. */
|
|
import type { FinancialStrategyDecision } from '@stock-bot/types';
|
|
import type {
|
|
DeepReadonly,
|
|
StrategyAdmissionFeedback,
|
|
StrategyDiagnostic,
|
|
StrategyDiagnosticSnapshot,
|
|
StrategyProgram,
|
|
} from '../contracts/canonical-strategy';
|
|
import {
|
|
nativeAdmissionOrders,
|
|
replayConfigSchema,
|
|
replayIdentitySchema,
|
|
type DecisionContext,
|
|
type PublishedObservation,
|
|
type ReplayIdentity,
|
|
type ReplayOutput,
|
|
type ReplayProjectionResult,
|
|
type ReplayReportResult,
|
|
type ReplayResult,
|
|
type ReplaySubmissionOutcome,
|
|
} from '../contracts/native-replay';
|
|
import {
|
|
freeze,
|
|
increment,
|
|
metadataSchema,
|
|
stageStrategyDecision,
|
|
stateCopy,
|
|
type Metadata,
|
|
} from '../strategies/strategy-decision';
|
|
import {
|
|
NativeReplaySession,
|
|
runReplaySession,
|
|
type prepareReplayLoad,
|
|
type ReplayController,
|
|
type ReplayMetrics,
|
|
type ReplayOptions,
|
|
} from './native-replay';
|
|
|
|
export type { StrategyProgram } from '../contracts/canonical-strategy';
|
|
export type StrategyReplayOptions = Omit<ReplayOptions, 'reverseCallbacks'>;
|
|
type StrategyRun<Result extends ReplayOutput> = {
|
|
result: Result;
|
|
/** decisionMs includes state staging, validation and admission feedback. */
|
|
metrics: ReplayMetrics;
|
|
diagnostics: DeepReadonly<StrategyDiagnosticSnapshot>;
|
|
};
|
|
|
|
export class StrategyReplayError extends Error {
|
|
constructor(
|
|
cause: unknown,
|
|
readonly diagnostics: DeepReadonly<StrategyDiagnosticSnapshot>
|
|
) {
|
|
super(cause instanceof Error ? cause.message : String(cause), { cause });
|
|
this.name = 'StrategyReplayError';
|
|
}
|
|
}
|
|
|
|
interface Slot {
|
|
program: Metadata & { decide: StrategyProgram['decide'] };
|
|
diagnostic: DeepReadonly<StrategyDiagnostic>;
|
|
pendingObservations: PublishedObservation[];
|
|
}
|
|
class StrategyController implements ReplayController {
|
|
private slots: Map<string, Slot>;
|
|
private committedBarriers = 0;
|
|
private lastBarrierId: string | null = null;
|
|
private observed = 0;
|
|
private staged: {
|
|
barrierId: string;
|
|
expectedRevision: number;
|
|
owners: {
|
|
ownerId: string;
|
|
diagnostic: StrategyDiagnostic;
|
|
decision: FinancialStrategyDecision;
|
|
}[];
|
|
} | null = null;
|
|
|
|
constructor(
|
|
private readonly identity: ReplayIdentity,
|
|
programs: readonly StrategyProgram[],
|
|
config: ReturnType<typeof replayConfigSchema.parse>
|
|
) {
|
|
this.slots = new Map(
|
|
programs.map(program => {
|
|
const { ownerId, strategyId, strategyVersion, mode, seed } = program;
|
|
const metadata = metadataSchema.parse({ ownerId, strategyId, strategyVersion, mode, seed });
|
|
const decide = program.decide;
|
|
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,
|
|
});
|
|
return [ownerId, { program: { ...metadata, decide }, diagnostic, pendingObservations: [] }];
|
|
})
|
|
);
|
|
const owners = config.matching.owners;
|
|
if (
|
|
this.slots.size !== programs.length ||
|
|
this.slots.size !== owners.length ||
|
|
owners.some(owner => this.slots.get(owner.ownerId)?.program.mode !== owner.mode.toLowerCase())
|
|
) {
|
|
throw new Error('Programs must exactly match configured owners and modes');
|
|
}
|
|
}
|
|
|
|
snapshot(): DeepReadonly<StrategyDiagnosticSnapshot> {
|
|
return freeze({
|
|
version: 1,
|
|
identity: this.identity,
|
|
committedBarriers: this.committedBarriers,
|
|
lastBarrierId: this.lastBarrierId,
|
|
strategies: [...this.slots.values()]
|
|
.sort((a, b) =>
|
|
a.program.ownerId < b.program.ownerId ? -1 : a.program.ownerId > b.program.ownerId ? 1 : 0
|
|
)
|
|
.map(slot => slot.diagnostic),
|
|
});
|
|
}
|
|
|
|
stage(context: DecisionContext, observations: readonly PublishedObservation[]) {
|
|
if (this.staged) {
|
|
throw new Error('Previous strategy barrier has not committed');
|
|
}
|
|
this.observed = increment(this.observed, observations.length);
|
|
const due = new Set(context.barrier.owner_ids);
|
|
if (
|
|
this.observed !== context.barrier.observation_count ||
|
|
due.size !== context.barrier.owner_ids.length ||
|
|
[...due].some(owner => !this.slots.has(owner)) ||
|
|
observations.some(observation => observation.available_at > context.barrier.at)
|
|
) {
|
|
throw new Error('Strategy barrier observation or owner mismatch');
|
|
}
|
|
const staged: NonNullable<StrategyController['staged']> = {
|
|
barrierId: context.barrier.barrier_id,
|
|
expectedRevision: increment(context.barrier.revision),
|
|
owners: [],
|
|
};
|
|
for (const slot of this.slots.values()) {
|
|
// Other owners may have slower cadence. Do not discard their warmup/prefix.
|
|
for (const observation of observations) {
|
|
slot.pendingObservations.push(observation);
|
|
}
|
|
if (!due.has(slot.program.ownerId)) {
|
|
continue;
|
|
}
|
|
staged.owners.push(
|
|
stageStrategyDecision(
|
|
this.identity.sessionId,
|
|
slot.program,
|
|
slot.diagnostic,
|
|
slot.pendingObservations,
|
|
context
|
|
)
|
|
);
|
|
}
|
|
this.staged = staged;
|
|
return staged.owners.map(owner => owner.decision);
|
|
}
|
|
|
|
committed(outcome: ReplaySubmissionOutcome): void {
|
|
const staged = this.staged;
|
|
if (
|
|
!staged ||
|
|
outcome.replayed ||
|
|
outcome.status !== 'Running' ||
|
|
outcome.revision !== staged.expectedRevision
|
|
) {
|
|
throw new Error('Unexpected strategy admission acknowledgement');
|
|
}
|
|
const orders = nativeAdmissionOrders(outcome.effects);
|
|
if (
|
|
orders.some(
|
|
order => !staged.owners.some(owner => owner.ownerId === order.order.decision.ownerId)
|
|
)
|
|
) {
|
|
throw new Error('Admission feedback belongs to an owner outside the barrier');
|
|
}
|
|
const nextCount = increment(this.committedBarriers);
|
|
const next = new Map(this.slots);
|
|
// Parse/detach ALL feedback before swapping any committed slot. Even an
|
|
// ambiguous/malformed acknowledgement leaves diagnostics at the old barrier.
|
|
for (const owner of staged.owners) {
|
|
const slot = this.slots.get(owner.ownerId);
|
|
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,
|
|
})),
|
|
};
|
|
next.set(owner.ownerId, {
|
|
program: slot.program,
|
|
diagnostic: freeze({ ...owner.diagnostic, previousAdmission }),
|
|
pendingObservations: [],
|
|
});
|
|
}
|
|
this.slots = next;
|
|
this.committedBarriers = nextCount;
|
|
this.lastBarrierId = staged.barrierId;
|
|
this.staged = null;
|
|
}
|
|
}
|
|
|
|
/* eslint-disable no-redeclare -- Keep selected native result formats precise. */
|
|
export function runStrategyReplay(
|
|
load: ReturnType<typeof prepareReplayLoad>,
|
|
programs: readonly StrategyProgram[],
|
|
options: StrategyReplayOptions & { resultFormat: 'report' }
|
|
): StrategyRun<ReplayReportResult>;
|
|
export function runStrategyReplay(
|
|
load: ReturnType<typeof prepareReplayLoad>,
|
|
programs: readonly StrategyProgram[],
|
|
options: StrategyReplayOptions & { resultFormat: 'projection' }
|
|
): StrategyRun<ReplayProjectionResult>;
|
|
export function runStrategyReplay(
|
|
load: ReturnType<typeof prepareReplayLoad>,
|
|
programs: readonly StrategyProgram[],
|
|
options?: StrategyReplayOptions & { resultFormat?: 'trace' }
|
|
): StrategyRun<ReplayResult>;
|
|
export function runStrategyReplay(
|
|
load: ReturnType<typeof prepareReplayLoad>,
|
|
programs: readonly StrategyProgram[],
|
|
options: StrategyReplayOptions
|
|
): StrategyRun<ReplayOutput>;
|
|
export function runStrategyReplay(
|
|
load: ReturnType<typeof prepareReplayLoad>,
|
|
programs: readonly StrategyProgram[],
|
|
options: StrategyReplayOptions = {}
|
|
): StrategyRun<ReplayOutput> {
|
|
/* eslint-enable no-redeclare */
|
|
const identity = freeze(replayIdentitySchema.parse(load.identity));
|
|
const config = replayConfigSchema.parse(load.config);
|
|
const controller = new StrategyController(identity, programs, config);
|
|
try {
|
|
// Native construction synchronously detaches prepared data/config into Rust.
|
|
// Caller mutations during later callbacks cannot rewrite that loaded input.
|
|
const output = runReplaySession(
|
|
new NativeReplaySession({ ...load, identity, config }),
|
|
controller,
|
|
{ ...options }
|
|
);
|
|
return { ...output, diagnostics: controller.snapshot() };
|
|
} catch (cause) {
|
|
throw new StrategyReplayError(cause, controller.snapshot());
|
|
}
|
|
}
|