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 }>;