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

@ -16,6 +16,14 @@
"./strategy": {
"types": "./dist/contracts/strategy.d.ts",
"default": "./dist/contracts/strategy.js"
},
"./canonical-replay": {
"types": "./dist/contracts/canonical-replay.d.ts",
"default": "./dist/contracts/canonical-replay.js"
},
"./canonical-research": {
"types": "./dist/contracts/canonical-research.d.ts",
"default": "./dist/contracts/canonical-research.js"
}
},
"scripts": {

View file

@ -1,10 +1,14 @@
import { z } from 'zod';
import type { financialDecimal } from '@stock-bot/types';
import {
HistoricalDataRequestError,
parseInstrumentId,
validateHistoricalDataRequest,
type HistoricalDatasetManifest,
} from '@stock-bot/types';
import { canonicalResearchSettingsSchema } from './canonical-research';
export type { financialDecimal };
/** Pure execution configuration; importing this subpath starts no configuration services. */
export const BACKTEST_DEFAULTS = Object.freeze({
@ -211,6 +215,8 @@ export function rejectCatalogVersionReferences(input: unknown): void {
const value = input as Record<string, unknown>;
if (
value.strategy === 'catalog' ||
(typeof value.kind === 'string' && value.kind.startsWith('canonical-research/')) ||
Object.hasOwn(value, 'canonical') ||
Object.hasOwn(value, 'strategyParameters') ||
Object.hasOwn(value, 'strategyVersionId') ||
Object.hasOwn(value, 'strategyVersionIds')
@ -315,6 +321,7 @@ export const CatalogBacktestConfigSchema = BacktestExecutionSettingsSchema.pick(
fillModel: true,
})
.partial()
.extend({ canonical: canonicalResearchSettingsSchema.optional() })
.strict();
export const CatalogBacktestDefinitionSchema = z
.object({

View file

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

View file

@ -0,0 +1,189 @@
/** Pure durable research contracts. Importing these never loads a native engine or strategy. */
import { z } from 'zod';
import type {
BacktestRunResult,
CanonicalBacktestAnalytics,
financialDecimal,
FinancialDecimal,
HistoricalDatasetManifestV2,
} from '@stock-bot/types';
import { parseFinancialDecimal } from '@stock-bot/types';
import { builtinStrategySelectionSchema } from './builtin-strategy';
import {
parseReplayReportValue,
replayConfigSchema,
type ReplayReportResult,
} from './canonical-replay';
import { parseStrategyVersionPackage, validateStrategyParameters } from './strategy';
export type { financialDecimal };
const hash = z.string().regex(/^[a-f0-9]{64}$/);
const decimal: z.ZodType<FinancialDecimal, z.ZodTypeDef, string> = z
.string()
.transform((value, context) => {
try {
return parseFinancialDecimal(value);
} catch {
context.addIssue({
code: z.ZodIssueCode.custom,
message: 'Use a finite decimal with at most eight fractional places',
fatal: true,
});
return z.NEVER;
}
});
const nonnegative = decimal.refine(value => !value.startsWith('-'));
const positive = nonnegative.refine(value => value !== '0.00000000');
const rate = nonnegative.refine(value => BigInt(value.replace('.', '')) <= 100000000n);
const adversePriceRate = rate.refine(value => value !== '1.00000000');
const duration = z.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER);
/** Explicit canonical quantities/notionals; legacy percentage risk settings are not converted. */
export const canonicalResearchSettingsSchema = z
.object({
version: z.literal(1),
seed: z.number().int().min(0).max(0xffffffff),
ownerBudget: positive,
feeRate: rate,
halfSpreadRate: adversePriceRate,
slippageRate: adversePriceRate,
latencyMs: duration,
participationRate: rate.refine(value => value !== '0.00000000'),
maxOrderQuantity: positive,
maxPositionQuantity: positive,
maxSymbolExposure: positive,
maxGrossExposure: positive,
maxDailyLoss: nonnegative,
maxDrawdownAmount: nonnegative,
maxMarkAgeMs: duration,
periodsPerYear: z.number().finite().positive(),
annualRiskFreeRate: z.number().finite().nullable(),
})
.strict();
export type CanonicalResearchSettings = z.input<typeof canonicalResearchSettingsSchema>;
export const canonicalBuildIdentitySchema = z
.object({
version: z.literal(1),
workerSha256: hash,
engineWrapperSha256: hash,
engineBinarySha256: hash,
dependencyLockSha256: hash,
runtime: z.literal('bun'),
runtimeVersion: z.string().min(1),
platform: z.string().min(1),
arch: z.string().min(1),
})
.strict();
export type CanonicalBuildIdentity = z.infer<typeof canonicalBuildIdentitySchema>;
const metricsPolicy = z
.object({
version: z.literal(1),
periodsPerYear: z.number().finite().positive(),
annualRiskFreeRate: z.number().finite().nullable(),
benchmark: z.null(),
})
.strict();
const admitted = z
.object({
kind: z.literal('canonical-research/v1'),
runId: z.string().uuid(),
backtestId: z.string().uuid(),
name: z.string().min(1),
strategy: z
.object({
familyId: z.string().uuid(),
versionId: z.string().uuid(),
origin: z.literal('builtin'),
reviewId: z.string().uuid(),
package: z.unknown().transform(parseStrategyVersionPackage),
selection: builtinStrategySelectionSchema,
})
.strict(),
datasetHash: hash,
policy: replayConfigSchema,
analyticsPolicy: metricsPolicy,
build: canonicalBuildIdentitySchema,
modelArtifacts: z.tuple([]),
})
.strict();
export const canonicalRunRequestSchema = admitted.superRefine((value, context) => {
const { strategy, policy } = value;
const selection = strategy.selection;
const ledger = policy.matching.risk.ledger;
const same = (a: unknown, b: unknown) => JSON.stringify(a) === JSON.stringify(b);
const valid =
strategy.package.program.strategyId === selection.strategyId &&
strategy.package.program.strategyVersion === selection.strategyVersion &&
ledger.sessionId === value.runId &&
ledger.accountId === `research:${value.runId}` &&
ledger.baseCurrency === 'USD' &&
ledger.reserveOwnerId === 'reserve' &&
selection.ownerId === `strategy:${strategy.versionId}` &&
same(ledger.ownerIds, [selection.ownerId]) &&
same(policy.matching.owners, [{ ownerId: selection.ownerId, mode: 'Target' }]) &&
same(policy.matching.series, [
{ instrumentId: selection.instrumentId, seriesId: selection.seriesId, mode: 'Open' },
]) &&
same(policy.cadence, [{ owner_id: selection.ownerId, series_ids: [selection.seriesId] }]) &&
!policy.allow_exploratory &&
BigInt(selection.ownerBudget.replace('.', '')) <=
BigInt(ledger.initialCapital.replace('.', ''));
if (!valid) {
context.addIssue({
code: z.ZodIssueCode.custom,
message: 'Unsupported or inconsistent single-asset canonical request',
});
}
try {
validateStrategyParameters(strategy.package, selection.parameters);
} catch (error) {
context.addIssue({ code: z.ZodIssueCode.custom, message: String(error) });
}
});
export type CanonicalRunRequest = z.infer<typeof canonicalRunRequestSchema>;
export interface CanonicalRunResult {
kind: 'canonical-result/v1';
runId: string;
backtestId: string;
status: 'completed';
completedAt: string;
executionTime: number;
financialEngine: 'rust';
strategyExecution: 'typescript-retained-builtin/v1';
request: CanonicalRunRequest;
financial: ReplayReportResult;
analytics: CanonicalBacktestAnalytics;
}
export type ResearchRunResult = BacktestRunResult | CanonicalRunResult;
export function isCanonicalRunResult(value: ResearchRunResult): value is CanonicalRunResult {
return 'kind' in value && value.kind === 'canonical-result/v1';
}
export interface CanonicalRunCapability {
available: boolean;
reason: string | null;
}
export interface CanonicalDatasetCatalogEntry {
hash: string;
createdAt: string;
manifest: HistoricalDatasetManifestV2 | null;
available: boolean;
reason: string | null;
}
/** Validate the authoritative financial envelope without legacy metric conversion. */
export function parseCanonicalFinancialResult(input: unknown, request: CanonicalRunRequest) {
return parseReplayReportValue(
input,
{
version: 1,
sessionId: request.runId,
datasetHash: request.datasetHash,
},
request.policy
);
}

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

@ -58,7 +58,8 @@ export async function runMigrations(container: IServiceContainer): Promise<void>
f === '15-canonical-paper-intents.sql' ||
f === '16-strategy-catalog.sql' ||
f === '17-research-retention.sql' ||
f === '18-backtest-strategy-versions.sql')
f === '18-backtest-strategy-versions.sql' ||
f === '19-canonical-research.sql')
) // Explicit additive migration allowlist; never replay destructive init migrations
.sort();

View file

@ -55,6 +55,10 @@ export function createBacktestV2Routes(container: IServiceContainer) {
}
});
app.get('/api/v2/backtests/:id/canonical-capability', async c =>
c.json(await backtestService.canonicalCapability(c.req.param('id')))
);
app.post('/api/v2/backtests', async c => {
try {
const body = await c.req.json();

View file

@ -2,6 +2,7 @@ import { Hono } from 'hono';
import { getLogger } from '@stock-bot/logger';
import { requireServices, type IServiceContainer } from '@stock-bot/services';
import { HistoricalDataRequestError } from '@stock-bot/types';
import { canonicalDatasetEntry } from '../services/canonical-research.service';
import { DatasetCatalogService } from '../services/dataset-catalog.service';
const logger = getLogger('dataset-catalog-routes');
@ -9,6 +10,57 @@ const logger = getLogger('dataset-catalog-routes');
export function createDatasetRoutes(container: IServiceContainer) {
const app = new Hono();
const catalog = new DatasetCatalogService(requireServices(container, 'postgres').postgres);
const database = requireServices(container, 'postgres').postgres;
app.get('/api/v2/datasets/canonical', async c => {
try {
const limit = c.req.query('limit') ?? '50';
const offset = c.req.query('offset') ?? '0';
if (
!/^\d+$/.test(limit) ||
!/^\d+$/.test(offset) ||
!Number.isSafeInteger(Number(limit)) ||
Number(limit) < 1 ||
!Number.isSafeInteger(Number(offset))
) {
return c.json(
{ error: 'Dataset pagination requires a positive limit and nonnegative offset' },
400
);
}
const rows = await database.query<{ hash: string; created_at: Date }>(
"SELECT hash,created_at FROM backtest_datasets WHERE payload#>>'{manifest,version}'='2' ORDER BY created_at DESC,hash LIMIT $1 OFFSET $2",
[Number(limit), Number(offset)]
);
const datasets = [];
for (const row of rows.rows) {
datasets.push(await canonicalDatasetEntry(database, row));
}
return c.json({ datasets });
} catch (error) {
logger.error('Failed to list canonical datasets', error);
return c.json({ error: 'Failed to list canonical datasets' }, 500);
}
});
app.get('/api/v2/datasets/canonical/:hash', async c => {
try {
const hash = c.req.param('hash');
if (!/^[a-f0-9]{64}$/.test(hash)) {
return c.json({ error: 'Invalid dataset hash' }, 400);
}
const row = (
await database.query<{ hash: string; created_at: Date }>(
'SELECT hash,created_at FROM backtest_datasets WHERE hash=$1',
[hash]
)
).rows[0];
return row
? c.json({ dataset: await canonicalDatasetEntry(database, row) })
: c.json({ error: 'Dataset not found' }, 404);
} catch (error) {
logger.error('Failed to get canonical dataset', error);
return c.json({ error: 'Failed to get canonical dataset' }, 500);
}
});
app.get('/api/v2/datasets', async c => {
try {
const limit = c.req.query('limit') ?? '50';

View file

@ -13,19 +13,25 @@ import {
rejectCatalogVersionReferences,
type BacktestDefinitionInput,
} from '@stock-bot/stock-config/backtest';
import {
canonicalRunRequestSchema,
parseCanonicalFinancialResult,
type CanonicalRunCapability,
type CanonicalRunResult,
type ResearchRunResult,
} from '@stock-bot/stock-config/canonical-research';
import {
assertStrategyJsonText,
canonicalStrategyJson,
validateStrategyParameters,
} from '@stock-bot/stock-config/strategy';
import type {
BacktestRunDatasetSelection,
BacktestRunResult,
StrategyParameterValue,
} from '@stock-bot/types';
import type { BacktestRunDatasetSelection, StrategyParameterValue } from '@stock-bot/types';
import { HistoricalDataRequestError } from '@stock-bot/types';
import { buildCanonicalBacktestReport } from '../../../orchestrator/src/backtest/canonical-result';
import { getWebSocketHandler } from '../websocket/run-updates';
import type { WebSocketHandler } from '../websocket/run-updates';
import { mapStoredBacktestResult, type StoredBacktestResult } from './backtest-result';
import { admitCanonicalRequest, validateCanonicalSetup } from './canonical-research.service';
import { assertSelectedDatasetMatchesRequest } from './dataset-catalog.service';
import { StrategyCatalogError, StrategyCatalogService } from './strategy-catalog.service';
@ -101,9 +107,10 @@ export class RunSubmissionConflictError extends Error {
}
export class CatalogExecutionUnavailableError extends Error {
readonly code = 'catalog_execution_unavailable';
constructor() {
constructor(reason?: string) {
super(
'Catalog strategy execution is unavailable until the canonical runner is integrated (R05); this saved draft cannot run through a legacy strategy'
reason ??
'Configure an approved built-in, eligible v2 dataset and canonical policy before execution'
);
}
}
@ -423,20 +430,44 @@ export class BacktestServiceV2 {
throw new BacktestRetentionError('backtest_archived');
}
const definition = this.mapBacktest(at(parent.rows, 0));
if (definition.strategyVersionId !== null || definition.strategy === 'catalog') {
throw new CatalogExecutionUnavailableError();
const catalog = definition.strategyVersionId !== null || definition.strategy === 'catalog';
if (catalog && multiplier !== null) {
throw new CatalogExecutionUnavailableError('Canonical research runs at maximum speed');
}
let canonical;
if (catalog) {
try {
canonical = await admitCanonicalRequest(
client,
this.container,
definition,
definition.id,
runId
);
} catch (error) {
throw new CatalogExecutionUnavailableError(
error instanceof Error ? error.message : 'Canonical execution unavailable'
);
}
}
const snapshot =
canonical ??
backtestRequestFromDefinition(legacyDefinition(definition), {
runId,
backtestId: definition.id,
speedMultiplier: multiplier,
});
if (!canonical) {
await assertSelectedDatasetMatchesRequest(
client,
snapshot as ReturnType<typeof backtestRequestFromDefinition>
);
}
const snapshot = backtestRequestFromDefinition(legacyDefinition(definition), {
runId,
backtestId: definition.id,
speedMultiplier: multiplier,
});
await assertSelectedDatasetMatchesRequest(client, snapshot);
const result = await client.query(
`INSERT INTO runs
(id, backtest_id, run_number, speed_multiplier, status, request_snapshot,
(id, backtest_id, run_number, speed_multiplier, status, request_snapshot, dataset_hash,
submission_principal, submission_key, submission_hash)
SELECT $1, $2, COALESCE(MAX(run_number), 0) + 1, $3, 'pending'::run_status, $4::jsonb, $5, $6, $7
SELECT $1, $2, COALESCE(MAX(run_number), 0) + 1, $3, 'pending'::run_status, $4::jsonb, $8, $5, $6, $7
FROM runs WHERE backtest_id = $2
${submission ? 'ON CONFLICT (submission_principal, submission_key) DO NOTHING' : ''}
RETURNING *`,
@ -448,6 +479,7 @@ export class BacktestServiceV2 {
submission?.principal ?? null,
submission?.key ?? null,
submissionHash,
canonical?.datasetHash ?? null,
]
);
// Different parent locks can race for one principal/key. The unique index waits for
@ -548,12 +580,18 @@ export class BacktestServiceV2 {
}
// Get run results
async getRunResults(runId: string): Promise<BacktestRunResult | null> {
const result = await this.container.postgres.query<StoredBacktestResult>(
async getRunResults(runId: string): Promise<ResearchRunResult | null> {
const result = await this.container.postgres.query<
StoredBacktestResult & {
canonical_result?: CanonicalRunResult | null;
request_snapshot?: unknown;
}
>(
`SELECT
br.*,
r.backtest_id,
r.status as run_status,
r.request_snapshot,
b.strategy,
b.symbols,
b.start_date,
@ -571,7 +609,54 @@ export class BacktestServiceV2 {
return null;
}
return mapStoredBacktestResult(at(result.rows, 0));
const row = at(result.rows, 0);
if (row.canonical_result !== null && row.canonical_result !== undefined) {
const saved = row.canonical_result;
const request = canonicalRunRequestSchema.parse(row.request_snapshot);
const financial = parseCanonicalFinancialResult(saved.financial, request);
if (
saved.kind !== 'canonical-result/v1' ||
saved.runId !== runId ||
saved.backtestId !== row.backtest_id ||
saved.status !== 'completed' ||
saved.financialEngine !== 'rust' ||
saved.strategyExecution !== 'typescript-retained-builtin/v1' ||
!Number.isFinite(Date.parse(saved.completedAt)) ||
!Number.isFinite(saved.executionTime) ||
saved.executionTime < 0 ||
canonicalStrategyJson(saved.request) !== canonicalStrategyJson(request) ||
canonicalStrategyJson(saved.analytics) !==
canonicalStrategyJson(
buildCanonicalBacktestReport(financial, request.analyticsPolicy).analytics
)
) {
throw new Error('Saved canonical result does not match its admitted request');
}
return saved;
}
if ((row.request_snapshot as { kind?: unknown } | null)?.kind === 'canonical-research/v1') {
throw new Error('Canonical result is missing; no legacy projection is available');
}
return mapStoredBacktestResult(row);
}
async canonicalCapability(id: string): Promise<CanonicalRunCapability> {
try {
await this.container.postgres.transaction(async client => {
const row = (await client.query('SELECT * FROM backtests WHERE id=$1 FOR UPDATE', [id]))
.rows[0];
if (!row || row.archived_at !== null) {
throw new Error('Backtest is missing or archived');
}
await admitCanonicalRequest(client, this.container, this.mapBacktest(row), id);
});
return { available: true, reason: null };
} catch (error) {
return {
available: false,
reason: error instanceof Error ? error.message : 'Canonical execution unavailable',
};
}
}
// Private methods
@ -616,6 +701,15 @@ export class BacktestServiceV2 {
'Strategy is archived; restore it before selecting a new version'
);
}
if (draft.config.canonical) {
await validateCanonicalSetup(client, { ...draft, strategyParameters: parameters });
return {
...draft,
startDate: new Date(draft.startDate).toISOString(),
endDate: new Date(draft.endDate).toISOString(),
strategyParameters: parameters,
};
}
const settings = backtestSettingsFromDefinition(draft);
await assertSelectedDatasetMatchesRequest(client, settings);
return {
@ -675,6 +769,15 @@ export class BacktestServiceV2 {
export function datasetSelectionForRun(row: QueryResultRow): BacktestRunDatasetSelection {
const hash = datasetHashSchema.safeParse(row.dataset_hash);
const pinnedHash = hash.success ? hash.data : null;
if ((row.request_snapshot as { kind?: unknown } | null)?.kind === 'canonical-research/v1') {
const canonical = canonicalRunRequestSchema.safeParse(row.request_snapshot);
return {
requestedHash: canonical.success ? canonical.data.datasetHash : null,
pinnedHash,
source: null,
state: canonical.success ? (pinnedHash ? 'pinned' : 'unavailable') : 'unknown',
};
}
let snapshot;
try {
snapshot = parseBacktestRequest(row.request_snapshot);

View file

@ -0,0 +1,273 @@
import { randomUUID } from 'node:crypto';
import type { PoolClient } from 'pg';
import type { IServiceContainer } from '@stock-bot/services';
import {
canonicalResearchSettingsSchema,
canonicalRunRequestSchema,
type CanonicalDatasetCatalogEntry,
type CanonicalRunRequest,
} from '@stock-bot/stock-config/canonical-research';
import { builtinStrategySelectionSchema } from '@stock-bot/stock-config/strategy';
import {
HistoricalDataRequestError,
parseFinancialDecimal,
type HistoricalDatasetV2,
type StrategyParameterValue,
} from '@stock-bot/types';
import { readCanonicalBuildIdentity } from '../../../orchestrator/src/backtest/canonical-build';
import { validateDatasetV2 } from '../../../orchestrator/src/data/historical-dataset-v2';
import type { DatasetCatalogQuery } from './dataset-catalog.service';
import { StrategyCatalogService } from './strategy-catalog.service';
export interface CanonicalTemplate {
name: string;
strategyVersionId?: string | null;
strategyParameters?: Record<string, StrategyParameterValue> | null;
symbols: string[];
startDate: string | Date;
endDate: string | Date;
initialCapital: number;
config?: Record<string, unknown>;
}
const invalid = (message: string): never => {
throw new HistoricalDataRequestError(message);
};
export async function readCanonicalDataset(
database: DatasetCatalogQuery,
hash: unknown
): Promise<HistoricalDatasetV2> {
if (typeof hash !== 'string' || !/^[a-f0-9]{64}$/.test(hash)) {
return invalid('Choose an explicitly retained v2 dataset');
}
const row = (await database.query('SELECT payload FROM backtest_datasets WHERE hash=$1', [hash]))
.rows[0];
if (!row) {
return invalid('Selected canonical dataset was not found');
}
let dataset;
try {
dataset = validateDatasetV2(row.payload);
} catch {
return invalid('Retained v2 dataset failed content validation');
}
if (dataset.manifest.hash !== hash) {
return invalid('Retained dataset identity mismatch');
}
if (dataset.manifest.eligibility !== 'eligible') {
return invalid(
'Canonical research requires an eligible dataset with known timing and action coverage'
);
}
if (
dataset.manifest.executionSeries.length !== 1 ||
dataset.manifest.series.length !== 1 ||
dataset.manifest.universe.instrumentIds.length !== 1
) {
return invalid(
'Canonical workbench currently supports one execution asset and one retained series'
);
}
return dataset;
}
export async function canonicalDatasetEntry(
database: DatasetCatalogQuery,
row: { hash: string; created_at: Date }
): Promise<CanonicalDatasetCatalogEntry> {
try {
const dataset = await readCanonicalDataset(database, row.hash);
return {
hash: row.hash,
createdAt: new Date(row.created_at).toISOString(),
manifest: dataset.manifest,
available: true,
reason: null,
};
} catch (error) {
if (!(error instanceof HistoricalDataRequestError)) {
throw error;
}
return {
hash: row.hash,
createdAt: new Date(row.created_at).toISOString(),
manifest: null,
available: false,
reason: error.message,
};
}
}
/** Separate v2 boundary: never round exchange-session times through the v1 daily parser. */
export async function validateCanonicalSetup(
database: DatasetCatalogQuery,
template: CanonicalTemplate
) {
const config = template.config ?? {};
if (
Object.keys(config).some(key => !['datasetHash', 'dataFrequency', 'canonical'].includes(key))
) {
return invalid('Canonical settings cannot include legacy fees, risk controls or fill models');
}
const settings = canonicalResearchSettingsSchema.parse(config.canonical);
const dataset = await readCanonicalDataset(database, config.datasetHash);
const execution = dataset.manifest.executionSeries[0];
const series = dataset.manifest.series.find(item => item.id === execution?.seriesId);
if (!execution || !series) {
return invalid('Retained dataset is missing its execution series');
}
if (
template.symbols.length !== 1 ||
template.symbols[0] !== execution.instrumentId ||
config.dataFrequency !== series.interval ||
new Date(template.startDate).getTime() !== dataset.manifest.bounds.tradeStart ||
new Date(template.endDate).getTime() !== dataset.manifest.bounds.tradeEnd
) {
return invalid(
'Canonical symbols, interval and exact trade bounds must match the retained dataset'
);
}
let initial;
try {
initial = parseFinancialDecimal(String(template.initialCapital));
} catch {
return invalid('Initial capital must be an exact supported financial decimal');
}
const units = BigInt(initial.replace('.', ''));
if (units <= 0n || units % 1000000n !== 0n) {
return invalid('Saved initial capital must be positive USD with at most two decimal places');
}
if (BigInt(settings.ownerBudget.replace('.', '')) > units) {
return invalid('Strategy owner budget cannot exceed initial capital');
}
return { settings, dataset, execution, series, initial };
}
/** Called under the backtest lock; this also serializes with family review/archive. */
export async function admitCanonicalRequest(
client: PoolClient,
container: IServiceContainer,
template: CanonicalTemplate,
backtestId: string,
runId = randomUUID()
): Promise<CanonicalRunRequest> {
if (!template.strategyVersionId || !template.strategyParameters) {
return invalid('Select an immutable strategy version and validated parameters');
}
const selected = (
await client.query(
`SELECT v.strategy_id,v.origin,s.archived_at FROM strategy_versions v JOIN strategies s ON s.id=v.strategy_id
WHERE v.id=$1 FOR UPDATE OF s`,
[template.strategyVersionId]
)
).rows[0];
if (!selected || selected.archived_at !== null || selected.origin !== 'builtin') {
return invalid(
'Only active, server-seeded built-in versions can execute; candidates require isolation'
);
}
const review = (
await client.query(
'SELECT id,decision FROM strategy_review_events WHERE version_id=$1 ORDER BY ordinal DESC LIMIT 1',
[template.strategyVersionId]
)
).rows[0];
if (review?.decision !== 'approve') {
return invalid('An operator must approve this built-in version before execution');
}
const pkg = await new StrategyCatalogService(container).getVersionArtifact(
template.strategyVersionId,
client
);
const { settings, dataset, execution, series, initial } = await validateCanonicalSetup(
client,
template
);
const calendar = dataset.manifest.calendars.find(item => item.id === series.calendarId);
if (!calendar) {
return invalid('Retained dataset is missing its execution calendar');
}
const { warmupStart, tradeEnd } = dataset.manifest.bounds;
const initialSession = calendar.sessions.filter(session => session.open <= warmupStart).at(-1);
if (!initialSession) {
return invalid('Retained calendar needs an account-session opening at or before warmup start');
}
// The account resets at this retained calendar's opens. This declared clock is
// distinct from venue order expiry; its identity and every boundary are frozen.
const riskSession = (session: typeof initialSession) => ({
calendarId: calendar.id,
calendarRevision: calendar.revision,
sessionId: session.date,
startsAt: session.open,
});
const ownerId = `strategy:${template.strategyVersionId}`;
const selection = builtinStrategySelectionSchema.parse({
strategyId: pkg.program.strategyId,
strategyVersion: pkg.program.strategyVersion,
ownerId,
seed: settings.seed,
instrumentId: execution.instrumentId,
seriesId: execution.seriesId,
ownerBudget: settings.ownerBudget,
parameters: template.strategyParameters,
// API/checkpoint identities are retained in the package, not selection fields.
});
return canonicalRunRequestSchema.parse({
kind: 'canonical-research/v1',
runId,
backtestId,
name: template.name,
strategy: {
familyId: selected.strategy_id,
versionId: template.strategyVersionId,
origin: 'builtin',
reviewId: review.id,
package: pkg,
selection,
},
datasetHash: dataset.manifest.hash,
policy: {
matching: {
risk: {
ledger: {
version: 1,
sessionId: runId,
accountId: `research:${runId}`,
baseCurrency: 'USD',
reserveOwnerId: 'reserve',
ownerIds: [ownerId],
initialCapital: initial,
riskSession: riskSession(initialSession),
},
feeRate: settings.feeRate,
maxOrderQuantity: settings.maxOrderQuantity,
maxPositionQuantity: settings.maxPositionQuantity,
maxSymbolExposure: settings.maxSymbolExposure,
maxGrossExposure: settings.maxGrossExposure,
maxDailyLoss: settings.maxDailyLoss,
maxDrawdownAmount: settings.maxDrawdownAmount,
maxMarkAgeMs: settings.maxMarkAgeMs,
},
owners: [{ ownerId, mode: 'Target' }],
series: [{ ...execution, mode: 'Open' }],
halfSpreadRate: settings.halfSpreadRate,
slippageRate: settings.slippageRate,
latencyMs: settings.latencyMs,
},
participation_rate: settings.participationRate,
cadence: [{ owner_id: ownerId, series_ids: [execution.seriesId] }],
allow_exploratory: false,
risk_boundaries: calendar.sessions
.filter(session => session.open > warmupStart && session.open <= tradeEnd)
.map(riskSession),
},
analyticsPolicy: {
version: 1,
periodsPerYear: settings.periodsPerYear,
annualRiskFreeRate: settings.annualRiskFreeRate,
benchmark: null,
},
build: await readCanonicalBuildIdentity(),
modelArtifacts: [],
});
}

View file

@ -105,7 +105,9 @@ const version = (row: QueryResultRow): StrategyVersionSummary => ({
runnable: false,
reason:
row.origin === 'builtin'
? 'Catalog versions require canonical workbench integration (R05) before execution.'
? row.review_status === 'approved'
? 'Configure a supported canonical dataset and explicit financial policy before execution.'
: 'An operator must approve this built-in version before configuring execution.'
: 'Candidate execution requires isolation (A02); publication and approval do not execute code.',
});
class ReceiptRace extends Error {}

View file

@ -1,6 +1,7 @@
import { ArrowLeftIcon, PlusIcon } from '@heroicons/react/24/outline';
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { Link, useNavigate, useParams } from 'react-router-dom';
import { isCanonicalRunResult } from '@stock-bot/stock-config/canonical-research';
import {
catalogExecutionReason,
supportedLegacyStrategy,
@ -10,6 +11,8 @@ import { ArchiveBacktestDialog } from './components/ArchiveBacktestDialog';
import { BacktestConfiguration } from './components/BacktestConfiguration';
import { BacktestPlayback } from './components/BacktestPlayback';
import { BacktestTrades } from './components/BacktestTrades';
import { CanonicalResults } from './components/CanonicalResults';
import { CanonicalSetup } from './components/CanonicalSetup';
import { RunControlsCompact } from './components/RunControlsCompact';
import { RunDataset } from './components/RunDataset';
import { RunsListWithMetrics } from './components/RunsListWithMetrics';
@ -32,6 +35,7 @@ export function BacktestDetailPageV2() {
const [activeTab, setActiveTab] = useState('details');
const [showNewRun, setShowNewRun] = useState(false);
const [showArchiveDialog, setShowArchiveDialog] = useState(false);
const [showCanonicalSetup, setShowCanonicalSetup] = useState(false);
const navigationGeneration = useRef(0);
const {
@ -39,6 +43,10 @@ export function BacktestDetailPageV2() {
runs,
currentRun,
runResults,
canonicalCapability,
capabilityError,
isCapabilityLoading,
refreshCanonicalCapability,
isLoading,
error,
submissionError,
@ -58,7 +66,8 @@ export function BacktestDetailPageV2() {
const unsupportedLegacy = Boolean(
backtest && !catalog && !supportedLegacyStrategy(backtest.strategy)
);
const canSubmit = (!archived && !catalog && !unsupportedLegacy) || hasPendingSubmission;
const executionUnavailable = catalog ? !canonicalCapability?.available : unsupportedLegacy;
const canSubmit = (!archived && !executionUnavailable) || hasPendingSubmission;
// Notifications invalidate the same persisted-state reader used by polling.
useWebSocket({
@ -77,6 +86,7 @@ export function BacktestDetailPageV2() {
navigationGeneration.current++;
setShowNewRun(false);
setShowArchiveDialog(false);
setShowCanonicalSetup(false);
return () => {
navigationGeneration.current++;
};
@ -260,7 +270,7 @@ export function BacktestDetailPageV2() {
<h3 className="text-lg font-medium text-text-primary">Run History</h3>
<button
onClick={() => setShowNewRun(true)}
disabled={archived || catalog || unsupportedLegacy}
disabled={archived || executionUnavailable}
className="inline-flex items-center px-4 py-2 bg-primary-500 text-white rounded-md text-sm font-medium hover:bg-primary-600 transition-colors"
>
<PlusIcon className="w-4 h-4 mr-2" />
@ -311,12 +321,42 @@ export function BacktestDetailPageV2() {
);
case 'settings':
return (
<div className="max-w-4xl mx-auto">
<BacktestConfiguration
onSubmit={handleConfigSubmit}
disabled={archived || isLoading}
initialConfig={backtestConfig}
/>
<div className="max-w-4xl mx-auto space-y-4">
{catalog && backtest && (showCanonicalSetup || backtest.config.canonical) ? (
<CanonicalSetup
key={backtest.id}
backtest={backtest}
disabled={archived || isLoading}
onSave={request => updateBacktest(backtest.id, request)}
onClose={
!backtest.config.canonical ? () => setShowCanonicalSetup(false) : undefined
}
/>
) : (
<>
{catalog && (
<div className="space-y-2">
<p className="text-sm text-text-secondary">
This draft is not configured for canonical execution. Select an eligible
retained dataset and inspect the simulation policy before running.
</p>
<button
type="button"
className="px-3 py-2 border border-border rounded-md text-primary-500 disabled:opacity-50"
disabled={archived || isLoading}
onClick={() => setShowCanonicalSetup(true)}
>
Configure canonical research
</button>
</div>
)}
<BacktestConfiguration
onSubmit={handleConfigSubmit}
disabled={archived || isLoading}
initialConfig={backtestConfig}
/>
</>
)}
</div>
);
case 'details':
@ -329,6 +369,9 @@ export function BacktestDetailPageV2() {
);
}
if (runResults && isCanonicalRunResult(runResults)) {
return <CanonicalResults key={runResults.runId} result={runResults} />;
}
return (
<div className="h-full overflow-hidden">
<BacktestPlayback
@ -339,6 +382,9 @@ export function BacktestDetailPageV2() {
</div>
);
case 'trades':
if (runResults && isCanonicalRunResult(runResults)) {
return <CanonicalResults key={runResults.runId} result={runResults} fillsOnly />;
}
return (
<div className="h-full overflow-y-auto">
<BacktestTrades result={runResults} isLoading={isLoading} />
@ -443,7 +489,7 @@ export function BacktestDetailPageV2() {
isSubmitting={isSubmitting}
hasPendingSubmission={hasPendingSubmission}
archived={archived}
executionUnavailable={catalog || unsupportedLegacy}
executionUnavailable={executionUnavailable}
/>
</div>
)}
@ -457,7 +503,19 @@ export function BacktestDetailPageV2() {
role="status"
className="mb-4 p-3 border border-border rounded-lg text-sm text-text-secondary"
>
{catalogExecutionReason}
{isCapabilityLoading
? 'Checking canonical execution eligibility...'
: canonicalCapability?.available
? 'Canonical execution is available for this saved configuration. Admission will verify it again before starting.'
: (capabilityError ?? canonicalCapability?.reason ?? catalogExecutionReason)}{' '}
<button
type="button"
className="text-primary-500 underline"
disabled={isCapabilityLoading || archived}
onClick={refreshCanonicalCapability}
>
Retry execution eligibility
</button>
{backtest?.strategyVersionId && (
<>
{' '}

View file

@ -0,0 +1,438 @@
import { useState } from 'react';
import { Line, LineChart, ResponsiveContainer, Tooltip, XAxis, YAxis } from 'recharts';
import type { CanonicalRunResult } from '@stock-bot/stock-config/canonical-research';
import type { CanonicalMetrics } from '@stock-bot/types';
import { actionClass } from '@/features/strategies/components/StrategyParameterForm';
const tableClass = 'w-full text-sm text-left border-collapse';
const cell = 'p-2 border-b border-border align-top';
export function canonicalTime(timestamp: number): string {
const date = new Date(timestamp);
return Number.isFinite(date.getTime()) ? date.toISOString() : `${timestamp} ms since Unix epoch`;
}
const reasonText = (reason: string | undefined) => reason?.replace(/-/g, ' ') ?? 'not reported';
const metricFields: { key: keyof CanonicalMetrics; label: string; percentage?: boolean }[] = [
{ key: 'totalReturn', label: 'Total return', percentage: true },
{ key: 'cagr', label: 'CAGR', percentage: true },
{ key: 'maxDrawdown', label: 'Sampled maximum drawdown', percentage: true },
{ key: 'exposureTime', label: 'Exposure time', percentage: true },
{ key: 'volatility', label: 'Annualized volatility', percentage: true },
{ key: 'downsideDeviation', label: 'Downside deviation', percentage: true },
{ key: 'sharpeRatio', label: 'Sharpe ratio' },
{ key: 'sortinoRatio', label: 'Sortino ratio' },
{ key: 'var95', label: 'Value at risk (95%)', percentage: true },
{ key: 'cvar95', label: 'Conditional value at risk (95%)', percentage: true },
{ key: 'var99', label: 'Value at risk (99%)', percentage: true },
{ key: 'roundTripCount', label: 'Completed round trips' },
{ key: 'winRate', label: 'Win rate', percentage: true },
{ key: 'profitFactor', label: 'Profit factor' },
{ key: 'avgWin', label: 'Average win' },
{ key: 'avgLoss', label: 'Average loss' },
{ key: 'alpha', label: 'Alpha' },
{ key: 'beta', label: 'Beta' },
{ key: 'informationRatio', label: 'Information ratio' },
];
export function CanonicalResults({
result,
fillsOnly = false,
}: {
result: CanonicalRunResult;
fillsOnly?: boolean;
}) {
const [showCurve, setShowCurve] = useState(false);
const { financial, analytics, request } = result;
const valuation = financial.projection.valuation;
const currency = financial.view.portfolio.baseCurrency;
const samples = [
{
timestamp: financial.reporting.tradeStart,
equity: financial.reporting.initialEquity,
label: 'Initial equity',
partial: false,
},
...financial.reporting.sessions.map(sample => ({
timestamp: sample.periodEnd,
equity: sample.equity,
label: sample.session.sessionId,
partial: sample.partialStart || sample.partialEnd,
})),
];
if (fillsOnly) {
return <CanonicalFills result={result} />;
}
return (
<div className="space-y-5 text-text-primary pb-4">
<section
aria-label="Canonical result provenance"
className="p-4 border border-border rounded-lg space-y-3"
>
<h3 className="font-semibold">Canonical research result</h3>
<p className="text-sm text-text-secondary">
Rust financial simulation · retained TypeScript built-in. Completion does not establish
strategy profitability or authorize trading.
</p>
<dl className="grid gap-3 text-sm sm:grid-cols-2 break-all">
<div>
<dt>Run</dt>
<dd>{result.runId}</dd>
</div>
<div>
<dt>Strategy version</dt>
<dd>{request.strategy.versionId}</dd>
</div>
<div>
<dt>Dataset hash</dt>
<dd>{request.datasetHash}</dd>
</div>
<div>
<dt>Executed strategy artifact SHA256</dt>
<dd>{request.strategy.package.artifact.sha256}</dd>
</div>
<div>
<dt>Native engine SHA256</dt>
<dd>{request.build.engineBinarySha256}</dd>
</div>
<div>
<dt>Worker SHA256</dt>
<dd>{request.build.workerSha256}</dd>
</div>
<div>
<dt>Engine wrapper SHA256</dt>
<dd>{request.build.engineWrapperSha256}</dd>
</div>
<div>
<dt>Dependency lock SHA256</dt>
<dd>{request.build.dependencyLockSha256}</dd>
</div>
<div>
<dt>Financial / reporting versions</dt>
<dd>
{financial.financialVersion} / {financial.reportingVersion}
</dd>
</div>
<div>
<dt>Runtime</dt>
<dd>
{request.build.runtime} {request.build.runtimeVersion} · {request.build.platform}/
{request.build.arch}
</dd>
</div>
</dl>
<details>
<summary className="cursor-pointer">Immutable configuration and reporting policy</summary>
<pre className="mt-2 text-xs overflow-auto max-h-96">
{JSON.stringify(
{
name: request.name,
strategy: {
familyId: request.strategy.familyId,
versionId: request.strategy.versionId,
origin: request.strategy.origin,
reviewId: request.strategy.reviewId,
program: request.strategy.package.program,
selection: request.strategy.selection,
source: request.strategy.package.source,
dependencyLockSha256: request.strategy.package.dependencyLock.sha256,
},
datasetHash: request.datasetHash,
policy: request.policy,
analyticsPolicy: analytics.policy,
build: request.build,
modelArtifacts: request.modelArtifacts,
},
null,
2
)}
</pre>
</details>
<ul className="list-disc pl-5 text-sm text-text-secondary space-y-1">
{[...financial.limitations, ...financial.modelLimitations].map((limitation, index) => (
<li key={index}>{limitation}</li>
))}
</ul>
</section>
<section className="space-y-3">
<h3 className="font-semibold">Authoritative terminal account ({currency})</h3>
<dl className="grid gap-3 sm:grid-cols-3 text-sm">
{(
[
'cash',
'markedHoldings',
'equity',
'remainingCost',
'realizedGrossPnl',
'unrealizedPnl',
'fees',
] as const
).map(key => (
<div key={key}>
<dt>
{
{
cash: 'Cash',
markedHoldings: 'Marked holdings',
equity: 'Equity',
remainingCost: 'Remaining cost',
realizedGrossPnl: 'Gross realized P&L',
unrealizedPnl: 'Unrealized P&L',
fees: 'Fees',
}[key]
}
</dt>
<dd className="font-mono">{valuation[key]}</dd>
</div>
))}
</dl>
<p className="text-xs text-text-secondary">
Decimal amounts come directly from Rust. Gross realized P&L excludes separately reported
fees. Holdings are valued using the last available marks.
</p>
</section>
<section className="space-y-3">
<h3 className="font-semibold">Canonical metrics</h3>
<p className="text-sm text-text-secondary">
{analytics.fillCount} fills · {analytics.completePeriodCount} complete periods ·{' '}
{analytics.periodicSampleCount} statistical samples. Returns use fractions, displayed as
percentages. Drawdown is sampled at period ends and the terminal boundary, not every
intraday price. Exposure uses elapsed calendar time.
</p>
<dl className="grid gap-3 sm:grid-cols-3 text-sm">
{metricFields.map(field => {
const value = analytics.metrics[field.key];
return (
<div key={field.key}>
<dt>{field.label}</dt>
<dd title={value === null ? undefined : String(value)}>
{value === null
? `Unavailable — ${reasonText(analytics.unavailable[field.key])}`
: field.percentage
? `${(value * 100).toFixed(2)}%`
: value.toFixed(2)}
</dd>
</div>
);
})}
</dl>
<p className="text-xs text-text-secondary">
Period calendar: {analytics.policy.calendarId}, revision{' '}
{analytics.policy.calendarRevision}. Annualization: {analytics.policy.periodsPerYear}{' '}
periods/year. Risk-free rate:{' '}
{analytics.policy.annualRiskFreeRate === null
? 'unknown'
: `${(analytics.policy.annualRiskFreeRate * 100).toFixed(2)}%`}
. Partial periods are visible but excluded from periodic statistics. Per-period mark
freshness is not certified.
</p>
</section>
<section className="space-y-3">
<h3 className="font-semibold">Equity samples</h3>
<button type="button" className={actionClass} onClick={() => setShowCurve(value => !value)}>
{showCurve ? 'Hide equity curve' : 'Show equity curve'}
</button>
{showCurve && (
<div aria-label="Canonical equity curve" className="h-64">
<ResponsiveContainer width="100%" height="100%">
<LineChart
data={samples.map(sample => ({
timestamp: sample.timestamp,
equity: Number(sample.equity),
}))}
>
<XAxis
type="number"
dataKey="timestamp"
domain={['dataMin', 'dataMax']}
tickFormatter={canonicalTime}
/>
<YAxis domain={['auto', 'auto']} />
<Tooltip labelFormatter={value => canonicalTime(Number(value))} />
<Line
type="linear"
dataKey="equity"
stroke="#3b82f6"
dot={false}
isAnimationActive={false}
/>
</LineChart>
</ResponsiveContainer>
<p className="text-xs text-text-muted">
The plot uses approximate numbers; exact sampled equity remains in the table.
</p>
</div>
)}
<div className="overflow-auto">
<table className={tableClass}>
<thead>
<tr>
<th className={cell}>Timestamp (UTC)</th>
<th className={cell}>Sample</th>
<th className={cell}>Equity ({currency})</th>
<th className={cell}>Period</th>
</tr>
</thead>
<tbody>
{samples.map((sample, index) => (
<tr key={index}>
<td className={cell}>{canonicalTime(sample.timestamp)}</td>
<td className={cell}>{sample.label}</td>
<td className={`${cell} font-mono`}>{sample.equity}</td>
<td className={cell}>
{index === 0 ? 'Initial' : sample.partial ? 'Partial' : 'Complete'}
</td>
</tr>
))}
</tbody>
</table>
</div>
</section>
<section className="space-y-3">
<h3 className="font-semibold">Owner positions</h3>
<p className="text-sm text-text-secondary">
These are owner books, not reconstructed round trips. Per-position marks, average prices
and unrealized P&L are unavailable in this report.
</p>
{!financial.view.portfolio.positions.length ? (
<p>No owner positions recorded.</p>
) : (
<div className="overflow-auto">
<table className={tableClass}>
<thead>
<tr>
{[
'Owner',
'Asset',
'Quantity',
`Remaining cost (${currency})`,
`Gross realized P&L (${currency})`,
].map(label => (
<th className={cell} key={label}>
{label}
</th>
))}
</tr>
</thead>
<tbody>
{financial.view.portfolio.positions.map(position => (
<tr key={`${position.ownerId}:${position.instrumentId}`}>
<td className={cell}>{position.ownerId}</td>
<td className={cell}>{position.instrumentId}</td>
<td className={`${cell} font-mono`}>{position.quantity}</td>
<td className={`${cell} font-mono`}>{position.remainingCost}</td>
<td className={`${cell} font-mono`}>{position.realizedGrossPnl}</td>
</tr>
))}
</tbody>
</table>
</div>
)}
<h4 className="font-medium">Owner valuations ({currency})</h4>
<div className="overflow-auto">
<table className={tableClass}>
<thead>
<tr>
{[
'Owner',
'Initial allocation',
'Marked holdings',
'Remaining cost',
'Gross realized P&L',
'Unrealized P&L',
'Fees',
'Equity contribution',
].map(label => (
<th className={cell} key={label}>
{label}
</th>
))}
</tr>
</thead>
<tbody>
{valuation.owners.map(owner => (
<tr key={owner.ownerId}>
<td className={cell}>{owner.ownerId}</td>
{(
[
'initialCapital',
'markedHoldings',
'remainingCost',
'realizedGrossPnl',
'unrealizedPnl',
'fees',
'equityContribution',
] as const
).map(key => (
<td className={`${cell} font-mono`} key={key}>
{owner[key]}
</td>
))}
</tr>
))}
</tbody>
</table>
</div>
</section>
</div>
);
}
function CanonicalFills({ result }: { result: CanonicalRunResult }) {
const fills = result.financial.projection.fills;
return (
<section className="space-y-4 text-text-primary">
<h3 className="font-semibold">Canonical fills ({result.analytics.fillCount})</h3>
<p className="text-sm text-text-secondary">
Actual Rust fill postings. A fill is not a completed round trip; gross realized P&L and fees
are separate. Win rate and round-trip statistics are unavailable.
</p>
{!fills.length ? (
<p role="status">No fills were executed in this completed run.</p>
) : (
<div className="overflow-auto">
<table className={tableClass}>
<thead>
<tr>
{[
'Time (UTC)',
'Owner',
'Asset',
'Side',
'Quantity',
'Price',
'Fee',
'Released basis',
'Gross realized P&L',
'Order / fill / decision',
].map(label => (
<th className={cell} key={label}>
{label}
</th>
))}
</tr>
</thead>
<tbody>
{fills.map(fill => (
<tr key={`${fill.ownerId}:${fill.fillId}`}>
<td className={cell}>{canonicalTime(fill.eventTime)}</td>
<td className={cell}>{fill.ownerId}</td>
<td className={cell}>{fill.instrumentId}</td>
<td className={cell}>{fill.side}</td>
<td className={`${cell} font-mono`}>{fill.quantity}</td>
<td className={`${cell} font-mono`}>{fill.price}</td>
<td className={`${cell} font-mono`}>{fill.fee.amount}</td>
<td className={`${cell} font-mono`}>{fill.releasedBasis}</td>
<td className={`${cell} font-mono`}>{fill.realizedGrossPnl}</td>
<td className={`${cell} text-xs break-all`}>
{fill.orderId}
<br />
{fill.fillId}
<br />
{fill.decision.decisionId}
</td>
</tr>
))}
</tbody>
</table>
</div>
)}
</section>
);
}

View file

@ -0,0 +1,610 @@
import { useEffect, useRef, useState } from 'react';
import {
canonicalResearchSettingsSchema,
type CanonicalDatasetCatalogEntry,
type CanonicalResearchSettings,
} from '@stock-bot/stock-config/canonical-research';
import { parseFinancialDecimal } from '@stock-bot/types';
import { actionClass, fieldClass } from '@/features/strategies/components/StrategyParameterForm';
import {
StrategySelection,
type CatalogSelection,
} from '@/features/strategies/components/StrategySelection';
import {
confirmDiscard,
useUnsavedWarning,
} from '@/features/strategies/components/useUnsavedWarning';
import {
backtestApiV2,
type Backtest,
type CreateBacktestRequest,
} from '../services/backtestApiV2';
type PolicyKey = Exclude<keyof CanonicalResearchSettings, 'version'>;
const policyFields: {
key: PolicyKey;
label: string;
group: string;
kind: 'decimal' | 'number' | 'nullable';
description: string;
}[] = [
{
key: 'ownerBudget',
label: 'Owner budget',
group: 'Capital allocation',
kind: 'decimal',
description: 'USD allocated to this strategy; it cannot exceed initial capital.',
},
{
key: 'feeRate',
label: 'Fee rate',
group: 'Execution',
kind: 'decimal',
description: 'Fraction of fill notional charged once per fill. 0.001 means 0.1%.',
},
{
key: 'halfSpreadRate',
label: 'Half-spread rate',
group: 'Execution',
kind: 'decimal',
description: 'Fractional price adjustment for one side of the simulated spread.',
},
{
key: 'slippageRate',
label: 'Slippage rate',
group: 'Execution',
kind: 'decimal',
description: 'Additional adverse price fraction per fill.',
},
{
key: 'participationRate',
label: 'Volume participation rate',
group: 'Execution',
kind: 'decimal',
description:
'Maximum fraction of previously available completed-bar volume used for liquidity; this is not contemporaneous liquidity.',
},
{
key: 'latencyMs',
label: 'Order latency (ms)',
group: 'Execution',
kind: 'number',
description: 'Nonnegative delay before an order becomes eligible.',
},
{
key: 'maxOrderQuantity',
label: 'Maximum order quantity',
group: 'Financial constraints',
kind: 'decimal',
description: 'Absolute asset quantity per order.',
},
{
key: 'maxPositionQuantity',
label: 'Maximum position quantity',
group: 'Financial constraints',
kind: 'decimal',
description: 'Absolute asset quantity held by the strategy.',
},
{
key: 'maxSymbolExposure',
label: 'Maximum asset exposure',
group: 'Financial constraints',
kind: 'decimal',
description: 'USD notional exposure to the selected asset.',
},
{
key: 'maxGrossExposure',
label: 'Maximum gross exposure',
group: 'Financial constraints',
kind: 'decimal',
description: 'USD gross exposure across the account.',
},
{
key: 'maxDailyLoss',
label: 'Maximum risk-period loss',
group: 'Financial constraints',
kind: 'decimal',
description:
'USD loss from the declared risk-period baseline; zero is an active zero threshold.',
},
{
key: 'maxDrawdownAmount',
label: 'Maximum drawdown amount',
group: 'Financial constraints',
kind: 'decimal',
description: 'USD decline from peak equity; zero is an active zero threshold.',
},
{
key: 'maxMarkAgeMs',
label: 'Maximum mark age (ms)',
group: 'Financial constraints',
kind: 'number',
description: 'Maximum age of an available mark for financial admission.',
},
{
key: 'seed',
label: 'Random seed',
group: 'Research and reporting',
kind: 'number',
description: 'Integer seed retained with the run.',
},
{
key: 'periodsPerYear',
label: 'Reporting periods per year',
group: 'Research and reporting',
kind: 'number',
description: 'Explicit annualization convention for complete declared risk periods.',
},
{
key: 'annualRiskFreeRate',
label: 'Annual risk-free rate',
group: 'Research and reporting',
kind: 'nullable',
description: 'Fraction per year. Leave blank for unknown; zero is an explicit assumption.',
},
];
type RawPolicy = Record<PolicyKey, string>;
function defaults(capital: number): CanonicalResearchSettings {
return {
version: 1,
ownerBudget: String(capital),
feeRate: '0.001',
halfSpreadRate: '0.0005',
slippageRate: '0.0005',
participationRate: '0.1',
latencyMs: 0,
maxOrderQuantity: '1000000',
maxPositionQuantity: '1000000',
maxSymbolExposure: String(capital),
maxGrossExposure: String(capital),
maxDailyLoss: '1000',
maxDrawdownAmount: '2000',
maxMarkAgeMs: 604800000,
seed: 1,
periodsPerYear: 252,
annualRiskFreeRate: null,
};
}
function initialPolicy(backtest: Backtest): RawPolicy {
const input = backtest.config.canonical;
const source = input && typeof input === 'object' ? input : defaults(backtest.initialCapital);
return Object.fromEntries(
policyFields.map(({ key }) => {
const value = Reflect.get(source, key);
return [key, value === undefined || value === null ? '' : String(value)];
})
) as RawPolicy;
}
export function canonicalDatasetFields(entry: CanonicalDatasetCatalogEntry) {
const manifest = entry.manifest;
if (
!entry.available ||
!manifest ||
manifest.version !== 2 ||
manifest.hash !== entry.hash ||
manifest.eligibility !== 'eligible' ||
manifest.executionSeries.length !== 1
) {
throw new Error(entry.reason ?? 'Choose an eligible single-asset canonical dataset.');
}
const execution = manifest.executionSeries[0];
if (!execution) {
throw new Error('Dataset execution series is missing.');
}
const series = manifest.series.find(
item => item.id === execution.seriesId && item.instrumentId === execution.instrumentId
);
if (!series) {
throw new Error('Dataset execution series is unavailable.');
}
const startDate = new Date(manifest.bounds.tradeStart).toISOString();
const endDate = new Date(manifest.bounds.tradeEnd).toISOString();
return {
symbols: [execution.instrumentId],
startDate,
endDate,
warmupStart: new Date(manifest.bounds.warmupStart).toISOString(),
dataFrequency: series.interval,
};
}
function parsePolicy(raw: RawPolicy): {
settings?: CanonicalResearchSettings;
errors: Partial<Record<PolicyKey, string>>;
} {
const values: Record<string, unknown> = { version: 1 };
const errors: Partial<Record<PolicyKey, string>> = {};
for (const field of policyFields) {
const text = raw[field.key];
try {
if (field.kind === 'nullable' && text.trim() === '') {
values[field.key] = null;
} else if (field.kind === 'decimal') {
values[field.key] = parseFinancialDecimal(text);
} else {
if (text.trim() === '' || !Number.isFinite(Number(text))) {
throw new Error('Enter a finite number.');
}
values[field.key] = Number(text);
}
} catch (cause) {
errors[field.key] = cause instanceof Error ? cause.message : 'Invalid value';
}
}
if (Object.keys(errors).length) {
return { errors };
}
const parsed = canonicalResearchSettingsSchema.safeParse(values);
if (!parsed.success) {
for (const issue of parsed.error.issues) {
const key = issue.path[0] as PolicyKey;
errors[key] = issue.message;
}
return { errors };
}
return { settings: parsed.data, errors };
}
export function CanonicalSetup({
backtest,
disabled = false,
onSave,
onClose,
}: {
backtest: Backtest;
disabled?: boolean;
onSave: (request: CreateBacktestRequest) => Promise<void>;
onClose?: () => void;
}) {
const [name, setName] = useState(backtest.name);
const [capital, setCapital] = useState(String(backtest.initialCapital));
const [raw, setRaw] = useState(() => initialPolicy(backtest));
const [hash, setHash] = useState(
typeof backtest.config.canonical === 'object' && typeof backtest.config.datasetHash === 'string'
? backtest.config.datasetHash
: ''
);
const [selection, setSelection] = useState<CatalogSelection>({
strategyVersionId: backtest.strategyVersionId,
strategyParameters: backtest.strategyParameters,
});
const [strategyValid, setStrategyValid] = useState(false);
const [epoch, setEpoch] = useState(0);
const [catalog, setCatalog] = useState<CanonicalDatasetCatalogEntry[]>([]);
const [dataset, setDataset] = useState<CanonicalDatasetCatalogEntry | null>(null);
const [catalogLoading, setCatalogLoading] = useState(true);
const [datasetLoading, setDatasetLoading] = useState(false);
const [catalogError, setCatalogError] = useState<string | null>(null);
const [datasetError, setDatasetError] = useState<string | null>(null);
const [retry, setRetry] = useState(0);
const [saving, setSaving] = useState(false);
const [error, setError] = useState<string | null>(null);
const [dirty, setDirty] = useState(false);
const authoritative = useRef(backtest);
const pending = useRef(false);
const active = useRef(true);
useUnsavedWarning(dirty);
useEffect(() => {
active.current = true;
return () => {
active.current = false;
};
}, []);
useEffect(() => {
if (backtest === authoritative.current) {
return;
}
authoritative.current = backtest;
setName(backtest.name);
setCapital(String(backtest.initialCapital));
setRaw(initialPolicy(backtest));
setHash(
typeof backtest.config.canonical === 'object' &&
typeof backtest.config.datasetHash === 'string'
? backtest.config.datasetHash
: ''
);
setSelection({
strategyVersionId: backtest.strategyVersionId,
strategyParameters: backtest.strategyParameters,
});
setStrategyValid(false);
setEpoch(value => value + 1);
setDirty(false);
setError(null);
}, [backtest]);
useEffect(() => {
const controller = new AbortController();
setCatalogLoading(true);
setCatalogError(null);
void backtestApiV2
.listCanonicalDatasets(controller.signal)
.then(entries => {
if (!controller.signal.aborted) {
setCatalog(entries);
}
})
.catch(cause => {
if (!controller.signal.aborted) {
setCatalogError(cause.message);
}
})
.finally(() => {
if (!controller.signal.aborted) {
setCatalogLoading(false);
}
});
return () => controller.abort();
}, [retry]);
useEffect(() => {
const controller = new AbortController();
setDataset(null);
setDatasetError(null);
setDatasetLoading(Boolean(hash));
if (hash) {
void backtestApiV2
.canonicalDataset(hash, controller.signal)
.then(entry => {
if (!controller.signal.aborted) {
if (entry.hash !== hash) {
throw new Error('Dataset lookup returned a different hash.');
}
setDataset(entry);
}
})
.catch(cause => {
if (!controller.signal.aborted) {
setDatasetError(cause.message);
}
})
.finally(() => {
if (!controller.signal.aborted) {
setDatasetLoading(false);
}
});
}
return () => controller.abort();
}, [hash, retry]);
const parsed = parsePolicy(raw);
let selectedFields: ReturnType<typeof canonicalDatasetFields> | undefined;
let compatibilityError: string | null = null;
if (dataset && dataset.hash === hash) {
try {
selectedFields = canonicalDatasetFields(dataset);
} catch (cause) {
compatibilityError = cause instanceof Error ? cause.message : 'Dataset is unsupported';
}
}
const validCapital =
capital.trim() !== '' && Number.isFinite(Number(capital)) && Number(capital) > 0;
const locked = disabled || saving;
const valid = Boolean(
name.trim() &&
validCapital &&
selectedFields &&
parsed.settings &&
selection.strategyVersionId &&
strategyValid
);
const save = async (event: React.FormEvent) => {
event.preventDefault();
if (locked || pending.current || !valid || !selectedFields || !parsed.settings) {
return;
}
pending.current = true;
setSaving(true);
setError(null);
try {
await onSave({
name,
strategy: 'catalog',
strategyVersionId: selection.strategyVersionId,
strategyParameters: selection.strategyParameters,
symbols: selectedFields.symbols,
startDate: selectedFields.startDate,
endDate: selectedFields.endDate,
initialCapital: Number(capital),
config: {
datasetHash: hash,
dataFrequency: selectedFields.dataFrequency,
canonical: parsed.settings,
},
});
if (active.current) {
setDirty(false);
}
} catch (cause) {
if (active.current) {
setError(cause instanceof Error ? cause.message : 'Could not save canonical setup');
}
} finally {
pending.current = false;
if (active.current) {
setSaving(false);
}
}
};
const options =
dataset && !catalog.some(entry => entry.hash === dataset.hash)
? [dataset, ...catalog]
: catalog;
return (
<form
className="space-y-5"
onSubmit={event => void save(event)}
onChange={() => setDirty(true)}
>
<h3 className="font-semibold text-text-primary">Canonical research setup</h3>
<p className="text-sm text-text-secondary">
Review every policy below. Rust enforces accounting, fills and financial limits. This
workflow supports one asset and reviewed built-in versions; saving does not start a run.
</p>
{dirty && (
<p role="status" className="text-sm text-text-secondary">
Unsaved canonical setup. Save or discard before leaving.
</p>
)}
<fieldset disabled={locked} className="space-y-4">
<label className="block text-sm">
Backtest name
<input
aria-label="Backtest name"
className={fieldClass}
value={name}
onChange={event => setName(event.target.value)}
required
/>
</label>
<label className="block text-sm">
Initial capital (USD)
<input
aria-label="Initial capital (USD)"
className={fieldClass}
value={capital}
onChange={event => setCapital(event.target.value)}
inputMode="decimal"
/>
</label>
{!validCapital && (
<p role="alert" className="text-error text-sm">
Initial capital must be a positive finite number.
</p>
)}
<label className="block text-sm">
Canonical dataset
<select
aria-label="Canonical dataset"
className={fieldClass}
value={hash}
onChange={event => setHash(event.target.value)}
>
<option value="">Select a retained single-asset dataset</option>
{hash && !options.some(entry => entry.hash === hash) && (
<option value={hash}>{hash} — retained selection</option>
)}
{options.map(entry => (
<option key={entry.hash} value={entry.hash} disabled={!entry.available}>
{entry.hash} —{' '}
{entry.manifest?.executionSeries.map(item => item.instrumentId).join(', ') ||
'Unknown asset'}
{entry.available ? '' : ` (${entry.reason ?? 'Unavailable'})`}
</option>
))}
</select>
</label>
{catalogLoading && <p role="status">Loading canonical datasets...</p>}
{!catalogLoading && !catalogError && !catalog.length && (
<p role="status">
No canonical datasets are available. Retain an eligible dataset with explicit sessions
and availability before configuring a run.
</p>
)}
{datasetLoading && <p role="status">Loading selected canonical dataset...</p>}
{[catalogError, datasetError, compatibilityError].filter(Boolean).map((message, index) => (
<p key={index} role="alert" className="text-error text-sm">
{message}
</p>
))}
{(catalogError || datasetError || compatibilityError) && (
<button
type="button"
className={actionClass}
onClick={() => setRetry(value => value + 1)}
>
Retry canonical datasets
</button>
)}
{hash && !selectedFields && !datasetLoading && (
<p className="text-sm text-text-secondary">
The selected hash is retained. Saving stays disabled until compatible metadata is
available.
</p>
)}
{selectedFields && (
<dl aria-label="Canonical dataset bounds" className="grid gap-2 text-sm sm:grid-cols-2">
<div>
<dt>Execution asset</dt>
<dd>{selectedFields.symbols.join(', ')}</dd>
</div>
<div>
<dt>Execution interval</dt>
<dd>{selectedFields.dataFrequency}</dd>
</div>
<div>
<dt>Trading start (UTC)</dt>
<dd>{selectedFields.startDate}</dd>
</div>
<div>
<dt>Trading end (UTC, exclusive)</dt>
<dd>{selectedFields.endDate}</dd>
</div>
<div>
<dt>Warmup start (UTC)</dt>
<dd>{selectedFields.warmupStart}</dd>
</div>
</dl>
)}
<StrategySelection
key={epoch}
allowArchivedSelection
value={selection}
onChange={setSelection}
onValidityChange={setStrategyValid}
disabled={locked}
/>
{[...new Set(policyFields.map(field => field.group))].map(group => (
<section key={group} className="space-y-3 border border-border rounded-md p-3">
<h4 className="font-medium text-text-primary">{group}</h4>
<div className="grid gap-4 sm:grid-cols-2">
{policyFields
.filter(field => field.group === group)
.map(field => (
<label key={field.key} className="block text-sm text-text-secondary">
{field.label}
<input
aria-label={field.label}
className={fieldClass}
type="text"
inputMode="decimal"
value={raw[field.key]}
onChange={event =>
setRaw(previous => ({ ...previous, [field.key]: event.target.value }))
}
aria-invalid={Boolean(parsed.errors[field.key])}
/>
<span className="block text-xs text-text-muted">{field.description}</span>
{parsed.errors[field.key] && (
<span role="alert" className="block text-error">
{parsed.errors[field.key]}
</span>
)}
</label>
))}
</div>
</section>
))}
</fieldset>
{error && (
<p role="alert" className="text-error text-sm">
{error}
</p>
)}
<button type="submit" className={actionClass} disabled={locked || !valid}>
{saving ? 'Saving canonical setup...' : 'Save canonical setup'}
</button>{' '}
{onClose && (
<button
type="button"
className={actionClass}
disabled={saving}
onClick={() => {
if (confirmDiscard(dirty)) {
onClose();
}
}}
>
Back to draft settings
</button>
)}
</form>
);
}

View file

@ -8,9 +8,10 @@ import {
import type { ColumnDef } from '@tanstack/react-table';
import { useEffect, useState } from 'react';
import { useNavigate, useParams } from 'react-router-dom';
import { isCanonicalRunResult } from '@stock-bot/stock-config/canonical-research';
import { DataTable } from '@/components/ui/DataTable';
import { browserLog } from '@/utils/browserLog';
import type { Run, RunResult } from '../services/backtestApiV2';
import type { Run } from '../services/backtestApiV2';
import { backtestApiV2 } from '../services/backtestApiV2';
interface RunsListProps {
@ -20,7 +21,15 @@ interface RunsListProps {
}
interface RunWithMetrics extends Run {
metrics?: RunResult['metrics'];
metrics?: {
totalReturn: number | null;
sharpeRatio: number | null;
maxDrawdown: number | null;
winRate: number | null;
profitFactor: number | null;
totalProfit?: number | null;
};
resultKind?: 'canonical' | 'legacy';
initialCapital?: number;
}
@ -32,17 +41,28 @@ export function RunsListWithMetrics({ runs, currentRunId, onSelectRun }: RunsLis
// Fetch metrics for completed runs
useEffect(() => {
const controller = new AbortController();
const fetchMetrics = async () => {
setLoadingMetrics(true);
const updatedRuns: RunWithMetrics[] = await Promise.all(
runs.map(async run => {
if (run.status === 'completed') {
try {
const results = await backtestApiV2.getRunResults(run.id);
const results = await backtestApiV2.getRunResults(run.id, controller.signal);
if (results.runId !== run.id || results.backtestId !== run.backtestId) {
throw new Error('Received results for a different backtest or run');
}
return {
...run,
metrics: results.metrics,
initialCapital: results.config?.initialCapital,
metrics: isCanonicalRunResult(results)
? results.analytics.metrics
: results.metrics,
resultKind: isCanonicalRunResult(results)
? ('canonical' as const)
: ('legacy' as const),
initialCapital: isCanonicalRunResult(results)
? undefined
: results.config?.initialCapital,
};
} catch (error) {
browserLog.error(`Failed to fetch metrics for run ${run.id}:`, error);
@ -52,13 +72,19 @@ export function RunsListWithMetrics({ runs, currentRunId, onSelectRun }: RunsLis
return run;
})
);
setRunsWithMetrics(updatedRuns);
setLoadingMetrics(false);
if (!controller.signal.aborted) {
setRunsWithMetrics(updatedRuns);
setLoadingMetrics(false);
}
};
if (runs.length > 0) {
fetchMetrics();
void fetchMetrics();
} else {
setRunsWithMetrics([]);
setLoadingMetrics(false);
}
return () => controller.abort();
}, [runs]);
const getStatusIcon = (status: Run['status']) => {
@ -114,6 +140,9 @@ export function RunsListWithMetrics({ runs, currentRunId, onSelectRun }: RunsLis
className={`text-sm font-medium ${row.original.id === currentRunId ? 'text-primary-500' : 'text-text-primary'}`}
>
#{getValue() as number}
{row.original.resultKind === 'canonical' && (
<span className="ml-1 text-xs text-text-secondary">Canonical</span>
)}
</span>
),
},
@ -212,14 +241,20 @@ export function RunsListWithMetrics({ runs, currentRunId, onSelectRun }: RunsLis
cell: ({ row }) => {
const metrics = row.original.metrics;
const value = metrics?.maxDrawdown;
// Canonical analytics report a positive loss magnitude; legacy results
// retain their signed drawdown convention.
const signedLoss =
row.original.resultKind === 'canonical' && value !== null && value !== undefined
? -value
: value;
return (
<span
className={`text-sm font-medium ${
value === undefined || value === null
signedLoss === undefined || signedLoss === null
? 'text-text-secondary'
: value > -0.1
: signedLoss > -0.1
? 'text-success'
: value > -0.2
: signedLoss > -0.2
? 'text-warning'
: 'text-error'
}`}

View file

@ -1,18 +1,25 @@
import { useCallback, useEffect, useRef, useState } from 'react';
import type { CanonicalRunCapability } from '@stock-bot/stock-config/canonical-research';
import {
catalogExecutionReason,
supportedLegacyStrategy,
} from '@/features/strategies/components/StrategySelection';
import { backtestApiV2, RunResultsUnavailableError } from '../services/backtestApiV2';
import type { Backtest, CreateBacktestRequest, Run, RunResult } from '../services/backtestApiV2';
import type {
Backtest,
CreateBacktestRequest,
ResearchRunResult,
Run,
} from '../services/backtestApiV2';
interface RunSelection {
id: string;
backtestId: string | null;
controller: AbortController;
timer?: ReturnType<typeof setTimeout>;
request?: Promise<void>;
refreshRequested: boolean;
results: RunResult | null;
results: ResearchRunResult | null;
}
const isActive = (run: Run) => ['pending', 'running', 'paused'].includes(run.status);
@ -23,7 +30,7 @@ export function useBacktestV2() {
const [backtest, setBacktest] = useState<Backtest | null>(null);
const [runs, setRuns] = useState<Run[]>([]);
const [currentRun, setCurrentRun] = useState<Run | null>(null);
const [runResults, setRunResults] = useState<RunResult | null>(null);
const [runResults, setRunResults] = useState<ResearchRunResult | null>(null);
const [isBacktestLoading, setIsBacktestLoading] = useState(false);
const [isRunLoading, setIsRunLoading] = useState(false);
const [error, setError] = useState<string | null>(null);
@ -45,9 +52,65 @@ export function useBacktestV2() {
} | null>(null);
const selection = useRef<RunSelection | null>(null);
const cancellation = useRef<RunSelection | null>(null);
const [capabilityRetry, setCapabilityRetry] = useState(0);
const [capabilityState, setCapabilityState] = useState<{
definition: Backtest;
retry: number;
capability: CanonicalRunCapability | null;
error: string | null;
} | null>(null);
const catalog = Boolean(backtest?.strategyVersionId) || backtest?.strategy === 'catalog';
useEffect(() => {
if (!backtest || !catalog || backtest.archivedAt) {
return;
}
const controller = new AbortController();
setCapabilityState({
definition: backtest,
retry: capabilityRetry,
capability: null,
error: null,
});
void backtestApiV2
.canonicalCapability(backtest.id, controller.signal)
.then(capability => {
if (!controller.signal.aborted && mounted.current) {
setCapabilityState({
definition: backtest,
retry: capabilityRetry,
capability,
error: null,
});
}
})
.catch(error => {
if (!controller.signal.aborted && mounted.current) {
setCapabilityState({
definition: backtest,
retry: capabilityRetry,
capability: null,
error: messageOf(error, 'Could not check execution eligibility'),
});
}
});
return () => controller.abort();
}, [backtest, catalog, capabilityRetry]);
const currentCapability =
capabilityState?.definition === backtest && capabilityState?.retry === capabilityRetry
? capabilityState
: null;
const canonicalCapability =
!backtest?.archivedAt && !isBacktestLoading ? (currentCapability?.capability ?? null) : null;
const capabilityError = currentCapability?.error ?? null;
const isCapabilityLoading =
catalog && !backtest?.archivedAt && !capabilityError && canonicalCapability === null;
const refreshCanonicalCapability = useCallback(() => setCapabilityRetry(value => value + 1), []);
const isSelected = useCallback(
(selected: RunSelection) => mounted.current && selection.current === selected,
(selected: RunSelection) =>
mounted.current &&
selection.current === selected &&
selected.backtestId === loadedBacktestId.current,
[]
);
@ -81,6 +144,17 @@ export function useBacktestV2() {
if (!isSelected(selected)) {
return;
}
if (
run.id !== selected.id ||
(selected.backtestId !== null && run.backtestId !== selected.backtestId)
) {
monitorAgain = false;
selected.refreshRequested = false;
selected.results = null;
setCurrentRun(null);
setRunResults(null);
throw new Error('Received a run for a different backtest or run selection');
}
setCurrentRun(run);
setRuns(previous =>
@ -106,8 +180,12 @@ export function useBacktestV2() {
if (!isSelected(selected)) {
return;
}
if (results && results.runId !== selected.id) {
throw new Error('Received results for a different run');
if (
results &&
(results.runId !== selected.id || results.backtestId !== run.backtestId)
) {
selected.refreshRequested = false;
throw new Error('Received results for a different backtest or run');
}
selected.results = results;
setRunResults(results);
@ -155,7 +233,11 @@ export function useBacktestV2() {
const selectRun = useCallback(
(runId: string | undefined) => {
if (runId && selection.current?.id === runId) {
if (
runId &&
selection.current?.id === runId &&
selection.current.backtestId === loadedBacktestId.current
) {
return refreshSelection(selection.current);
}
stopMonitoring();
@ -170,6 +252,7 @@ export function useBacktestV2() {
const selected: RunSelection = {
id: runId,
backtestId: loadedBacktestId.current,
controller: new AbortController(),
refreshRequested: false,
results: null,
@ -180,45 +263,55 @@ export function useBacktestV2() {
[refreshSelection, stopMonitoring]
);
const loadBacktest = useCallback(async (id: string) => {
const generation = ++backtestGeneration.current;
if (loadedBacktestId.current !== id) {
submission.current = null;
setSubmissionError(null);
setIsSubmitting(false);
}
loadedBacktestId.current = id;
setIsBacktestLoading(true);
setError(null);
setBacktest(null);
setRuns([]);
try {
const [loadedBacktest, loadedRuns] = await Promise.all([
backtestApiV2.getBacktest(id),
backtestApiV2.listRuns(id),
]);
if (!mounted.current || generation !== backtestGeneration.current) {
return;
const loadBacktest = useCallback(
async (id: string) => {
const generation = ++backtestGeneration.current;
if (loadedBacktestId.current !== id) {
submission.current = null;
setSubmissionError(null);
setIsSubmitting(false);
// Parent-only route changes do not rerun the page's runId effect. Fence
// the old request chain and validate the same selection against its new parent.
loadedBacktestId.current = id;
void selectRun(selection.current?.id);
}
setBacktest(loadedBacktest);
// Run polling may already have a newer version of the selected row.
setRuns(previous =>
loadedRuns.map(run =>
run.id === selection.current?.id
? (previous.find(item => item.id === run.id) ?? run)
: run
)
);
} catch (err) {
if (mounted.current && generation === backtestGeneration.current) {
setError(messageOf(err, 'Failed to load backtest'));
loadedBacktestId.current = id;
setIsBacktestLoading(true);
setError(null);
setBacktest(null);
setRuns([]);
try {
const [loadedBacktest, loadedRuns] = await Promise.all([
backtestApiV2.getBacktest(id),
backtestApiV2.listRuns(id),
]);
if (!mounted.current || generation !== backtestGeneration.current) {
return;
}
if (loadedBacktest.id !== id || loadedRuns.some(run => run.backtestId !== id)) {
throw new Error('Received a definition or run history for a different backtest');
}
setBacktest(loadedBacktest);
// Run polling may already have a newer version of the selected row.
setRuns(previous =>
loadedRuns.map(run =>
run.id === selection.current?.id
? (previous.find(item => item.id === run.id) ?? run)
: run
)
);
} catch (err) {
if (mounted.current && generation === backtestGeneration.current) {
setError(messageOf(err, 'Failed to load backtest'));
}
} finally {
if (mounted.current && generation === backtestGeneration.current) {
setIsBacktestLoading(false);
}
}
} finally {
if (mounted.current && generation === backtestGeneration.current) {
setIsBacktestLoading(false);
}
}
}, []);
},
[selectRun]
);
const createBacktest = useCallback(
async (request: CreateBacktestRequest) => {
@ -334,11 +427,13 @@ export function useBacktestV2() {
if (!backtest || backtest.id !== loadedBacktestId.current || submission.current?.pending) {
return undefined;
}
if ((backtest.strategyVersionId || backtest.strategy === 'catalog') && !submission.current) {
setSubmissionError(catalogExecutionReason);
if (catalog && !canonicalCapability?.available && !submission.current) {
setSubmissionError(
capabilityError ?? canonicalCapability?.reason ?? catalogExecutionReason
);
return undefined;
}
if (!supportedLegacyStrategy(backtest.strategy) && !submission.current) {
if (!catalog && !supportedLegacyStrategy(backtest.strategy) && !submission.current) {
setSubmissionError(
'This legacy strategy is not supported for new submissions by this form.'
);
@ -351,7 +446,7 @@ export function useBacktestV2() {
const intent = (submission.current ??= {
backtestId: backtest.id,
key: crypto.randomUUID(),
body: { speedMultiplier },
body: { speedMultiplier: catalog ? null : speedMultiplier },
pending: false,
});
intent.pending = true;
@ -386,7 +481,7 @@ export function useBacktestV2() {
}
}
},
[backtest]
[backtest, catalog, canonicalCapability, capabilityError]
);
const cancelRun = useCallback(async () => {
@ -431,6 +526,10 @@ export function useBacktestV2() {
runs,
currentRun,
runResults,
canonicalCapability,
capabilityError,
isCapabilityLoading,
refreshCanonicalCapability,
isLoading: isBacktestLoading || isRunLoading,
error: runError ?? error,
submissionError,

View file

@ -1,3 +1,8 @@
import type {
CanonicalDatasetCatalogEntry,
CanonicalRunCapability,
ResearchRunResult,
} from '@stock-bot/stock-config/canonical-research';
import type {
BacktestRunDatasetSelection,
BacktestRunResult,
@ -58,6 +63,7 @@ export interface CreateRunRequest {
}
export type RunResult = BacktestRunResult;
export type { ResearchRunResult };
export class RunResultsUnavailableError extends Error {
constructor() {
@ -79,6 +85,38 @@ async function requestError(response: Response, fallback: string): Promise<Error
}
export const backtestApiV2 = {
async canonicalCapability(id: string, signal?: AbortSignal): Promise<CanonicalRunCapability> {
const response = await fetch(
`${API_BASE_URL}/api/v2/backtests/${encodeURIComponent(id)}/canonical-capability`,
{ signal }
);
if (!response.ok) {
throw await requestError(response, 'Could not check canonical execution eligibility');
}
return response.json();
},
async listCanonicalDatasets(signal?: AbortSignal): Promise<CanonicalDatasetCatalogEntry[]> {
const response = await fetch(`${API_BASE_URL}/api/v2/datasets/canonical?limit=50&offset=0`, {
signal,
});
if (!response.ok) {
throw await requestError(response, 'Could not load canonical datasets');
}
return (await response.json()).datasets;
},
async canonicalDataset(
hash: string,
signal?: AbortSignal
): Promise<CanonicalDatasetCatalogEntry> {
const response = await fetch(
`${API_BASE_URL}/api/v2/datasets/canonical/${encodeURIComponent(hash)}`,
{ signal }
);
if (!response.ok) {
throw await requestError(response, 'Could not load canonical dataset');
}
return (await response.json()).dataset;
},
async listDatasets(
limit = 50,
offset = 0,
@ -229,7 +267,7 @@ export const backtestApiV2 = {
return response.json();
},
async getRunResults(runId: string, signal?: AbortSignal): Promise<RunResult> {
async getRunResults(runId: string, signal?: AbortSignal): Promise<ResearchRunResult> {
const response = await fetch(`${API_BASE_URL}/api/v2/runs/${runId}/results`, { signal });
if (response.status === 404) {

View file

@ -5,6 +5,7 @@ import type {
StrategyVersionPackage,
StrategyVersionSummary,
} from '@stock-bot/types';
import { BuiltinReview } from './components/BuiltinReview';
import { actionClass, fieldClass, StrategyParameterForm } from './components/StrategyParameterForm';
import { versionPath } from './components/StrategySelection';
import { confirmDiscard, useUnsavedWarning } from './components/useUnsavedWarning';
@ -344,9 +345,27 @@ function StrategyDetail({ strategyId, versionId }: { strategyId: string; version
{version && version.id === versionId && (
<>
<VersionIdentity version={version} />
<VersionComparison key={version.id} version={version} versions={versions} />
{version.origin === 'builtin' && (
<BuiltinReview
key={`review:${version.id}`}
version={version}
onReviewed={reviewed => {
if (selectedVersionId.current === reviewed.id) {
setVersion(reviewed);
setVersions(items =>
items.map(item => (item.id === reviewed.id ? reviewed : item))
);
}
}}
/>
)}
<VersionComparison
key={`artifacts:${version.id}`}
version={version}
versions={versions}
/>
<StrategyParameterForm
key={version.id}
key={`parameters:${version.id}`}
versionId={version.id}
schema={version.package.parameterSchema}
onEdit={() => setParameterEdits(true)}
@ -471,8 +490,9 @@ function StrategyDetail({ strategyId, versionId }: { strategyId: string; version
<section className="text-sm text-text-secondary space-y-2">
<h3 className="font-medium text-text-primary">Version history</h3>
<p>
No runs using retained versions are available yet. Legacy name-based runs are
not evidence for this version.
Open a saved backtest to inspect its runs and exact executed version.
Version-specific run history is not exposed here; legacy name-based runs are not
evidence for this version.
</p>
<p>Deployment history is not available in this catalog yet.</p>
</section>
@ -498,7 +518,7 @@ function VersionIdentity({ version }: { version: StrategyVersionSummary }) {
<p role="status">
{version.origin === 'candidate'
? 'Candidate execution is unavailable until isolated execution is supported.'
: 'Execution of this retained built-in version is not available from the workbench yet.'}
: 'Canonical execution requires approval, a matching executable build, a supported dataset and an explicit simulation policy.'}
</p>
<p>
Program: {pkg.program.strategyId} / {pkg.program.strategyVersion}

View file

@ -86,8 +86,8 @@ export function StrategyListPage() {
</button>
</div>
<p className="text-sm text-text-secondary">
Organize immutable strategy packages and prepare backtest drafts. Catalog execution is not
available yet.
Organize immutable strategy packages and prepare backtests. Canonical execution requires a
reviewed built-in version, supported dataset and explicit simulation policy.
</p>
{showCreate && (
<form

View file

@ -0,0 +1,139 @@
import { useEffect, useRef, useState } from 'react';
import type { StrategyVersionSummary } from '@stock-bot/types';
import { API_BASE_URL, apiFetch } from '@/lib/api';
import { strategyApi } from '../services/strategyApi';
import { actionClass, fieldClass } from './StrategyParameterForm';
/** Human approval records review; it cannot make candidate code executable. */
export function BuiltinReview({
version,
onReviewed,
}: {
version: StrategyVersionSummary;
onReviewed: (version: StrategyVersionSummary) => void;
}) {
const [access, setAccess] = useState<'loading' | 'operator' | 'denied' | 'error'>('loading');
const [retry, setRetry] = useState(0);
const [reason, setReason] = useState('');
const [busy, setBusy] = useState(false);
const [error, setError] = useState<string | null>(null);
const active = useRef(true);
const pending = useRef(false);
useEffect(() => {
active.current = true;
return () => {
active.current = false;
};
}, []);
useEffect(() => {
const controller = new AbortController();
setAccess('loading');
void apiFetch(`${API_BASE_URL}/api/auth/session`, { signal: controller.signal })
.then(async response => {
if (!response.ok) {
throw new Error('Access check failed');
}
const session: { authenticated?: boolean; role?: string } = await response.json();
if (!controller.signal.aborted) {
setAccess(session.authenticated && session.role === 'admin' ? 'operator' : 'denied');
}
})
.catch(() => {
if (!controller.signal.aborted) {
setAccess('error');
}
});
return () => controller.abort();
}, [retry]);
const review = async () => {
if (
access !== 'operator' ||
!reason.trim() ||
pending.current ||
version.origin !== 'builtin'
) {
return;
}
pending.current = true;
setBusy(true);
setError(null);
try {
const result = await strategyApi.review(version.id, { decision: 'approve', reason });
if (active.current) {
onReviewed(result.version);
setReason('');
}
} catch (cause) {
if (active.current) {
setError(cause instanceof Error ? cause.message : 'Review failed');
}
} finally {
pending.current = false;
if (active.current) {
setBusy(false);
}
}
};
if (version.origin !== 'builtin') {
return null;
}
return (
<section className="space-y-3 border border-border rounded-md p-3">
<h3 className="font-medium">Built-in version review</h3>
<p className="text-sm text-text-secondary">
Review the retained artifact and its provenance before approval. Approval does not establish
profitability, bypass financial limits or authorize paper/live deployment.
</p>
{access === 'loading' && <p role="status">Checking operator access...</p>}
{access === 'denied' && (
<p role="status">An authenticated human operator must approve this version.</p>
)}
{access === 'error' && (
<div>
<p role="alert">Operator access could not be checked.</p>
<button
type="button"
className={actionClass}
onClick={() => setRetry(value => value + 1)}
>
Retry operator access
</button>
</div>
)}
{access === 'operator' && version.reviewStatus !== 'approved' && (
<>
<label className="block text-sm">
Review reason
<textarea
aria-label="Review reason"
className={fieldClass}
value={reason}
disabled={busy}
onChange={event => setReason(event.target.value)}
/>
</label>
<button
type="button"
className={actionClass}
disabled={busy || !reason.trim()}
onClick={() => void review()}
>
{busy ? 'Recording review...' : 'Approve built-in version'}
</button>
</>
)}
{version.reviewStatus === 'approved' && (
<p role="status">
This immutable built-in version has an approval record. Backtest admission still checks
the artifact, build, dataset and policy.
</p>
)}
{error && (
<p role="alert" className="text-error text-sm">
{error} If the response was lost, reload the version to inspect its review status before
submitting another review.
</p>
)}
</section>
);
}

View file

@ -238,7 +238,8 @@ export function StrategyParameterForm({
</button>
{validated && (
<p role="status" className="text-sm text-text-secondary">
Parameters validated for this immutable version. Execution remains unavailable.
Parameters validated for this immutable version. Execution eligibility depends on the
saved dataset, policy and reviewed executable.
</p>
)}
{error && (

View file

@ -9,7 +9,7 @@ export interface CatalogSelection {
strategyParameters?: Parameters | null;
}
export const catalogExecutionReason =
'Catalog versions are save-only. Execution of retained versions is not available yet.';
'Save a version, then configure a supported canonical dataset and simulation policy. Execution eligibility is checked for each saved backtest.';
export function versionPath(version: Pick<StrategyVersionSummary, 'strategyId' | 'id'>) {
return `/strategies/${encodeURIComponent(version.strategyId)}/versions/${encodeURIComponent(version.id)}`;
}
@ -223,7 +223,7 @@ export function StrategySelection({
<p className="text-xs text-text-muted">
{selected.origin === 'candidate'
? 'Candidate execution is unavailable until isolated execution is supported.'
: 'This retained built-in version cannot be executed from the workbench yet.'}
: 'Reviewed built-in versions require a supported dataset, explicit policy and matching executable build before execution.'}
</p>
{family?.archived && (
<p role="status" className="text-sm text-text-secondary">

View file

@ -52,6 +52,11 @@ export const strategyApi = {
`strategy-versions/${id(versionId)}/validate`,
json('POST', { parameters })
),
review: (versionId: string, body: { decision: 'approve'; reason: string }) =>
request<{ version: StrategyVersionSummary }>(
`strategy-versions/${id(versionId)}/reviews`,
json('POST', body)
),
clone: (versionId: string, body: { name: string; description: string }, key: string) =>
request<{ strategy: StrategyRecord; version: StrategyVersionSummary }>(
`strategy-versions/${id(versionId)}/clone`,

View file

@ -0,0 +1,94 @@
-- Additive single-asset retained-builtin research; historical results remain unchanged.
ALTER TABLE backtest_results ADD COLUMN IF NOT EXISTS canonical_result JSONB;
DO $$ BEGIN
IF NOT EXISTS (SELECT 1 FROM pg_constraint WHERE conname='canonical_result_envelope' AND conrelid='backtest_results'::regclass) THEN
ALTER TABLE backtest_results ADD CONSTRAINT canonical_result_envelope CHECK (
canonical_result IS NULL OR (
jsonb_typeof(canonical_result)='object'
AND canonical_result->>'kind'='canonical-result/v1'
AND canonical_result->>'runId'=run_id::text
) IS TRUE
);
END IF;
END $$;
CREATE OR REPLACE FUNCTION require_active_backtest_for_new_run() RETURNS trigger
LANGUAGE plpgsql AS $$
DECLARE parent RECORD; selected RECORD; approval RECORD; retained JSONB; snapshot JSONB;
BEGIN
SELECT * INTO parent FROM backtests WHERE id=NEW.backtest_id FOR UPDATE;
IF NOT FOUND THEN RETURN NEW; END IF;
IF parent.archived_at IS NOT NULL THEN
RAISE EXCEPTION 'Backtest is archived; restore it before submitting a new run' USING ERRCODE='23514';
END IF;
snapshot := NEW.request_snapshot;
IF parent.strategy_version_id IS NULL AND parent.strategy <> 'catalog' THEN
IF snapshot->>'kind'='canonical-research/v1' THEN
RAISE EXCEPTION 'Canonical research requires a catalog template' USING ERRCODE='23514';
END IF;
RETURN NEW;
END IF;
IF (snapshot->>'kind'='canonical-research/v1'
AND snapshot->>'runId'=NEW.id::text
AND snapshot->>'backtestId'=NEW.backtest_id::text
AND snapshot#>>'{strategy,versionId}'=parent.strategy_version_id::text
AND snapshot->>'datasetHash'=NEW.dataset_hash
AND NEW.status='pending' AND NEW.speed_multiplier IS NULL) IS NOT TRUE THEN
RAISE EXCEPTION 'Catalog strategy execution requires an admitted canonical request' USING ERRCODE='23514';
END IF;
-- This is the same family lock used by operator review and archive. Later
-- review changes affect new admissions, never rewrite accepted snapshots.
SELECT v.*,s.archived_at AS family_archived INTO selected FROM strategy_versions v
JOIN strategies s ON s.id=v.strategy_id WHERE v.id=parent.strategy_version_id FOR UPDATE OF s;
SELECT id,decision INTO approval FROM strategy_review_events
WHERE version_id=parent.strategy_version_id ORDER BY ordinal DESC LIMIT 1;
IF (selected.origin='builtin' AND selected.family_archived IS NULL
AND approval.decision='approve'
AND snapshot#>>'{strategy,origin}'='builtin'
AND snapshot#>>'{strategy,familyId}'=selected.strategy_id::text
AND snapshot#>>'{strategy,reviewId}'=approval.id::text
AND snapshot#>'{strategy,package}'=selected.envelope
AND snapshot#>'{strategy,selection,parameters}'=parent.strategy_parameters
AND snapshot#>>'{strategy,selection,ownerId}'='strategy:'||selected.id::text) IS NOT TRUE THEN
RAISE EXCEPTION 'Canonical research requires the exact approved retained built-in version' USING ERRCODE='23514';
END IF;
SELECT payload INTO retained FROM backtest_datasets WHERE hash=NEW.dataset_hash;
IF (retained#>>'{manifest,version}'='2'
AND retained#>>'{manifest,eligibility}'='eligible'
AND jsonb_array_length(retained#>'{manifest,executionSeries}')=1
AND jsonb_array_length(retained#>'{manifest,series}')=1
AND jsonb_array_length(snapshot#>'{policy,matching,series}')=1
AND jsonb_array_length(snapshot#>'{policy,matching,owners}')=1
AND jsonb_array_length(snapshot#>'{policy,matching,risk,ledger,ownerIds}')=1
AND snapshot#>>'{policy,allow_exploratory}'='false'
AND snapshot#>>'{strategy,selection,instrumentId}'=retained#>>'{manifest,executionSeries,0,instrumentId}'
AND snapshot#>>'{strategy,selection,seriesId}'=retained#>>'{manifest,executionSeries,0,seriesId}'
AND snapshot#>>'{policy,matching,series,0,instrumentId}'=snapshot#>>'{strategy,selection,instrumentId}'
AND snapshot#>>'{policy,matching,series,0,seriesId}'=snapshot#>>'{strategy,selection,seriesId}') IS NOT TRUE THEN
RAISE EXCEPTION 'Canonical research requires one eligible retained v2 execution asset' USING ERRCODE='23514';
END IF;
RETURN NEW;
END $$;
CREATE OR REPLACE FUNCTION require_canonical_result_identity() RETURNS trigger
LANGUAGE plpgsql AS $$
DECLARE snapshot JSONB;
BEGIN
SELECT request_snapshot INTO snapshot FROM runs WHERE id=NEW.run_id;
IF snapshot->>'kind'='canonical-research/v1' THEN
IF (NEW.canonical_result->>'kind'='canonical-result/v1'
AND NEW.canonical_result->'request'=snapshot
AND NEW.canonical_result->>'runId'=NEW.run_id::text
AND NEW.canonical_result->>'backtestId'=snapshot->>'backtestId'
AND NEW.canonical_result->>'financialEngine'='rust'
AND NEW.canonical_result->>'strategyExecution'='typescript-retained-builtin/v1') IS NOT TRUE THEN
RAISE EXCEPTION 'Canonical result must retain its exact admitted request' USING ERRCODE='23514';
END IF;
ELSIF NEW.canonical_result IS NOT NULL THEN
RAISE EXCEPTION 'Legacy runs cannot receive canonical results' USING ERRCODE='23514';
END IF;
RETURN NEW;
END $$;
DROP TRIGGER IF EXISTS canonical_result_identity ON backtest_results;
CREATE TRIGGER canonical_result_identity BEFORE INSERT ON backtest_results
FOR EACH ROW EXECUTE FUNCTION require_canonical_result_identity();

View file

@ -522,3 +522,18 @@ R10 is accepted and committed as `8cca0ee`, superseding its uncommitted handoff
The browser gate exposed intermittent Chromium control-pipe loss across serial launches, not a financial assertion failure. Isolated workflows passed. The fixture now shares one suite-owned Chromium process while giving each workflow a fresh context/server/schema/queue; the complete suite passed without retries. Production workers are unchanged. The release addon matches the prior wave and checkout library; no Rust financial semantics changed. Both exact disposable containers were stopped; development services were untouched.
No new R02 commit, push, PR, performance work or trading/default activation. **Next after acceptance/commit: R05**, connecting verified retained executable identity and canonical reports to durable runs. Start with a trusted-built-in single-asset vertical slice; do not certify a retained hash while executing an unrelated current built-in. Candidate execution remains gated by A02 and multi-asset default by the explicit mark-policy decision. R03 research metadata is also ready for disjoint work, but does not unlock catalog execution.
## Twenty-third-wave handoff — 2026-10-23
R02 is accepted and committed as `d929db7`. The initial R05 vertical slice is independently reviewed and `partial_validated_uncommitted`; R05 remains **in_progress**. Fifty-four implementation/contract/migration/test files connect approved retained built-ins, eligible single-series v2 datasets and explicit financial/reporting settings to the existing durable Rust runner. Isolated worker, durable and frontend worktrees plus evidence remain under `/tmp/stock-bot-wave23.D3gFzn/`.
- **Executable provenance:** Admission freezes exact retained package/lock bytes, version/review, parameters, dataset hash, seed, financial/time/reporting policies and worker/native/runtime build identities. The child verifies and imports the retained bundle; it never substitutes a current built-in by name. Approval/archive changes serialize with admission; accepted receipts and snapshots remain usable afterward.
- **Durability:** One queue/runner/repository lifecycle handles leases, heartbeats, fencing, cancellation/reaping and atomic results. Corrupt data, wrong builds or a non-native runner fail without provider/legacy fallback. Migration 19 preserves retention and adds versioned canonical results without rewriting old rows.
- **Workbench:** Review built-ins, save exact canonical settings against a retained dataset, submit, inspect canonical Rust balances/owners/fills/metrics/provenance, and reopen results. Exact UTC/DST warmup boundaries survive save/admission. Zeros and unavailable reasons are preserved; fills do not become invented round trips. Cross-parent results and late navigation replies are rejected; canonical positive drawdowns use correct severity colours.
- **Validation:** All relevant gates passed across the recorded commands: build/source/contracts/secrets; 93 tooling, 43 utility, 44 calculation, **576 final integration** and **150 Rust** tests (4 manual ignored); full PostgreSQL/Redis **150 tests / 1154 assertions**, plus **13 final release-admission/durability tests / 106 assertions**; Chromium **9 workflows / 164 assertions**. The canonical browser fixture proves two expected fills, `9969.30000000` equity, exact saved provenance and zero provider reads. Final strict new-test/script checks, application lint, modern test lint, formatting and diff checks passed.
The initial aggregate check exposed stale pure-contract allowlists and lint issues; those were corrected and affected gates rerun. Optional lint over all touched old fixtures still reports eight existing curly-rule errors in two files changed only to apply migration 19; no suppressions or unrelated cleanup. Full commands, review dispositions and exact source hashes are in `manifest.json` → `twenty_third_wave_validation`. The release addon equals the prior wave/checkout release hash; Rust financial code is unchanged. Both exact disposable fixture containers were stopped; no development/production state was seeded or migrated.
Deployment requires the existing native research runner (`useRustEngine: true`) and matching immutable build files. Capability is input/artifact validation, not worker health. An incompatible deployment fails an accepted run; historical build restoration belongs to R12. [R05](backlog/tasks/R05.md#first-vertical-slice--2026-10-23) documents the explicit offline v2 import and remaining source-preparation contract. No candidate/multi-asset/default activation, benchmark or performance work, new-wave commit, push or PR.
**Next after acceptance/commit: R03 research projects, hypotheses and evidence-linked findings APIs.** It is independently ready and adds useful research workflow without pretending full R05 is finished. R05's source-to-v2 preparation and broader cutover remain tracked; R06/S06 dependencies are not released by this partial milestone.

View file

@ -1,6 +1,6 @@
# Canonical development backlog
**First twenty-one waves committed; R02 is validated and awaiting acceptance/commit.** R10 is accepted as `8cca0ee`. R02 adds catalog/version browsing and validated saved backtest setups; catalog execution remains gated by R05. Performance work remains paused. See [current handoff](../ROADMAP.md#twenty-second-wave-handoff--2026-10-23) and manifest execution scope.
**First twenty-two waves committed; the initial R05 vertical slice is validated and uncommitted.** R02 is accepted as `d929db7`. Reviewed built-ins can now run against one eligible retained v2 dataset through the durable Rust engine and reopen canonical results in the web workbench. Full R05 remains in progress. Performance work remains paused. See [current handoff](../ROADMAP.md#twenty-third-wave-handoff--2026-10-23) and manifest execution scope.
## One source of truth
@ -73,10 +73,10 @@ Relative size: S narrow correction, M coherent boundary, L sensitive owner-contr
| Task | Priority / status | Implementation prerequisites | Release gate | Specialist / size |
| --- | --- | --- | --- | --- |
| [R01 Persist immutable strategy versions and parameter schemas](tasks/R01.md) | P1 / done | O01, ADR-006 | — | Full-stack research product / M |
| [R02 Deliver strategy catalog and version-aware backtest setup](tasks/R02.md) | P1 / review | R01, W03, ADR-006 | W04 | Full-stack research product / M |
| [R02 Deliver strategy catalog and version-aware backtest setup](tasks/R02.md) | P1 / done | R01, W03, ADR-006 | W04 | Full-stack research product / M |
| [R03 Add projects, hypotheses and evidence-linked findings APIs](tasks/R03.md) | P1 / ready | R01, R10, ADR-006 | — | Full-stack research product / M |
| [R04 Deliver research workspace and save-findings flow](tasks/R04.md) | P1 / blocked | R03, W02, ADR-006 | W04 | Full-stack research product / M |
| [R05 Freeze complete provenance and cut over durable canonical runs](tasks/R05.md) | P0 / ready | F08, S02, R01, R10, D01, W03, C06, ADR-006 | Multi-asset default mark-policy disposition | Full-stack research product / M |
| [R05 Freeze complete provenance and cut over durable canonical runs](tasks/R05.md) | P0 / in_progress | F08, S02, R01, R10, D01, W03, C06, ADR-006 | Multi-asset default mark-policy disposition | Full-stack research product / M |
| [R06 Create immutable experiments and bounded sweep expansion](tasks/R06.md) | P1 / blocked | R05, ADR-006 | — | Full-stack research product / M |
| [R07 Deliver sweep configuration and comparable-result views](tasks/R07.md) | P1 / blocked | R06, ADR-006 | W04 | Full-stack research product / M |
| [R08 Add bounded chronological and reset-segment validation](tasks/R08.md) | P1 / blocked | R06, ADR-006 | — | Quantitative research integrity / M |

View file

@ -1,16 +1,16 @@
{
"schema_version": 1,
"plan_revision": "2026-10-23.48",
"plan_revision": "2026-10-23.50",
"repository_base": "b7aeca4",
"plan_status": "twenty_second_wave_review",
"plan_status": "twenty_third_wave_partial_validated",
"execution_authorized": true,
"execution_scope": {
"authorized_by": "User: commit and continue after validated R10 handoff named R02 next. R10 committed 8cca0ee588b55cf904f46199ccb65942de70ee99.",
"authorized_by": "User: commit and continue after validated R02 handoff; R02 committed d929db707a4894096b8b31ebd25c5e39d15289c1.",
"tasks": [
"R02"
"R05"
],
"permissions": [
"R02 isolated implementation, correctness tests, independent review and planning updates; prior R10 commit authorized and completed"
"R05 trusted-built-in single-asset retained-v2 vertical slice, isolated implementation, correctness tests, cross-agent review and planning updates"
],
"excluded": [
"performance_profiling_or_optimization",
@ -20,11 +20,15 @@
"pull_requests",
"live_or_paper_operations",
"default_engine_cutover",
"candidate_execution",
"provider_to_v2_inference",
"multi_asset_activation",
"other_backlog_tasks"
],
"pending_policy_decisions": [
"ADR-007",
"ADR-008"
"ADR-008",
"Simultaneous multi-asset mark/risk policy before default activation"
]
},
"canonical_metadata": "This manifest alone owns task status, dependency edges, approvals, assignments and write locks. Task Markdown owns scope and acceptance criteria. Index/roadmap are derived views.",
@ -1442,7 +1446,7 @@
"epic": "E6",
"priority": "P1",
"severity": "High",
"status": "review",
"status": "done",
"dependencies": [
"R01",
"W03"
@ -1465,12 +1469,12 @@
"assignment": "/root",
"branch": null,
"pull_request": null,
"completed_commit": null,
"completed_commit": "d929db707a4894096b8b31ebd25c5e39d15289c1",
"blocker": null,
"release_gates": [
"W04"
],
"integration_state": "validated_uncommitted",
"integration_state": "validated_committed",
"integration_base": "8cca0ee588b55cf904f46199ccb65942de70ee99",
"worktree": "/home/boki/repos/stock-bot",
"implementation_slices": [
@ -1565,7 +1569,7 @@
"epic": "E6",
"priority": "P0",
"severity": "Critical",
"status": "ready",
"status": "in_progress",
"dependencies": [
"F08",
"S02",
@ -1592,14 +1596,45 @@
"web-backtest-detail"
],
"parallel_policy": "Allowed only with satisfied dependencies/approvals and disjoint write locks AND actual files; see agents/integration.md.",
"assignment": null,
"assignment": "/root",
"branch": null,
"pull_request": null,
"completed_commit": null,
"blocker": null,
"release_gates": [
"Explicit owner disposition of the simultaneous multi-asset mark/risk policy before canonical default activation"
]
],
"integration_state": "partial_validated_uncommitted",
"integration_base": "d929db707a4894096b8b31ebd25c5e39d15289c1",
"worktree": "/home/boki/repos/stock-bot",
"implementation_slices": [
{
"owner": "/root",
"scope": "Shared pure contracts, admission/API, migration19, offline dataset import, browser/fixture integration and planning"
},
{
"owner": "/root/s04_controls_audit",
"worktree": "/tmp/stock-bot-wave23.D3gFzn/durable",
"scope": "One durable runner/repository/adapter lifecycle and focused recovery tests"
},
{
"owner": "/root/s03_review",
"worktree": "/tmp/stock-bot-wave23.D3gFzn/worker",
"scope": "Retained executable bytes and exact worker/native build verification with child tests"
},
{
"owner": "/root/s04_feed_audit",
"worktree": "/tmp/stock-bot-wave23.D3gFzn/frontend",
"scope": "Explicit canonical setup/capability and canonical result UI; focused DOM tests"
}
],
"reviewed_by": [
"/root/s03_review",
"/root/s04_controls_audit",
"/root/s04_feed_audit"
],
"verification_reference": "ROADMAP.md#twenty-third-wave-handoff--2026-10-23",
"review_notes": "Reviewed retained-builtin/single-asset vertical slice only. Full R05 remains in progress; provider-to-v2 preparation and broader cutover are not claimed. Corrected warmup clock, series/rate/decimal admission mismatches, concurrent approval proof, UI parent identity and drawdown severity."
},
{
"id": "R06",
@ -7007,5 +7042,173 @@
"ea7d33b519a35b14ca493e460734a70d98937507a29406765edff53688f12b9a"
],
"next": "After acceptance/commit, R05: integrate verified retained executable identity, frozen provenance and existing canonical reports with the durable runner. Begin with a trusted-built-in single-asset slice, without claiming all R05 complete or enabling candidates/multi-asset default. R03 is independently ready. Performance remains deferred."
},
"twenty_third_wave": [
"R05"
],
"twenty_third_wave_base": "d929db707a4894096b8b31ebd25c5e39d15289c1",
"twenty_third_wave_notes": [
"Initial R05 vertical slice only: approved server-seeded built-in, exact retained bundle, eligible retained v2 dataset, one execution asset/series/owner, explicit financial and analytics policy.",
"Reuses existing queue/runner/recovery/Rust semantics. No automatic v1 conversion or provider calendar inference; add explicit offline validated dataset import.",
"Canonical request/result discriminants bypass legacy input and financial metric conversion; raw retained payload and full installed build identity frozen. Later review/archive affects new admissions only; accepted frozen requests remain replayable under matching installed build.",
"R05 remains incomplete until remaining provider preparation/default-cutover gates are explicitly resolved. No candidate/multi-asset/default activation or performance work."
],
"twenty_third_wave_validation": {
"state": "partial_validated_uncommitted",
"log_directory": "/tmp/stock-bot-wave23.D3gFzn",
"integration_base": "d929db707a4894096b8b31ebd25c5e39d15289c1",
"source_archive": "/tmp/stock-bot-wave23.D3gFzn/r05-integrated-source.tar",
"source_archive_sha256": "8d1102108d92e91c98333d1886400bd1f9c6351889f28455826394b265eacc5a",
"source_file_count": 54,
"source_sha256": {
"apps/stock/config/package.json": "7c6229de79360036584d332459d301811fcc6ea246c099ac9f5ce97e73251973",
"apps/stock/config/src/contracts/backtest.ts": "29981152d55a21b0526f8df2f4a609e4e26df830bb6679acf5414484e185864e",
"apps/stock/config/src/contracts/canonical-replay.ts": "61089f847e079b0166cb6ba6f53c50c8fa050fbf9f795ffe0e0a763c80d0033c",
"apps/stock/config/src/contracts/canonical-research.ts": "a724a679a3fbd1e5e1ec50ec9cf648d75ec4adf060a11518b7044aaacc107607",
"apps/stock/orchestrator/src/backtest/BacktestRunner.ts": "9a3fb70f4624fa661eb74b253398363c96999a15f033e3e9f51927e49870d1cf",
"apps/stock/orchestrator/src/backtest/NativeBacktestWorker.ts": "9dd451a232c9e76792f1302184827c678d45746f6fb538e816bc36afd865077a",
"apps/stock/orchestrator/src/backtest/PostgresBacktestRunRepository.ts": "8c1addf002fc5663b88c5f8ec9d8db6f12740c57083246fad1b04beee68f3648",
"apps/stock/orchestrator/src/backtest/RustBacktestAdapter.ts": "307f1575d9e728eee1d6895b976d878f9d873e764ef2525ae4d78e94aa302f90",
"apps/stock/orchestrator/src/backtest/canonical-build.ts": "a3024df5208fc3a9564a90744971a5e9f8e1c957060cdb97675b2b687fc2a56b",
"apps/stock/orchestrator/src/backtest/execution-engine.ts": "dadf54be396473ca12acf24fc7837622008e043b5ef37f145151f315bc947c92",
"apps/stock/orchestrator/src/backtest/native-worker-protocol.ts": "d0c31a6a75a1fa81a9f2e82560b9f83d28344ad8a93aaa252eebdf506dba45a3",
"apps/stock/orchestrator/src/backtest/native-worker.ts": "14f68b63f1f6893e9521f9671784962874ff7ddf52905ce1493bd781180f4a25",
"apps/stock/orchestrator/src/backtest/run-repository.ts": "f7069873b7b929b03dea847efd1ee09738640cc7351c978698b29b2aa9dcd6b4",
"apps/stock/orchestrator/src/contracts/native-replay.ts": "08a774154ded32580a8d31d5e09ccfb9700d00405f7838aa1f9e98643cf1adc1",
"apps/stock/web-api/src/migrations/migration-runner.ts": "a4ee363ca81ef9981a37f171c5784b519e593d03e0ce806e844e766587a3afb6",
"apps/stock/web-api/src/routes/backtests-v2.routes.ts": "b1fc489f4f355f4aee7a898e796dbbbbe0a576660f366bdd4ad70d87e07ebb13",
"apps/stock/web-api/src/routes/datasets.routes.ts": "9cfcee18ec39d085f23b23291c26ab56d41609fc21d9b1b3b4ccb1ace3f0884a",
"apps/stock/web-api/src/services/backtest-v2.service.ts": "94ff256df957939e018936323aa33507210ea2c081fd3e93cd697df1fb32eaf5",
"apps/stock/web-api/src/services/canonical-research.service.ts": "4efd29de567eeb0d7513e00d3c770dd0e1cf076ed2227eb73144484cfab32748",
"apps/stock/web-api/src/services/strategy-catalog.service.ts": "10453640baa5d84ec09b0d1dd70c8037d04d08443b274a6bb2773e09459479e4",
"apps/stock/web-app/src/features/backtest/BacktestDetailPageV2.tsx": "850d6a9f64bc11c8140a725f4cb5f899270eb9bb33e7b380c53d087b6cb13f2d",
"apps/stock/web-app/src/features/backtest/components/CanonicalResults.tsx": "820457a455bbe7791676319dc82bbf73e68d9da57e260f6e35ce723f029ceff9",
"apps/stock/web-app/src/features/backtest/components/CanonicalSetup.tsx": "a778105db06ded3645019f528e0ce2436aa5621ede1032fc69a1ccfe5fd81c11",
"apps/stock/web-app/src/features/backtest/components/RunsListWithMetrics.tsx": "f844eeb08fb3dd974c2a2f855b4c01e3252f778ff5252be94f7b8bf0174bb653",
"apps/stock/web-app/src/features/backtest/hooks/useBacktestV2.ts": "a035f631f107260d4a069e24b6153e6533b5890a27211731c4a0d0392e2ccc22",
"apps/stock/web-app/src/features/backtest/services/backtestApiV2.ts": "1fe7c23e8a12d9ff4e952b1be3c8c743cc806d6a56c966a9320d36091e3acf28",
"apps/stock/web-app/src/features/strategies/StrategyDetailPage.tsx": "e3854ab84b6ef1daed69dab0c0f0369fee19dd3457e10313cbe886f2c0c332bd",
"apps/stock/web-app/src/features/strategies/StrategyListPage.tsx": "f87b82af088a389d47b9ad2c28496e0adb3f730c4085e3d15173f8bf5bcdf080",
"apps/stock/web-app/src/features/strategies/components/BuiltinReview.tsx": "7af2c7de0aabd032e37dca37129ae3bb62d641b903773a72b98a5cafa081b647",
"apps/stock/web-app/src/features/strategies/components/StrategyParameterForm.tsx": "895a793f592b7351ed9581746199605b6ef0d845aac9e619c2165056fba28735",
"apps/stock/web-app/src/features/strategies/components/StrategySelection.tsx": "5ea0a513195a1b78ffc81e7fa70202c0aaef3b54da96728732aa2612b9dd85b3",
"apps/stock/web-app/src/features/strategies/services/strategyApi.ts": "1bb46b0406bc96817e0565118972ca6334bfc201c5ededb077c8f3635c5b510c",
"database/postgres/init/19-canonical-research.sql": "be6d7ab04523017d8bb6769b18aa706288286ffbda5e187a052872ab27218dc9",
"libs/core/types/src/financial-engine.ts": "f03f22774c8ad1ae17cdb381c7c30f20c8de7b28a77ef57de5064f134009bdff",
"libs/core/types/src/index.ts": "3f8d8a1bd2e460b6c5520df27ea9eb42228e40958e19eae18419e1e447abe162",
"scripts/import-research-dataset.ts": "8f5074b971cc9c3cc3cd4508cbd1da6272f83e31f5c2694ea935963054707321",
"scripts/package-builtin-strategies.ts": "e35988c768966986718808fc700886f65bd1b1c3754cd3f7993319bf1e5c4f77",
"scripts/test/architecture.test.ts": "0534a42d6921fc7cd9e3a816014affe9947dd64c1017aeaadcf071b5d5fb7bc8",
"test/e2e/fixture.ts": "f19cc8945ad489e175626df1b813527a6dd07c5fdceb09ccf94eef143fdd0adb",
"test/e2e/workbench.test.ts": "36c540a8fa074cc92f87c827728ceea1cc88dde4d3ec1e31fffbfb8a39cdabcf",
"test/fixtures/canonical-research.ts": "204c3a2565cc84aaea4ee3ad844381fdb506043e9e50fc7df0ea03fe86ce3f95",
"test/integration/canonical-durable-runner.test.ts": "ab7051dd578f39a08aeca2d1ab596b9324a32cc5cb4af10f73d265e89bf3a1cb",
"test/integration/canonical-workbench.test.tsx": "6cdb55719f72b8406ab4c300e1abf121daae1cee840e8c274f2de6bb2bfe5a71",
"test/integration/retained-strategy-worker.test.ts": "08cae3e8fa0d077c8750affe592a2f289b251dca6713e78d1c88e89596dc089f",
"test/integration/strategy-workbench.test.tsx": "511ff13931331ad2c242a74b69657faf670c31b469042c7828283e3702038327",
"test/postgres/canonical-durable-backtest.test.ts": "c034854d83af39daa3366ad845c49ee3653557be5469bc80b9747f3d16de2e08",
"test/postgres/canonical-research.test.ts": "2e27c9dcccd958c5b0fc3c29d50cb02a4751b1ad99865718929f45ab7a4966bf",
"test/postgres/catalog-backtest-drafts.test.ts": "5c19b8be2ded6b6d4db934763f8f2a09782adf3074895116440e9f131f75a9d3",
"test/postgres/dataset-catalog.test.ts": "fcea7827851481f146c7d81bd67052ccc8d38f15807d30b508cce51af46daa81",
"test/postgres/durable-backtest.test.ts": "462cc1ccd27f1e5e0561fd2acba6d451f654da010b84b37b0ebaa6b02162851f",
"test/postgres/migration-runner.test.ts": "026a74d85779d740e6f7372bf25c3f509131e5f262a0bb56d7b1701e28c86624",
"test/postgres/research-retention.test.ts": "4724d498d2fbd5c6fc52825cff545c5d0064e99c650aa27764f4ecd8530c3d28",
"test/postgres/research-runtime-isolation.test.ts": "b94f7ad1a4a5b272fbe1f15fca48b3b3e30918c3261846dcd95be8f779d4bda9",
"test/postgres/strategy-catalog.test.ts": "2edb7d920b63a40cfd6fc3cbe612032ac8888a21048004a7e28c5722609d0e15"
},
"checks": [
{
"command": "CARGO_BUILD_JOBS=2 bun run check",
"log": "/tmp/stock-bot-wave23.D3gFzn/check.log",
"outcome": "Build, source types, contracts, secrets, 43 utility, 44 calculation, 565 integration and 150 Rust tests passed (4 manual Rust tests ignored). Initial pure-contract allowlist and lint failures were fixed and rerun below; the aggregate command itself initially exited nonzero."
},
{
"command": "bun run test:tooling",
"log": "/tmp/stock-bot-wave23.D3gFzn/tooling-final.log",
"outcome": "93 tests / 12167 assertions passed after extending the guarded pure contract graph. No service/native/browser boundary exemptions."
},
{
"command": "bun run lint:check",
"log": "/tmp/stock-bot-wave23.D3gFzn/lint-final.log",
"outcome": "Passed on final application/library source."
},
{
"command": "bun run typecheck",
"log": "/tmp/stock-bot-wave23.D3gFzn/source-types-final.log",
"outcome": "Passed. Final strict changed-test gate also covers the subsequent shared rate and UI refinements."
},
{
"command": "PIPELINE_TEST_DATABASE_URL=<disposable PG> BACKTEST_TEST_REDIS_URL=<dedicated Redis /15> bun run test:postgres",
"log": "/tmp/stock-bot-wave23.D3gFzn/postgres.log",
"outcome": "150 tests / 1154 assertions passed, including retained execution, legacy durability, recovery, order execution, migrations and isolation."
},
{
"command": "PIPELINE_TEST_DATABASE_URL=<disposable PG> BACKTEST_TEST_REDIS_URL=<dedicated Redis /15> bun test test/postgres/canonical-research.test.ts test/postgres/canonical-durable-backtest.test.ts",
"log": "/tmp/stock-bot-wave23.D3gFzn/canonical-postgres-final.log",
"outcome": "Final release-addon admission/durability regressions passed: 13 tests / 106 assertions. Includes rate boundaries, genuine approval race in both lock orderings, exact UTC/DST warmup clock, direct SQL guards, frozen evidence and result reopening."
},
{
"command": "CARGO_BUILD_JOBS=2 bun run --cwd apps/stock/engine build:release",
"log": "/tmp/stock-bot-wave23.D3gFzn/native-release.log",
"outcome": "Restored release addon; SHA256 ef00eed556f5c32332d36a9a00ef710682e90deb00b54552e4b5c8bfdfbe8103 equals checkout release library and prior wave. No Rust financial source changes."
},
{
"command": "bun test test/integration/retained-strategy-worker.test.ts test/integration/canonical-durable-runner.test.ts test/integration/typescript-strategy-runtime.test.ts",
"log": "/tmp/stock-bot-wave23.D3gFzn/release-native-final.log",
"outcome": "16 tests / 83 assertions passed in the two existing requested files. Third named path does not exist; full integration run below includes the actual strategy-runtime.test.ts. No additional coverage claimed for the nonexistent path."
},
{
"command": "bun run test:integration",
"log": "/tmp/stock-bot-wave23.D3gFzn/integration-final.log",
"outcome": "576 tests / 4907 assertions passed against final release addon, including new unsupported-runner and browser identity/severity regressions."
},
{
"command": "PIPELINE_TEST_DATABASE_URL=<disposable PG> BACKTEST_TEST_REDIS_URL=<dedicated Redis /15> bun run test:e2e",
"log": "/tmp/stock-bot-wave23.D3gFzn/e2e.log",
"outcome": "9 workflows / 164 assertions passed, including actual approval -> retained canonical setup -> durable dispatch -> exact Rust fills/equity/provenance -> reload. Existing legacy, archive, cancellation and dataset workflows passed. Zero provider fallback in canonical fixture."
},
{
"command": "node_modules/.bin/tsc --project /tmp/stock-bot-wave23.D3gFzn/tests-tsconfig.json --noEmit",
"log": "/tmp/stock-bot-wave23.D3gFzn/strict-tests-final.log",
"outcome": "Passed for new and modern changed tests, shared/source dependencies, offline importer and browser fixture."
},
{
"command": "node_modules/.bin/eslint <new/modern changed test files> --max-warnings 0",
"log": "/tmp/stock-bot-wave23.D3gFzn/scoped-modern-test-lint.log",
"outcome": "Passed. Optional lint over all touched fixtures also reports 8 pre-existing curly-rule errors in two legacy files whose only edits add migration19; see scoped-test-lint.log."
},
{
"command": "node_modules/.bin/prettier --check <changed non-script TypeScript/JSON files>; git diff --check",
"log": "/tmp/stock-bot-wave23.D3gFzn/scoped-format-final.log",
"outcome": "Passed. New offline script was separately formatted; existing scripts retain their repository formatting convention."
}
],
"reviews": [
{
"reviewer": "/root/s03_review",
"scope": "Root contracts/API/SQL/import plus native prerequisite and approval-race assertions",
"outcome": "No remaining production must-fix; strengthened concurrency evidence and added missing native-capability failure regression."
},
{
"reviewer": "/root/s04_controls_audit",
"scope": "Retained worker and integrated UI/runner contract interactions",
"outcome": "Exact retained bytes/build and worker lifecycle accepted. Parent identity and canonical drawdown blockers fixed with focused regressions."
},
{
"reviewer": "/root/s04_feed_audit",
"scope": "Durable runner/repository, final API/rate boundaries, independent final UI guard review",
"outcome": "No remaining blockers after adverse-price-rate alignment; no legacy fallback or alternate simulator."
}
],
"limitations": [
"Partial R05 only: approved server-seeded built-ins; exactly one eligible retained v2 dataset series/asset/owner. Candidates, source-to-v2 inference, multi-asset/default activation and paper/live operations remain excluded.",
"Eligibility is an input/artifact preflight, not a remote-worker health check. Deploy native research runner/useRustEngine:true with matching immutable worker/addon/runtime/lock; mismatches fail durably.",
"Historical executable-build retention/restoration and exact reproduction workflow remain R12. Statistical policy v1 must retain its meaning; changed analytics require versioned readers.",
"Initial capital fits the existing two-decimal USD template column; exact engine financial fields remain eight-place strings. Fills are not reported as completed round trips; unsupported metrics remain null with reasons.",
"No production/development datasets, strategy catalog or schema were mutated. Offline import/seeding are explicit operator actions.",
"Performance work and benchmarks remain paused. No new-wave commit, push, PR, trading activation or default cutover."
],
"cleanup": "Both exact --rm disposable PostgreSQL/Redis containers stopped; development services untouched. Worktrees and evidence logs retained.",
"next": "After acceptance/commit, R03 research projects, hypotheses and evidence-linked findings APIs is independently ready. Keep R05 in progress until explicit source-v2 preparation and broader cutover scope are completed; R06/S06 remain blocked."
}
}

View file

@ -74,3 +74,34 @@ Keep migrations additive and previous results readable. Do not add a switch that
## Handoff
Report scope changes (if any), fixture expectations, API/schema changes, measurements, remaining limitations and commit/PR references once authorized. Request independent review; only the integration/planning owner may mark the manifest done.
## First vertical slice — 2026-10-23
The additive slice connects the approved, server-seeded catalog built-ins to the existing durable runner and canonical Rust session. It supports one eligible retained v2 dataset, one series/asset/owner, explicit USD cash-funded long-only execution and reporting settings. HTTP-published or cloned candidates remain excluded even if reviewed. R05 is **not complete**: source-request preparation into eligible v2 data and broader cutover remain outstanding. No multi-asset/default activation is implied.
The pinned request is `canonical-research/v1` in `apps/stock/config/src/contracts/canonical-research.ts`. It retains the full checksummed executable package and dependency lock, normalized parameters, review receipt, dataset hash, seed, complete replay/financial/reporting policies and installed worker/native/runtime build identity. Admission and review/archive serialize on the strategy-family row; accepted receipt replay precedes current eligibility checks. Later edits or review revocation affect new submissions only. Account risk boundaries use actual retained calendar opens, including warmup and DST; daily bounds remain exact UTC instants.
The child imports the retained ESM bytes through a temporary Blob URL, verifies the package/build before strategy factory execution, and runs the existing deterministic TypeScript callback loop against Rust. The current built-in constructor is not a fallback. Durable claiming, heartbeat, cancellation/reaping, lease fencing and atomic result persistence are shared with legacy work. A build mismatch, corrupt dataset or runner without canonical capability fails with a durable diagnostic and no legacy/provider fallback.
Migration 19 adds `canonical_result` to existing results and strengthens admission/result identity guards; it preserves retention triggers. `canonical-result/v1` bypasses legacy percentage conversion and placeholder metrics. Existing required legacy JSON columns contain JSON null for canonical results. F08 remains the statistical evaluator; exact Rust financial facts, zeros, unavailable reasons, owner books and fills survive reopening. Reporting policy version 1 must keep its existing meaning; changed statistics require a new version and compatible retained readers.
### Operator workflow and deployment prerequisite
Use the R01 offline packaging/seeding workflow for repository built-ins, review a retained version in the web catalog, save a backtest, then open Settings → Configure canonical research. An explicitly prepared v2 dataset can be retained with:
```sh
RESEARCH_DATASET_DATABASE_URL=<database> bun run scripts/import-research-dataset.ts --file <v2-dataset.json>
```
The importer validates content/hash before connecting, never infers calendars/actions, does not migrate tables and never overwrites retained bytes. Normal startup migrations own the schema. The canonical picker validates retained content and shows unsupported entries as unavailable. All capital, cost, risk and statistical settings are explicit; legacy settings are not silently translated. Initial capital must fit the existing USD-cent template column, while engine quantities/notionals retain checked eight-place decimals.
Deploy the existing **native research runner (`useRustEngine: true`)**, bundled `orchestrator/dist/native-worker.js`, engine wrapper/addon and lockfile from the same build. Keep executable files immutable while jobs launch/run. Eligibility is an input/artifact preflight, not a worker health check. Accepted runs fail closed after an incompatible deployment; retaining/restoring historical executable builds and an exact reproduction workflow remain R12. No production database was seeded or migrated by this development wave.
### Remaining work and release gates
- Add explicit provider/source preparation only when it can supply v2 availability, calendar, action coverage and universe evidence; do not relabel v1 data eligible or infer missing facts. Freeze the immutable preparation request and bind the first verified dataset atomically before decisions.
- Preserve the current single-asset restriction until the simultaneous-mark policy is resolved. Candidate execution still requires A02 isolation; paper/live operation and default simulator retirement remain separately gated.
- R03 research projects/hypotheses/findings is independently ready and can deliver useful product work without opening these execution gates. R06 remains dependent on completed R05 scope; do not mark it ready from this partial milestone alone.
- No profiling, performance optimization, benchmark runs, DSL, second job engine, simulator or deployment framework was added.
Final validation and source identity are recorded in `manifest.json` → `twenty_third_wave_validation` and the roadmap handoff.

View file

@ -5,7 +5,7 @@
*/
export const FINANCIAL_PROTOCOL_VERSION = 1 as const;
export const MAX_FINANCIAL_POSTING = '792281625142643375935.43950335';
declare const financialDecimal: unique symbol;
export declare const financialDecimal: unique symbol;
export type FinancialDecimal = string & { readonly [financialDecimal]: true };
export interface DecisionIdentity {

View file

@ -112,6 +112,7 @@ export {
parseFinancialEffects,
} from './financial-engine';
export type {
financialDecimal,
FinancialDecimal,
DecisionIdentity,
RiskSessionIdentity,

View file

@ -0,0 +1,56 @@
/** Explicit offline custody of an existing v2 dataset. No provider/calendar inference. */
import { readFile } from 'node:fs/promises';
import { Pool } from 'pg';
import { validateDatasetV2 } from '../apps/stock/orchestrator/src/data/historical-dataset-v2';
export async function retainResearchDataset(database: Pick<Pool, 'query'>, input: unknown) {
const dataset = validateDatasetV2(input);
await database.query(
'INSERT INTO backtest_datasets(hash,payload) VALUES($1,$2::jsonb) ON CONFLICT(hash) DO NOTHING',
[dataset.manifest.hash, JSON.stringify(dataset)]
);
const stored = (
await database.query('SELECT payload FROM backtest_datasets WHERE hash=$1', [
dataset.manifest.hash,
])
).rows[0];
if (!stored || validateDatasetV2(stored.payload).manifest.hash !== dataset.manifest.hash) {
throw new Error('Retained dataset content does not match the imported identity');
}
return dataset.manifest;
}
if (import.meta.main) {
let database: Pool | undefined;
try {
const args = process.argv.slice(2);
if (args.length !== 2 || args[0] !== '--file' || !args[1]) {
throw new Error(
'Usage: RESEARCH_DATASET_DATABASE_URL=<database> bun run scripts/import-research-dataset.ts --file <v2-dataset.json>'
);
}
const connectionString = process.env.RESEARCH_DATASET_DATABASE_URL;
if (
!connectionString ||
!['postgres:', 'postgresql:'].includes(new URL(connectionString).protocol)
) {
throw new Error(
'Set RESEARCH_DATASET_DATABASE_URL explicitly; this command retains research data'
);
}
const input: unknown = JSON.parse(await readFile(args[1], 'utf8'));
// Validate before opening a database connection. Existing startup migrations
// own the schema; import never updates/deletes retained data or migrates tables.
validateDatasetV2(input);
database = new Pool({ connectionString, connectionTimeoutMillis: 5000 });
const manifest = await retainResearchDataset(database, input);
process.stdout.write(
`${JSON.stringify({ hash: manifest.hash, barCount: manifest.barCount, eligibility: manifest.eligibility, limitations: manifest.limitations }, null, 2)}\n`
);
} catch (error) {
process.stderr.write(`${error instanceof Error ? error.message : String(error)}\n`);
process.exitCode = 1;
} finally {
await database?.end();
}
}

View file

@ -26,6 +26,7 @@ const workspaceSources: Record<string, string> = {
'@stock-bot/calculations': 'libs/calculations/src/index.ts',
'@stock-bot/calculations/indicators': 'libs/calculations/src/indicators/index.ts',
'@stock-bot/calculations/returns': 'libs/calculations/src/returns.ts',
'@stock-bot/stock-config/canonical-replay': 'apps/stock/config/src/contracts/canonical-replay.ts',
'@stock-bot/stock-config/strategy': 'apps/stock/config/src/contracts/strategy.ts',
'@stock-bot/stock-config/backtest': 'apps/stock/config/src/contracts/backtest.ts',
};

View file

@ -62,10 +62,11 @@ describe('orchestrator architecture boundaries', () => {
expect(
path === 'types.ts' ||
path.startsWith('contracts/') ||
path === 'backtest/native-worker-protocol.ts'
path === 'backtest/native-worker-protocol.ts' ||
path === 'backtest/canonical-result.ts'
).toBe(true);
for (const specifier of imports.get(file) ?? []) {
expect(specifier.startsWith('.') || ['zod', '@stock-bot/types', '@stock-bot/stock-config/backtest', '@stock-bot/stock-config/strategy'].includes(specifier)).toBe(
expect(specifier.startsWith('.') || ['zod', '@stock-bot/types', '@stock-bot/stock-config/backtest', '@stock-bot/stock-config/strategy', '@stock-bot/stock-config/canonical-replay', '@stock-bot/stock-config/canonical-research', '@stock-bot/calculations/analytics', '@stock-bot/calculations/returns'].includes(specifier)).toBe(
true
);
}
@ -75,7 +76,7 @@ describe('orchestrator architecture boundaries', () => {
it('the shared backtest contract loads no configuration manager, services or application runtime', async () => {
const entry = resolve(root, '../../config/src/contracts/backtest.ts');
expect(runtimeImports(entry).sort()).toEqual(['@stock-bot/types', 'zod']);
expect(runtimeImports(entry).sort()).toEqual(['./canonical-research', '@stock-bot/types', 'zod']);
const bundle = await Bun.build({ entrypoints: [entry], target: 'browser' });
expect(bundle.success).toBe(true);
const code = await bundle.outputs[0]?.text();
@ -87,9 +88,9 @@ describe('orchestrator architecture boundaries', () => {
it('shared strategy catalog contracts cannot import strategy execution or application services', async () => {
const directory = resolve(root, '../../config/src/contracts');
for (const name of ['strategy.ts', 'builtin-strategy.ts', 'strategy-names.ts']) {
for (const name of ['strategy.ts', 'builtin-strategy.ts', 'strategy-names.ts', 'canonical-research.ts', 'canonical-replay.ts']) {
for (const specifier of runtimeImports(join(directory, name))) {
expect(['zod', '@stock-bot/types', './builtin-strategy', './strategy-names'].includes(specifier)).toBe(true);
expect(['zod', '@stock-bot/types', './builtin-strategy', './strategy-names', './strategy', './canonical-replay'].includes(specifier)).toBe(true);
}
}
const bundle = await Bun.build({

View file

@ -290,6 +290,7 @@ export async function fixture(browser: Browser, native = false) {
'16-strategy-catalog.sql',
'17-research-retention.sql',
'18-backtest-strategy-versions.sql',
'19-canonical-research.sql',
]) {
await pool.query(
readFileSync(new URL(`../../database/postgres/init/${name}`, import.meta.url), 'utf8')
@ -331,8 +332,15 @@ export async function fixture(browser: Browser, native = false) {
maxAttempts: 3,
});
const controlled = new FixtureEngine();
const historicalDataReads: string[] = [];
const runStorage: Pick<StorageService, 'getHistoricalBars'> = {
async getHistoricalBars(...args) {
historicalDataReads.push(args[0]);
return storage.getHistoricalBars(...args);
},
};
const engine = native
? new RustBacktestAdapter({ logger, storage }, { timeoutMs: 15000 })
? new RustBacktestAdapter({ logger, storage: runStorage }, { timeoutMs: 15000 })
: controlled;
const runner = new BacktestRunner({
engine,
@ -560,6 +568,7 @@ export async function fixture(browser: Browser, native = false) {
login,
close,
unexpectedNetwork,
historicalDataReads,
seedCatalog: () => seedBuiltinCatalog(new StrategyCatalogService(container)),
};
} catch (error) {

View file

@ -1,6 +1,13 @@
import { createHash, randomUUID } from 'node:crypto';
import { afterAll, beforeAll, expect, test } from 'bun:test';
import { chromium, type Browser, type Request } from 'playwright';
import {
canonicalResearchSettingsSchema,
type CanonicalRunResult,
} from '@stock-bot/stock-config/canonical-research';
import { retainResearchDataset } from '../../scripts/import-research-dataset';
import { canonicalSettings } from '../fixtures/canonical-research';
import { canonicalSmaFixture } from '../fixtures/canonical-sma';
import {
fixture as createFixture,
createInBrowser,
@ -537,7 +544,7 @@ test('browser_catalog_version_parameters_clone_and_saved_draft', async () => {
await f.page.getByRole('button', { name: 'Validate parameters', exact: true }).click();
await visible(
f.page,
'Parameters validated for this immutable version. Execution remains unavailable.'
'Parameters validated for this immutable version. Execution eligibility depends on the saved dataset, policy and reviewed executable.'
);
await f.page.getByRole('button', { name: 'Use in backtest', exact: true }).click();
await f.page.waitForURL(
@ -561,7 +568,7 @@ test('browser_catalog_version_parameters_clone_and_saved_draft', async () => {
await f.page.getByRole('button', { name: 'Validate parameters', exact: true }).click();
await visible(
f.page,
'Parameters validated for this immutable version. Execution remains unavailable.'
'Parameters validated for this immutable version. Execution eligibility depends on the saved dataset, policy and reviewed executable.'
);
expect(
await f.page.getByRole('button', { name: 'Save and run', exact: true }).isDisabled()
@ -608,7 +615,7 @@ test('browser_catalog_version_parameters_clone_and_saved_draft', async () => {
await f.page.getByRole('button', { name: 'Validate parameters', exact: true }).click();
await visible(
f.page,
'Parameters validated for this immutable version. Execution remains unavailable.'
'Parameters validated for this immutable version. Execution eligibility depends on the saved dataset, policy and reviewed executable.'
);
};
const saveVisibleSettings = async () => {
@ -701,3 +708,206 @@ test('browser_catalog_version_parameters_clone_and_saved_draft', async () => {
await f.close();
}
});
test('browser_approved_canonical_strategy_setup_run_and_reopen', async () => {
const f = await fixture(true);
f.page.on('dialog', dialog => void dialog.accept());
try {
const oracle = canonicalSmaFixture();
const retained = await retainResearchDataset(f.pool, oracle.dataset);
const seeded = await f.seedCatalog();
const selected = seeded.find(item => item.package.program.strategyId === 'sma_crossover')!;
expect(selected.reviewStatus).toBe('pending');
await f.login();
await f.page.goto(`${f.origin}/strategies/${selected.strategyId}/versions/${selected.id}`);
// Approval is an authenticated human review of an immutable built-in, not a run bypass.
await f.page
.getByLabel('Review reason', { exact: true })
.fill('Reviewed retained SMA fixture and next-open oracle.');
const approval = f.page.waitForResponse(
response =>
response.request().method() === 'POST' &&
response.url().endsWith(`/strategy-versions/${selected.id}/reviews`)
);
await f.page.getByRole('button', { name: 'Approve built-in version', exact: true }).click();
expect((await approval).status()).toBe(201);
await visible(f.page, /This immutable built-in version has an approval record/);
await f.page.getByLabel('fastPeriod', { exact: true }).fill('2');
await f.page.getByLabel('slowPeriod', { exact: true }).fill('3');
const validate = async () => {
const response = f.page.waitForResponse(
reply =>
reply.request().method() === 'POST' &&
reply.url().endsWith(`/strategy-versions/${selected.id}/validate`)
);
await f.page.getByRole('button', { name: 'Validate parameters', exact: true }).click();
expect((await response).status()).toBe(200);
await visible(f.page, /Parameters validated for this immutable version/);
};
await validate();
await f.page.getByRole('button', { name: 'Use in backtest', exact: true }).click();
await f.page.waitForURL(
url =>
url.pathname === '/backtests' && url.searchParams.get('strategyVersionId') === selected.id
);
await f.page.getByPlaceholder('My Strategy Backtest').fill('Reviewed canonical browser oracle');
await until(
async () =>
(await f.page.getByLabel('Immutable strategy version', { exact: true }).inputValue()) ===
selected.id,
'canonical draft immutable version'
);
await f.page.locator('input[type="date"]').nth(0).fill('2024-01-01');
await f.page.locator('input[type="date"]').nth(1).fill('2024-01-02');
expect(await f.page.getByLabel('fastPeriod', { exact: true }).inputValue()).toBe('2');
expect(await f.page.getByLabel('slowPeriod', { exact: true }).inputValue()).toBe('3');
await validate();
expect(
await f.page.getByRole('button', { name: 'Save and run', exact: true }).isDisabled()
).toBe(true);
await f.page.getByRole('button', { name: 'Save', exact: true }).click();
await f.page.waitForURL(/\/backtests\/[^/?]+$/);
const backtestId = f.page.url().split('/').at(-1)!;
expect((await f.pool.query('SELECT * FROM runs')).rowCount).toBe(0);
expect((await f.pool.query('SELECT * FROM backtest_dispatch')).rowCount).toBe(0);
await f.page.getByRole('button', { name: 'Runs', exact: true }).click();
expect(await f.page.getByRole('button', { name: 'New Run', exact: true }).isDisabled()).toBe(
true
);
await f.page.getByRole('button', { name: 'Settings', exact: true }).click();
await f.page.getByRole('button', { name: 'Configure canonical research', exact: true }).click();
await f.page.getByLabel('Canonical dataset', { exact: true }).selectOption(retained.hash);
await visible(f.page, new Date(retained.bounds.tradeStart).toISOString());
await visible(f.page, new Date(retained.bounds.tradeEnd).toISOString());
await f.page.getByLabel('Initial capital (USD)', { exact: true }).fill('10000');
const policyFields = [
['Owner budget', canonicalSettings.ownerBudget],
['Fee rate', canonicalSettings.feeRate],
['Half-spread rate', canonicalSettings.halfSpreadRate],
['Slippage rate', canonicalSettings.slippageRate],
['Volume participation rate', canonicalSettings.participationRate],
['Order latency (ms)', canonicalSettings.latencyMs],
['Maximum order quantity', canonicalSettings.maxOrderQuantity],
['Maximum position quantity', canonicalSettings.maxPositionQuantity],
['Maximum asset exposure', canonicalSettings.maxSymbolExposure],
['Maximum gross exposure', canonicalSettings.maxGrossExposure],
['Maximum risk-period loss', canonicalSettings.maxDailyLoss],
['Maximum drawdown amount', canonicalSettings.maxDrawdownAmount],
['Maximum mark age (ms)', canonicalSettings.maxMarkAgeMs],
['Random seed', canonicalSettings.seed],
['Reporting periods per year', canonicalSettings.periodsPerYear],
['Annual risk-free rate', canonicalSettings.annualRiskFreeRate],
] as const;
for (const [label, value] of policyFields) {
await f.page.getByLabel(label, { exact: true }).fill(value === null ? '' : String(value));
}
await until(
async () =>
(await f.page.getByLabel('Immutable strategy version', { exact: true }).inputValue()) ===
selected.id,
'canonical setup immutable version'
);
await validate();
const saving = f.page.waitForResponse(
response =>
response.request().method() === 'PUT' && response.url().endsWith(`/backtests/${backtestId}`)
);
await f.page.getByRole('button', { name: 'Save canonical setup', exact: true }).click();
const savedResponse = await saving;
expect(savedResponse.status()).toBe(200);
const sent = savedResponse.request().postDataJSON();
expect(sent.config).toEqual({
datasetHash: retained.hash,
dataFrequency: '1m',
canonical: canonicalResearchSettingsSchema.parse(canonicalSettings),
});
expect(sent.symbols).toEqual(['X0.US']);
expect(sent.initialCapital).toBe(10000);
expect(sent.startDate).toBe(new Date(retained.bounds.tradeStart).toISOString());
expect(sent.endDate).toBe(new Date(retained.bounds.tradeEnd).toISOString());
expect(sent.strategyVersionId).toBe(selected.id);
expect(sent.strategyParameters).toEqual({ fastPeriod: 2, slowPeriod: 3 });
await visible(f.page, /Canonical execution is available for this saved configuration/);
await f.page.getByRole('button', { name: 'Runs', exact: true }).click();
const accepted = await submitInBrowser(f.page);
expect(accepted.status()).toBe(202);
expect(accepted.request().postDataJSON()).toEqual({ speedMultiplier: null });
const run = await accepted.json();
const admitted = (
await f.pool.query('SELECT request_snapshot,dataset_hash FROM runs WHERE id=$1', [run.id])
).rows[0];
expect(admitted.dataset_hash).toBe(retained.hash);
expect(admitted.request_snapshot.kind).toBe('canonical-research/v1');
expect(admitted.request_snapshot.strategy.versionId).toBe(selected.id);
expect(admitted.request_snapshot.strategy.selection.parameters).toEqual({
fastPeriod: 2,
slowPeriod: 3,
});
expect(admitted.request_snapshot.strategy.package.artifact.sha256).toBe(
selected.package.artifact.sha256
);
await visible(f.page, 'Pending');
f.dispatcher.start();
await visible(f.page, 'Canonical research result');
await visible(f.page, 'Completed');
const result = (await f.request(`/api/v2/runs/${run.id}/results`)) as CanonicalRunResult;
expect(result.kind).toBe('canonical-result/v1');
expect(result.request).toEqual(admitted.request_snapshot);
expect(result.financialEngine).toBe('rust');
expect(String(result.financial.projection.valuation.equity)).toBe('9969.30000000');
expect(String(result.financial.projection.valuation.fees)).toBe('0.70000000');
expect(
result.financial.projection.fills.map(fill => [
fill.side,
String(fill.quantity),
String(fill.price),
String(fill.fee.amount),
])
).toEqual([
['buy', '10.00000000', '5.00000000', '0.50000000'],
['sell', '10.00000000', '2.00000000', '0.20000000'],
]);
expect(result.analytics.metrics.roundTripCount).toBeNull();
await visible(f.page, '9969.30000000');
await visible(f.page, 'Unavailable — unsupported round trips');
const provenance = f.page.getByRole('region', {
name: 'Canonical result provenance',
exact: true,
});
expect(await provenance.textContent()).toContain(selected.id);
expect(await provenance.textContent()).toContain(retained.hash);
expect(await provenance.textContent()).toContain(selected.package.artifact.sha256);
expect(await provenance.textContent()).toContain(result.request.build.engineBinarySha256);
expect(
await f.page.getByText('Research only · Unverified economics', { exact: true }).count()
).toBe(0);
await f.page.getByRole('button', { name: 'Trades', exact: true }).click();
await visible(f.page, 'Canonical fills (2)');
expect(await f.page.locator('tbody tr').count()).toBe(2);
await visible(f.page, '0.50000000');
await visible(f.page, '0.20000000');
const completedUrl = f.page.url();
await f.page.reload();
await visible(f.page, 'Canonical research result');
await visible(f.page, '9969.30000000');
expect(f.page.url()).toBe(completedUrl);
await f.page.getByRole('button', { name: 'Trades', exact: true }).click();
await visible(f.page, 'Canonical fills (2)');
expect(await f.request(`/api/v2/runs/${run.id}/results`)).toEqual(result);
const stored = (
await f.pool.query(
'SELECT canonical_result,metrics,trades FROM backtest_results WHERE run_id=$1',
[run.id]
)
).rows[0];
expect(stored.canonical_result).toEqual(result);
expect(stored.metrics).toBeNull();
expect(stored.trades).toBeNull();
expect((await f.pool.query('SELECT * FROM backtest_results')).rowCount).toBe(1);
expect(f.historicalDataReads).toEqual([]);
expect(f.unexpectedNetwork).toEqual([]);
} finally {
await f.close();
}
});

91
test/fixtures/canonical-research.ts vendored Normal file
View file

@ -0,0 +1,91 @@
import type { CanonicalResearchSettings } from '@stock-bot/stock-config/canonical-research';
import { createDatasetV2 } from '../../apps/stock/orchestrator/src/data/historical-dataset-v2';
export const canonicalSettings: CanonicalResearchSettings = {
version: 1,
seed: 42,
ownerBudget: '40',
feeRate: '0.01',
halfSpreadRate: '0',
slippageRate: '0',
latencyMs: 0,
participationRate: '1',
maxOrderQuantity: '10000',
maxPositionQuantity: '10000',
maxSymbolExposure: '10000',
maxGrossExposure: '10000',
maxDailyLoss: '10000',
maxDrawdownAmount: '10000',
maxMarkAgeMs: 345600000,
periodsPerYear: 252,
annualRiskFreeRate: 0,
};
/** Explicit retained exchange sessions straddle US DST; labels are never UTC midnights. */
export function canonicalDailyDataset() {
const sessions = [
{
date: '2024-03-08',
open: Date.parse('2024-03-08T14:30:00Z'),
close: Date.parse('2024-03-08T21:00:00Z'),
},
{
date: '2024-03-11',
open: Date.parse('2024-03-11T13:30:00Z'),
close: Date.parse('2024-03-11T20:00:00Z'),
},
];
const start = sessions[0]!.open,
end = sessions[1]!.close;
return createDatasetV2({
metadata: {
calendars: [
{
id: 'retained-test-calendar',
venue: 'TEST',
timeZone: 'America/New_York',
revision: 'dst-fixture-v1',
source: 'synthetic',
startDate: '2024-03-08',
endDate: '2024-03-12',
sessions,
},
],
series: [
{
id: 'X0.US:1d',
instrumentId: 'X0.US',
interval: '1d',
calendarId: 'retained-test-calendar',
venue: 'TEST',
source: { provider: 'synthetic', revision: 'v1' },
timestamp: 'session-date',
availability: 'explicit',
adjustment: 'raw',
},
],
executionSeries: [{ instrumentId: 'X0.US', seriesId: 'X0.US:1d' }],
bounds: { warmupStart: start, tradeStart: sessions[1]!.open, tradeEnd: end },
universe: {
selection: 'point-in-time',
asOf: start,
revision: 'v1',
instrumentIds: ['X0.US'],
},
corporateActions: [
{ instrumentId: 'X0.US', status: 'action-free', start, end, revision: 'v1', actions: [] },
],
},
bars: sessions.map((session, index) => ({
seriesId: 'X0.US:1d',
timestamp: session.date,
availableAt: session.close,
sourceSequence: index,
open: 10,
high: 12,
low: 9,
close: 11,
volume: 1000,
})),
});
}

View file

@ -0,0 +1,331 @@
import { randomUUID } from 'node:crypto';
import { EventEmitter } from 'node:events';
import { describe, expect, test } from 'bun:test';
import {
canonicalRunRequestSchema,
type CanonicalRunResult,
} from '@stock-bot/stock-config/canonical-research';
import type { HistoricalDatasetV2 } from '@stock-bot/types';
import { builtinCatalogDescriptors } from '../../apps/stock/config/src/contracts/strategy';
import { BacktestRunner } from '../../apps/stock/orchestrator/src/backtest/BacktestRunner';
import {
BacktestCancelledError,
type BacktestExecutionEngine,
} from '../../apps/stock/orchestrator/src/backtest/execution-engine';
import {
BacktestLeaseLostError,
type BacktestRunRepository,
} from '../../apps/stock/orchestrator/src/backtest/run-repository';
import { canonicalSmaFixture } from '../fixtures/canonical-sma';
const logger = { error() {} };
function setup() {
const versionId = randomUUID(),
runId = randomUUID(),
ownerId = `strategy:${versionId}`;
const { dataset, config, selections } = canonicalSmaFixture([ownerId]);
config.matching.risk.ledger.sessionId = runId;
config.matching.risk.ledger.accountId = `research:${runId}`;
const descriptor = builtinCatalogDescriptors.find(d => d.program.strategyId === 'sma_crossover')!;
const request = canonicalRunRequestSchema.parse({
kind: 'canonical-research/v1',
runId,
backtestId: randomUUID(),
name: 'Runner boundary',
strategy: {
familyId: randomUUID(),
versionId,
origin: 'builtin',
reviewId: randomUUID(),
selection: selections[0],
package: {
version: 1,
program: descriptor.program,
parameterSchema: descriptor.parameterSchema,
artifact: {
format: 'esm-bundle/v1',
entryExport: descriptor.entryExport,
content: 'not executed by this lifecycle fixture',
sha256: 'a'.repeat(64),
},
dependencyLock: { format: 'bun-lock/v1', content: 'fixture', sha256: 'b'.repeat(64) },
source: { revision: 'c'.repeat(40), dirty: false },
build: { tool: 'bun', version: 'fixture', target: 'browser' },
},
},
datasetHash: dataset.manifest.hash,
policy: config,
analyticsPolicy: { version: 1, periodsPerYear: 252, annualRiskFreeRate: 0, benchmark: null },
modelArtifacts: [],
build: {
version: 1,
workerSha256: 'd'.repeat(64),
engineWrapperSha256: 'e'.repeat(64),
engineBinarySha256: 'f'.repeat(64),
dependencyLockSha256: 'b'.repeat(64),
runtime: 'bun',
runtimeVersion: 'fixture',
platform: 'linux',
arch: 'x64',
},
});
const events: string[] = [];
let result: CanonicalRunResult | undefined;
let heartbeatFailure = false;
let status = 'pending';
const repo: BacktestRunRepository = {
async start() {
throw new Error('legacy claim must not run');
},
async startCanonical(input) {
events.push('claim');
status = 'running';
return {
runId,
backtestId: request.backtestId,
attemptId: 'attempt',
config: structuredClone(input),
};
},
async load() {
return { status, config: structuredClone(request) };
},
async rejectPending() {
events.push('reject');
status = 'failed';
},
async heartbeat() {
events.push('heartbeat');
if (heartbeatFailure) {
throw new Error('lost');
}
return { cancelRequested: false };
},
async loadDataset() {
throw new Error('v1 data must not run');
},
async freezeDataset() {
throw new Error('provider freeze must not run');
},
async loadCanonicalDataset(_id, _attempt, hash) {
expect(hash).toBe(dataset.manifest.hash);
events.push('dataset');
return dataset;
},
async complete() {
throw new Error('legacy completion must not run');
},
async completeCanonical(input) {
events.push('complete');
result = input;
status = 'completed';
},
async updateProgress() {
events.push('progress');
},
async fail() {
events.push('fail');
status = 'failed';
},
async cancel() {
events.push('cancel');
status = 'cancelled';
},
async updateControl() {},
};
const engine = Object.assign(new EventEmitter(), {
async runBacktest(): Promise<never> {
throw new Error('legacy simulator must not run');
},
async runCanonical(
_input: typeof request,
resolve: (signal: AbortSignal) => Promise<HistoricalDatasetV2>
) {
await resolve(new AbortController().signal);
events.push('execute');
// Economic validation belongs to the actual worker/SQL fixtures; this fixture probes lifecycle only.
return {
financial: {} as CanonicalRunResult['financial'],
analytics: {} as CanonicalRunResult['analytics'],
};
},
async stopBacktest() {
events.push('stop');
},
async pauseBacktest() {},
async resumeBacktest() {},
setSpeedMultiplier() {},
getStatus() {
return { isRunning: false, isPaused: false, progress: 0, currentTime: 0 };
},
async shutdown() {},
}) satisfies BacktestExecutionEngine;
const runner = new BacktestRunner({
engine,
repository: repo,
engineName: 'native',
logger,
heartbeatMs: 5,
heartbeatTimeoutMs: 50,
async prepare() {
throw new Error('legacy preparation must not run');
},
});
return {
request,
dataset,
repo,
engine,
runner,
events,
get result() {
return result;
},
loseLease() {
heartbeatFailure = true;
},
};
}
function deferred<T>() {
let resolve!: (value: T) => void;
let reject!: (error: Error) => void;
const promise = new Promise<T>((a, b) => {
resolve = a;
reject = b;
});
return { promise, resolve, reject };
}
describe('canonical jobs share the durable runner lifecycle', () => {
test('queued canonical result preserves admitted request and bypasses every legacy seam', async () => {
const f = setup();
expect(await f.runner.runQueued(f.request.runId)).toEqual({
runId: f.request.runId,
status: 'completed',
});
expect(f.events).toEqual(['claim', 'heartbeat', 'dataset', 'execute', 'complete']);
expect(f.result?.request).toEqual(f.request);
expect(f.result?.kind).toBe('canonical-result/v1');
expect(await f.runner.runQueued(f.request.runId)).toEqual({
runId: f.request.runId,
status: 'completed',
});
expect(f.events.filter(e => e === 'execute')).toHaveLength(1);
await expect(f.runner.runBacktest(f.request)).rejects.toThrow();
await f.runner.shutdown();
});
test('legacy entry refuses canonical markers even when the remaining fields look legacy', async () => {
const f = setup();
const legacy = {
mode: 'backtest',
strategy: 'sma-crossover',
symbols: ['X.US'],
startDate: '2024-01-01T00:00:00.000Z',
endDate: '2024-02-01T00:00:00.000Z',
initialCapital: 10000,
dataFrequency: '1d',
};
for (const marker of [
{ kind: 'canonical-research/v1' },
{ kind: 'canonical-research/v999' },
{ canonical: {} },
]) {
await expect(f.runner.runBacktest({ ...legacy, ...marker })).rejects.toThrow(
'Retained strategy versions'
);
}
expect(f.events).toEqual([]);
await f.runner.shutdown();
});
test('a runner without canonical execution fails without preparation or legacy/provider fallback', async () => {
const f = setup();
const engine: BacktestExecutionEngine = f.engine;
delete engine.runCanonical;
const fail = f.repo.fail.bind(f.repo);
let savedFailure: string | undefined;
f.repo.fail = async (runId, error, attemptId) => {
savedFailure = error;
await fail(runId, error, attemptId);
};
try {
await expect(f.runner.runQueued(f.request.runId)).rejects.toThrow(
'Canonical execution capabilities are unavailable'
);
expect(savedFailure).toBe('Canonical execution capabilities are unavailable');
expect(f.events).toEqual(['claim', 'heartbeat', 'fail']);
expect(f.result).toBeUndefined();
expect(await f.runner.runQueued(f.request.runId)).toEqual({
runId: f.request.runId,
status: 'failed',
});
expect(f.events).toEqual(['claim', 'heartbeat', 'fail']);
} finally {
await f.runner.shutdown();
}
});
test('cancel waits for execution to finish before committing cancellation', async () => {
const f = setup(),
entered = deferred<void>(),
reaped = deferred<void>(),
exit = deferred<never>();
f.engine.runCanonical = async () => {
entered.resolve();
return exit.promise;
};
f.engine.stopBacktest = async () => {
f.events.push('stop');
await reaped.promise;
exit.reject(new BacktestCancelledError());
};
const run = f.runner.runQueued(f.request.runId);
const failed = run.catch(error => error);
await entered.promise;
let stopped = false;
const stop = f.runner.stopBacktest(f.request.runId).then(() => {
stopped = true;
});
await Promise.resolve();
expect(stopped).toBe(false);
expect(f.events).not.toContain('cancel');
reaped.resolve();
await stop;
expect(await failed).toBeInstanceOf(BacktestCancelledError);
expect(f.events).toContain('cancel');
expect(f.events).not.toContain('complete');
await f.runner.shutdown();
});
test('lease loss stops execution without overwriting a newer owner terminal state', async () => {
const f = setup(),
entered = deferred<void>(),
exit = deferred<never>();
f.engine.runCanonical = async () => {
entered.resolve();
return exit.promise;
};
f.engine.stopBacktest = async () => {
f.events.push('stop');
exit.reject(new BacktestCancelledError());
};
const run = f.runner.runQueued(f.request.runId);
const failed = run.catch(error => error);
await entered.promise;
f.loseLease();
expect(await failed).toBeInstanceOf(BacktestLeaseLostError);
expect(f.events).toContain('stop');
expect(f.events).not.toContain('fail');
expect(f.events).not.toContain('cancel');
expect(f.events).not.toContain('complete');
await f.runner.shutdown();
});
test('invalid persisted canonical kind never becomes a legacy run', async () => {
const f = setup();
f.repo.load = async () => ({
status: 'pending',
config: { ...f.request, kind: 'canonical-research/v2' },
});
await expect(f.runner.runQueued(f.request.runId)).rejects.toThrow();
expect(f.events).toEqual(['reject']);
await f.runner.shutdown();
});
});

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,351 @@
import { fork } from 'node:child_process';
import { createHash } from 'node:crypto';
import { fileURLToPath } from 'node:url';
import { beforeAll, describe, expect, test } from 'bun:test';
import {
canonicalRunRequestSchema,
type CanonicalRunRequest,
} from '@stock-bot/stock-config/canonical-research';
import { parseFinancialDecimal, type StrategyVersionPackage } from '@stock-bot/types';
import {
canonicalWorkerUrl,
readCanonicalBuildIdentity,
} from '../../apps/stock/orchestrator/src/backtest/canonical-build';
import { buildCanonicalBacktestReport } from '../../apps/stock/orchestrator/src/backtest/canonical-result';
import { prepareReplayLoad } from '../../apps/stock/orchestrator/src/backtest/native-replay';
import {
nativeWorkerRequestSchema,
parseRetainedStrategyResult,
} from '../../apps/stock/orchestrator/src/backtest/native-worker-protocol';
import { NativeBacktestWorker } from '../../apps/stock/orchestrator/src/backtest/NativeBacktestWorker';
import { runStrategyReplay } from '../../apps/stock/orchestrator/src/backtest/strategy-runtime';
import { createBuiltinStrategy } from '../../apps/stock/orchestrator/src/strategies/canonical-builtins';
import { packageBuiltinStrategies } from '../../scripts/package-builtin-strategies';
import { nativeReplayFixture } from '../fixtures/native-replay';
const runId = 'b96aae03-f6d6-43b5-a006-a160e37f012b';
const versionId = '212a7d31-893d-46c9-910b-2234566f20d6';
const ownerId = `strategy:${versionId}`;
const sha = (content: string) => createHash('sha256').update(content, 'utf8').digest('hex');
let packages: StrategyVersionPackage[];
beforeAll(async () => {
packages = await packageBuiltinStrategies();
});
async function input(strategyId = 'sma_crossover') {
const { dataset, config } = nativeReplayFixture(24, 1, [ownerId]);
config.matching.risk.ledger.sessionId = runId;
config.matching.risk.ledger.accountId = `research:${runId}`;
const pkg = structuredClone(packages.find(item => item.program.strategyId === strategyId)!);
const request = canonicalRunRequestSchema.parse({
kind: 'canonical-research/v1',
runId,
backtestId: '4ea6a0fa-7bab-416f-b99e-ef9456567f66',
name: 'Exact retained built-in',
strategy: {
familyId: '05c49df3-08a4-40c5-b78d-4ee3364ac7a9',
versionId,
origin: 'builtin',
reviewId: 'e06828fc-8b37-4631-bf32-828d6095fdb6',
package: pkg,
selection: {
strategyId,
strategyVersion: pkg.program.strategyVersion,
ownerId,
seed: 17,
instrumentId: 'X0.US',
seriesId: 'X0.US:1m',
ownerBudget: '100',
parameters:
strategyId === 'sma_crossover'
? { fastPeriod: 1, slowPeriod: 2 }
: {
lookbackPeriod: 2,
trendPeriod: 3,
momentumPeriod: 1,
volatilityPeriod: 2,
entryZScore: 1,
exitZScore: 0,
minTrendReturn: -0.9,
minMomentumReturn: -0.9,
maxVolatility: 1,
minNotionalVolume: '0',
regimeFilter: 'none',
},
},
},
datasetHash: dataset.manifest.hash,
policy: config,
analyticsPolicy: { version: 1, periodsPerYear: 252, annualRiskFreeRate: 0, benchmark: null },
build: await readCanonicalBuildIdentity(),
modelArtifacts: [],
});
return { type: 'runRetainedStrategy' as const, request, dataset };
}
function retainedSource(request: CanonicalRunRequest, source: string) {
request.strategy.package.artifact.content = source;
request.strategy.package.artifact.sha256 = sha(source);
}
async function execute(value: Awaited<ReturnType<typeof input>>) {
const raw = await new NativeBacktestWorker().execute(
value,
new AbortController().signal,
() => {}
);
return { raw, result: parseRetainedStrategyResult(raw, value.request) };
}
describe('retained canonical strategy worker', () => {
test.each(['sma_crossover', 'mean_reversion'])(
'%s exact packaged bytes match the native report and repeat identically',
async strategyId => {
const value = await input(strategyId);
const load = prepareReplayLoad(value.dataset, value.request.policy);
const direct = runStrategyReplay(
load,
[createBuiltinStrategy(value.request.strategy.selection)],
{
resultFormat: 'report',
}
).result;
const expected = buildCanonicalBacktestReport(direct, value.request.analyticsPolicy);
const first = await execute(value);
expect(first.result.financial).toEqual(expected.financial);
expect(first.result.analytics).toEqual(expected.analytics);
expect(first.result.build).toEqual(value.request.build);
expect(first.result.artifactHash).toBe(value.request.strategy.package.artifact.sha256);
expect((await execute(value)).raw).toBe(first.raw);
}
);
test('a retained version executes its own bytes when the current constructor differs', async () => {
const value = await input();
const current = runStrategyReplay(
prepareReplayLoad(value.dataset, value.request.policy),
[createBuiltinStrategy(value.request.strategy.selection)],
{ resultFormat: 'report' }
).result;
expect(current.projection.fills.length).toBeGreaterThan(0);
// An earlier retained implementation that holds cash, with the same author API.
retainedSource(
value.request,
`export function createSmaStrategy(selection) {
return { ownerId:selection.ownerId, strategyId:selection.strategyId,
strategyVersion:selection.strategyVersion, seed:selection.seed, mode:'target',
initialState:{draws:0}, decide(context) { context.random();
return {nextState:{draws:context.state.draws+1}, intent:{mode:'target',targets:[]}}; }
};
}`
);
const first = await execute(value);
expect(first.result.financial.projection.fills).toEqual([]);
expect(first.result.financial.projection.valuation.equity).toBe(parseFinancialDecimal('10000'));
expect(first.result.analytics.metrics.exposureTime).toBe(0);
expect(first.result.analytics.metrics.roundTripCount).toBeNull();
expect((await execute(value)).raw).toBe(first.raw);
});
test('build and retained hashes are checked before module or factory side effects', async () => {
for (const changed of [
'workerSha256',
'engineWrapperSha256',
'engineBinarySha256',
'dependencyLockSha256',
'runtimeVersion',
'platform',
'arch',
] as const) {
const value = await input();
retainedSource(value.request, 'throw new Error("RETAINED_MODULE_EXECUTED");');
value.request.build[changed] = changed.endsWith('Sha256') ? 'f'.repeat(64) : 'wrong-build';
await expect(execute(value)).rejects.toThrow('build identity mismatch');
}
for (const changed of ['artifact', 'dependencyLock'] as const) {
const value = await input();
retainedSource(value.request, 'throw new Error("RETAINED_MODULE_EXECUTED");');
value.request.strategy.package[changed].sha256 = 'f'.repeat(64);
await expect(execute(value)).rejects.toThrow('artifact or dependency lock hash mismatch');
}
const verified = await input();
retainedSource(verified.request, 'throw new Error("RETAINED_MODULE_EXECUTED");');
await expect(execute(verified)).rejects.toThrow('RETAINED_MODULE_EXECUTED');
});
test('eligible exact single-series data and ownership are required before bundle import', async () => {
const value = await input();
retainedSource(value.request, 'throw new Error("RETAINED_MODULE_EXECUTED");');
const corrupt = {
...value,
dataset: {
manifest: structuredClone(value.dataset.manifest),
bars: value.dataset.bars.map(bar => ({ ...bar })),
},
};
corrupt.dataset.bars[0]!.volume += 1;
await expect(execute(corrupt)).rejects.toThrow('Dataset v2');
const other = nativeReplayFixture(24, 2, [ownerId]).dataset;
value.request.datasetHash = other.manifest.hash;
await expect(
new NativeBacktestWorker().execute(
{ ...value, dataset: other },
new AbortController().signal,
() => {}
)
).rejects.toThrow('Execution series must exactly match');
const candidate = await input();
expect(() =>
nativeWorkerRequestSchema.parse({
...candidate,
request: {
...candidate.request,
strategy: { ...candidate.request.strategy, origin: 'candidate' },
},
})
).toThrow();
const owners = await input();
owners.request.policy.matching.risk.ledger.ownerIds.push('second-owner');
await expect(execute(owners)).rejects.toThrow('single-asset');
});
test('factory identity, missing exports, thrown decisions and no-result exits fail closed', async () => {
for (const [source, reason] of [
['export const somethingElse = 1;', 'factory export is missing'],
['export function createSmaStrategy() { return {}; }', 'factory identity or API mismatch'],
[
'export function createSmaStrategy(selection) { selection.seed = 99; return {}; }',
'readonly',
],
['process.exit(0);', 'exited without a result'],
[
'export function createSmaStrategy() { throw new Error("bad retained factory"); }',
'bad retained factory',
],
[
'export function createSmaStrategy(selection) { return { ...selection, mode:"target", initialState:null, decide() { throw new Error("bad retained decision"); } }; }',
'bad retained decision',
],
]) {
const value = await input();
retainedSource(value.request, source!);
await expect(execute(value)).rejects.toThrow(reason!);
}
});
test('capture detaches all admitted inputs before the caller can mutate them', async () => {
const value = structuredClone(await input());
const captured = structuredClone(value.request);
const running = new NativeBacktestWorker().execute(
value,
new AbortController().signal,
() => {}
);
value.request.strategy.package.artifact.content = 'throw new Error("mutated");';
value.request.strategy.selection.seed = 222;
value.request.build.engineBinarySha256 = 'f'.repeat(64);
(value.dataset.bars as unknown[]).length = 0;
const result = parseRetainedStrategyResult(await running, captured);
expect(result.artifactHash).toBe(captured.strategy.package.artifact.sha256);
expect(result.financial.projection.fills.length).toBeGreaterThan(0);
});
test('result parser rejects false identity, policy and statistical claims', async () => {
const value = await input();
const { raw } = await execute(value);
for (const mutate of [
(result: ReturnType<typeof JSON.parse>) => {
result.type = 'strategyReplayResult';
},
(result: ReturnType<typeof JSON.parse>) => {
result.version = 2;
},
(result: ReturnType<typeof JSON.parse>) => {
result.artifactHash = 'f'.repeat(64);
},
(result: ReturnType<typeof JSON.parse>) => {
result.build.workerSha256 = 'f'.repeat(64);
},
(result: ReturnType<typeof JSON.parse>) => {
result.financial.identity.sessionId = 'wrong';
},
(result: ReturnType<typeof JSON.parse>) => {
result.financial.identity.datasetHash = 'f'.repeat(64);
},
(result: ReturnType<typeof JSON.parse>) => {
result.financial.policy.matching.risk.feeRate = '0';
},
(result: ReturnType<typeof JSON.parse>) => {
result.analytics.metrics.exposureTime = null;
},
(result: ReturnType<typeof JSON.parse>) => {
result.analytics.metrics.roundTripCount = 0;
},
(result: ReturnType<typeof JSON.parse>) => {
result.analytics.policy.periodsPerYear = 365;
},
]) {
const result = JSON.parse(raw);
mutate(result);
expect(() => parseRetainedStrategyResult(JSON.stringify(result), value.request)).toThrow();
}
});
test('alternate and source workers cannot claim the bundled worker identity', async () => {
const value = await input();
const sourceUrl = new URL(
'../../apps/stock/orchestrator/src/backtest/native-worker.ts',
import.meta.url
);
await expect(
new NativeBacktestWorker(sourceUrl).execute(value, new AbortController().signal, () => {})
).rejects.toThrow('canonical bundled worker');
expect(
await new NativeBacktestWorker(canonicalWorkerUrl).execute(
value,
new AbortController().signal,
() => {}
)
).toContain('retainedStrategyResult');
// Bypass the supervisor to test the source child's independent own-file check.
const messages = await new Promise<{ type: string; message?: string }[]>((resolve, reject) => {
const child = fork(fileURLToPath(sourceUrl), [], {
execPath: process.execPath,
execArgv: [],
serialization: 'json',
stdio: ['ignore', 'ignore', 'pipe', 'ipc'],
});
const received: { type: string; message?: string }[] = [];
const timer = setTimeout(() => {
child.kill('SIGKILL');
reject(new Error('Source worker timeout'));
}, 5000);
child.stderr?.resume();
child.on('message', message => received.push(message as { type: string; message?: string }));
child.on('error', reject);
child.on('close', () => {
clearTimeout(timer);
resolve(received);
});
child.send(value);
});
expect(messages).toEqual([
{
type: 'error',
message: 'Canonical research requires the bundled worker from this checkout',
},
]);
});
test('hard cancellation discards retained execution and the worker can be reused', async () => {
const value = await input();
const worker = new NativeBacktestWorker();
const abort = new AbortController();
await expect(
worker.execute(value, abort.signal, () => abort.abort(new Error('cancel retained replay')))
).rejects.toThrow('cancel retained replay');
expect(
JSON.parse(await worker.execute(value, new AbortController().signal, () => {})).type
).toBe('retainedStrategyResult');
});
});

View file

@ -953,7 +953,7 @@ describe('strategy workbench', () => {
await flush(() => {
void latest.createRun(null);
});
expect(latest.submissionError).toContain('save-only');
expect(latest.submissionError).toContain('configure a supported canonical dataset');
expect(requests.some(item => item.method === 'POST')).toBe(false);
let cancelled = false;
await flush(() =>

View file

@ -0,0 +1,368 @@
import { randomUUID } from 'node:crypto';
import { readFileSync } from 'node:fs';
import { afterEach, describe, expect, test } from 'bun:test';
import { Pool } from 'pg';
import { getLogger, setLoggerConfig } from '@stock-bot/logger';
import { PostgreSQLClient } from '@stock-bot/postgres';
import type { Queue } from '@stock-bot/services';
import { parseBacktestRequest } from '@stock-bot/stock-config/backtest';
import {
canonicalRunRequestSchema,
type CanonicalRunResult,
} from '@stock-bot/stock-config/canonical-research';
import { BacktestRunner } from '../../apps/stock/orchestrator/src/backtest/BacktestRunner';
import { readCanonicalBuildIdentity } from '../../apps/stock/orchestrator/src/backtest/canonical-build';
import { BacktestCancelledError } from '../../apps/stock/orchestrator/src/backtest/execution-engine';
import { PostgresBacktestRunRepository } from '../../apps/stock/orchestrator/src/backtest/PostgresBacktestRunRepository';
import { BacktestLeaseLostError } from '../../apps/stock/orchestrator/src/backtest/run-repository';
import { RustBacktestAdapter } from '../../apps/stock/orchestrator/src/backtest/RustBacktestAdapter';
import { BacktestDispatcher } from '../../apps/stock/web-api/src/services/BacktestDispatcher';
import { packageBuiltinStrategies } from '../../scripts/package-builtin-strategies';
import { canonicalSmaFixture } from '../fixtures/canonical-sma';
setLoggerConfig({ logLevel: 'fatal', logConsole: false });
const logger = getLogger('canonical-durable-test');
const url = process.env.PIPELINE_TEST_DATABASE_URL;
const cleanup: (() => Promise<void>)[] = [];
afterEach(async () => {
for (const close of cleanup.splice(0).reverse()) {
await close();
}
});
let packages: ReturnType<typeof packageBuiltinStrategies> | undefined;
async function fixture(options: { corruptDataset?: boolean; buildMismatch?: boolean } = {}) {
if (!url || !new URL(url).pathname.startsWith('/stock_bot_safety')) {
throw new Error('Dedicated stock_bot_safety PostgreSQL required');
}
const schema = `stock_bot_safety_canonical_${randomUUID().replaceAll('-', '')}`;
const admin = new Pool({ connectionString: url });
await admin.query(`CREATE SCHEMA ${schema}`);
const pool = new Pool({ connectionString: url, options: `-c search_path=${schema}` });
cleanup.push(async () => {
await pool.end();
await admin.query(`DROP SCHEMA ${schema} CASCADE`);
await admin.end();
});
await pool.query(`CREATE TYPE run_status AS ENUM ('pending','running','completed','failed','cancelled','paused');
CREATE TABLE backtests (id uuid PRIMARY KEY,name text NOT NULL,strategy text NOT NULL,symbols jsonb NOT NULL,
start_date timestamptz NOT NULL,end_date timestamptz NOT NULL,initial_capital numeric NOT NULL,config jsonb,
created_at timestamptz DEFAULT NOW(),updated_at timestamptz DEFAULT NOW());
CREATE TABLE runs (id uuid PRIMARY KEY,backtest_id uuid REFERENCES backtests(id),run_number integer,
status run_status DEFAULT 'pending',speed_multiplier numeric,progress numeric DEFAULT 0,error text,
started_at timestamptz,completed_at timestamptz,paused_at timestamptz,current_simulation_date timestamptz,
created_at timestamptz DEFAULT NOW(),updated_at timestamptz DEFAULT NOW(),UNIQUE(backtest_id,run_number));
CREATE TABLE backtest_results(run_id uuid REFERENCES runs(id),completed_at timestamptz,
metrics jsonb NOT NULL,equity_curve jsonb NOT NULL,ohlc_data jsonb NOT NULL,trades jsonb NOT NULL,positions jsonb NOT NULL,analytics jsonb NOT NULL,execution_time integer);`);
for (const filename of [
'09-backtest-run-contract.sql',
'10-durable-backtest-dispatch.sql',
'12-historical-datasets.sql',
'14-backtest-submission.sql',
'16-strategy-catalog.sql',
'17-research-retention.sql',
'18-backtest-strategy-versions.sql',
'19-canonical-research.sql',
]) {
await pool.query(
readFileSync(new URL(`../../database/postgres/init/${filename}`, import.meta.url), 'utf8')
);
}
const postgres = new PostgreSQLClient(
{ host: 'unused', port: 5432, database: 'unused', username: 'unused', password: 'unused' },
logger
);
Object.defineProperty(postgres, 'connectionPool', { get: () => pool });
Object.defineProperty(postgres, 'query', { value: pool.query.bind(pool) });
const versionId = randomUUID(),
familyId = randomUUID(),
reviewId = randomUUID(),
runId = randomUUID(),
backtestId = randomUUID();
const oracle = canonicalSmaFixture([`strategy:${versionId}`]);
oracle.config.matching.risk.ledger.sessionId = runId;
oracle.config.matching.risk.ledger.accountId = `research:${runId}`;
const pkg = (await (packages ??= packageBuiltinStrategies())).find(
p => p.program.strategyId === 'sma_crossover'
)!;
const build = await readCanonicalBuildIdentity();
if (options.buildMismatch) {
build.workerSha256 = '0'.repeat(64);
}
const request = canonicalRunRequestSchema.parse({
kind: 'canonical-research/v1',
runId,
backtestId,
name: 'Retained canonical oracle',
strategy: {
familyId,
versionId,
reviewId,
origin: 'builtin',
package: pkg,
selection: oracle.selections[0],
},
datasetHash: oracle.dataset.manifest.hash,
policy: oracle.config,
analyticsPolicy: { version: 1, periodsPerYear: 252, annualRiskFreeRate: 0, benchmark: null },
build,
modelArtifacts: [],
});
const payload = {
...oracle.dataset,
bars: oracle.dataset.bars.map((bar, i) => ({
...bar,
...(options.corruptDataset && i === 0 ? { close: 999 } : {}),
})),
};
await pool.query(
`INSERT INTO strategies(id,name,owner_principal,updated_by,builtin_key) VALUES ($1,'Fixture','operator','operator','sma_crossover')`,
[familyId]
);
await pool.query(
`INSERT INTO strategy_versions(id,strategy_id,ordinal,envelope,created_by,origin,submission_key,submission_fingerprint)
VALUES ($1,$2,1,$3,'operator','builtin',$4,$5)`,
[versionId, familyId, pkg, randomUUID(), 'a'.repeat(64)]
);
await pool.query(
`INSERT INTO strategy_review_events(id,version_id,ordinal,decision,actor,reason) VALUES ($1,$2,1,'approve','operator','fixture')`,
[reviewId, versionId]
);
await pool.query(`INSERT INTO backtest_datasets(hash,payload) VALUES ($1,$2)`, [
request.datasetHash,
payload,
]);
await pool.query(
`INSERT INTO backtests(id,name,strategy,symbols,start_date,end_date,initial_capital,config,strategy_version_id,strategy_parameters)
VALUES ($1,$2,'catalog',$3,$4,$5,10000,'{}',$6,$7)`,
[
backtestId,
request.name,
JSON.stringify(['X0.US']),
new Date(oracle.dataset.manifest.bounds.tradeStart),
new Date(oracle.dataset.manifest.bounds.tradeEnd),
versionId,
request.strategy.selection.parameters,
]
);
const admit = async () => {
await pool.query(
`INSERT INTO runs(id,backtest_id,run_number,status,request_snapshot,dataset_hash) VALUES ($1,$2,1,'pending',$3,$4)`,
[runId, backtestId, request, request.datasetHash]
);
await pool.query('INSERT INTO backtest_dispatch(run_id) VALUES ($1)', [runId]);
};
const repository = new PostgresBacktestRunRepository(postgres, 5000);
const storage = {
async getHistoricalBars(): Promise<never> {
throw new Error('Canonical replay must never fetch provider data');
},
};
const engine = new RustBacktestAdapter({ logger, storage }, { timeoutMs: 10000 });
const runner = new BacktestRunner({
engine,
repository,
engineName: 'native',
logger,
heartbeatMs: 20,
});
const dispatcher = new BacktestDispatcher(
postgres,
{
async add() {
return {} as Awaited<ReturnType<Queue['add']>>;
},
},
logger,
{ intervalMs: 20, republishMs: 20, maxAttempts: 3 }
);
cleanup.push(() => runner.shutdown());
cleanup.push(() => dispatcher.shutdown());
const row = async () => (await pool.query('SELECT * FROM runs WHERE id=$1', [runId])).rows[0];
const saved = async () =>
(await pool.query('SELECT * FROM backtest_results WHERE run_id=$1', [runId])).rows[0];
return {
pool,
repository,
engine,
runner,
dispatcher,
request,
dataset: oracle.dataset,
admit,
row,
saved,
};
}
(url ? describe : describe.skip)('retained canonical durable PostgreSQL execution', () => {
test('only a matching admitted canonical snapshot can be claimed', async () => {
const f = await fixture();
await expect(f.repository.startCanonical(f.request)).rejects.toThrow('missing');
expect((await f.pool.query('SELECT * FROM runs')).rowCount).toBe(0);
const raw = {
...parseBacktestRequest({
mode: 'backtest',
strategy: 'sma-crossover',
symbols: ['X.US'],
startDate: '2024-01-01T00:00:00.000Z',
endDate: '2024-02-01T00:00:00.000Z',
initialCapital: 10000,
dataFrequency: '1d',
}),
kind: 'canonical-research/v999',
};
await expect(f.repository.start(raw)).rejects.toThrow('Retained strategy versions');
expect((await f.pool.query('SELECT * FROM runs')).rowCount).toBe(0);
await f.admit();
await expect(f.repository.startCanonical({ ...f.request, name: 'different' })).rejects.toThrow(
'snapshot'
);
expect((await f.row()).attempt_number).toBe(0);
const claim = await f.repository.startCanonical(f.request);
expect(claim.config).toEqual(f.request);
await expect(f.repository.startCanonical(f.request)).rejects.toThrow('claimed');
});
test('retained worker result survives template edits/archive and approval revocation; terminal replay is an acknowledgement', async () => {
const f = await fixture();
await f.admit();
await f.pool.query(
`UPDATE backtests SET name='edited',strategy_parameters='{"fastPeriod":3,"slowPeriod":8}',archived_at=NOW() WHERE id=$1`,
[f.request.backtestId]
);
await f.pool.query(
`INSERT INTO strategy_review_events(id,version_id,ordinal,decision,actor,reason) VALUES ($1,$2,2,'revoke','operator','later')`,
[randomUUID(), f.request.strategy.versionId]
);
expect(await f.runner.runQueued(f.request.runId)).toEqual({
runId: f.request.runId,
status: 'completed',
});
const row = await f.saved(),
result = row.canonical_result as CanonicalRunResult;
expect(result.request).toEqual(f.request);
expect(String(result.financial.projection.valuation.equity)).toBe('9969.30000000');
expect(result.financial.projection.fills).toHaveLength(2);
expect(result.financial.projection.fills.map(fill => String(fill.fee.amount))).toEqual([
'0.50000000',
'0.20000000',
]);
for (const key of [
'metrics',
'equity_curve',
'trades',
'positions',
'analytics',
'configuration',
'engine',
]) {
expect(row[key]).toBeNull();
}
const legacyNulls = (
await f.pool.query(
`SELECT metrics IS NOT NULL AND metrics='null'::jsonb AS absent_projection FROM backtest_results WHERE run_id=$1`,
[f.request.runId]
)
).rows[0];
expect(legacyNulls.absent_projection).toBe(true);
await f.runner.runQueued(f.request.runId);
expect((await f.row()).attempt_number).toBe(1);
expect((await f.pool.query('SELECT * FROM backtest_results')).rowCount).toBe(1);
await expect(
f.pool.query(`UPDATE backtest_results SET canonical_result='{}' WHERE run_id=$1`, [
f.request.runId,
])
).rejects.toThrow('Retained');
});
test('expired owner is fenced and replacement reuses the identical snapshot and dataset', async () => {
const f = await fixture();
await f.admit();
const old = await f.repository.startCanonical(f.request);
expect(
await f.repository.loadCanonicalDataset(old.runId, old.attemptId, f.request.datasetHash)
).toEqual(f.dataset);
const baseline = await f.engine.runCanonical(f.request, async () => f.dataset);
await f.pool.query(
`UPDATE runs SET lease_expires_at=clock_timestamp()-INTERVAL '1 second' WHERE id=$1`,
[old.runId]
);
await f.dispatcher.tick();
expect((await f.row()).status).toBe('pending');
const replacement = await f.repository.startCanonical(f.request);
const result: CanonicalRunResult = {
kind: 'canonical-result/v1',
runId: f.request.runId,
backtestId: f.request.backtestId,
status: 'completed',
completedAt: new Date().toISOString(),
executionTime: 1,
financialEngine: 'rust',
strategyExecution: 'typescript-retained-builtin/v1',
request: f.request,
...baseline,
};
await expect(
f.repository.loadCanonicalDataset(old.runId, old.attemptId, f.request.datasetHash)
).rejects.toBeInstanceOf(BacktestLeaseLostError);
await expect(f.repository.completeCanonical(result, old.attemptId)).rejects.toBeInstanceOf(
BacktestLeaseLostError
);
const repeated = await f.engine.runCanonical(replacement.config, signal =>
f.repository.loadCanonicalDataset(
replacement.runId,
replacement.attemptId,
replacement.config.datasetHash,
signal
)
);
expect(repeated).toEqual(baseline);
await f.repository.completeCanonical({ ...result, ...repeated }, replacement.attemptId);
expect((await f.row()).attempt_number).toBe(2);
expect((await f.saved()).canonical_result.financial).toEqual(baseline.financial);
});
test('cancellation wins against late canonical completion without a partial result', async () => {
const f = await fixture();
await f.admit();
const claim = await f.repository.startCanonical(f.request);
const report = await f.engine.runCanonical(f.request, async () => f.dataset);
await f.pool.query('UPDATE runs SET cancel_requested=true WHERE id=$1', [claim.runId]);
const result: CanonicalRunResult = {
kind: 'canonical-result/v1',
runId: f.request.runId,
backtestId: f.request.backtestId,
status: 'completed',
completedAt: new Date().toISOString(),
executionTime: 1,
financialEngine: 'rust',
strategyExecution: 'typescript-retained-builtin/v1',
request: f.request,
...report,
};
await expect(f.repository.completeCanonical(result, claim.attemptId)).rejects.toBeInstanceOf(
BacktestCancelledError
);
expect(await f.saved()).toBeUndefined();
await f.repository.cancel(claim.runId, claim.attemptId);
expect((await f.row()).status).toBe('cancelled');
});
test('a failed canonical result insert rolls back terminal completion and records failure', async () => {
const f = await fixture();
await f.admit();
await f.pool.query(
`ALTER TABLE backtest_results ADD CONSTRAINT injected_result_failure CHECK (canonical_result IS NULL)`
);
await expect(f.runner.runQueued(f.request.runId)).rejects.toThrow('injected_result_failure');
expect((await f.row()).status).toBe('failed');
expect(await f.saved()).toBeUndefined();
});
for (const defect of ['corruptDataset', 'buildMismatch'] as const) {
test(`${defect} fails closed without provider fallback or result`, async () => {
const f = await fixture({ [defect]: true });
await f.admit();
await expect(f.runner.runQueued(f.request.runId)).rejects.toThrow();
expect((await f.row()).status).toBe('failed');
expect(await f.saved()).toBeUndefined();
expect((await f.row()).request_snapshot).toEqual(f.request);
expect((await f.row()).dataset_hash).toBe(f.request.datasetHash);
});
}
});

View file

@ -0,0 +1,424 @@
import { randomUUID } from 'node:crypto';
import { readFileSync } from 'node:fs';
import { afterEach, describe, expect, test } from 'bun:test';
import { Hono } from 'hono';
import { Pool } from 'pg';
import { getLogger, setLoggerConfig } from '@stock-bot/logger';
import { PostgreSQLClient } from '@stock-bot/postgres';
import {
canonicalResearchSettingsSchema,
canonicalRunRequestSchema,
} from '@stock-bot/stock-config/canonical-research';
import { BacktestRunner } from '../../apps/stock/orchestrator/src/backtest/BacktestRunner';
import { PostgresBacktestRunRepository } from '../../apps/stock/orchestrator/src/backtest/PostgresBacktestRunRepository';
import { RustBacktestAdapter } from '../../apps/stock/orchestrator/src/backtest/RustBacktestAdapter';
import { createDatasetV2 } from '../../apps/stock/orchestrator/src/data/historical-dataset-v2';
import { createBacktestV2Routes } from '../../apps/stock/web-api/src/routes/backtests-v2.routes';
import { BacktestServiceV2 } from '../../apps/stock/web-api/src/services/backtest-v2.service';
import { StrategyCatalogService } from '../../apps/stock/web-api/src/services/strategy-catalog.service';
import { retainResearchDataset } from '../../scripts/import-research-dataset';
import { packageBuiltinStrategies } from '../../scripts/package-builtin-strategies';
import { canonicalDailyDataset, canonicalSettings } from '../fixtures/canonical-research';
import { canonicalSmaFixture } from '../fixtures/canonical-sma';
import { nativeReplayFixture } from '../fixtures/native-replay';
setLoggerConfig({ logLevel: 'fatal', logConsole: false });
const logger = getLogger('canonical-admission');
const url = process.env.PIPELINE_TEST_DATABASE_URL;
const cleanup: (() => Promise<void>)[] = [];
let packages: ReturnType<typeof packageBuiltinStrategies> | undefined;
afterEach(async () => {
for (const close of cleanup.splice(0).reverse()) {
await close();
}
});
async function fixture(dataset = canonicalSmaFixture().dataset) {
if (!url || !new URL(url).pathname.startsWith('/stock_bot_safety')) {
throw new Error('Disposable safety database required');
}
const schema = 'stock_bot_safety_canonical_api_' + randomUUID().replaceAll('-', '');
const admin = new Pool({ connectionString: url });
await admin.query(`CREATE SCHEMA ${schema}`);
const pool = new Pool({
connectionString: url,
application_name: schema,
options: `-c search_path=${schema} -c statement_timeout=10000`,
});
cleanup.push(async () => {
await pool.end();
await admin.query(`DROP SCHEMA ${schema} CASCADE`);
await admin.end();
});
for (const name of [
'06-create-backtest-tables.sql',
'07-fix-execution-time-type.sql',
'08-create-runs-table.sql',
'09-backtest-run-contract.sql',
'10-durable-backtest-dispatch.sql',
'12-historical-datasets.sql',
'14-backtest-submission.sql',
'16-strategy-catalog.sql',
'17-research-retention.sql',
'18-backtest-strategy-versions.sql',
'19-canonical-research.sql',
]) {
await pool.query(
readFileSync(new URL(`../../database/postgres/init/${name}`, import.meta.url), 'utf8')
);
}
const postgres = new PostgreSQLClient(
{ host: 'unused', port: 5432, database: 'unused', username: 'unused', password: 'unused' },
logger
);
Object.defineProperty(postgres, 'connectionPool', { get: () => pool });
Object.defineProperty(postgres, 'query', { value: pool.query.bind(pool) });
const container = { postgres, logger };
const api = new BacktestServiceV2(container);
const catalog = new StrategyCatalogService(container);
const pkg = (await (packages ??= packageBuiltinStrategies()))[0]!;
const version = await catalog.seedBuiltin('Retained SMA', pkg, 'seed');
await retainResearchDataset(pool, dataset);
const definition = {
name: 'Canonical API',
strategy: 'catalog',
strategyVersionId: version.id,
strategyParameters: { fastPeriod: 2, slowPeriod: 3 },
symbols: dataset.manifest.executionSeries.map(s => s.instrumentId),
startDate: new Date(dataset.manifest.bounds.tradeStart).toISOString(),
endDate: new Date(dataset.manifest.bounds.tradeEnd).toISOString(),
initialCapital: 10000,
config: {
datasetHash: dataset.manifest.hash,
dataFrequency: dataset.manifest.series[0]!.interval,
canonical: canonicalSettings,
},
};
const draft = await api.createBacktest(definition, { autoStart: false });
const approve = () =>
catalog.reviewVersion(
version.id,
{ decision: 'approve', reason: 'Reviewed retained builtin' },
'operator'
);
const execute = async (id: string) => {
const engine = new RustBacktestAdapter({
logger,
storage: {
async getHistoricalBars() {
throw new Error('Canonical execution must never load provider data');
},
},
});
const runner = new BacktestRunner({
engine,
engineName: 'native',
repository: new PostgresBacktestRunRepository(postgres),
logger,
});
try {
await runner.runQueued(id);
} finally {
await runner.shutdown();
}
};
return {
pool,
schema,
api,
catalog,
pkg,
version,
draft,
definition,
dataset,
approve,
execute,
app: new Hono().route('/', createBacktestV2Routes(container)),
};
}
describe.skipIf(!url)('canonical research admission and saved evidence', () => {
test('approved exact artifact/policy/dataset admission, receipt replay and native results survive template and review changes', async () => {
const f = await fixture();
expect((await f.api.canonicalCapability(f.draft.id)).available).toBe(false);
await expect(f.api.createRun({ backtestId: f.draft.id })).rejects.toThrow('approve');
expect((await f.pool.query('SELECT * FROM runs')).rowCount).toBe(0);
await f.approve();
expect(await f.api.canonicalCapability(f.draft.id)).toEqual({ available: true, reason: null });
const receipt = { principal: 'operator' as const, key: 'original' };
const run = await f.api.createRun({ backtestId: f.draft.id }, receipt);
const frozen = (
await f.pool.query('SELECT request_snapshot,dataset_hash FROM runs WHERE id=$1', [run.id])
).rows[0];
const request = canonicalRunRequestSchema.parse(frozen.request_snapshot);
expect(request.strategy.package).toEqual(f.pkg);
expect(request.datasetHash).toBe(f.dataset.manifest.hash);
expect(frozen.dataset_hash).toBe(request.datasetHash);
expect(run.dataset.state).toBe('pinned');
expect(String(request.policy.matching.risk.ledger.initialCapital)).toBe('10000.00000000');
await f.api.updateBacktest(f.draft.id, {
name: 'Changed',
strategyParameters: { fastPeriod: 3, slowPeriod: 5 },
});
await f.catalog.reviewVersion(
f.version.id,
{ decision: 'revoke', reason: 'Block new admissions' },
'operator'
);
await f.api.archiveBacktest(f.draft.id, true);
expect((await f.api.createRun({ backtestId: f.draft.id }, receipt)).id).toBe(run.id);
await expect(f.api.createRun({ backtestId: f.draft.id })).rejects.toThrow('archived');
await f.execute(run.id);
const result = await f.api.getRunResults(run.id);
expect(result && 'kind' in result && result.kind).toBe('canonical-result/v1');
if (!result || !('kind' in result)) {
throw new Error('Missing canonical result');
}
expect(result.request).toEqual(request);
expect(String(result.financial.projection.valuation.equity)).toBe('9969.30000000');
expect(result.financial.projection.fills).toHaveLength(2);
expect(result.analytics.metrics.roundTripCount).toBeNull();
expect(result.analytics.unavailable.roundTripCount).toBe('unsupported-round-trips');
expect(await f.api.getRunResults(run.id)).toEqual(result);
expect((await f.pool.query('SELECT * FROM backtest_dispatch')).rowCount).toBe(1);
await expect(
f.pool.query('UPDATE backtest_results SET canonical_result=$1 WHERE run_id=$2', [{}, run.id])
).rejects.toThrow('Retained');
});
test('exact non-midnight daily bounds and retained DST account boundaries are frozen', async () => {
const f = await fixture(canonicalDailyDataset());
await f.approve();
const run = await f.api.createRun({ backtestId: f.draft.id });
const request = canonicalRunRequestSchema.parse(
(await f.pool.query('SELECT request_snapshot FROM runs WHERE id=$1', [run.id])).rows[0]
.request_snapshot
);
expect(request.policy.matching.risk.ledger.riskSession.startsAt).toBe(
Date.parse('2024-03-08T14:30:00Z')
);
expect(request.policy.risk_boundaries[0]?.startsAt).toBe(Date.parse('2024-03-11T13:30:00Z'));
expect((await f.api.getBacktest(f.draft.id))?.startDate.toISOString()).toBe(
'2024-03-11T13:30:00.000Z'
);
await expect(
f.api.updateBacktest(f.draft.id, { startDate: '2024-03-08T00:00:00Z' })
).rejects.toThrow('exact trade bounds');
await f.execute(run.id);
const result = await f.api.getRunResults(run.id);
if (!result || !('kind' in result)) {
throw new Error('Missing canonical result');
}
expect(result.analytics.metrics.exposureTime).toBe(0);
expect(result.analytics.metrics.totalReturn).toBe(0);
});
test('candidates, legacy settings, wrong asset/timeframe, multi-asset datasets and pacing never admit work', async () => {
const f = await fixture();
await f.approve();
const clone = await f.catalog.cloneVersion(
f.version.id,
{ name: 'Candidate' },
'operator',
'candidate'
);
await f.catalog.reviewVersion(
clone.version.id,
{ decision: 'approve', reason: 'Still untrusted' },
'operator'
);
const candidate = await f.api.createBacktest(
{ ...f.definition, strategyVersionId: clone.version.id },
{ autoStart: false }
);
await expect(f.api.createRun({ backtestId: candidate.id })).rejects.toThrow('candidates');
await expect(f.api.createRun({ backtestId: f.draft.id, speedMultiplier: 2 })).rejects.toThrow(
'maximum speed'
);
for (const change of [
{ symbols: ['Y.US'] },
{ config: { ...f.definition.config, commission: 0.1 } },
{ config: { ...f.definition.config, dataFrequency: '1d' } },
]) {
await expect(f.api.updateBacktest(f.draft.id, change)).rejects.toThrow();
}
const multi = nativeReplayFixture(5, 2).dataset;
await retainResearchDataset(f.pool, multi);
await expect(
f.api.updateBacktest(f.draft.id, {
config: { ...f.definition.config, datasetHash: multi.manifest.hash },
})
).rejects.toThrow('one execution asset');
expect((await f.pool.query('SELECT * FROM runs')).rowCount).toBe(0);
expect((await f.pool.query('SELECT * FROM backtest_dispatch')).rowCount).toBe(0);
});
test('offline import is repeat-safe and rejects corruption; direct SQL cannot bypass snapshot/version binding', async () => {
const f = await fixture();
await f.approve();
await retainResearchDataset(f.pool, f.dataset);
expect((await f.pool.query('SELECT * FROM backtest_datasets')).rowCount).toBe(1);
const changed = {
...f.dataset,
bars: f.dataset.bars.map((bar, index) => ({
...bar,
volume: bar.volume + (index === 0 ? 1 : 0),
})),
};
await expect(retainResearchDataset(f.pool, changed)).rejects.toThrow();
await expect(
f.pool.query('INSERT INTO runs(id,backtest_id,run_number) VALUES($1,$2,1)', [
randomUUID(),
f.draft.id,
])
).rejects.toThrow('canonical request');
const run = await f.api.createRun({ backtestId: f.draft.id });
const snapshot = (await f.pool.query('SELECT request_snapshot FROM runs WHERE id=$1', [run.id]))
.rows[0].request_snapshot;
const id = randomUUID();
snapshot.runId = id;
snapshot.strategy.package.artifact.content += '\n/* forged */';
await expect(
f.pool.query(
'INSERT INTO runs(id,backtest_id,run_number,request_snapshot,dataset_hash,speed_multiplier) VALUES($1,$2,2,$3,$4,NULL)',
[id, f.draft.id, snapshot, f.dataset.manifest.hash]
)
).rejects.toThrow('exact approved');
expect((await f.pool.query('SELECT * FROM runs')).rowCount).toBe(1);
});
test('extra series and malformed financial settings reject before saving or dispatching', async () => {
const f = await fixture();
await f.approve();
const { calendars, series, executionSeries, bounds, universe, corporateActions } =
f.dataset.manifest;
const extraId = 'X0.US:aux';
const extra = createDatasetV2({
metadata: {
calendars,
series: [...series, { ...series[0]!, id: extraId }],
executionSeries,
bounds,
universe,
corporateActions,
},
bars: f.dataset.bars.flatMap(
({
instrumentId: _instrument,
eventTime: _event,
intervalEnd: _end,
intervalStart,
...bar
}) => [
{ ...bar, timestamp: intervalStart },
{ ...bar, seriesId: extraId, timestamp: intervalStart },
]
),
});
await retainResearchDataset(f.pool, extra);
await expect(
f.api.updateBacktest(f.draft.id, {
config: { ...f.definition.config, datasetHash: extra.manifest.hash },
})
).rejects.toThrow('one retained series');
for (const change of [
{ config: { ...f.definition.config, canonical: { ...canonicalSettings, feeRate: '1e-3' } } },
{
config: { ...f.definition.config, canonical: { ...canonicalSettings, ownerBudget: 'wat' } },
},
{ initialCapital: 1e22 },
{
config: {
...f.definition.config,
canonical: { ...canonicalSettings, halfSpreadRate: '1' },
},
},
{
config: { ...f.definition.config, canonical: { ...canonicalSettings, slippageRate: '1' } },
},
]) {
const response = await f.app.request(`/api/v2/backtests/${f.draft.id}`, {
method: 'PUT',
headers: { 'content-type': 'application/json' },
body: JSON.stringify(change),
});
expect(response.status).toBe(400);
}
for (const key of ['halfSpreadRate', 'slippageRate'] as const) {
expect(
canonicalResearchSettingsSchema.safeParse({ ...canonicalSettings, [key]: '0.99999999' })
.success
).toBe(true);
}
expect((await f.api.getBacktest(f.draft.id))?.config).toEqual(f.draft.config);
expect((await f.pool.query('SELECT * FROM runs')).rowCount).toBe(0);
});
test('concurrent approval revocation and admission follow the same family lock in either ordering', async () => {
for (const revokeFirst of [true, false]) {
const f = await fixture();
await f.approve();
const held = await f.pool.connect();
await held.query('BEGIN');
await held.query('SELECT id FROM strategies WHERE id=$1 FOR UPDATE', [f.version.strategyId]);
const waiters = async (count: number) => {
const deadline = Date.now() + 5000;
while (Date.now() < deadline) {
const waiting = await f.pool.query(
"SELECT count(*)::int AS count FROM pg_stat_activity WHERE application_name=$1 AND wait_event_type='Lock'",
[f.schema]
);
if (waiting.rows[0].count >= count) {
return;
}
await Bun.sleep(10);
}
throw new Error('Expected family row lock waiters');
};
const revoke = () =>
f.catalog.reviewVersion(
f.version.id,
{ decision: 'revoke', reason: 'Concurrent review' },
'operator'
);
const admit = () => f.api.createRun({ backtestId: f.draft.id });
const first = (revokeFirst ? revoke() : admit()).then(
value => ({ value }),
error => ({ error })
);
try {
await waiters(1);
const second = (revokeFirst ? admit() : revoke()).then(
value => ({ value }),
error => ({ error })
);
await waiters(2);
await held.query('COMMIT');
const outcomes = await Promise.all([first, second]);
const admission = outcomes[revokeFirst ? 1 : 0]!;
const revocation = outcomes[revokeFirst ? 0 : 1]!;
expect('error' in revocation).toBe(false);
expect(
(
await f.pool.query(
'SELECT decision FROM strategy_review_events WHERE version_id=$1 ORDER BY ordinal DESC LIMIT 1',
[f.version.id]
)
).rows[0].decision
).toBe('revoke');
expect('error' in admission).toBe(revokeFirst);
if (revokeFirst && 'error' in admission) {
expect(String(admission.error)).toContain('approve');
}
expect((await f.pool.query('SELECT * FROM runs')).rowCount).toBe(revokeFirst ? 0 : 1);
if (!revokeFirst && 'value' in admission) {
await f.execute(admission.value.id);
expect((await f.api.getRun(admission.value.id))?.status).toBe('completed');
}
} finally {
await held.query('ROLLBACK');
held.release();
}
}
});
});

View file

@ -99,6 +99,7 @@ async function fixture() {
'16-strategy-catalog.sql',
'17-research-retention.sql',
'18-backtest-strategy-versions.sql',
'19-canonical-research.sql',
]) {
await pool.query(sql(name));
}

View file

@ -72,6 +72,7 @@ async function fixture() {
'16-strategy-catalog.sql',
'17-research-retention.sql',
'18-backtest-strategy-versions.sql',
'19-canonical-research.sql',
]) {
await pool.query(
readFileSync(new URL(`../../database/postgres/init/${name}`, import.meta.url), 'utf8')

View file

@ -83,6 +83,7 @@ async function fixture() {
'16-strategy-catalog.sql',
'17-research-retention.sql',
'18-backtest-strategy-versions.sql',
'19-canonical-research.sql',
]) {
await pool.query(
readFileSync(new URL(`../../database/postgres/init/${filename}`, import.meta.url), 'utf8')

View file

@ -21,6 +21,7 @@ const migrations = [
'16-strategy-catalog.sql',
'17-research-retention.sql',
'18-backtest-strategy-versions.sql',
'19-canonical-research.sql',
];
const cleanup: (() => Promise<void>)[] = [];
afterEach(async () => {

View file

@ -20,7 +20,11 @@ const cleanup: (() => Promise<void>)[] = [];
const sql = (name: string) =>
readFileSync(new URL(`../../database/postgres/init/${name}`, import.meta.url), 'utf8');
const retention =
sql('17-research-retention.sql') + '\n' + sql('18-backtest-strategy-versions.sql');
sql('17-research-retention.sql') +
'\n' +
sql('18-backtest-strategy-versions.sql') +
'\n' +
sql('19-canonical-research.sql');
const request = {
name: 'Retained evidence',
strategy: 'sma-crossover',

View file

@ -68,6 +68,7 @@ async function fixture() {
'16-strategy-catalog.sql',
'17-research-retention.sql',
'18-backtest-strategy-versions.sql',
'19-canonical-research.sql',
]) {
await pool.query(
readFileSync(new URL(`../../database/postgres/init/${filename}`, import.meta.url), 'utf8')

View file

@ -401,7 +401,7 @@ describe.skipIf(!url)('immutable strategy catalog on real PostgreSQL', () => {
reviewStatus: 'pending',
runnable: false,
});
expect(seeded[0]!.reason).toContain('R05');
expect(seeded[0]!.reason).toContain('approve');
expect(await f.api.listStrategies()).toHaveLength(1);
await expect(f.api.seedBuiltin('Fake builtin', candidate(), 'fake')).rejects.toMatchObject({
status: 400,