feat(research): cut over canonical runtime and enforce agent budgets

This commit is contained in:
Boki 2026-10-24 16:47:19 -04:00
parent ab08db82fd
commit bbf0dd4453
103 changed files with 6138 additions and 3112 deletions

View file

@ -3,22 +3,21 @@ import type { Logger } from '@stock-bot/services';
import { parseBacktestRequest } from '@stock-bot/stock-config/backtest';
import {
canonicalRunRequestSchema,
isCanonicalRunResult,
type CanonicalRunRequest,
type CanonicalRunResult,
type ResearchRunResult,
} from '@stock-bot/stock-config/canonical-research';
import type { BacktestRunResult, HistoricalDatasetManifest } from '@stock-bot/types';
import { prepareDataset } from '../data/historical-dataset';
import type { BacktestRunResult } from '@stock-bot/types';
import type { BacktestConfig } from '../types';
import { BacktestCancelledError, type BacktestExecutionEngine } from './execution-engine';
import { normalizeBacktestResult } from './result';
import {
BacktestCancelledError,
LEGACY_EXECUTION_RETIRED,
type BacktestExecutionEngine,
} from './execution-engine';
import {
BacktestConflictError,
BacktestLeaseLostError,
type BacktestRunRepository,
type CanonicalRunClaim,
type RunClaim,
} from './run-repository';
export { parseBacktestRequest };
@ -32,16 +31,16 @@ function parseDurableRequest(input: unknown): DurableRequest {
: parseBacktestRequest(input);
}
/** One application workflow for HTTP, jobs, and both execution backends. */
/** One canonical workflow for durably admitted research jobs. */
export class BacktestRunner extends EventEmitter {
private busy = false;
private active: RunClaim | CanonicalRunClaim | undefined;
private active: CanonicalRunClaim | undefined;
private leaseFailure: BacktestLeaseLostError | undefined;
private cancelled = false;
private progressWrites: Promise<void> = Promise.resolve();
private closing = false;
private phase: 'preparing' | 'executing' | 'persisting' = 'preparing';
private execution: Promise<ResearchRunResult> | undefined;
private execution: Promise<CanonicalRunResult> | undefined;
constructor(
private readonly dependencies: {
@ -51,20 +50,18 @@ export class BacktestRunner extends EventEmitter {
logger: Pick<Logger, 'error'>;
heartbeatMs?: number;
heartbeatTimeoutMs?: number;
prepare?: (config: BacktestConfig) => Promise<void>;
}
) {
super();
}
/** Retained only to diagnose obsolete callers; canonical work requires durable admission. */
async runBacktest(input: unknown): Promise<BacktestRunResult> {
return this.begin(parseBacktestRequest(input));
parseBacktestRequest(input);
throw new BacktestConflictError(LEGACY_EXECUTION_RETIRED);
}
private begin(config: BacktestConfig): Promise<BacktestRunResult>;
private begin(config: CanonicalRunRequest): Promise<CanonicalRunResult>;
private begin(config: DurableRequest): Promise<ResearchRunResult>;
private begin(config: DurableRequest): Promise<ResearchRunResult> {
private begin(config: CanonicalRunRequest): Promise<CanonicalRunResult> {
if (this.closing) {
throw new BacktestConflictError('Backtest runner is shutting down');
}
@ -101,15 +98,32 @@ export class BacktestRunner extends EventEmitter {
);
throw error;
}
const result = await this.begin({ ...snapshot, runId });
if (!isCanonicalRequest(snapshot)) {
await this.dependencies.repository.rejectPending(runId, LEGACY_EXECUTION_RETIRED);
const retired = await this.dependencies.repository.load(runId);
return { runId, status: retired?.status ?? 'missing' };
}
const result = await this.begin(snapshot);
return { runId, status: result.status };
}
private async execute(config: DurableRequest): Promise<ResearchRunResult> {
private async execute(config: CanonicalRunRequest): Promise<CanonicalRunResult> {
const started = performance.now();
this.progressWrites = Promise.resolve();
let heartbeatTimer: ReturnType<typeof setInterval> | undefined;
let heartbeatWork: Promise<void> | undefined;
let executionDeadline: ReturnType<typeof setTimeout> | undefined;
let deadlineFailure: Error | undefined;
let deadlineStop: Promise<void> | undefined;
const checkDeadline = () => {
const deadline = this.active?.executionDeadlineAt;
if (deadline !== undefined && Date.now() >= deadline) {
deadlineFailure ??= new Error('Research attempt exceeded its admitted execution deadline');
}
if (deadlineFailure) {
throw deadlineFailure;
}
};
const heartbeat = async () => {
const active = this.active;
if (!active) {
@ -183,19 +197,43 @@ export class BacktestRunner extends EventEmitter {
};
this.dependencies.engine.on('progress', onProgress);
try {
if (isCanonicalRequest(config)) {
if (!this.dependencies.repository.startCanonical) {
throw new Error('Canonical run repository is unavailable');
}
this.active = await this.dependencies.repository.startCanonical(config);
} else {
this.active = await this.dependencies.repository.start(config);
if (!this.dependencies.repository.startCanonical) {
throw new Error('Canonical run repository is unavailable');
}
this.active = await this.dependencies.repository.startCanonical(config);
if (
this.active.executionDeadlineAt !== undefined &&
(!Number.isSafeInteger(this.active.executionDeadlineAt) ||
this.active.executionDeadlineAt - Date.now() > 2_147_483_647)
) {
throw new Error('Invalid admitted research execution deadline');
}
checkDeadline();
if (this.active.executionDeadlineAt !== undefined) {
executionDeadline = setTimeout(
() => {
deadlineFailure = new Error(
'Research attempt exceeded its admitted execution deadline'
);
if (this.phase === 'executing') {
deadlineStop = this.dependencies.engine.stopBacktest().catch(error => {
this.dependencies.logger.error('Could not stop expired research attempt', {
error,
});
});
}
},
Math.max(0, this.active.executionDeadlineAt - Date.now())
);
executionDeadline.unref();
}
const executionConfig = canonicalRunRequestSchema.parse(this.active.config);
if (
executionConfig.runId !== this.active.runId ||
executionConfig.backtestId !== this.active.backtestId
) {
throw new Error('Canonical claim identity mismatch');
}
const executionConfig = parseDurableRequest({
...this.active.config,
runId: this.active.runId,
backtestId: this.active.backtestId,
});
heartbeatTimer = setInterval(() => {
if (!heartbeatWork) {
heartbeatWork = heartbeat().finally(() => {
@ -205,15 +243,7 @@ export class BacktestRunner extends EventEmitter {
}, this.dependencies.heartbeatMs ?? 5_000);
heartbeatTimer.unref();
await heartbeat();
if (this.leaseFailure) {
throw this.leaseFailure;
}
if (this.cancelled) {
throw new BacktestCancelledError();
}
if (!isCanonicalRequest(executionConfig)) {
await this.dependencies.prepare?.(executionConfig);
}
checkDeadline();
if (this.leaseFailure) {
throw this.leaseFailure;
}
@ -221,8 +251,8 @@ export class BacktestRunner extends EventEmitter {
throw new BacktestCancelledError();
}
this.phase = 'executing';
let result: ResearchRunResult;
if (isCanonicalRequest(executionConfig)) {
let result: CanonicalRunResult;
{
const engine = this.dependencies.engine;
const repository = this.dependencies.repository;
const loadCanonicalDataset = repository.loadCanonicalDataset;
@ -254,89 +284,40 @@ export class BacktestRunner extends EventEmitter {
request: executionConfig,
...report,
};
} else {
let manifest: HistoricalDatasetManifest | undefined;
const claim = this.active;
const raw = await this.dependencies.engine.runBacktest(
executionConfig,
async (load, signal) => {
signal?.throwIfAborted();
const saved = await this.dependencies.repository.loadDataset(
claim.runId,
claim.attemptId,
executionConfig.datasetHash,
signal
);
const dataset = await prepareDataset(saved ?? (await load()), executionConfig, signal);
signal?.throwIfAborted();
const frozen =
saved ??
(await this.dependencies.repository.freezeDataset(
claim.runId,
claim.attemptId,
dataset,
signal
));
signal?.throwIfAborted();
manifest = frozen.manifest;
return frozen;
}
);
if (!manifest) {
throw new Error('Backtest engine did not resolve frozen execution inputs');
}
if (this.leaseFailure) {
throw this.leaseFailure;
}
try {
result = normalizeBacktestResult(
raw,
this.dependencies.engineName,
executionConfig,
this.active,
performance.now() - started,
this.cancelled,
manifest
);
} catch (error) {
throw new Error('Backtest engine returned an invalid result', { cause: error });
}
}
checkDeadline();
this.phase = 'persisting';
await this.progressWrites;
if (this.leaseFailure) {
throw this.leaseFailure;
}
if (isCanonicalRunResult(result)) {
const completeCanonical = this.dependencies.repository.completeCanonical;
if (!completeCanonical) {
throw new Error('Canonical result persistence is unavailable');
}
await completeCanonical.call(this.dependencies.repository, result, this.active.attemptId);
} else {
await this.dependencies.repository.complete(result, this.active.attemptId);
const completeCanonical = this.dependencies.repository.completeCanonical;
if (!completeCanonical) {
throw new Error('Canonical result persistence is unavailable');
}
checkDeadline();
await completeCanonical.call(this.dependencies.repository, result, this.active.attemptId);
// Observers cannot turn a committed success into a failed run.
this.publish('complete', result);
return result;
} catch (error) {
await this.progressWrites;
let failure = this.leaseFailure ?? error;
let failure = this.leaseFailure ?? deadlineFailure ?? error;
if (this.active && !(failure instanceof BacktestLeaseLostError)) {
try {
if (error instanceof BacktestCancelledError) {
if (failure instanceof BacktestCancelledError) {
await this.dependencies.repository.cancel(this.active.runId, this.active.attemptId);
} else {
await this.dependencies.repository.fail(
this.active.runId,
error instanceof Error ? error.message : String(error),
failure instanceof Error ? failure.message : String(failure),
this.active.attemptId
);
}
} catch (persistenceError) {
this.dependencies.logger.error('Could not record backtest failure', { persistenceError });
// A cancellation acknowledgement must never conceal a failed status write.
if (error instanceof BacktestCancelledError) {
if (failure instanceof BacktestCancelledError) {
failure = persistenceError;
}
}
@ -352,6 +333,10 @@ export class BacktestRunner extends EventEmitter {
}
throw failure;
} finally {
if (executionDeadline) {
clearTimeout(executionDeadline);
}
await deadlineStop;
if (heartbeatTimer) {
clearInterval(heartbeatTimer);
}

View file

@ -16,6 +16,7 @@ import {
import { canonicalWorkerUrl } from './canonical-build';
import {
nativeWorkerMessageSchema,
nativeWorkerRequestSchema,
parseRetainedStrategyResult,
retainedStrategyRequestSchema,
type NativeWorkerRequest,
@ -34,6 +35,7 @@ export class NativeBacktestWorker {
onProgress: (progress: { progress: number; message: string }) => void
): Promise<string> {
signal.throwIfAborted();
request = nativeWorkerRequestSchema.parse(request);
if (this.active) {
throw new BacktestConflictError('A native backtest worker is already running');
}

View file

@ -137,12 +137,12 @@ export class PostgresBacktestRunRepository implements BacktestRunRepository {
const attemptId = randomUUID();
return this.ownedTransaction(request.runId, async client => {
const claimed = await client.query(
`UPDATE runs SET status='running', progress=0, error=NULL,
`UPDATE runs AS r SET status='running', progress=0, error=NULL,
started_at=NOW(), completed_at=NULL, paused_at=NULL, updated_at=NOW(),
attempt_id=$3, attempt_number=attempt_number+1,
lease_expires_at=clock_timestamp()+$4::interval
WHERE id=$1 AND backtest_id=$2 AND status='pending' AND NOT cancel_requested
AND request_snapshot IS NOT NULL RETURNING id,backtest_id,request_snapshot,dataset_hash`,
AND request_snapshot IS NOT NULL RETURNING id,backtest_id,request_snapshot,dataset_hash,(to_jsonb(r)->>'research_deadline_at')::timestamptz AS research_deadline_at`,
[request.runId, request.backtestId, attemptId, `${this.leaseMs} milliseconds`]
);
const row = claimed.rows[0];
@ -163,6 +163,9 @@ export class PostgresBacktestRunRepository implements BacktestRunRepository {
backtestId: String(row.backtest_id),
attemptId,
config: frozen,
...(row.research_deadline_at
? { executionDeadlineAt: new Date(row.research_deadline_at).getTime() }
: {}),
};
});
}

View file

@ -1,24 +1,22 @@
import { EventEmitter } from 'node:events';
import type { Logger } from '@stock-bot/services';
import { parseBacktestRequest } from '@stock-bot/stock-config/backtest';
import {
canonicalRunRequestSchema,
type CanonicalRunRequest,
type CanonicalRunResult,
} from '@stock-bot/stock-config/canonical-research';
import type { HistoricalDatasetV2 } from '@stock-bot/types';
import { resolveDataset, type DatasetResolver } from '../data/historical-dataset';
import { PREPARATION_BATCH_SIZE, preparationCheckpoint } from '../data/preparation';
import type { DatasetResolver } from '../data/historical-dataset';
import type { StorageService } from '../services/StorageService';
import type { BacktestConfig } from '../types';
import {
BacktestCancelledError,
BacktestTimeoutError,
LEGACY_EXECUTION_RETIRED,
type BacktestExecutionEngine,
} from './execution-engine';
import { nativeResultSchema, type NativeBacktestResult } from './native-result';
import { resolveNativeStrategies } from './native-strategies';
import { parseRetainedStrategyResult, type NativeWorkerRequest } from './native-worker-protocol';
import type { NativeBacktestResult } from './native-result';
import { parseRetainedStrategyResult } from './native-worker-protocol';
import { NativeBacktestWorker } from './NativeBacktestWorker';
export type BacktestResult = NativeBacktestResult;
@ -52,22 +50,10 @@ export class RustBacktestAdapter extends EventEmitter implements BacktestExecuti
}
async runBacktest(
input: BacktestConfig,
dataset?: DatasetResolver
_input: BacktestConfig,
_dataset?: DatasetResolver
): Promise<NativeBacktestResult> {
const config = parseBacktestRequest(input);
return this.runOwned(Date.parse(config.startDate), async (signal, aborted) => {
resolveNativeStrategies(config);
const data = await Promise.race([this.loadData(config, signal, dataset), aborted]);
signal.throwIfAborted();
const raw = await this.worker.execute({ type: 'run', config, data }, signal, progress => {
this.progress = progress.progress;
this.publish('progress', progress);
});
const result = nativeResultSchema.parse(JSON.parse(raw));
this.currentTime = Date.parse(config.endDate);
return result;
});
throw new Error(LEGACY_EXECUTION_RETIRED);
}
async runCanonical(
@ -95,7 +81,7 @@ export class RustBacktestAdapter extends EventEmitter implements BacktestExecuti
);
}
/** One ownership/deadline/cancellation lifecycle for legacy and canonical work. */
/** One ownership/deadline/cancellation lifecycle for canonical work. */
private async runOwned<Result>(
initialTime: number,
work: (signal: AbortSignal, aborted: Promise<never>) => Promise<Result>
@ -147,25 +133,6 @@ export class RustBacktestAdapter extends EventEmitter implements BacktestExecuti
}
}
private async loadData(
config: BacktestConfig,
signal: AbortSignal,
resolver?: DatasetResolver
): Promise<Extract<NativeWorkerRequest, { type: 'run' }>['data']> {
signal.throwIfAborted();
const dataset = await resolveDataset(this.dependencies.storage, config, resolver, signal);
signal.throwIfAborted();
const data: Extract<NativeWorkerRequest, { type: 'run' }>['data'] = [];
for (const bar of dataset.bars) {
data.push({ ...bar, type: 'bar' });
if (data.length % PREPARATION_BATCH_SIZE === 0) {
await preparationCheckpoint(signal);
}
}
signal.throwIfAborted();
return data;
}
private publish(event: string, data: unknown): void {
try {
this.emit(event, data);

View file

@ -46,3 +46,7 @@ export class BacktestTimeoutError extends Error {
this.name = 'BacktestTimeoutError';
}
}
/** Old requests remain readable, but must be explicitly reconfigured for canonical admission. */
export const LEGACY_EXECUTION_RETIRED =
'Legacy backtest execution is retired. Select an approved strategy version and retained canonical dataset.';

View file

@ -262,6 +262,15 @@ export interface ReplayController {
): FinancialStrategyDecision[];
committed?(outcome: ReplaySubmissionOutcome): void;
}
/** Restricted hosts communicate asynchronously; financial transitions still run
* on the same native session and the same ordered pull loop. */
export interface AsyncReplayController {
stage(
context: DecisionContext,
observations: readonly PublishedObservation[]
): Promise<FinancialStrategyDecision[]>;
committed?(outcome: ReplaySubmissionOutcome): Promise<void>;
}
/* eslint-disable no-redeclare -- TypeScript overloads preserve the existing trace result type. */
export function runReplayConformance(
session: NativeReplaySession,
@ -329,6 +338,63 @@ export function runReplaySession(
controller: ReplayController,
options: ReplayOptions = {}
) {
const loop = replaySteps(session, options);
try {
let step = loop.next();
while (!step.done) {
const action = step.value;
step = loop.next(
action.kind === 'stage'
? controller.stage(action.context, action.observations)
: controller.committed?.(action.outcome)
);
}
return step.value;
} finally {
// A controller may throw while the generator is suspended at a decision.
// Closing it runs the native disposal even without another advance call.
loop.return(undefined as never);
}
}
export async function runReplaySessionAsync(
session: NativeReplaySession,
controller: AsyncReplayController,
options: ReplayOptions = {}
) {
const loop = replaySteps(session, options);
try {
let step = loop.next();
while (!step.done) {
const action = step.value;
step = loop.next(
action.kind === 'stage'
? await controller.stage(action.context, action.observations)
: await controller.committed?.(action.outcome)
);
}
return step.value;
} finally {
loop.return(undefined as never);
}
}
type ReplayAction =
| {
kind: 'stage';
context: DecisionContext;
observations: readonly PublishedObservation[];
}
| { kind: 'committed'; outcome: ReplaySubmissionOutcome };
function* replaySteps(
session: NativeReplaySession,
options: ReplayOptions
): Generator<
ReplayAction,
{ result: ReplayOutput; metrics: ReplayMetrics },
FinancialStrategyDecision[] | void
> {
const metrics: ReplayMetrics = {
advanceCalls: 0,
submitCalls: 0,
@ -386,7 +452,10 @@ export function runReplaySession(
observations = [];
// Stage all decisions before one admission. A thrown fixture disposes
// the attempt; it cannot publish a partial barrier or successful run.
const decisions = controller.stage(context, publishedDelta);
const decisions = yield { kind: 'stage', context, observations: publishedDelta };
if (!Array.isArray(decisions)) {
throw new Error('Replay controller did not return decisions');
}
metrics.decisionMs += performance.now() - start;
const submitStart = performance.now(),
outcome = session.submit(context.barrier.barrier_id, decisions);
@ -395,11 +464,9 @@ export function runReplaySession(
if (typeof outcome.status === 'object') {
throw new Error(outcome.status.Failed.diagnostic);
}
if (controller.committed) {
const commitStart = performance.now();
controller.committed(outcome);
metrics.decisionMs += performance.now() - commitStart;
}
const commitStart = performance.now();
yield { kind: 'committed', outcome };
metrics.decisionMs += performance.now() - commitStart;
break;
}
}

View file

@ -11,28 +11,9 @@ import type { CanonicalBacktestAnalytics } from '@stock-bot/types';
import { replayTraceSchema } from '../contracts/native-replay';
import type { ReplayReportResult } from '../contracts/native-replay';
import { strategyReplayRequestSchema } from '../contracts/strategy-replay';
import { BacktestConfigSchema } from '../types';
import { buildCanonicalBacktestReport } from './canonical-result';
const finite = z.number().finite();
const legacyRequestSchema = z.object({
type: z.literal('run'),
config: BacktestConfigSchema,
data: z.array(
z.object({
symbol: z.string(),
timestamp: finite,
type: z.literal('bar'),
open: finite,
high: finite,
low: finite,
close: finite,
volume: finite,
vwap: finite,
})
),
});
export const retainedStrategyRequestSchema = z
.object({
type: z.literal('runRetainedStrategy'),
@ -42,7 +23,6 @@ export const retainedStrategyRequestSchema = z
.strict();
export const nativeWorkerRequestSchema = z.union([
legacyRequestSchema,
replayTraceSchema,
strategyReplayRequestSchema,
retainedStrategyRequestSchema,

View file

@ -1,5 +1,4 @@
import { createHash } from 'node:crypto';
import { BacktestEngine } from '@stock-bot/engine';
import type { StrategyProgram } from '../contracts/canonical-strategy';
import type { StrategyReplayResult } from '../contracts/strategy-replay';
import {
@ -10,7 +9,6 @@ import { freeze } from '../strategies/strategy-decision';
import { verifyCanonicalWorkerBuild } from './canonical-build';
import { buildCanonicalBacktestReport } from './canonical-result';
import { executeReplayTrace, prepareReplayLoad } from './native-replay';
import { resolveNativeStrategies } from './native-strategies';
import {
nativeWorkerRequestSchema,
type NativeWorkerMessage,
@ -138,34 +136,11 @@ process.once('message', async (input: unknown) => {
if (request.type === 'runReplayTrace') {
await send({ type: 'progress', progress: 0, message: 'Canonical replay trace started' });
// One load and a local pull loop; no per-observation IPC. The supervisor
// can still SIGKILL native work, exactly as for the legacy one-shot path.
// can still SIGKILL native work, without changing financial execution semantics.
const { result } = executeReplayTrace(request);
await send({ type: 'result', result: JSON.stringify(result) });
return;
}
const { config, data } = request;
const engine = new BacktestEngine({
name: config.name ?? 'Backtest',
strategy: config.strategy,
symbols: config.symbols,
startDate: config.startDate,
endDate: config.endDate,
initialCapital: config.initialCapital,
commission: config.commission ?? 0.001,
slippage: config.slippage ?? 0.0001,
dataFrequency: config.dataFrequency,
});
if (config.riskLimits) {
engine.updateRiskLimits(config.riskLimits);
}
for (const { strategy, name, id, parameters } of resolveNativeStrategies(config)) {
engine.addNativeStrategy(strategy, name, id, parameters);
}
data.sort((a, b) => a.timestamp - b.timestamp);
engine.loadMarketData(data);
await send({ type: 'progress', progress: 0, message: 'Native execution started' });
// This synchronous call is deliberately confined to the child process.
await send({ type: 'result', result: engine.run() });
} catch (error) {
await send({ type: 'error', message: error instanceof Error ? error.message : String(error) });
process.exitCode = 1;

View file

@ -15,6 +15,8 @@ export interface RunClaim extends RunIdentity {
}
export interface CanonicalRunClaim extends RunIdentity {
/** Authoritative per-attempt research budget deadline; outside financial semantics. */
executionDeadlineAt?: number;
attemptId: string;
config: CanonicalRunRequest;
}

View file

@ -1,39 +1,24 @@
/** 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 { StrategyController } from '../strategies/strategy-controller';
import { freeze } from '../strategies/strategy-decision';
import {
NativeReplaySession,
runReplaySession,
type prepareReplayLoad,
type ReplayController,
type ReplayMetrics,
type ReplayOptions,
} from './native-replay';
@ -57,169 +42,6 @@ export class StrategyReplayError extends Error {
}
}
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>,