diff --git a/apps/stock/config/package.json b/apps/stock/config/package.json index decbf931..181c5ab4 100644 --- a/apps/stock/config/package.json +++ b/apps/stock/config/package.json @@ -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": { diff --git a/apps/stock/config/src/contracts/backtest.ts b/apps/stock/config/src/contracts/backtest.ts index 2bc5f4e8..911a3578 100644 --- a/apps/stock/config/src/contracts/backtest.ts +++ b/apps/stock/config/src/contracts/backtest.ts @@ -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; 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({ diff --git a/apps/stock/config/src/contracts/canonical-replay.ts b/apps/stock/config/src/contracts/canonical-replay.ts new file mode 100644 index 00000000..76439354 --- /dev/null +++ b/apps/stock/config/src/contracts/canonical-replay.ts @@ -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 = 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; +export type ReplayIdentity = z.infer; + +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; +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; +export type ReplayResult = z.infer; +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; +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; +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; +export type ReplayReportResult = z.infer; +export const replayResultFormatSchema = z.enum(['trace', 'projection', 'report']); +export type ReplayResultFormat = z.infer; +export type ReplayOutput = ReplayResult | ReplayProjectionResult | ReplayReportResult; +export type DecisionContext = Extract; +export type PublishedObservation = z.infer; + +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; diff --git a/apps/stock/config/src/contracts/canonical-research.ts b/apps/stock/config/src/contracts/canonical-research.ts new file mode 100644 index 00000000..76ca27e2 --- /dev/null +++ b/apps/stock/config/src/contracts/canonical-research.ts @@ -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 = 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; + +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; + +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; + +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 + ); +} diff --git a/apps/stock/orchestrator/src/backtest/BacktestRunner.ts b/apps/stock/orchestrator/src/backtest/BacktestRunner.ts index ce678c70..13d86a6f 100644 --- a/apps/stock/orchestrator/src/backtest/BacktestRunner.ts +++ b/apps/stock/orchestrator/src/backtest/BacktestRunner.ts @@ -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 = Promise.resolve(); private closing = false; private phase: 'preparing' | 'executing' | 'persisting' = 'preparing'; - private execution: Promise | undefined; + private execution: Promise | undefined; constructor( private readonly dependencies: { @@ -41,7 +58,13 @@ export class BacktestRunner extends EventEmitter { } async runBacktest(input: unknown): Promise { - const config = parseBacktestRequest(input); + return this.begin(parseBacktestRequest(input)); + } + + private begin(config: BacktestConfig): Promise; + private begin(config: CanonicalRunRequest): Promise; + private begin(config: DurableRequest): Promise; + private begin(config: DurableRequest): Promise { 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 { + private async execute(config: DurableRequest): Promise { const started = performance.now(); this.progressWrites = Promise.resolve(); let heartbeatTimer: ReturnType | 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; diff --git a/apps/stock/orchestrator/src/backtest/NativeBacktestWorker.ts b/apps/stock/orchestrator/src/backtest/NativeBacktestWorker.ts index 261dd7c8..c7f877ad 100644 --- a/apps/stock/orchestrator/src/backtest/NativeBacktestWorker.ts +++ b/apps/stock/orchestrator/src/backtest/NativeBacktestWorker.ts @@ -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) { diff --git a/apps/stock/orchestrator/src/backtest/PostgresBacktestRunRepository.ts b/apps/stock/orchestrator/src/backtest/PostgresBacktestRunRepository.ts index 19d08806..9f83746c 100644 --- a/apps/stock/orchestrator/src/backtest/PostgresBacktestRunRepository.ts +++ b/apps/stock/orchestrator/src/backtest/PostgresBacktestRunRepository.ts @@ -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 { + 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 { + 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 { 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, + 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 { + 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, diff --git a/apps/stock/orchestrator/src/backtest/RustBacktestAdapter.ts b/apps/stock/orchestrator/src/backtest/RustBacktestAdapter.ts index 6d280da7..94ad5200 100644 --- a/apps/stock/orchestrator/src/backtest/RustBacktestAdapter.ts +++ b/apps/stock/orchestrator/src/backtest/RustBacktestAdapter.ts @@ -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 { + 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 + ): Promise> { + 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( + initialTime: number, + work: (signal: AbortSignal, aborted: Promise) => Promise + ): Promise { 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; diff --git a/apps/stock/orchestrator/src/backtest/canonical-build.ts b/apps/stock/orchestrator/src/backtest/canonical-build.ts new file mode 100644 index 00000000..97987229 --- /dev/null +++ b/apps/stock/orchestrator/src/backtest/canonical-build.ts @@ -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 { + 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 { + 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 { + 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; +} diff --git a/apps/stock/orchestrator/src/backtest/execution-engine.ts b/apps/stock/orchestrator/src/backtest/execution-engine.ts index d79413b0..f6ed88ae 100644 --- a/apps/stock/orchestrator/src/backtest/execution-engine.ts +++ b/apps/stock/orchestrator/src/backtest/execution-engine.ts @@ -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; + runCanonical?( + request: CanonicalRunRequest, + resolveDataset: (signal: AbortSignal) => Promise + ): Promise>; stopBacktest(): Promise; pauseBacktest(): Promise; resumeBacktest(): Promise; diff --git a/apps/stock/orchestrator/src/backtest/native-worker-protocol.ts b/apps/stock/orchestrator/src/backtest/native-worker-protocol.ts index 27a891d9..eec75783 100644 --- a/apps/stock/orchestrator/src/backtest/native-worker-protocol.ts +++ b/apps/stock/orchestrator/src/backtest/native-worker-protocol.ts @@ -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() }), diff --git a/apps/stock/orchestrator/src/backtest/native-worker.ts b/apps/stock/orchestrator/src/backtest/native-worker.ts index 0ac4b591..e36a1a21 100644 --- a/apps/stock/orchestrator/src/backtest/native-worker.ts +++ b/apps/stock/orchestrator/src/backtest/native-worker.ts @@ -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 { 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; + 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); diff --git a/apps/stock/orchestrator/src/backtest/run-repository.ts b/apps/stock/orchestrator/src/backtest/run-repository.ts index c14f6b04..7b8b962a 100644 --- a/apps/stock/orchestrator/src/backtest/run-repository.ts +++ b/apps/stock/orchestrator/src/backtest/run-repository.ts @@ -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; + /** Only already admitted canonical rows may be claimed; no implicit creation. */ + startCanonical?(request: CanonicalRunRequest): Promise; + loadCanonicalDataset?( + runId: string, + attemptId: string, + requestedHash: string, + signal?: AbortSignal + ): Promise; + completeCanonical?(result: CanonicalRunResult, attemptId: string): Promise; load(runId: string): Promise<{ status: string; config: unknown } | null>; rejectPending(runId: string, error: string): Promise; heartbeat(runId: string, attemptId: string): Promise<{ cancelRequested: boolean }>; diff --git a/apps/stock/orchestrator/src/contracts/native-replay.ts b/apps/stock/orchestrator/src/contracts/native-replay.ts index 60457c21..e9ebce46 100644 --- a/apps/stock/orchestrator/src/contracts/native-replay.ts +++ b/apps/stock/orchestrator/src/contracts/native-replay.ts @@ -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; -export type ReplayIdentity = z.infer; - -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; -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; -export type ReplayResult = z.infer; -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; -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; -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; -export type ReplayReportResult = z.infer; -export const replayResultFormatSchema = z.enum(['trace', 'projection', 'report']); -export type ReplayResultFormat = z.infer; -export type ReplayOutput = ReplayResult | ReplayProjectionResult | ReplayReportResult; -export type DecisionContext = Extract; -export type PublishedObservation = z.infer; - -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; +/** Compatibility export: pure financial replay contracts are shared with research APIs. */ +export * from '@stock-bot/stock-config/canonical-replay'; diff --git a/apps/stock/web-api/src/migrations/migration-runner.ts b/apps/stock/web-api/src/migrations/migration-runner.ts index 423eec97..689f523e 100644 --- a/apps/stock/web-api/src/migrations/migration-runner.ts +++ b/apps/stock/web-api/src/migrations/migration-runner.ts @@ -58,7 +58,8 @@ export async function runMigrations(container: IServiceContainer): Promise 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(); diff --git a/apps/stock/web-api/src/routes/backtests-v2.routes.ts b/apps/stock/web-api/src/routes/backtests-v2.routes.ts index c63941c6..82fad44c 100644 --- a/apps/stock/web-api/src/routes/backtests-v2.routes.ts +++ b/apps/stock/web-api/src/routes/backtests-v2.routes.ts @@ -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(); diff --git a/apps/stock/web-api/src/routes/datasets.routes.ts b/apps/stock/web-api/src/routes/datasets.routes.ts index be1547eb..9ed8a53d 100644 --- a/apps/stock/web-api/src/routes/datasets.routes.ts +++ b/apps/stock/web-api/src/routes/datasets.routes.ts @@ -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'; diff --git a/apps/stock/web-api/src/services/backtest-v2.service.ts b/apps/stock/web-api/src/services/backtest-v2.service.ts index 543c1b41..1263dc51 100644 --- a/apps/stock/web-api/src/services/backtest-v2.service.ts +++ b/apps/stock/web-api/src/services/backtest-v2.service.ts @@ -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 + ); } - 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 { - const result = await this.container.postgres.query( + async getRunResults(runId: string): Promise { + 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 { + 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); diff --git a/apps/stock/web-api/src/services/canonical-research.service.ts b/apps/stock/web-api/src/services/canonical-research.service.ts new file mode 100644 index 00000000..2b087281 --- /dev/null +++ b/apps/stock/web-api/src/services/canonical-research.service.ts @@ -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 | null; + symbols: string[]; + startDate: string | Date; + endDate: string | Date; + initialCapital: number; + config?: Record; +} +const invalid = (message: string): never => { + throw new HistoricalDataRequestError(message); +}; + +export async function readCanonicalDataset( + database: DatasetCatalogQuery, + hash: unknown +): Promise { + 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 { + 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 { + 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: [], + }); +} diff --git a/apps/stock/web-api/src/services/strategy-catalog.service.ts b/apps/stock/web-api/src/services/strategy-catalog.service.ts index d767498b..be588c4b 100644 --- a/apps/stock/web-api/src/services/strategy-catalog.service.ts +++ b/apps/stock/web-api/src/services/strategy-catalog.service.ts @@ -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 {} diff --git a/apps/stock/web-app/src/features/backtest/BacktestDetailPageV2.tsx b/apps/stock/web-app/src/features/backtest/BacktestDetailPageV2.tsx index 3e612cb6..873fed04 100644 --- a/apps/stock/web-app/src/features/backtest/BacktestDetailPageV2.tsx +++ b/apps/stock/web-app/src/features/backtest/BacktestDetailPageV2.tsx @@ -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() {

Run History

+ + )} + + + )} ); case 'details': @@ -329,6 +369,9 @@ export function BacktestDetailPageV2() { ); } + if (runResults && isCanonicalRunResult(runResults)) { + return ; + } return (
); case 'trades': + if (runResults && isCanonicalRunResult(runResults)) { + return ; + } return (
@@ -443,7 +489,7 @@ export function BacktestDetailPageV2() { isSubmitting={isSubmitting} hasPendingSubmission={hasPendingSubmission} archived={archived} - executionUnavailable={catalog || unsupportedLegacy} + executionUnavailable={executionUnavailable} />
)} @@ -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)}{' '} + {backtest?.strategyVersionId && ( <> {' '} diff --git a/apps/stock/web-app/src/features/backtest/components/CanonicalResults.tsx b/apps/stock/web-app/src/features/backtest/components/CanonicalResults.tsx new file mode 100644 index 00000000..fd6150d7 --- /dev/null +++ b/apps/stock/web-app/src/features/backtest/components/CanonicalResults.tsx @@ -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 ; + } + return ( +
+
+

Canonical research result

+

+ Rust financial simulation · retained TypeScript built-in. Completion does not establish + strategy profitability or authorize trading. +

+
+
+
Run
+
{result.runId}
+
+
+
Strategy version
+
{request.strategy.versionId}
+
+
+
Dataset hash
+
{request.datasetHash}
+
+
+
Executed strategy artifact SHA256
+
{request.strategy.package.artifact.sha256}
+
+
+
Native engine SHA256
+
{request.build.engineBinarySha256}
+
+
+
Worker SHA256
+
{request.build.workerSha256}
+
+
+
Engine wrapper SHA256
+
{request.build.engineWrapperSha256}
+
+
+
Dependency lock SHA256
+
{request.build.dependencyLockSha256}
+
+
+
Financial / reporting versions
+
+ {financial.financialVersion} / {financial.reportingVersion} +
+
+
+
Runtime
+
+ {request.build.runtime} {request.build.runtimeVersion} · {request.build.platform}/ + {request.build.arch} +
+
+
+
+ Immutable configuration and reporting policy +
+            {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
+            )}
+          
+
+
    + {[...financial.limitations, ...financial.modelLimitations].map((limitation, index) => ( +
  • {limitation}
  • + ))} +
+
+
+

Authoritative terminal account ({currency})

+
+ {( + [ + 'cash', + 'markedHoldings', + 'equity', + 'remainingCost', + 'realizedGrossPnl', + 'unrealizedPnl', + 'fees', + ] as const + ).map(key => ( +
+
+ { + { + cash: 'Cash', + markedHoldings: 'Marked holdings', + equity: 'Equity', + remainingCost: 'Remaining cost', + realizedGrossPnl: 'Gross realized P&L', + unrealizedPnl: 'Unrealized P&L', + fees: 'Fees', + }[key] + } +
+
{valuation[key]}
+
+ ))} +
+

+ Decimal amounts come directly from Rust. Gross realized P&L excludes separately reported + fees. Holdings are valued using the last available marks. +

+
+
+

Canonical metrics

+

+ {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. +

+
+ {metricFields.map(field => { + const value = analytics.metrics[field.key]; + return ( +
+
{field.label}
+
+ {value === null + ? `Unavailable — ${reasonText(analytics.unavailable[field.key])}` + : field.percentage + ? `${(value * 100).toFixed(2)}%` + : value.toFixed(2)} +
+
+ ); + })} +
+

+ 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. +

+
+
+

Equity samples

+ + {showCurve && ( +
+ + ({ + timestamp: sample.timestamp, + equity: Number(sample.equity), + }))} + > + + + canonicalTime(Number(value))} /> + + + +

+ The plot uses approximate numbers; exact sampled equity remains in the table. +

+
+ )} +
+ + + + + + + + + + + {samples.map((sample, index) => ( + + + + + + + ))} + +
Timestamp (UTC)SampleEquity ({currency})Period
{canonicalTime(sample.timestamp)}{sample.label}{sample.equity} + {index === 0 ? 'Initial' : sample.partial ? 'Partial' : 'Complete'} +
+
+
+
+

Owner positions

+

+ These are owner books, not reconstructed round trips. Per-position marks, average prices + and unrealized P&L are unavailable in this report. +

+ {!financial.view.portfolio.positions.length ? ( +

No owner positions recorded.

+ ) : ( +
+ + + + {[ + 'Owner', + 'Asset', + 'Quantity', + `Remaining cost (${currency})`, + `Gross realized P&L (${currency})`, + ].map(label => ( + + ))} + + + + {financial.view.portfolio.positions.map(position => ( + + + + + + + + ))} + +
+ {label} +
{position.ownerId}{position.instrumentId}{position.quantity}{position.remainingCost}{position.realizedGrossPnl}
+
+ )} +

Owner valuations ({currency})

+
+ + + + {[ + 'Owner', + 'Initial allocation', + 'Marked holdings', + 'Remaining cost', + 'Gross realized P&L', + 'Unrealized P&L', + 'Fees', + 'Equity contribution', + ].map(label => ( + + ))} + + + + {valuation.owners.map(owner => ( + + + {( + [ + 'initialCapital', + 'markedHoldings', + 'remainingCost', + 'realizedGrossPnl', + 'unrealizedPnl', + 'fees', + 'equityContribution', + ] as const + ).map(key => ( + + ))} + + ))} + +
+ {label} +
{owner.ownerId} + {owner[key]} +
+
+
+
+ ); +} +function CanonicalFills({ result }: { result: CanonicalRunResult }) { + const fills = result.financial.projection.fills; + return ( +
+

Canonical fills ({result.analytics.fillCount})

+

+ 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. +

+ {!fills.length ? ( +

No fills were executed in this completed run.

+ ) : ( +
+ + + + {[ + 'Time (UTC)', + 'Owner', + 'Asset', + 'Side', + 'Quantity', + 'Price', + 'Fee', + 'Released basis', + 'Gross realized P&L', + 'Order / fill / decision', + ].map(label => ( + + ))} + + + + {fills.map(fill => ( + + + + + + + + + + + + + ))} + +
+ {label} +
{canonicalTime(fill.eventTime)}{fill.ownerId}{fill.instrumentId}{fill.side}{fill.quantity}{fill.price}{fill.fee.amount}{fill.releasedBasis}{fill.realizedGrossPnl} + {fill.orderId} +
+ {fill.fillId} +
+ {fill.decision.decisionId} +
+
+ )} +
+ ); +} diff --git a/apps/stock/web-app/src/features/backtest/components/CanonicalSetup.tsx b/apps/stock/web-app/src/features/backtest/components/CanonicalSetup.tsx new file mode 100644 index 00000000..6f712f13 --- /dev/null +++ b/apps/stock/web-app/src/features/backtest/components/CanonicalSetup.tsx @@ -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; +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; +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>; +} { + const values: Record = { version: 1 }; + const errors: Partial> = {}; + 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; + 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({ + strategyVersionId: backtest.strategyVersionId, + strategyParameters: backtest.strategyParameters, + }); + const [strategyValid, setStrategyValid] = useState(false); + const [epoch, setEpoch] = useState(0); + const [catalog, setCatalog] = useState([]); + const [dataset, setDataset] = useState(null); + const [catalogLoading, setCatalogLoading] = useState(true); + const [datasetLoading, setDatasetLoading] = useState(false); + const [catalogError, setCatalogError] = useState(null); + const [datasetError, setDatasetError] = useState(null); + const [retry, setRetry] = useState(0); + const [saving, setSaving] = useState(false); + const [error, setError] = useState(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 | 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 ( +
void save(event)} + onChange={() => setDirty(true)} + > +

Canonical research setup

+

+ 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. +

+ {dirty && ( +

+ Unsaved canonical setup. Save or discard before leaving. +

+ )} +
+ + + {!validCapital && ( +

+ Initial capital must be a positive finite number. +

+ )} + + {catalogLoading &&

Loading canonical datasets...

} + {!catalogLoading && !catalogError && !catalog.length && ( +

+ No canonical datasets are available. Retain an eligible dataset with explicit sessions + and availability before configuring a run. +

+ )} + {datasetLoading &&

Loading selected canonical dataset...

} + {[catalogError, datasetError, compatibilityError].filter(Boolean).map((message, index) => ( +

+ {message} +

+ ))} + {(catalogError || datasetError || compatibilityError) && ( + + )} + {hash && !selectedFields && !datasetLoading && ( +

+ The selected hash is retained. Saving stays disabled until compatible metadata is + available. +

+ )} + {selectedFields && ( +
+
+
Execution asset
+
{selectedFields.symbols.join(', ')}
+
+
+
Execution interval
+
{selectedFields.dataFrequency}
+
+
+
Trading start (UTC)
+
{selectedFields.startDate}
+
+
+
Trading end (UTC, exclusive)
+
{selectedFields.endDate}
+
+
+
Warmup start (UTC)
+
{selectedFields.warmupStart}
+
+
+ )} + + {[...new Set(policyFields.map(field => field.group))].map(group => ( +
+

{group}

+
+ {policyFields + .filter(field => field.group === group) + .map(field => ( + + ))} +
+
+ ))} +
+ {error && ( +

+ {error} +

+ )} + {' '} + {onClose && ( + + )} +
+ ); +} diff --git a/apps/stock/web-app/src/features/backtest/components/RunsListWithMetrics.tsx b/apps/stock/web-app/src/features/backtest/components/RunsListWithMetrics.tsx index ce02c4c8..518a16a2 100644 --- a/apps/stock/web-app/src/features/backtest/components/RunsListWithMetrics.tsx +++ b/apps/stock/web-app/src/features/backtest/components/RunsListWithMetrics.tsx @@ -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' && ( + Canonical + )} ), }, @@ -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 ( -0.1 + : signedLoss > -0.1 ? 'text-success' - : value > -0.2 + : signedLoss > -0.2 ? 'text-warning' : 'text-error' }`} diff --git a/apps/stock/web-app/src/features/backtest/hooks/useBacktestV2.ts b/apps/stock/web-app/src/features/backtest/hooks/useBacktestV2.ts index a58ae72d..ac2261a1 100644 --- a/apps/stock/web-app/src/features/backtest/hooks/useBacktestV2.ts +++ b/apps/stock/web-app/src/features/backtest/hooks/useBacktestV2.ts @@ -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; request?: Promise; 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(null); const [runs, setRuns] = useState([]); const [currentRun, setCurrentRun] = useState(null); - const [runResults, setRunResults] = useState(null); + const [runResults, setRunResults] = useState(null); const [isBacktestLoading, setIsBacktestLoading] = useState(false); const [isRunLoading, setIsRunLoading] = useState(false); const [error, setError] = useState(null); @@ -45,9 +52,65 @@ export function useBacktestV2() { } | null>(null); const selection = useRef(null); const cancellation = useRef(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, diff --git a/apps/stock/web-app/src/features/backtest/services/backtestApiV2.ts b/apps/stock/web-app/src/features/backtest/services/backtestApiV2.ts index 4b454b40..7c5c38a4 100644 --- a/apps/stock/web-app/src/features/backtest/services/backtestApiV2.ts +++ b/apps/stock/web-app/src/features/backtest/services/backtestApiV2.ts @@ -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 { + 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 { + 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 { + 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 { + async getRunResults(runId: string, signal?: AbortSignal): Promise { const response = await fetch(`${API_BASE_URL}/api/v2/runs/${runId}/results`, { signal }); if (response.status === 404) { diff --git a/apps/stock/web-app/src/features/strategies/StrategyDetailPage.tsx b/apps/stock/web-app/src/features/strategies/StrategyDetailPage.tsx index c15a26bf..c2590839 100644 --- a/apps/stock/web-app/src/features/strategies/StrategyDetailPage.tsx +++ b/apps/stock/web-app/src/features/strategies/StrategyDetailPage.tsx @@ -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 && ( <> - + {version.origin === 'builtin' && ( + { + if (selectedVersionId.current === reviewed.id) { + setVersion(reviewed); + setVersions(items => + items.map(item => (item.id === reviewed.id ? reviewed : item)) + ); + } + }} + /> + )} + setParameterEdits(true)} @@ -471,8 +490,9 @@ function StrategyDetail({ strategyId, versionId }: { strategyId: string; version

Version history

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

Deployment history is not available in this catalog yet.

@@ -498,7 +518,7 @@ function VersionIdentity({ version }: { version: StrategyVersionSummary }) {

{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.'}

Program: {pkg.program.strategyId} / {pkg.program.strategyVersion} diff --git a/apps/stock/web-app/src/features/strategies/StrategyListPage.tsx b/apps/stock/web-app/src/features/strategies/StrategyListPage.tsx index 911e7ac5..3f7b25c7 100644 --- a/apps/stock/web-app/src/features/strategies/StrategyListPage.tsx +++ b/apps/stock/web-app/src/features/strategies/StrategyListPage.tsx @@ -86,8 +86,8 @@ export function StrategyListPage() {

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

{showCreate && (
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(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 ( +
+

Built-in version review

+

+ Review the retained artifact and its provenance before approval. Approval does not establish + profitability, bypass financial limits or authorize paper/live deployment. +

+ {access === 'loading' &&

Checking operator access...

} + {access === 'denied' && ( +

An authenticated human operator must approve this version.

+ )} + {access === 'error' && ( +
+

Operator access could not be checked.

+ +
+ )} + {access === 'operator' && version.reviewStatus !== 'approved' && ( + <> +