feat(research): run retained strategies through durable canonical engine

This commit is contained in:
Boki 2026-10-23 21:59:09 -04:00
parent d929db707a
commit 618fb9e33c
58 changed files with 6596 additions and 779 deletions

View file

@ -1,6 +1,13 @@
import { EventEmitter } from 'node:events';
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 { BacktestConfig } from '../types';
@ -10,21 +17,31 @@ import {
BacktestConflictError,
BacktestLeaseLostError,
type BacktestRunRepository,
type CanonicalRunClaim,
type RunClaim,
} from './run-repository';
export { parseBacktestRequest };
type DurableRequest = BacktestConfig | CanonicalRunRequest;
function isCanonicalRequest(value: DurableRequest): value is CanonicalRunRequest {
return 'kind' in value && value.kind === 'canonical-research/v1';
}
function parseDurableRequest(input: unknown): DurableRequest {
return input && typeof input === 'object' && 'kind' in input
? canonicalRunRequestSchema.parse(input)
: parseBacktestRequest(input);
}
/** One application workflow for HTTP, jobs, and both execution backends. */
export class BacktestRunner extends EventEmitter {
private busy = false;
private active: RunClaim | undefined;
private active: RunClaim | 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<BacktestRunResult> | undefined;
private execution: Promise<ResearchRunResult> | undefined;
constructor(
private readonly dependencies: {
@ -41,7 +58,13 @@ export class BacktestRunner extends EventEmitter {
}
async runBacktest(input: unknown): Promise<BacktestRunResult> {
const config = parseBacktestRequest(input);
return this.begin(parseBacktestRequest(input));
}
private begin(config: BacktestConfig): Promise<BacktestRunResult>;
private begin(config: CanonicalRunRequest): Promise<CanonicalRunResult>;
private begin(config: DurableRequest): Promise<ResearchRunResult>;
private begin(config: DurableRequest): Promise<ResearchRunResult> {
if (this.closing) {
throw new BacktestConflictError('Backtest runner is shutting down');
}
@ -65,9 +88,12 @@ export class BacktestRunner extends EventEmitter {
if (['completed', 'cancelled', 'failed'].includes(run.status)) {
return { runId, status: run.status };
}
let snapshot: BacktestConfig;
let snapshot: DurableRequest;
try {
snapshot = parseBacktestRequest(run.config);
snapshot = parseDurableRequest(run.config);
if (isCanonicalRequest(snapshot) && snapshot.runId !== runId) {
throw new Error('Canonical queued run identity mismatch');
}
} catch (error) {
await this.dependencies.repository.rejectPending(
runId,
@ -75,11 +101,11 @@ export class BacktestRunner extends EventEmitter {
);
throw error;
}
const result = await this.runBacktest({ ...snapshot, runId });
const result = await this.begin({ ...snapshot, runId });
return { runId, status: result.status };
}
private async execute(config: BacktestConfig): Promise<BacktestRunResult> {
private async execute(config: DurableRequest): Promise<ResearchRunResult> {
const started = performance.now();
this.progressWrites = Promise.resolve();
let heartbeatTimer: ReturnType<typeof setInterval> | undefined;
@ -157,8 +183,15 @@ export class BacktestRunner extends EventEmitter {
};
this.dependencies.engine.on('progress', onProgress);
try {
this.active = await this.dependencies.repository.start(config);
const executionConfig = parseBacktestRequest({
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);
}
const executionConfig = parseDurableRequest({
...this.active.config,
runId: this.active.runId,
backtestId: this.active.backtestId,
@ -178,7 +211,9 @@ export class BacktestRunner extends EventEmitter {
if (this.cancelled) {
throw new BacktestCancelledError();
}
await this.dependencies.prepare?.(executionConfig);
if (!isCanonicalRequest(executionConfig)) {
await this.dependencies.prepare?.(executionConfig);
}
if (this.leaseFailure) {
throw this.leaseFailure;
}
@ -186,59 +221,101 @@ export class BacktestRunner extends EventEmitter {
throw new BacktestCancelledError();
}
this.phase = 'executing';
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(
let result: ResearchRunResult;
if (isCanonicalRequest(executionConfig)) {
const engine = this.dependencies.engine;
const repository = this.dependencies.repository;
const loadCanonicalDataset = repository.loadCanonicalDataset;
if (!engine.runCanonical || !loadCanonicalDataset || !repository.completeCanonical) {
throw new Error('Canonical execution capabilities are unavailable');
}
const claim = this.active;
const report = await engine.runCanonical(executionConfig, signal =>
loadCanonicalDataset.call(
repository,
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(
)
);
if (this.cancelled) {
throw new BacktestCancelledError();
}
result = {
kind: 'canonical-result/v1',
runId: claim.runId,
backtestId: claim.backtestId,
status: 'completed',
completedAt: new Date().toISOString(),
executionTime: performance.now() - started,
financialEngine: 'rust',
strategyExecution: 'typescript-retained-builtin/v1',
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,
dataset,
executionConfig.datasetHash,
signal
));
signal?.throwIfAborted();
manifest = frozen.manifest;
return frozen;
);
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 });
}
);
if (!manifest) {
throw new Error('Backtest engine did not resolve frozen execution inputs');
}
if (this.leaseFailure) {
throw this.leaseFailure;
}
this.phase = 'persisting';
let result: BacktestRunResult;
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 });
}
await this.progressWrites;
if (this.leaseFailure) {
throw this.leaseFailure;
}
await this.dependencies.repository.complete(result, this.active.attemptId);
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);
}
// Observers cannot turn a committed success into a failed run.
this.publish('complete', result);
return result;

View file

@ -1,4 +1,5 @@
import { fork, type ChildProcess } from 'node:child_process';
import { realpathSync } from 'node:fs';
import { fileURLToPath } from 'node:url';
import {
parseReplayProjectionResult,
@ -12,19 +13,20 @@ import {
parseStrategyReplayResult,
strategyReplayRequestSchema,
} from '../contracts/strategy-replay';
import { nativeWorkerMessageSchema, type NativeWorkerRequest } from './native-worker-protocol';
import { canonicalWorkerUrl } from './canonical-build';
import {
nativeWorkerMessageSchema,
parseRetainedStrategyResult,
retainedStrategyRequestSchema,
type NativeWorkerRequest,
} from './native-worker-protocol';
import { BacktestConflictError } from './run-repository';
/** Hard cancellation requires a process boundary: a thread cannot interrupt native Rust. */
export class NativeBacktestWorker {
private active: ChildProcess | undefined;
constructor(
private readonly workerUrl = new URL(
import.meta.url.endsWith('.ts') ? './native-worker.ts' : './native-worker.js',
import.meta.url
)
) {}
constructor(private readonly workerUrl?: URL) {}
async execute(
request: NativeWorkerRequest,
@ -37,11 +39,30 @@ export class NativeBacktestWorker {
}
// Detach the entire normalized strategy request, including the frozen-data
// payload. The caller must not mutate what is sent or what counts as success.
const retainedRequest =
request.type === 'runRetainedStrategy'
? structuredClone(retainedStrategyRequestSchema.parse(request))
: undefined;
const strategyRequest =
request.type === 'runStrategyReplay'
? structuredClone(strategyReplayRequestSchema.parse(request))
: undefined;
const submitted = strategyRequest ?? request;
const submitted = retainedRequest ?? strategyRequest ?? request;
if (
retainedRequest &&
this.workerUrl &&
realpathSync(fileURLToPath(this.workerUrl)) !==
realpathSync(fileURLToPath(canonicalWorkerUrl))
) {
throw new Error('Retained strategy execution requires the canonical bundled worker');
}
const workerUrl = retainedRequest
? canonicalWorkerUrl
: (this.workerUrl ??
new URL(
import.meta.url.endsWith('.ts') ? './native-worker.ts' : './native-worker.js',
import.meta.url
));
// Capture expected identity/policy before asynchronous execution. A caller
// mutating its request cannot change which completed child result is valid.
const expectedReplay =
@ -56,7 +77,7 @@ export class NativeBacktestWorker {
format: replayResultFormatSchema.parse(submitted.resultFormat ?? 'trace'),
}
: undefined;
const child = fork(fileURLToPath(this.workerUrl), [], {
const child = fork(fileURLToPath(workerUrl), [], {
execPath: process.execPath,
execArgv: [],
serialization: 'json',
@ -94,6 +115,14 @@ export class NativeBacktestWorker {
if (message.type === 'error') {
terminate(new Error(message.message));
} else if (message.type === 'result') {
if (retainedRequest) {
try {
parseRetainedStrategyResult(message.result, retainedRequest.request);
} catch (error) {
terminate(error instanceof Error ? error : new Error(String(error)));
return;
}
}
if (expectedReplay) {
try {
if (strategyRequest) {

View file

@ -6,14 +6,23 @@ import {
parseBacktestRequest,
rejectCatalogVersionReferences,
} from '@stock-bot/stock-config/backtest';
import type { BacktestRunResult, HistoricalDataset } from '@stock-bot/types';
import {
canonicalRunRequestSchema,
parseCanonicalFinancialResult,
type CanonicalRunRequest,
type CanonicalRunResult,
} from '@stock-bot/stock-config/canonical-research';
import { canonicalStrategyJson } from '@stock-bot/stock-config/strategy';
import type { BacktestRunResult, HistoricalDataset, HistoricalDatasetV2 } from '@stock-bot/types';
import { prepareDataset } from '../data/historical-dataset';
import { assertDatasetV2Executable } from '../data/historical-dataset-v2';
import type { BacktestConfig } from '../types';
import { BacktestCancelledError } from './execution-engine';
import {
BacktestConflictError,
BacktestLeaseLostError,
type BacktestRunRepository,
type CanonicalRunClaim,
type RunClaim,
} from './run-repository';
@ -123,6 +132,89 @@ export class PostgresBacktestRunRepository implements BacktestRunRepository {
});
}
async startCanonical(input: CanonicalRunRequest): Promise<CanonicalRunClaim> {
const request = canonicalRunRequestSchema.parse(input);
const attemptId = randomUUID();
return this.ownedTransaction(request.runId, async client => {
const claimed = await client.query(
`UPDATE runs 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`,
[request.runId, request.backtestId, attemptId, `${this.leaseMs} milliseconds`]
);
const row = claimed.rows[0];
if (!row) {
throw new BacktestConflictError('Run is missing, already claimed, or terminal');
}
const frozen = canonicalRunRequestSchema.parse(row.request_snapshot);
if (
canonicalStrategyJson(frozen) !== canonicalStrategyJson(request) ||
row.dataset_hash !== frozen.datasetHash
) {
throw new BacktestConflictError(
'Canonical request does not match its admitted snapshot and dataset'
);
}
return {
runId: String(row.id),
backtestId: String(row.backtest_id),
attemptId,
config: frozen,
};
});
}
async loadCanonicalDataset(
runId: string,
attemptId: string,
requestedHash: string,
signal?: AbortSignal
): Promise<HistoricalDatasetV2> {
signal?.throwIfAborted();
return this.ownedTransaction(runId, async client => {
const owned = await client.query(
`SELECT dataset_hash,request_snapshot FROM runs WHERE id=$1 AND attempt_id=$2
AND lease_expires_at>clock_timestamp() AND status IN ('running','paused') AND NOT cancel_requested`,
[runId, attemptId]
);
const row = owned.rows[0];
if (!row) {
throw new BacktestLeaseLostError('Execution lease lost');
}
const request = canonicalRunRequestSchema.parse(row.request_snapshot);
if (row.dataset_hash !== requestedHash || request.datasetHash !== requestedHash) {
throw new BacktestConflictError('Canonical dataset does not match its immutable binding');
}
const saved = await client.query('SELECT payload FROM backtest_datasets WHERE hash=$1', [
requestedHash,
]);
if (!saved.rows[0]) {
throw new Error('Frozen canonical dataset not found');
}
signal?.throwIfAborted();
const dataset = assertDatasetV2Executable(saved.rows[0].payload);
if (dataset.manifest.hash !== requestedHash || dataset.manifest.eligibility !== 'eligible') {
throw new BacktestConflictError(
'Stored canonical dataset identity or eligibility mismatch'
);
}
signal?.throwIfAborted();
// Validation may outlast a lease; do not let a late read authorize execution.
const stillOwned = await client.query(
`SELECT id FROM runs WHERE id=$1 AND attempt_id=$2 AND lease_expires_at>clock_timestamp()
AND status IN ('running','paused') AND NOT cancel_requested`,
[runId, attemptId]
);
if (!stillOwned.rows.length) {
throw new BacktestLeaseLostError('Execution lease lost while validating dataset');
}
return dataset;
});
}
async rejectPending(runId: string, error: string) {
await this.postgres.transaction(async client => {
await client.query(
@ -259,26 +351,8 @@ export class PostgresBacktestRunRepository implements BacktestRunRepository {
async complete(result: BacktestRunResult, attemptId: string): Promise<void> {
await this.ownedTransaction(result.runId, async client => {
const updated = await client.query(
`UPDATE runs SET status = $2::run_status, progress = CASE WHEN $2::run_status = 'completed' THEN 100 ELSE progress END,
completed_at = $3, updated_at = NOW(), error = NULL, lease_expires_at = NULL
WHERE id = $1 AND backtest_id = $4 AND status IN ('running', 'paused')
AND attempt_id = $5 AND lease_expires_at > clock_timestamp() AND NOT cancel_requested RETURNING id, dataset_hash`,
[result.runId, result.status, result.completedAt, result.backtestId, attemptId]
);
if (!updated.rows.length) {
const cancellation = await client.query(
`SELECT id FROM runs
WHERE id = $1 AND attempt_id = $2 AND lease_expires_at > clock_timestamp()
AND status IN ('running', 'paused') AND cancel_requested`,
[result.runId, attemptId]
);
if (cancellation.rows.length) {
throw new BacktestCancelledError();
}
throw new BacktestLeaseLostError('Execution lease lost');
}
if (!result.config.dataset || result.config.dataset.hash !== updated.rows[0]?.dataset_hash) {
const updated = await this.markComplete(client, result, attemptId);
if (!result.config.dataset || result.config.dataset.hash !== updated.dataset_hash) {
throw new BacktestConflictError('Result does not reference the run frozen dataset');
}
await client.query(
@ -302,6 +376,69 @@ export class PostgresBacktestRunRepository implements BacktestRunRepository {
});
}
private async markComplete(
client: PoolClient,
result: Pick<BacktestRunResult, 'runId' | 'backtestId' | 'status' | 'completedAt'>,
attemptId: string
) {
const updated = await client.query(
`UPDATE runs SET status = $2::run_status, progress = CASE WHEN $2::run_status = 'completed' THEN 100 ELSE progress END,
completed_at = $3, updated_at = NOW(), error = NULL, lease_expires_at = NULL
WHERE id = $1 AND backtest_id = $4 AND status IN ('running', 'paused')
AND attempt_id = $5 AND lease_expires_at > clock_timestamp() AND NOT cancel_requested RETURNING id, dataset_hash`,
[result.runId, result.status, result.completedAt, result.backtestId, attemptId]
);
if (!updated.rows.length) {
const cancellation = await client.query(
`SELECT id FROM runs
WHERE id = $1 AND attempt_id = $2 AND lease_expires_at > clock_timestamp()
AND status IN ('running', 'paused') AND cancel_requested`,
[result.runId, attemptId]
);
if (cancellation.rows.length) {
throw new BacktestCancelledError();
}
throw new BacktestLeaseLostError('Execution lease lost');
}
return updated.rows[0];
}
async completeCanonical(result: CanonicalRunResult, attemptId: string): Promise<void> {
const request = canonicalRunRequestSchema.parse(result.request);
if (
result.kind !== 'canonical-result/v1' ||
result.status !== 'completed' ||
result.runId !== request.runId ||
result.backtestId !== request.backtestId ||
result.financialEngine !== 'rust' ||
result.strategyExecution !== 'typescript-retained-builtin/v1'
) {
throw new BacktestConflictError('Canonical result identity mismatch');
}
parseCanonicalFinancialResult(result.financial, request);
await this.ownedTransaction(result.runId, async client => {
const frozen = await client.query(
'SELECT request_snapshot,dataset_hash FROM runs WHERE id=$1',
[result.runId]
);
const row = frozen.rows[0];
if (
!row ||
canonicalStrategyJson(row.request_snapshot) !== canonicalStrategyJson(request) ||
row.dataset_hash !== request.datasetHash
) {
throw new BacktestConflictError('Canonical result does not match its admitted inputs');
}
await this.markComplete(client, result, attemptId);
await client.query(
`INSERT INTO backtest_results
(run_id,completed_at,execution_time,canonical_result,metrics,equity_curve,ohlc_data,trades,positions,analytics)
VALUES ($1,$2,$3,$4::jsonb,'null'::jsonb,'null'::jsonb,'null'::jsonb,'null'::jsonb,'null'::jsonb,'null'::jsonb)`,
[result.runId, result.completedAt, Math.round(result.executionTime), JSON.stringify(result)]
);
});
}
async updateProgress(
runId: string,
progress: number,

View file

@ -1,6 +1,12 @@
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 { StorageService } from '../services/StorageService';
@ -12,7 +18,7 @@ import {
} from './execution-engine';
import { nativeResultSchema, type NativeBacktestResult } from './native-result';
import { resolveNativeStrategies } from './native-strategies';
import type { NativeWorkerRequest } from './native-worker-protocol';
import { parseRetainedStrategyResult, type NativeWorkerRequest } from './native-worker-protocol';
import { NativeBacktestWorker } from './NativeBacktestWorker';
export type BacktestResult = NativeBacktestResult;
@ -49,12 +55,56 @@ export class RustBacktestAdapter extends EventEmitter implements BacktestExecuti
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;
});
}
async runCanonical(
input: CanonicalRunRequest,
resolveDataset: (signal: AbortSignal) => Promise<HistoricalDatasetV2>
): Promise<Pick<CanonicalRunResult, 'financial' | 'analytics'>> {
const request = canonicalRunRequestSchema.parse(input);
return this.runOwned(
request.policy.matching.risk.ledger.riskSession.startsAt,
async (signal, aborted) => {
const dataset = await Promise.race([resolveDataset(signal), aborted]);
signal.throwIfAborted();
const raw = await this.worker.execute(
{ type: 'runRetainedStrategy', request, dataset },
signal,
progress => {
this.progress = progress.progress;
this.publish('progress', progress);
}
);
const result = parseRetainedStrategyResult(raw, request);
this.currentTime = dataset.manifest.bounds.tradeEnd;
return { financial: result.financial, analytics: result.analytics };
}
);
}
/** One ownership/deadline/cancellation lifecycle for legacy and canonical work. */
private async runOwned<Result>(
initialTime: number,
work: (signal: AbortSignal, aborted: Promise<never>) => Promise<Result>
): Promise<Result> {
if (this.closing || this.active) {
throw new Error(
this.closing ? 'Native backtest engine is shutting down' : 'Backtest already running'
);
}
const config = parseBacktestRequest(input);
const controller = new AbortController();
let finished!: () => void;
this.active = {
@ -64,7 +114,7 @@ export class RustBacktestAdapter extends EventEmitter implements BacktestExecuti
}),
};
this.progress = 0;
this.currentTime = Date.parse(config.startDate);
this.currentTime = initialTime;
const timeout = setTimeout(
() => controller.abort(new BacktestTimeoutError(this.timeoutMs)),
this.timeoutMs
@ -77,17 +127,7 @@ export class RustBacktestAdapter extends EventEmitter implements BacktestExecuti
});
signal.addEventListener('abort', onAbort, { once: true });
try {
resolveNativeStrategies(config);
// Race the read too: a slow database must not prevent cancellation. A late read
// cannot spawn a worker after the run has been stopped.
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);
const result = await work(signal, aborted);
this.progress = 100;
this.publish('complete', result);
return result;

View file

@ -0,0 +1,79 @@
/** Read-only build identity. This module never imports the native addon or strategy code. */
import { createHash } from 'node:crypto';
import { realpathSync } from 'node:fs';
import { readFile } from 'node:fs/promises';
import { dirname, isAbsolute, relative, resolve } from 'node:path';
import { fileURLToPath, pathToFileURL } from 'node:url';
import {
canonicalBuildIdentitySchema,
type CanonicalBuildIdentity,
} from '@stock-bot/stock-config/canonical-research';
import { canonicalStrategyJson } from '@stock-bot/stock-config/strategy';
const engineWrapper = realpathSync(fileURLToPath(import.meta.resolve('@stock-bot/engine')));
const repositoryRoot = resolve(dirname(engineWrapper), '../../..');
const ownPath = relative(repositoryRoot, realpathSync(fileURLToPath(import.meta.url)));
if (isAbsolute(ownPath) || ownPath === '..' || ownPath.startsWith('../')) {
throw new Error('Canonical engine resolves outside this checkout');
}
if (engineWrapper !== resolve(repositoryRoot, 'apps/stock/engine/index.mjs')) {
throw new Error('Unsupported canonical engine wrapper location');
}
export const canonicalWorkerUrl = pathToFileURL(
resolve(repositoryRoot, 'apps/stock/orchestrator/dist/native-worker.js')
);
async function hashLocalFile(path: string): Promise<string> {
if (realpathSync(path) !== path) {
throw new Error('Canonical build artifacts must belong to this checkout');
}
return createHash('sha256')
.update(await readFile(path))
.digest('hex');
}
/** Capture all executable worker/native bytes and the runtime that interprets them. */
export async function readCanonicalBuildIdentity(): Promise<CanonicalBuildIdentity> {
if (typeof Bun === 'undefined') {
throw new Error('Canonical research requires the Bun runtime');
}
const [workerSha256, engineWrapperSha256, engineBinarySha256, dependencyLockSha256] =
await Promise.all([
hashLocalFile(fileURLToPath(canonicalWorkerUrl)),
hashLocalFile(engineWrapper),
hashLocalFile(resolve(repositoryRoot, 'apps/stock/engine/dist/engine.node')),
hashLocalFile(resolve(repositoryRoot, 'bun.lock')),
]);
return canonicalBuildIdentitySchema.parse({
version: 1,
workerSha256,
engineWrapperSha256,
engineBinarySha256,
dependencyLockSha256,
runtime: 'bun',
runtimeVersion: Bun.version,
platform: process.platform,
arch: process.arch,
});
}
/** The running child supplies its own module URL, never a URL from the request. */
export async function verifyCanonicalWorkerBuild(
expected: CanonicalBuildIdentity,
actualWorkerUrl: string
): Promise<CanonicalBuildIdentity> {
if (
realpathSync(fileURLToPath(actualWorkerUrl)) !== realpathSync(fileURLToPath(canonicalWorkerUrl))
) {
throw new Error('Canonical research requires the bundled worker from this checkout');
}
const actual = await readCanonicalBuildIdentity();
if (
canonicalStrategyJson(actual) !==
canonicalStrategyJson(canonicalBuildIdentitySchema.parse(expected))
) {
throw new Error('Canonical worker/native/runtime build identity mismatch');
}
return actual;
}

View file

@ -1,4 +1,9 @@
import type { EventEmitter } from 'node:events';
import type {
CanonicalRunRequest,
CanonicalRunResult,
} from '@stock-bot/stock-config/canonical-research';
import type { HistoricalDatasetV2 } from '@stock-bot/types';
import type { DatasetResolver } from '../data/historical-dataset';
import type { BacktestConfig } from '../types';
import type { NativeBacktestResult } from './native-result';
@ -10,6 +15,10 @@ export interface BacktestExecutionEngine extends Pick<EventEmitter, 'on' | 'off'
config: BacktestConfig,
dataset?: DatasetResolver
): Promise<BacktestResult | NativeBacktestResult>;
runCanonical?(
request: CanonicalRunRequest,
resolveDataset: (signal: AbortSignal) => Promise<HistoricalDatasetV2>
): Promise<Pick<CanonicalRunResult, 'financial' | 'analytics'>>;
stopBacktest(): Promise<void>;
pauseBacktest(): Promise<void>;
resumeBacktest(): Promise<void>;

View file

@ -1,7 +1,18 @@
import { z } from 'zod';
import {
canonicalBuildIdentitySchema,
canonicalRunRequestSchema,
parseCanonicalFinancialResult,
type CanonicalBuildIdentity,
type CanonicalRunRequest,
} from '@stock-bot/stock-config/canonical-research';
import { canonicalStrategyJson } from '@stock-bot/stock-config/strategy';
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({
@ -22,12 +33,61 @@ const legacyRequestSchema = z.object({
),
});
export const retainedStrategyRequestSchema = z
.object({
type: z.literal('runRetainedStrategy'),
request: canonicalRunRequestSchema,
dataset: z.unknown(),
})
.strict();
export const nativeWorkerRequestSchema = z.union([
legacyRequestSchema,
replayTraceSchema,
strategyReplayRequestSchema,
retainedStrategyRequestSchema,
]);
export interface RetainedStrategyResult {
type: 'retainedStrategyResult';
version: 1;
build: CanonicalBuildIdentity;
artifactHash: string;
financial: ReplayReportResult;
analytics: CanonicalBacktestAnalytics;
}
const retainedStrategyResultSchema = z
.object({
type: z.literal('retainedStrategyResult'),
version: z.literal(1),
build: canonicalBuildIdentitySchema,
artifactHash: z.string().regex(/^[a-f0-9]{64}$/),
financial: z.unknown(),
analytics: z.unknown(),
})
.strict();
/** Financial facts are validated, never recalculated. F08 alone owns statistical reporting. */
export function parseRetainedStrategyResult(
input: string,
request: CanonicalRunRequest
): RetainedStrategyResult {
const envelope = retainedStrategyResultSchema.parse(JSON.parse(input));
if (
canonicalStrategyJson(envelope.build) !== canonicalStrategyJson(request.build) ||
envelope.artifactHash !== request.strategy.package.artifact.sha256
) {
throw new Error('Retained strategy result build/artifact identity mismatch');
}
const financial = parseCanonicalFinancialResult(envelope.financial, request);
const analytics = buildCanonicalBacktestReport(financial, request.analyticsPolicy).analytics;
if (canonicalStrategyJson(envelope.analytics) !== canonicalStrategyJson(analytics)) {
throw new Error('Retained strategy result analytics do not match the frozen policy');
}
return { ...envelope, financial, analytics };
}
export const nativeWorkerMessageSchema = z.discriminatedUnion('type', [
z.object({ type: z.literal('progress'), progress: finite.min(0).max(100), message: z.string() }),
z.object({ type: z.literal('result'), result: z.string() }),

View file

@ -1,12 +1,21 @@
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 {
createBuiltinStrategy,
validateBuiltinStrategyBindings,
} from '../strategies/canonical-builtins';
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 } from './native-worker-protocol';
import {
nativeWorkerRequestSchema,
type NativeWorkerMessage,
type RetainedStrategyResult,
} from './native-worker-protocol';
import { runStrategyReplay } from './strategy-runtime';
/** One process, one native engine, one request. No database or service-container access. */
@ -23,6 +32,79 @@ function send(message: NativeWorkerMessage): Promise<void> {
process.once('message', async (input: unknown) => {
try {
const request = nativeWorkerRequestSchema.parse(input);
if (request.type === 'runRetainedStrategy') {
const admitted = request.request;
// Identity checks precede bundle import, including any top-level module side effects.
const build = await verifyCanonicalWorkerBuild(admitted.build, import.meta.url);
const pkg = admitted.strategy.package;
const hash = (content: string) => createHash('sha256').update(content, 'utf8').digest('hex');
if (
hash(pkg.artifact.content) !== pkg.artifact.sha256 ||
hash(pkg.dependencyLock.content) !== pkg.dependencyLock.sha256
) {
throw new Error('Retained strategy artifact or dependency lock hash mismatch');
}
if (pkg.program.apiVersion !== 'canonical-ts/v1') {
throw new Error('Unsupported retained strategy API version');
}
const load = prepareReplayLoad(request.dataset, admitted.policy);
if (
load.identity.datasetHash !== admitted.datasetHash ||
load.manifest.eligibility !== 'eligible' ||
load.manifest.series.length !== 1
) {
throw new Error('Retained strategy requires its exact eligible single-series dataset');
}
const selection = admitted.strategy.selection;
validateBuiltinStrategyBindings([selection], load);
// Only server-admitted built-ins reach this trusted worker path. Candidate
// execution requires separate isolation; import is never performed by an API.
// Bun's data-URL loader rejects real bundle-sized specifiers. A Blob keeps
// these exact UTF-8 bytes in memory without temporary files surviving SIGKILL.
const moduleUrl = URL.createObjectURL(
new Blob([pkg.artifact.content], { type: 'text/javascript' })
);
let module: Record<string, unknown>;
try {
module = await import(moduleUrl);
} finally {
URL.revokeObjectURL(moduleUrl);
}
const factory = module[pkg.artifact.entryExport];
if (typeof factory !== 'function') {
throw new Error('Retained strategy factory export is missing');
}
const program = factory(freeze(structuredClone(selection))) as StrategyProgram;
if (
!program ||
typeof program !== 'object' ||
program.ownerId !== selection.ownerId ||
program.strategyId !== selection.strategyId ||
program.strategyVersion !== selection.strategyVersion ||
program.seed !== selection.seed ||
program.mode !== 'target' ||
typeof program.decide !== 'function'
) {
throw new Error('Retained strategy factory identity or API mismatch');
}
await send({
type: 'progress',
progress: 0,
message: 'Retained canonical strategy replay started',
});
const { result } = runStrategyReplay(load, [program], { resultFormat: 'report' });
const report = buildCanonicalBacktestReport(result, admitted.analyticsPolicy);
const envelope: RetainedStrategyResult = {
type: 'retainedStrategyResult',
version: 1,
build,
artifactHash: pkg.artifact.sha256,
financial: report.financial,
analytics: report.analytics,
};
await send({ type: 'result', result: JSON.stringify(envelope) });
return;
}
if (request.type === 'runStrategyReplay') {
const load = prepareReplayLoad(request.dataset, request.config);
validateBuiltinStrategyBindings(request.strategies, load);

View file

@ -1,4 +1,8 @@
import type { BacktestRunResult, HistoricalDataset } from '@stock-bot/types';
import type {
CanonicalRunRequest,
CanonicalRunResult,
} from '@stock-bot/stock-config/canonical-research';
import type { BacktestRunResult, HistoricalDataset, HistoricalDatasetV2 } from '@stock-bot/types';
import type { BacktestConfig } from '../types';
export interface RunIdentity {
@ -10,9 +14,23 @@ export interface RunClaim extends RunIdentity {
config: BacktestConfig;
}
export interface CanonicalRunClaim extends RunIdentity {
attemptId: string;
config: CanonicalRunRequest;
}
/** Every execution write must prove ownership of an unexpired attempt. */
export interface BacktestRunRepository {
start(config: BacktestConfig): Promise<RunClaim>;
/** Only already admitted canonical rows may be claimed; no implicit creation. */
startCanonical?(request: CanonicalRunRequest): Promise<CanonicalRunClaim>;
loadCanonicalDataset?(
runId: string,
attemptId: string,
requestedHash: string,
signal?: AbortSignal
): Promise<HistoricalDatasetV2>;
completeCanonical?(result: CanonicalRunResult, attemptId: string): Promise<void>;
load(runId: string): Promise<{ status: string; config: unknown } | null>;
rejectPending(runId: string, error: string): Promise<void>;
heartbeat(runId: string, attemptId: string): Promise<{ cancelRequested: boolean }>;

View file

@ -1,553 +1,2 @@
/** Schema-only native session protocol. No runtime, storage or native imports. */
import { z } from 'zod';
import {
parseFinancialDecimal,
parseFinancialSnapshot,
parseFinancialStrategyDecision,
} from '@stock-bot/types';
const id = z
.string()
.min(1)
.refine(value =>
[...value].every(char => char.charCodeAt(0) >= 32 && char.charCodeAt(0) !== 127)
);
const counter = z.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER);
const time = z.number().int().min(-Number.MAX_SAFE_INTEGER).max(Number.MAX_SAFE_INTEGER);
const decimal = z.string().transform(value => parseFinancialDecimal(value));
const riskSession = z
.object({ calendarId: id, calendarRevision: id, sessionId: id, startsAt: time })
.strict();
export const replayIdentitySchema = z
.object({
version: z.literal(1),
sessionId: id,
datasetHash: z.string().regex(/^[a-f0-9]{64}$/),
})
.strict();
export const replayConfigSchema = z
.object({
matching: z
.object({
risk: z
.object({
ledger: z
.object({
version: z.literal(1),
sessionId: id,
accountId: id,
baseCurrency: id,
reserveOwnerId: id,
ownerIds: z.array(id),
initialCapital: decimal,
riskSession,
})
.strict(),
feeRate: decimal,
maxOrderQuantity: decimal,
maxPositionQuantity: decimal,
maxSymbolExposure: decimal,
maxGrossExposure: decimal,
maxDailyLoss: decimal,
maxDrawdownAmount: decimal,
maxMarkAgeMs: counter,
})
.strict(),
owners: z.array(z.object({ ownerId: id, mode: z.enum(['Target', 'Orders']) }).strict()),
series: z.array(
z.object({ instrumentId: id, seriesId: id, mode: z.literal('Open') }).strict()
),
halfSpreadRate: decimal,
slippageRate: decimal,
latencyMs: counter,
})
.strict(),
participation_rate: decimal,
cadence: z.array(z.object({ owner_id: id, series_ids: z.array(id) }).strict()),
allow_exploratory: z.boolean(),
risk_boundaries: z.array(riskSession),
})
.strict();
export type ReplayConfig = z.input<typeof replayConfigSchema>;
export type ReplayIdentity = z.infer<typeof replayIdentitySchema>;
const observationSchema = z
.object({
series_id: id,
instrument_id: id,
interval_start: time,
interval_end: time,
event_time: time,
available_at: time,
source_sequence: counter,
open: decimal,
high: decimal,
low: decimal,
close: decimal,
volume: decimal,
})
.strict();
const barrierSchema = z
.object({
barrier_id: id,
at: time,
revision: counter,
owner_ids: z.array(id),
observation_count: counter,
inputs: z.array(
z
.object({
series_id: id,
availability: z.union([
z.literal('Missing'),
z
.object({ Fresh: z.object({ event_time: time, available_at: time }).strict() })
.strict(),
z
.object({ Stale: z.object({ event_time: time, available_at: time }).strict() })
.strict(),
]),
})
.strict()
),
})
.strict();
const viewSchema = z
.object({
admissionRevision: counter,
portfolio: z.unknown().transform(value => parseFinancialSnapshot(value)),
equity: decimal,
availableCash: decimal,
// These are read-only native diagnostic projections, not a second admission API.
orders: z.array(z.record(z.unknown())),
reservations: z.array(z.record(z.unknown())),
risk: z
.object({
dailyBaseline: decimal,
peakEquity: decimal,
dailyHalted: z.boolean(),
drawdownHalted: z.boolean(),
riskSession,
lastEventTime: time,
})
.strict(),
})
.strict();
export const stepSchema = z
.object({
identity: replayIdentitySchema,
observations: z.array(observationSchema),
step: z.discriminatedUnion('type', [
z.object({ type: z.literal('progress'), processed: counter }).strict(),
z
.object({ type: z.literal('decisionBatch'), barrier: barrierSchema, view: viewSchema })
.strict(),
z.object({ type: z.literal('complete') }).strict(),
z.object({ type: z.literal('failed'), diagnostic: z.string() }).strict(),
]),
})
.strict();
const outcomeSchema = z
.object({
replayed: z.boolean(),
revision: counter,
status: z.union([
z.literal('Running'),
z.literal('Complete'),
z.object({ Failed: z.object({ diagnostic: z.string() }).strict() }).strict(),
]),
effects: z.array(z.record(z.unknown())),
})
.strict();
export const submissionSchema = z
.object({ identity: replayIdentitySchema, outcome: outcomeSchema })
.strict();
export type ReplaySubmissionOutcome = z.infer<typeof outcomeSchema>;
const resultSchema = z
.object({
identity: replayIdentitySchema,
status: z.literal('complete'),
manifest: z.record(z.unknown()),
policy: replayConfigSchema,
view: viewSchema,
receipts: z.array(z.object({ input: z.unknown(), outcome: outcomeSchema }).strict()),
limitations: z.array(z.string()),
modelLimitations: z.array(z.string()),
})
.strict();
export type ReplayStep = z.infer<typeof stepSchema>;
export type ReplayResult = z.infer<typeof resultSchema>;
const nonnegative = decimal.refine(value => !value.startsWith('-'));
const positive = nonnegative.refine(value => value !== '0.00000000');
const nativeOrderStatusSchema = z.union([
z.enum(['Open', 'Filled', 'Cancelled', 'Expired']),
z
.object({
Rejected: z.enum([
'OrderSize',
'PositionSize',
'SymbolExposure',
'GrossExposure',
'InsufficientCash',
'InsufficientInventory',
'MissingMark',
'StaleMark',
'DailyLoss',
'Drawdown',
'InactiveOrder',
]),
})
.strict(),
]);
export type NativeOrderStatus = z.infer<typeof nativeOrderStatusSchema>;
const managedOrderSchema = z
.object({
order: z
.object({
orderId: id,
decision: z.object({ ownerId: id, decisionId: id, sequence: counter }).strict(),
instrumentId: id,
side: z.enum(['buy', 'sell']),
quantity: positive,
limitPrice: positive.nullable(),
origin: z.enum(['Explicit', 'Target']),
})
.strict(),
timeInForce: z.enum(['DAY', 'GTC', 'IOC', 'FOK']),
submittedAt: z
.object({
at: time,
phase: z.enum(['Observation', 'Decision', 'Execution', 'SessionClose']),
instrumentId: id,
sourceSequence: counter,
})
.strict(),
readyAt: time,
venueSession: id.nullable(),
remaining: nonnegative,
filled: nonnegative,
status: nativeOrderStatusSchema,
admissionSequence: counter,
})
.strict();
// Shared wire projections; the native reducers remain their only financial authority.
export {
viewSchema as nativeFinancialViewSchema,
outcomeSchema as nativeMatchingOutcomeSchema,
managedOrderSchema as nativeManagedOrderSchema,
};
const admissionEffectSchema = z.union([
z.object({ Order: managedOrderSchema }).strict(),
z.object({ Risk: z.record(z.unknown()) }).strict(),
z.object({ Operator: z.record(z.unknown()) }).strict(),
]);
/** Decode only the existing native facts needed for strategy admission feedback.
* Other nested risk/ledger diagnostics are never interpreted as TS accounting. */
export function nativeAdmissionOrders(effects: ReplaySubmissionOutcome['effects']) {
return effects.flatMap(effect => {
const parsed = admissionEffectSchema.parse(effect);
return 'Order' in parsed ? [parsed.Order] : [];
});
}
const ownerValuationSchema = z
.object({
ownerId: id,
initialCapital: nonnegative,
markedHoldings: nonnegative,
remainingCost: nonnegative,
realizedGrossPnl: decimal,
unrealizedPnl: decimal,
fees: nonnegative,
equityContribution: decimal,
})
.strict();
export const financialProjectionSchema = z
.object({
valuation: z
.object({
cash: nonnegative,
markedHoldings: nonnegative,
equity: nonnegative,
remainingCost: nonnegative,
realizedGrossPnl: decimal,
unrealizedPnl: decimal,
fees: nonnegative,
owners: z.array(ownerValuationSchema),
})
.strict(),
fills: z.array(
z
.object({
commandId: id,
eventTime: time,
ownerId: id,
decision: z.object({ ownerId: id, decisionId: id, sequence: counter }).strict(),
orderId: id,
fillId: id,
instrumentId: id,
side: z.enum(['buy', 'sell']),
quantity: positive,
price: positive,
fee: z.object({ feeId: id, amount: nonnegative }).strict(),
// Gross notional cash movement; the separate fee posting is not included.
cashDelta: decimal,
quantityDelta: decimal,
releasedBasis: nonnegative,
realizedGrossPnl: decimal,
})
.strict()
.refine(fill => fill.ownerId === fill.decision.ownerId, 'Fill ownership mismatch')
),
})
.strict();
const projectionResultSchema = resultSchema
.omit({ receipts: true })
.extend({
format: z.literal('projection'),
projectionVersion: z.literal(1),
financialVersion: z.literal(1),
projection: financialProjectionSchema,
})
.strict();
export type ReplayProjectionResult = z.infer<typeof projectionResultSchema>;
export const replayReportingSchema = z
.object({
calendarId: id,
calendarRevision: id,
tradeStart: time,
tradeEnd: time,
initialEquity: nonnegative,
sampling: z.literal('account-boundary-after-observations-v1'),
exposureBasis: z.literal('elapsed-calendar-time'),
sessions: z.array(
z
.object({
session: riskSession,
periodStart: time,
periodEnd: time,
partialStart: z.boolean(),
partialEnd: z.boolean(),
equity: nonnegative,
})
.strict()
),
occupiedIntervals: z.array(z.object({ start: time, end: time }).strict()),
occupiedMs: z.string().regex(/^(0|[1-9][0-9]*)$/),
elapsedMs: z.string().regex(/^(0|[1-9][0-9]*)$/),
})
.strict();
const reportResultSchema = projectionResultSchema
.extend({
format: z.literal('report'),
reportingVersion: z.literal(1),
reporting: replayReportingSchema,
})
.strict();
export type ReplayReporting = z.infer<typeof replayReportingSchema>;
export type ReplayReportResult = z.infer<typeof reportResultSchema>;
export const replayResultFormatSchema = z.enum(['trace', 'projection', 'report']);
export type ReplayResultFormat = z.infer<typeof replayResultFormatSchema>;
export type ReplayOutput = ReplayResult | ReplayProjectionResult | ReplayReportResult;
export type DecisionContext = Extract<ReplayStep['step'], { type: 'decisionBatch' }>;
export type PublishedObservation = z.infer<typeof observationSchema>;
export function sameIdentity(actual: ReplayIdentity, expected: ReplayIdentity): void {
if (
actual.version !== expected.version ||
actual.sessionId !== expected.sessionId ||
actual.datasetHash !== expected.datasetHash
) {
throw new Error('Native replay identity mismatch');
}
}
export function parseReplayResult(
input: string,
identity: ReplayIdentity,
expectedPolicy?: ReplayConfig
): ReplayResult {
return parseReplayResultValue(JSON.parse(input), identity, expectedPolicy);
}
function checkResultIdentity(
result: ReplayOutput,
identity: ReplayIdentity,
expectedPolicy?: ReplayConfig
): void {
sameIdentity(result.identity, identity);
const ledger = result.policy.matching.risk.ledger,
portfolio = result.view.portfolio;
if (
result.manifest.version !== 2 ||
result.manifest.hash !== identity.datasetHash ||
ledger.sessionId !== identity.sessionId ||
portfolio.sessionId !== identity.sessionId ||
portfolio.accountId !== ledger.accountId ||
portfolio.baseCurrency !== ledger.baseCurrency ||
portfolio.reserveOwnerId !== ledger.reserveOwnerId ||
(expectedPolicy &&
JSON.stringify(result.policy) !== JSON.stringify(replayConfigSchema.parse(expectedPolicy)))
) {
throw new Error('Native replay result identity mismatch');
}
}
export function parseReplayResultValue(
input: unknown,
identity: ReplayIdentity,
expectedPolicy?: ReplayConfig
): ReplayResult {
const result = resultSchema.parse(input);
checkResultIdentity(result, identity, expectedPolicy);
return result;
}
export function parseReplayProjectionValue(
input: unknown,
identity: ReplayIdentity,
expectedPolicy?: ReplayConfig
): ReplayProjectionResult {
const result = projectionResultSchema.parse(input);
checkResultIdentity(result, identity, expectedPolicy);
checkProjection(result);
return result;
}
function checkProjection(result: ReplayProjectionResult | ReplayReportResult): void {
if (
result.projection.valuation.cash !== result.view.portfolio.cash ||
result.projection.valuation.equity !== result.view.equity
) {
throw new Error('Native replay projection does not match terminal view');
}
}
export function parseReplayProjectionResult(
input: string,
identity: ReplayIdentity,
expectedPolicy?: ReplayConfig
): ReplayProjectionResult {
return parseReplayProjectionValue(JSON.parse(input), identity, expectedPolicy);
}
export function parseReplayReportValue(
input: unknown,
identity: ReplayIdentity,
expectedPolicy?: ReplayConfig
): ReplayReportResult {
const result = reportResultSchema.parse(input);
checkResultIdentity(result, identity, expectedPolicy);
checkProjection(result);
const report = result.reporting;
const bounds = z.object({ tradeStart: time, tradeEnd: time }).parse(result.manifest.bounds);
const initial = result.policy.matching.risk.ledger;
if (
report.tradeStart !== bounds.tradeStart ||
report.tradeEnd !== bounds.tradeEnd ||
report.tradeStart >= report.tradeEnd ||
report.calendarId !== initial.riskSession.calendarId ||
report.calendarRevision !== initial.riskSession.calendarRevision ||
report.initialEquity !== initial.initialCapital ||
report.sessions.at(-1)?.equity !== result.view.equity
) {
throw new Error('Native replay reporting identity or terminal value mismatch');
}
// Check calendar partition/labels, not equity arithmetic or financial accounting.
const boundaries = [...result.policy.risk_boundaries].sort((a, b) => a.startsAt - b.startsAt);
let session = initial.riskSession;
let start = report.tradeStart,
index = 0;
for (const boundary of boundaries) {
if (boundary.startsAt <= report.tradeStart) {
session = boundary;
continue;
}
if (boundary.startsAt > report.tradeEnd) {
break;
}
const actual = report.sessions[index++];
if (
!actual ||
JSON.stringify(actual.session) !== JSON.stringify(session) ||
actual.periodStart !== start ||
actual.periodEnd !== boundary.startsAt ||
actual.partialStart !== (start !== session.startsAt) ||
actual.partialEnd
) {
throw new Error('Native replay reporting session partition mismatch');
}
start = boundary.startsAt;
session = boundary;
}
if (start < report.tradeEnd) {
const actual = report.sessions[index++];
if (
!actual ||
JSON.stringify(actual.session) !== JSON.stringify(session) ||
actual.periodStart !== start ||
actual.periodEnd !== report.tradeEnd ||
actual.partialStart !== (start !== session.startsAt) ||
!actual.partialEnd
) {
throw new Error('Native replay reporting final session mismatch');
}
}
if (index !== report.sessions.length) {
throw new Error('Native replay reporting has extra sessions');
}
let occupied = 0n,
previousEnd: number | undefined;
for (const interval of report.occupiedIntervals) {
if (
interval.start < report.tradeStart ||
interval.end > report.tradeEnd ||
interval.start >= interval.end ||
(previousEnd !== undefined && interval.start <= previousEnd)
) {
throw new Error('Native replay reporting intervals are not a clipped union');
}
occupied += BigInt(interval.end) - BigInt(interval.start);
previousEnd = interval.end;
}
if (
report.occupiedMs !== String(occupied) ||
report.elapsedMs !== String(BigInt(report.tradeEnd) - BigInt(report.tradeStart))
) {
throw new Error('Native replay reporting duration mismatch');
}
return result;
}
export function parseReplayReportResult(
input: string,
identity: ReplayIdentity,
expectedPolicy?: ReplayConfig
): ReplayReportResult {
return parseReplayReportValue(JSON.parse(input), identity, expectedPolicy);
}
export const replayTraceSchema = z
.object({
type: z.literal('runReplayTrace'),
version: z.literal(1),
dataset: z.unknown(),
config: replayConfigSchema,
eventBudget: counter.positive(),
resultFormat: replayResultFormatSchema.optional(),
trace: z.array(
z
.object({
at: time,
ownerId: id,
intent: z.unknown().transform(
intent =>
parseFinancialStrategyDecision({
version: 1,
sessionId: 'trace',
barrierId: 'trace',
revision: 0,
decision: { ownerId: 'trace', decisionId: 'trace', sequence: 0 },
intent,
}).intent
),
})
.strict()
),
})
.strict();
export type ReplayTraceRequest = z.input<typeof replayTraceSchema>;
/** Compatibility export: pure financial replay contracts are shared with research APIs. */
export * from '@stock-bot/stock-config/canonical-replay';