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

@ -1,9 +1,13 @@
import { ServiceContainerBuilder } from '@stock-bot/di';
import { defined } from '@stock-bot/invariants';
import { registerOrchestratorServices } from '../src/container';
import { ModeManager } from '../src/core/ModeManager';
import { ExecutionService } from '../src/services/ExecutionService';
import { MarketDataService } from '../src/services/MarketDataService';
import { StorageService } from '../src/services/StorageService';
import { createBuiltinStrategyRegistry } from '../src/strategies/builtin-strategies';
import { StrategyManager } from '../src/strategies/StrategyManager';
import type { OrchestratorServices } from '../src/types';
/** Offline examples explicitly opt into seeded synthetic data. No provider credentials are used. */
/** Legacy algorithm examples only: no queue, HTTP server, durable runs, or paper account. */
export async function createExampleRuntime() {
const di = await new ServiceContainerBuilder()
.withOptions({
@ -16,18 +20,52 @@ export async function createExampleRuntime() {
enableProxy: false,
})
.build();
await registerOrchestratorServices(di, {
initializeMode: false,
const container = di.resolve('serviceContainer') as OrchestratorServices;
const storageService = new StorageService(container, null, null, null, {
allowSyntheticData: true,
syntheticSeed: 42,
});
const container = di.resolve('serviceContainer') as OrchestratorServices;
const marketDataService: MarketDataService = new MarketDataService({
logger: container.logger,
storage: storageService,
drainStrategies: () => strategyManager.drain(),
});
const executionService = new ExecutionService(container, storageService, {
allowedMode: 'backtest',
});
const registry = createBuiltinStrategyRegistry();
const strategyManager: StrategyManager = new StrategyManager({
logger: container.logger,
marketData: marketDataService,
execution: executionService,
createStrategy: config => registry.create(config, { modeManager, execution: executionService }),
});
const modeManager: ModeManager = new ModeManager({
allowedMode: 'backtest',
logger: container.logger,
marketData: marketDataService,
execution: executionService,
storage: storageService,
strategies: strategyManager,
});
const custom = container.custom ?? {};
if (!container.custom) {
Object.defineProperty(container, 'custom', { value: custom, enumerable: true });
}
Object.assign(custom, {
StorageService: storageService,
MarketDataService: marketDataService,
ExecutionService: executionService,
StrategyManager: strategyManager,
ModeManager: modeManager,
});
strategyManager.setupEventListeners();
return {
container,
storageService: defined(container.custom?.StorageService),
marketDataService: defined(container.custom?.MarketDataService),
executionService: defined(container.custom?.ExecutionService),
modeManager: defined(container.custom?.ModeManager),
strategyManager: defined(container.custom?.StrategyManager),
storageService,
marketDataService,
executionService,
modeManager,
strategyManager,
};
}

View file

@ -1,13 +1,14 @@
import type { BacktestRunner } from '../src/backtest/BacktestRunner';
import type { BacktestEngine } from '../src/backtest/BacktestEngine';
import { BacktestConfigSchema, type BacktestConfig } from '../src/types';
/**
* Call with the application's already-composed TypeScript runner and real historical range.
* Preserved offline prototype for older strategy algorithms; not a production research route.
* Importing this example starts no services, loads no model and submits no work.
* The caller owns runner/service shutdown; the ordinary runner persists the actual result.
* A standalone prototype engine owns this demonstration. It does not create durable research results.
* Production research uses approved retained versions and the canonical runner.
*/
export function runMultiStrategyBacktest(
runner: Pick<BacktestRunner, 'runBacktest'>,
runner: Pick<BacktestEngine, 'runBacktest'>,
range: Pick<BacktestConfig, 'symbols' | 'startDate' | 'endDate'>
) {
const request = BacktestConfigSchema.parse({

View file

@ -3,7 +3,7 @@ import { z } from 'zod';
import { defined } from '@stock-bot/invariants';
import { HistoricalDataRequestError } from '@stock-bot/types';
import { parseBacktestRequest } from '../../backtest/BacktestRunner';
import { BacktestCancelledError } from '../../backtest/execution-engine';
import { BacktestCancelledError, LEGACY_EXECUTION_RETIRED } from '../../backtest/execution-engine';
import { BacktestConflictError } from '../../backtest/run-repository';
import type { OrchestratorServices as IServiceContainer } from '../../types';
@ -239,60 +239,8 @@ export function createBacktestRoutes(container: IServiceContainer): Hono {
return new Response(stream);
});
// Validate backtest configuration
app.post('/validate', async c => {
try {
const body = await c.req.json();
const config = parseBacktestRequest(body);
// Additional validation logic
const validation = {
valid: true,
warnings: [] as string[],
estimatedDuration: 0,
};
// Check data availability
const startDate = new Date(config.startDate);
const endDate = new Date(config.endDate);
const days = (endDate.getTime() - startDate.getTime()) / (1000 * 60 * 60 * 24);
if (days > 365) {
validation.warnings.push('Large date range may take significant time to process');
}
if (config.symbols.length > 100) {
validation.warnings.push('Large number of symbols may impact performance');
}
// Estimate duration (simplified)
validation.estimatedDuration = days * config.symbols.length * 0.1; // seconds
return c.json(validation);
} catch (error) {
if (error instanceof BacktestConflictError) {
return c.json({ error: error.message }, 409);
}
if (error instanceof z.ZodError) {
return c.json(
{
valid: false,
error: 'Invalid configuration',
details: error.errors,
},
400
);
}
return c.json(
{
valid: false,
error: error instanceof Error ? error.message : 'Validation failed',
},
500
);
}
});
// The old route cannot approve unversioned strategies or mutable provider inputs.
app.post('/validate', c => c.json({ valid: false, error: LEGACY_EXECUTION_RETIRED }, 409));
return app;
}

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>,

View file

@ -1,26 +1,18 @@
import { asValue, type AwilixContainer } from 'awilix';
import type { ServiceCradle as ServiceDefinitions } from '@stock-bot/di';
import { BacktestEngine } from './backtest/BacktestEngine';
import { BacktestRunner } from './backtest/BacktestRunner';
import type { BacktestExecutionEngine } from './backtest/execution-engine';
import { PostgresBacktestRunRepository } from './backtest/PostgresBacktestRunRepository';
import { UnavailableBacktestRunRepository } from './backtest/run-repository';
import { RustBacktestAdapter } from './backtest/RustBacktestAdapter';
import type { PaperConfigurationInput, PaperRuntime } from './contracts/paper-runtime';
import { ModeManager } from './core/ModeManager';
import { PostgresCanonicalExecutionRepository } from './execution/PostgresCanonicalExecutionRepository';
import { BacktestHandler } from './handlers/backtest/backtest.handler';
import { CanonicalPaperRuntime } from './paper/CanonicalPaperRuntime';
import { validatePaperConfiguration } from './paper/feed';
import { PaperTradingManager } from './paper/PaperTradingManager';
import { AnalyticsService } from './services/AnalyticsService';
import { ExecutionService } from './services/ExecutionService';
import { MarketDataService } from './services/MarketDataService';
import { StorageService } from './services/StorageService';
import { createBuiltinStrategyRegistry } from './strategies/builtin-strategies';
import { createBuiltinStrategy } from './strategies/canonical-builtins';
import { StrategyManager } from './strategies/StrategyManager';
import type { StrategyRegistry } from './strategies/StrategyRegistry';
import type { OrchestratorServices as IServiceContainer } from './types';
export type OrchestratorRole = 'paper' | 'research-only';
@ -32,10 +24,8 @@ export function assertSupportedComposition(role: OrchestratorRole, useRustEngine
if (typeof useRustEngine !== 'boolean') {
throw new Error('Runtime useRustEngine option must be a boolean');
}
if (role !== 'research-only' && !useRustEngine) {
throw new Error(
'Unsupported runtime combination: TypeScript backtests require a research-only composition; paper requires the isolated native engine'
);
if (!useRustEngine) {
throw new Error('Legacy financial execution is retired; the canonical Rust engine is required');
}
}
@ -51,12 +41,10 @@ export async function registerOrchestratorServices(
allowSyntheticData?: boolean;
syntheticSeed?: number;
nativeExecutionTimeoutMs?: number;
strategyRegistry?: StrategyRegistry;
canonicalPaper?: PaperConfigurationInput;
paperTradingCapital?: number;
} = {}
): Promise<void> {
const role = options.role === undefined ? 'paper' : options.role;
const role = options.role === undefined ? 'research-only' : options.role;
const useRustEngine = options.useRustEngine === undefined ? true : options.useRustEngine;
assertSupportedComposition(role, useRustEngine);
if (options.canonicalPaper !== undefined && role !== 'paper') {
@ -66,7 +54,11 @@ export async function registerOrchestratorServices(
options.canonicalPaper === undefined
? undefined
: validatePaperConfiguration(options.canonicalPaper);
const allowedMode = role === 'research-only' ? 'backtest' : 'paper';
if (role === 'paper' && !canonicalPaper) {
throw new Error(
'Paper composition requires explicit canonicalPaper configuration; accounts are never migrated automatically'
);
}
// Create a service adapter that provides the expected interface
const services = container.resolve('serviceContainer') as IServiceContainer;
@ -75,22 +67,18 @@ export async function registerOrchestratorServices(
Object.defineProperty(services, 'custom', { value: custom, enumerable: true });
}
if (
custom.CanonicalPaperRuntime ||
container.hasRegistration('CanonicalPaperRuntime') ||
(canonicalPaper &&
(
[
'ModeManager',
'ExecutionService',
'MarketDataService',
'StrategyManager',
'PaperTradingManager',
'BacktestEngine',
'BacktestRunner',
] as const
).some(key => custom[key] || container.hasRegistration(key)))
[
'CanonicalPaperRuntime',
'ModeManager',
'ExecutionService',
'MarketDataService',
'StrategyManager',
'PaperTradingManager',
'BacktestEngine',
'BacktestRunner',
].some(key => custom[key as keyof typeof custom] || container.hasRegistration(key))
) {
throw new Error('Canonical paper requires a fresh runtime composition');
throw new Error('Canonical execution requires a fresh runtime composition');
}
// Create storage service first as it's needed by other services
@ -102,181 +90,71 @@ export async function registerOrchestratorServices(
options
);
if (canonicalPaper) {
if (!services.postgres) {
throw new Error('Canonical paper requires durable PostgreSQL custody');
}
const paper = new CanonicalPaperRuntime({
repository: new PostgresCanonicalExecutionRepository(services.postgres),
programs: canonicalPaper.strategies.map(createBuiltinStrategy),
});
const engine = new RustBacktestAdapter(
{ logger: services.logger, storage: storageService },
{ timeoutMs: options.nativeExecutionTimeoutMs }
);
const runner = new BacktestRunner({
engine,
engineName: 'native',
repository: new PostgresBacktestRunRepository(services.postgres),
logger: services.logger,
});
const analytics = new AnalyticsService(services);
// No legacy order gateway, feed listener or mode initializer is exposed in
// this composition. Research still runs in the existing isolated worker.
Object.assign(custom, {
StorageService: storageService,
AnalyticsService: analytics,
CanonicalPaperRuntime: paper,
BacktestEngine: engine,
BacktestRunner: runner,
});
const canonicalContainer = container as AwilixContainer<
ServiceDefinitions & {
StorageService: StorageService;
AnalyticsService: AnalyticsService;
CanonicalPaperRuntime: PaperRuntime;
BacktestEngine: BacktestExecutionEngine;
BacktestRunner: BacktestRunner;
orchestratorServices: IServiceContainer;
}
>;
canonicalContainer.register({
StorageService: asValue(storageService),
AnalyticsService: asValue(analytics),
CanonicalPaperRuntime: asValue(paper),
BacktestEngine: asValue(engine),
BacktestRunner: asValue(runner),
orchestratorServices: asValue(services),
});
container
.resolve('handlerScanner')
.registerHandlerClass(BacktestHandler, { serviceName: 'orchestrator' });
try {
if (options.initializeMode !== false) {
await paper.initialize(canonicalPaper);
}
services.queueManager?.getQueue('orchestrator', { workers: 1, concurrency: 1 });
} catch (error) {
await paper.shutdown().catch(() => {});
throw error;
}
return;
if (canonicalPaper && !services.postgres) {
throw new Error('Canonical paper requires durable PostgreSQL custody');
}
// Callbacks are invoked after composition: the feed drains the manager, and
// factories receive the current mode without either service locating its peers.
const marketDataService: MarketDataService = new MarketDataService({
logger: services.logger,
storage: storageService,
drainStrategies: () => strategyManager.drain(),
});
const executionService = new ExecutionService(services, storageService, { allowedMode });
const analyticsService = new AnalyticsService(services);
const registry = options.strategyRegistry ?? createBuiltinStrategyRegistry();
const strategyManager: StrategyManager = new StrategyManager({
logger: services.logger,
marketData: marketDataService,
execution: executionService,
createStrategy: config => registry.create(config, { modeManager, execution: executionService }),
});
const modeManager: ModeManager = new ModeManager({
allowedMode,
logger: services.logger,
marketData: marketDataService,
execution: executionService,
storage: storageService,
strategies: strategyManager,
});
const backtestEngine = useRustEngine
? new RustBacktestAdapter(
{ logger: services.logger, storage: storageService },
{
timeoutMs: options.nativeExecutionTimeoutMs,
}
)
: new BacktestEngine({
logger: services.logger,
storage: storageService,
strategies: strategyManager,
execution: executionService,
getTradingEngine: () => modeManager.getTradingEngine(),
});
const paperTradingManager = new PaperTradingManager(
services,
storageService,
marketDataService,
executionService
const paper =
canonicalPaper && services.postgres
? new CanonicalPaperRuntime({
repository: new PostgresCanonicalExecutionRepository(services.postgres),
programs: canonicalPaper.strategies.map(createBuiltinStrategy),
})
: undefined;
const engine = new RustBacktestAdapter(
{ logger: services.logger, storage: storageService },
{ timeoutMs: options.nativeExecutionTimeoutMs }
);
const backtestRunner = new BacktestRunner({
engine: backtestEngine,
engineName: useRustEngine ? 'native' : 'typescript',
const runner = new BacktestRunner({
engine,
engineName: 'native',
repository: services.postgres
? new PostgresBacktestRunRepository(services.postgres)
: new UnavailableBacktestRunRepository(),
logger: services.logger,
prepare: useRustEngine ? undefined : config => modeManager.initializeMode(config),
});
// Store custom services
const analytics = new AnalyticsService(services);
// Both roles share canonical research. Only an explicitly configured paper
// composition owns account custody; startup never activates it.
Object.assign(custom, {
StorageService: storageService,
MarketDataService: marketDataService,
ExecutionService: executionService,
AnalyticsService: analyticsService,
StrategyManager: strategyManager,
BacktestEngine: backtestEngine,
BacktestRunner: backtestRunner,
PaperTradingManager: paperTradingManager,
ModeManager: modeManager,
AnalyticsService: analytics,
BacktestEngine: engine,
BacktestRunner: runner,
...(paper ? { CanonicalPaperRuntime: paper } : {}),
});
// Register services in the Awilix container for resolution
const orchestratorContainer = container as AwilixContainer<
const canonicalContainer = container as AwilixContainer<
ServiceDefinitions & {
StorageService: StorageService;
MarketDataService: MarketDataService;
ExecutionService: ExecutionService;
AnalyticsService: AnalyticsService;
StrategyManager: StrategyManager;
CanonicalPaperRuntime: PaperRuntime;
BacktestEngine: BacktestExecutionEngine;
BacktestRunner: BacktestRunner;
PaperTradingManager: PaperTradingManager;
ModeManager: ModeManager;
orchestratorServices: IServiceContainer;
}
>;
orchestratorContainer.register({
canonicalContainer.register({
StorageService: asValue(storageService),
MarketDataService: asValue(marketDataService),
ExecutionService: asValue(executionService),
AnalyticsService: asValue(analyticsService),
StrategyManager: asValue(strategyManager),
BacktestEngine: asValue(backtestEngine),
BacktestRunner: asValue(backtestRunner),
PaperTradingManager: asValue(paperTradingManager),
ModeManager: asValue(modeManager),
AnalyticsService: asValue(analytics),
BacktestEngine: asValue(engine),
BacktestRunner: asValue(runner),
orchestratorServices: asValue(services),
...(paper ? { CanonicalPaperRuntime: asValue(paper) } : {}),
});
container
.resolve('handlerScanner')
.registerHandlerClass(BacktestHandler, { serviceName: 'orchestrator' });
// Setup event listeners after all services are registered
strategyManager.setupEventListeners();
// Initialize mode manager with default paper trading mode
if (role === 'paper' && options.initializeMode !== false) {
await modeManager.initializeMode({
mode: 'paper',
startingCapital: options.paperTradingCapital ?? 100000,
});
try {
if (paper && canonicalPaper && options.initializeMode !== false) {
await paper.initialize(canonicalPaper);
}
services.queueManager?.getQueue('orchestrator', { workers: 1, concurrency: 1 });
} catch (error) {
await paper?.shutdown().catch(() => {});
throw error;
}
// Start job consumption only after the shared graph and initial mode are ready.
services.queueManager?.getQueue('orchestrator', { workers: 1, concurrency: 1 });
}
// For backward compatibility, export a container getter
// Kept only as an explicit diagnostic for obsolete integration code.
export function getContainer(): IServiceContainer {
throw new Error(
'Container should be accessed through ServiceApplication. Update your code to use dependency injection.'

View file

@ -2,6 +2,7 @@ import { z } from 'zod';
import { BaseHandler, Handler, Operation } from '@stock-bot/handlers';
import { defined } from '@stock-bot/invariants';
import type { BacktestRunner } from '../../backtest/BacktestRunner';
import { LEGACY_EXECUTION_RETIRED } from '../../backtest/execution-engine';
import type { OrchestratorServices } from '../../types';
@Handler('orchestrator')
@ -22,10 +23,7 @@ export class BacktestHandler extends BaseHandler<OrchestratorServices> {
const { runId } = z.object({ runId: z.string().uuid() }).parse(payload);
return this.runner.runQueued(runId);
}
// Old jobs omitted these fields. Normalize the envelope, never the execution result.
const config = { mode: 'backtest', dataFrequency: '1d', ...payload };
const results = await this.runner.runBacktest(config);
return { success: true, backtestId: results.backtestId, runId: results.runId, results };
throw new Error(LEGACY_EXECUTION_RETIRED);
}
@Operation('cancel-backtest')

View file

@ -19,7 +19,7 @@ const logger = getLogger('orchestrator');
// Get service-specific config
const serviceConfig = config.services?.orchestrator || {
port: 2004,
defaultMode: 'paper',
defaultMode: 'backtest',
paperTradingCapital: 100000,
enableWebSocket: true,
};

View file

@ -1,30 +1,24 @@
import { Hono } from 'hono';
import { Server as SocketIOServer } from 'socket.io';
import type { Server as SocketIOServer } from 'socket.io';
import { createAnalyticsRoutes } from '../api/rest/analytics';
import { createBacktestRoutes } from '../api/rest/backtest';
import { createOrderRoutes } from '../api/rest/orders';
import { createPaperRoutes } from '../api/rest/paper';
import { createPositionRoutes } from '../api/rest/positions';
import { setupWebSocketHandlers } from '../api/websocket';
import type { OrchestratorServices as IServiceContainer } from '../types';
/**
* Create all routes for the orchestrator service
*/
export function createRoutes(services: IServiceContainer, io?: SocketIOServer): Hono {
export function createRoutes(services: IServiceContainer, _io?: SocketIOServer): Hono {
const app = new Hono();
services.logger.info('Creating orchestrator routes');
// Health check with mode status
app.get('/health', c => {
const modeManager = services.custom?.ModeManager;
return c.json({
status: 'healthy',
service: 'orchestrator',
mode: services.custom?.CanonicalPaperRuntime
? 'paper'
: modeManager?.getCurrentMode() || 'unknown',
execution: services.custom?.CanonicalPaperRuntime ? 'canonical-paper' : 'legacy',
mode: services.custom?.CanonicalPaperRuntime ? 'paper' : 'research-only',
execution: services.custom?.CanonicalPaperRuntime ? 'canonical-paper' : 'canonical-research',
timestamp: new Date().toISOString(),
});
});
@ -38,37 +32,28 @@ export function createRoutes(services: IServiceContainer, io?: SocketIOServer):
...(await services.custom.CanonicalPaperRuntime.status()),
});
}
const execution = services.custom?.ExecutionService;
if (!execution) {
return c.json({ error: 'Execution gateway unavailable' }, 503);
}
return c.json(await execution.getRecoveryStatus());
return c.json({ error: 'Research-only runtime has no account execution gateway' }, 503);
} catch (error) {
services.logger.error('Could not read strategy recovery status', { error });
return c.json({ error: 'Strategy recovery status unavailable' }, 503);
}
});
app.route('/api/paper', createPaperRoutes(services));
if (services.custom?.CanonicalPaperRuntime) {
// Legacy numeric gateways cannot operate on a controlled canonical account.
const unavailable = new Hono().all('*', c =>
c.json({ error: 'Legacy account gateway unavailable in canonical paper mode' }, 409)
);
app.route('/api/orders', unavailable);
app.route('/api/positions', unavailable);
} else {
app.route('/api/orders', createOrderRoutes(services));
app.route('/api/positions', createPositionRoutes(services));
}
// Retired gateways remain explicit diagnostics, never a fallback simulator.
const unavailable = new Hono().all('*', c =>
c.json(
{
error:
'Legacy account execution is retired; use the explicitly configured canonical paper runtime',
},
409
)
);
app.route('/api/orders', unavailable);
app.route('/api/positions', unavailable);
app.route('/api/analytics', createAnalyticsRoutes(services));
app.route('/api/backtest', createBacktestRoutes(services));
// Setup WebSocket handlers if Socket.IO is provided
if (io && !services.custom?.CanonicalPaperRuntime) {
setupWebSocketHandlers(io, services);
services.logger.info('WebSocket handlers configured');
}
// Add request logging middleware
app.use('*', async (c, next) => {
const start = Date.now();

View file

@ -20,9 +20,9 @@ export async function createContainer(
}
const role =
options.role === undefined
? settings?.defaultMode === 'backtest'
? 'research-only'
: 'paper'
? settings?.defaultMode === 'paper'
? 'paper'
: 'research-only'
: options.role;
const configuredEngine = config.services?.orchestrator?.backtesting?.useRustEngine;
const useRustEngine = configuredEngine === undefined ? true : configuredEngine;
@ -35,6 +35,11 @@ export async function createContainer(
settings?.canonicalPaper === undefined
? undefined
: validatePaperConfiguration(paperConfigurationSchema.parse(settings.canonicalPaper));
if (role === 'paper' && !canonicalPaper) {
throw new Error(
'Paper composition requires explicit canonicalPaper configuration; accounts are never migrated automatically'
);
}
if (canonicalPaper && !config.database?.postgres?.enabled) {
throw new Error('Canonical paper requires durable PostgreSQL custody');
}
@ -57,7 +62,6 @@ export async function createContainer(
syntheticSeed: config.services?.orchestrator?.backtesting?.syntheticSeed ?? 42,
nativeExecutionTimeoutMs: config.services?.orchestrator?.backtesting?.executionTimeoutMs,
canonicalPaper,
paperTradingCapital: settings?.paperTradingCapital,
});
return container.resolve('serviceContainer') as OrchestratorServices;
}

View file

@ -0,0 +1,189 @@
/** Pure decision staging shared by trusted and OS-isolated strategy hosts.
* This module never imports a native engine, dataset loader or service container. */
import type { FinancialStrategyDecision } from '@stock-bot/types';
import type {
DeepReadonly,
StrategyAdmissionFeedback,
StrategyDiagnostic,
StrategyDiagnosticSnapshot,
StrategyProgram,
} from '../contracts/canonical-strategy';
import {
nativeAdmissionOrders,
type DecisionContext,
type PublishedObservation,
type replayConfigSchema,
type ReplayIdentity,
type ReplaySubmissionOutcome,
} from '../contracts/native-replay';
import {
freeze,
increment,
metadataSchema,
stageStrategyDecision,
stateCopy,
type Metadata,
} from '../strategies/strategy-decision';
interface Slot {
program: Metadata & { decide: StrategyProgram['decide'] };
diagnostic: DeepReadonly<StrategyDiagnostic>;
pendingObservations: PublishedObservation[];
}
export class StrategyController {
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;
}
}