diff --git a/apps/stock/orchestrator/package.json b/apps/stock/orchestrator/package.json index 0e4e657b..90888fcc 100644 --- a/apps/stock/orchestrator/package.json +++ b/apps/stock/orchestrator/package.json @@ -15,6 +15,7 @@ "build:rust": "cd ../engine && cargo build --release && napi build --platform --release" }, "dependencies": { + "@stock-bot/research": "workspace:*", "@stock-bot/calculations": "workspace:*", "decimal.js-light": "2.5.1", "@stock-bot/engine": "*", diff --git a/apps/stock/orchestrator/src/backtest/canonical-result.ts b/apps/stock/orchestrator/src/backtest/canonical-result.ts index 4e50d271..4f11f3ce 100644 --- a/apps/stock/orchestrator/src/backtest/canonical-result.ts +++ b/apps/stock/orchestrator/src/backtest/canonical-result.ts @@ -1,195 +1,2 @@ -import { z } from 'zod'; -import { - dayMs, - drawdownAnalysis, - nullable, - ratio, - returnStatistics, -} from '@stock-bot/calculations/analytics'; -import { cagr, simpleReturn } from '@stock-bot/calculations/returns'; -import type { - CanonicalBacktestAnalytics, - CanonicalMetrics, - CanonicalMetricsInput, - CanonicalMetricUnavailableReason, - CanonicalSessionReturn, -} from '@stock-bot/types'; -import type { ReplayReportResult } from '../contracts/native-replay'; - -const metricsInput = z - .object({ - version: z.literal(1), - periodsPerYear: z.number().finite().positive(), - annualRiskFreeRate: z.number().finite().nullable(), - benchmark: z.null(), - }) - .strict(); - -export interface CanonicalBacktestReport { - /** Exact validated Rust facts; never converted through the legacy DTO. */ - financial: ReplayReportResult; - analytics: CanonicalBacktestAnalytics; -} - -/** Consume a validated report from the native protocol parser. Financial facts - * stay untouched; only statistical reporting converts decimal equity to numbers. - * Persistence/public-result migration belongs to the separately gated R05 path. */ -export function buildCanonicalBacktestReport( - financial: ReplayReportResult, - input: CanonicalMetricsInput -): CanonicalBacktestReport { - const policy = metricsInput.parse(input); - const reporting = financial.reporting; - const initial = Number(reporting.initialEquity); - const terminal = Number(financial.projection.valuation.equity); - const elapsedMs = Number(reporting.elapsedMs); - let previous = initial; - const sessionReturns: CanonicalSessionReturn[] = reporting.sessions.map(session => { - const current = Number(session.equity); - const value = previous > 0 ? nullable(simpleReturn(previous, current)) : null; - const reason = - value === null - ? previous <= 0 - ? ('nonpositive-baseline' as const) - : ('nonfinite-result' as const) - : undefined; - previous = current; - return { - sessionId: session.session.sessionId, - periodStart: session.periodStart, - periodEnd: session.periodEnd, - partialStart: session.partialStart, - partialEnd: session.partialEnd, - value, - eligible: !session.partialStart && !session.partialEnd && value !== null, - ...(reason ? { reason } : {}), - }; - }); - const complete = sessionReturns.filter(session => !session.partialStart && !session.partialEnd); - // One undefined complete return invalidates this statistical sequence. A later - // positive baseline must not silently turn it into a shorter, different sample. - const periodicReturns = complete.every( - (session): session is CanonicalSessionReturn & { value: number } => session.value !== null - ) - ? complete.map(session => session.value) - : null; - const statistics = - periodicReturns === null - ? null - : returnStatistics(periodicReturns, policy.annualRiskFreeRate, policy.periodsPerYear); - const points = [ - { timestamp: reporting.tradeStart, value: initial }, - ...reporting.sessions.map(session => ({ - timestamp: session.periodEnd, - value: Number(session.equity), - })), - ]; - const metrics: CanonicalMetrics = { - totalReturn: initial > 0 ? nullable(simpleReturn(initial, terminal)) : null, - cagr: initial > 0 ? cagr(initial, terminal, elapsedMs / dayMs / 365) : null, - maxDrawdown: initial > 0 ? drawdownAnalysis(points, initial).maxDrawdown : null, - exposureTime: ratio(Number(reporting.occupiedMs), elapsedMs), - volatility: statistics?.volatility ?? null, - downsideDeviation: statistics?.downsideDeviation ?? null, - sharpeRatio: statistics?.sharpeRatio ?? null, - sortinoRatio: statistics?.sortinoRatio ?? null, - var95: statistics?.var95 ?? null, - cvar95: statistics?.cvar95 ?? null, - var99: statistics?.var99 ?? null, - alpha: null, - beta: null, - informationRatio: null, - roundTripCount: null, - winRate: null, - profitFactor: null, - avgWin: null, - avgLoss: null, - }; - const unavailable: CanonicalBacktestAnalytics['unavailable'] = { - alpha: 'missing-benchmark', - beta: 'missing-benchmark', - informationRatio: 'missing-benchmark', - roundTripCount: 'unsupported-round-trips', - winRate: 'unsupported-round-trips', - profitFactor: 'unsupported-round-trips', - avgWin: 'unsupported-round-trips', - avgLoss: 'unsupported-round-trips', - }; - if (metrics.totalReturn === null) { - unavailable.totalReturn = initial <= 0 ? 'nonpositive-baseline' : 'nonfinite-result'; - } - if (metrics.maxDrawdown === null) { - unavailable.maxDrawdown = 'nonpositive-baseline'; - } - if (metrics.exposureTime === null) { - unavailable.exposureTime = elapsedMs === 0 ? 'zero-duration' : 'nonfinite-result'; - } - if (metrics.cagr === null) { - unavailable.cagr = - initial <= 0 - ? 'nonpositive-baseline' - : elapsedMs === 0 - ? 'zero-duration' - : terminal < 0 - ? 'negative-terminal-equity' - : 'nonfinite-result'; - } - const minimumPeriods = { - volatility: 2, - downsideDeviation: 2, - sharpeRatio: 2, - sortinoRatio: 2, - var95: 20, - cvar95: 20, - var99: 100, - }; - for (const key of Object.keys(minimumPeriods) as (keyof typeof minimumPeriods)[]) { - if (metrics[key] !== null) { - continue; - } - let reason: CanonicalMetricUnavailableReason = 'nonfinite-result'; - if (periodicReturns === null) { - reason = 'undefined-period-return'; - } else if ( - ['downsideDeviation', 'sharpeRatio', 'sortinoRatio'].includes(key) && - policy.annualRiskFreeRate === null - ) { - reason = 'missing-risk-free'; - } else if (periodicReturns.length < minimumPeriods[key]) { - reason = 'insufficient-periods'; - } else if (key === 'sharpeRatio' && statistics?.volatility === 0) { - reason = 'zero-variance'; - } else if (key === 'sortinoRatio' && statistics?.downsideDeviation === 0) { - reason = 'zero-downside-deviation'; - } - unavailable[key] = reason; - } - return { - financial, - analytics: { - version: 1, - policy: { - ...policy, - calendarId: reporting.calendarId, - calendarRevision: reporting.calendarRevision, - sampling: reporting.sampling, - marks: 'last-available-no-per-session-freshness-certification', - returnUnit: 'fraction', - variance: 'sample-n-minus-one', - riskFreeConversion: 'annual-rate-divided-by-periods-per-year', - downside: 'full-series-rms-relative-to-risk-free', - partialPeriods: 'visible-excluded-from-periodic-statistics', - drawdown: 'session-end-and-terminal-sampled', - exposureBasis: reporting.exposureBasis, - cagrBasis: 'elapsed-calendar-days-365', - zeroTerminalCagr: 'negative-one-for-positive-elapsed-time', - }, - sessionReturns, - completePeriodCount: complete.length, - periodicSampleCount: periodicReturns?.length ?? 0, - fillCount: financial.projection.fills.length, - metrics, - unavailable, - }, - }; -} +/** Compatibility entrypoint for the shared, purely statistical report builder. */ +export * from '@stock-bot/research/results'; diff --git a/apps/stock/orchestrator/src/data/historical-dataset-v2.ts b/apps/stock/orchestrator/src/data/historical-dataset-v2.ts index da196bc2..2c2bb194 100644 --- a/apps/stock/orchestrator/src/data/historical-dataset-v2.ts +++ b/apps/stock/orchestrator/src/data/historical-dataset-v2.ts @@ -1,612 +1,12 @@ -import { createHash } from 'node:crypto'; -import { z } from 'zod'; import { - parseInstrumentId, - type HistoricalBarV2, - type HistoricalDatasetInputV2, - type HistoricalDatasetMetadataV2, - type HistoricalDatasetV2, -} from '@stock-bot/types'; + createDatasetV2FromLegacy, + parseHistoricalDatasetMetadataV2, +} from '@stock-bot/research/datasets'; +import type { HistoricalDatasetMetadataV2, HistoricalDatasetV2 } from '@stock-bot/types'; import { validateDataset } from './historical-dataset'; -const text = z.string().min(1); -const instant = z.number().int().nonnegative().max(8_640_000_000_000_000); -const sequence = z.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER); -const price = z.number().finite().positive(); -const day = z - .string() - .regex(/^\d{4}-\d{2}-\d{2}$/) - .refine(value => { - const parsed = Date.parse(value); - return Number.isFinite(parsed) && new Date(parsed).toISOString().slice(0, 10) === value; - }, 'Invalid session date'); -const hash = z - .string() - .length(64) - .regex(/^[a-f0-9]{64}$/); -const prices = { - open: price, - high: price, - low: price, - close: price, - volume: z.number().finite().nonnegative(), -}; -const metadataSchema = z - .object({ - calendars: z - .array( - z - .object({ - id: text, - venue: text, - timeZone: text, - revision: text, - source: text, - startDate: day, - endDate: day, - sessions: z - .array(z.object({ date: day, open: instant, close: instant }).strict()) - .min(1), - }) - .strict() - ) - .min(1), - series: z - .array( - z - .object({ - id: text, - instrumentId: text, - interval: z.enum(['1m', '5m', '15m', '1h', '1d']), - calendarId: text, - venue: text, - source: z.object({ provider: text, revision: text }).strict(), - timestamp: z.enum(['session-date', 'interval-start', 'interval-end']), - availability: z.enum(['explicit', 'interval-end-assumption']), - adjustment: z.enum(['raw', 'provider-adjusted']), - }) - .strict() - ) - .min(1), - executionSeries: z.array(z.object({ instrumentId: text, seriesId: text }).strict()).min(1), - bounds: z.object({ warmupStart: instant, tradeStart: instant, tradeEnd: instant }).strict(), - universe: z - .object({ - selection: z.enum(['point-in-time', 'current-constituents', 'unknown']), - asOf: instant.nullable(), - revision: text, - instrumentIds: z.array(text).min(1), - }) - .strict(), - corporateActions: z - .array( - z - .object({ - instrumentId: text, - status: z.enum(['unknown', 'action-free', 'known-actions']), - start: instant, - end: instant, - revision: text, - actions: z.array( - z - .object({ - effectiveAt: instant, - kind: z.enum(['split', 'dividend', 'other']), - reference: text, - }) - .strict() - ), - }) - .strict() - ) - .min(1), - }) - .strict(); -const sourceBarSchema = z - .object({ - seriesId: text, - timestamp: z.union([day, instant]), - availableAt: instant.optional(), - sourceSequence: sequence, - ...prices, - vwap: price.nullable().optional(), - }) - .strict(); -const barSchema = z - .object({ - seriesId: text, - instrumentId: text, - intervalStart: instant, - intervalEnd: instant, - eventTime: instant, - availableAt: instant, - sourceSequence: sequence, - ...prices, - vwap: price.nullable(), - }) - .strict(); -const manifestSchema = metadataSchema - .extend({ - version: z.literal(2), - hash, - normalizationRevision: z.literal('historical-normalization-v2'), - parentDatasetHash: hash.nullable(), - volumePolicy: z.literal('reported'), - qualityPolicy: z.literal('reject-invalid-no-interpolation'), - intradayPolicy: z.literal('full-duration-session-contained'), - eligibility: z.enum(['eligible', 'exploratory', 'ineligible']), - limitations: z.array(text), - barCount: z.number().int().positive(), - }) - .strict(); -const durations = { '1m': 60_000, '5m': 300_000, '15m': 900_000, '1h': 3_600_000 }; -const prepared = new WeakSet(); -const compare = (a: string, b: string) => (a < b ? -1 : a > b ? 1 : 0); - -function unique(values: readonly string[], label: string): void { - if (new Set(values).size !== values.length) { - throw new Error(`Duplicate ${label}`); - } -} - -function parseMetadata(input: unknown) { - const metadata = metadataSchema.parse(input); - const { bounds, universe } = metadata; - if (bounds.warmupStart > bounds.tradeStart || bounds.tradeStart >= bounds.tradeEnd) { - throw new Error('Invalid warmup/trade bounds'); - } - unique( - metadata.calendars.map(c => c.id), - 'calendar' - ); - metadata.calendars.sort((a, b) => compare(a.id, b.id)); - for (const calendar of metadata.calendars) { - if (calendar.startDate >= calendar.endDate) { - throw new Error('Invalid calendar coverage'); - } - const formatter = new Intl.DateTimeFormat('en-CA', { - timeZone: calendar.timeZone, - year: 'numeric', - month: '2-digit', - day: '2-digit', - }); - const localDate = (time: number) => { - const parts = formatter.formatToParts(time); - return ['year', 'month', 'day'] - .map(key => parts.find(part => part.type === key)?.value ?? '') - .join('-'); - }; - if ( - localDate(bounds.warmupStart) < calendar.startDate || - localDate(bounds.tradeEnd - 1) >= calendar.endDate - ) { - throw new Error('Calendar coverage must include warmup and trade bounds'); - } - unique( - calendar.sessions.map(s => s.date), - 'calendar session' - ); - calendar.sessions.sort((a, b) => compare(a.date, b.date)); - let previousClose = -1; - for (const session of calendar.sessions) { - if ( - session.date < calendar.startDate || - session.date >= calendar.endDate || - session.open >= session.close || - session.open < previousClose || - localDate(session.open) !== session.date || - localDate(session.close) !== session.date - ) { - throw new Error('Invalid retained calendar session'); - } - previousClose = session.close; - } - } - unique( - metadata.series.map(s => s.id), - 'series' - ); - metadata.series.sort((a, b) => compare(a.id, b.id)); - for (const series of metadata.series) { - parseInstrumentId(series.instrumentId); - const calendar = metadata.calendars.find(c => c.id === series.calendarId); - if ( - !calendar || - calendar.venue !== series.venue || - (series.interval === '1d') !== (series.timestamp === 'session-date') - ) { - throw new Error('Unknown calendar/venue or incompatible timestamp mapping'); - } - } - const instruments = [...new Set(metadata.series.map(s => s.instrumentId))].sort(compare); - unique( - metadata.executionSeries.map(s => s.instrumentId), - 'execution instrument' - ); - unique( - metadata.executionSeries.map(s => s.seriesId), - 'execution series' - ); - metadata.executionSeries.sort((a, b) => compare(a.instrumentId, b.instrumentId)); - if ( - JSON.stringify(metadata.executionSeries.map(s => s.instrumentId)) !== - JSON.stringify(instruments) || - metadata.executionSeries.some( - e => !metadata.series.some(s => s.id === e.seriesId && s.instrumentId === e.instrumentId) - ) - ) { - throw new Error('Choose exactly one execution series per instrument'); - } - unique(universe.instrumentIds, 'universe instrument'); - universe.instrumentIds.sort(compare); - if ( - JSON.stringify(universe.instrumentIds) !== JSON.stringify(instruments) || - (universe.selection === 'point-in-time' && - (universe.asOf === null || universe.asOf > bounds.tradeStart)) - ) { - throw new Error('Invalid universe/as-of selection'); - } - unique( - metadata.corporateActions.map(c => c.instrumentId), - 'action coverage' - ); - metadata.corporateActions.sort((a, b) => compare(a.instrumentId, b.instrumentId)); - if ( - JSON.stringify(metadata.corporateActions.map(c => c.instrumentId)) !== - JSON.stringify(instruments) - ) { - throw new Error('Corporate-action coverage required for every instrument'); - } - for (const coverage of metadata.corporateActions) { - if ( - coverage.start > bounds.warmupStart || - coverage.end < bounds.tradeEnd || - coverage.start >= coverage.end || - (coverage.status === 'known-actions') !== coverage.actions.length > 0 || - coverage.actions.some(a => a.effectiveAt < coverage.start || a.effectiveAt >= coverage.end) - ) { - throw new Error('Invalid corporate-action coverage'); - } - unique( - coverage.actions.map(a => a.reference), - 'corporate-action reference' - ); - coverage.actions.sort( - (a, b) => a.effectiveAt - b.effectiveAt || compare(a.reference, b.reference) - ); - } - return metadata; -} - -/** Validate and detach complete operator declarations before a stored-source read. */ -export function parseHistoricalDatasetMetadataV2(input: unknown): HistoricalDatasetMetadataV2 { - return parseMetadata(input); -} - -function assess(metadata: HistoricalDatasetMetadataV2, parentDatasetHash: string | null) { - const limitations = [ - 'Open liquidity must use previously available volume; intraday partial bars are unsupported', - ]; - let eligibility: 'eligible' | 'exploratory' | 'ineligible' = 'eligible'; - if (parentDatasetHash) { - limitations.push('Legacy v1 VWAP provenance is unavailable; converted VWAP is null'); - } - if (metadata.universe.selection !== 'point-in-time') { - eligibility = 'exploratory'; - limitations.push('Universe selection is not verified point-in-time'); - } - for (const coverage of metadata.corporateActions) { - if (coverage.status === 'unknown') { - if (eligibility !== 'ineligible') { - eligibility = 'exploratory'; - } - limitations.push(`Unknown corporate-action coverage: ${coverage.instrumentId}`); - } - if ( - coverage.actions.some( - a => - a.effectiveAt >= metadata.bounds.warmupStart && a.effectiveAt < metadata.bounds.tradeEnd - ) - ) { - eligibility = 'ineligible'; - limitations.push(`Unsupported corporate actions in dataset range: ${coverage.instrumentId}`); - } - } - for (const selection of metadata.executionSeries) { - if (metadata.series.find(s => s.id === selection.seriesId)?.adjustment !== 'raw') { - eligibility = 'ineligible'; - limitations.push(`Adjusted prices cannot execute: ${selection.seriesId}`); - } - } - for (const series of metadata.series) { - if (series.availability === 'interval-end-assumption') { - limitations.push(`Availability assumes zero data delay at interval end: ${series.id}`); - } - } - return { eligibility, limitations }; -} - -/** Per-preparation indexes, not a cross-dataset cache. Session lookup is logarithmic. */ -function indexMetadata(metadata: HistoricalDatasetMetadataV2) { - return { - series: new Map(metadata.series.map(series => [series.id, series])), - calendars: new Map( - metadata.calendars.map(calendar => [ - calendar.id, - { - ...calendar, - byDate: new Map(calendar.sessions.map(session => [session.date, session])), - }, - ]) - ), - }; -} - -function containingSession( - sessions: HistoricalDatasetMetadataV2['calendars'][number]['sessions'], - start: number, - end: number -) { - let low = 0, - high = sessions.length; - while (low < high) { - const middle = Math.floor((low + high) / 2); - if ((sessions[middle]?.open ?? Infinity) <= start) { - low = middle + 1; - } else { - high = middle; - } - } - const session = sessions[low - 1]; - return session && end <= session.close ? session : undefined; -} - -function validateBars( - metadata: HistoricalDatasetMetadataV2, - input: readonly unknown[] -): HistoricalBarV2[] { - if (!input.length) { - throw new Error('Dataset requires bars'); - } - const index = indexMetadata(metadata); - const intervals = new Set(), - sequences = new Set(), - seen = new Set(); - const bars = input.map(value => { - const bar = barSchema.parse(value); - const series = index.series.get(bar.seriesId); - const calendar = series && index.calendars.get(series.calendarId); - const session = - calendar && containingSession(calendar.sessions, bar.intervalStart, bar.intervalEnd); - const duration = series?.interval === '1d' ? null : series ? durations[series.interval] : null; - if ( - !series || - bar.instrumentId !== series.instrumentId || - !session || - bar.intervalStart >= bar.intervalEnd || - (duration === null - ? bar.intervalStart !== session.open || bar.intervalEnd !== session.close - : bar.intervalEnd - bar.intervalStart !== duration) || - bar.eventTime !== bar.intervalEnd || - bar.availableAt < bar.eventTime || - (series.availability === 'interval-end-assumption' && bar.availableAt !== bar.intervalEnd) || - bar.intervalStart < metadata.bounds.warmupStart || - bar.intervalStart >= metadata.bounds.tradeEnd || - bar.intervalEnd > metadata.bounds.tradeEnd || - bar.high < Math.max(bar.open, bar.close) || - bar.low > Math.min(bar.open, bar.close) - ) { - throw new Error('Invalid bar values, session interval or availability'); - } - const intervalKey = JSON.stringify([bar.seriesId, bar.intervalStart, bar.intervalEnd]); - const sequenceKey = JSON.stringify([bar.seriesId, bar.sourceSequence]); - if (intervals.has(intervalKey) || sequences.has(sequenceKey)) { - throw new Error('Duplicate or conflicting bar interval/source sequence'); - } - intervals.add(intervalKey); - sequences.add(sequenceKey); - seen.add(bar.seriesId); - return bar; - }); - if (seen.size !== metadata.series.length) { - throw new Error('Every declared series requires observations'); - } - let previous: HistoricalBarV2 | undefined; - for (const bar of [...bars].sort( - (a, b) => compare(a.seriesId, b.seriesId) || a.intervalStart - b.intervalStart - )) { - if (previous?.seriesId === bar.seriesId && bar.intervalStart < previous.intervalEnd) { - throw new Error('Overlapping intervals within one series'); - } - previous = bar; - } - bars.sort( - (a, b) => - a.availableAt - b.availableAt || - compare(a.instrumentId, b.instrumentId) || - compare(a.seriesId, b.seriesId) || - a.sourceSequence - b.sourceSequence - ); - return bars; -} - -function freeze(value: T): T { - if (value && typeof value === 'object') { - for (const child of Object.values(value)) { - freeze(child); - } - Object.freeze(value); - } - return value; -} - -function finish( - metadata: ReturnType, - bars: HistoricalBarV2[], - parentDatasetHash: string | null -): HistoricalDatasetV2 { - const manifest = { - ...metadata, - version: 2 as const, - normalizationRevision: 'historical-normalization-v2' as const, - parentDatasetHash, - volumePolicy: 'reported' as const, - qualityPolicy: 'reject-invalid-no-interpolation' as const, - intradayPolicy: 'full-duration-session-contained' as const, - ...assess(metadata, parentDatasetHash), - barCount: bars.length, - }; - const digest = createHash('sha256').update(`{"manifest":${JSON.stringify(manifest)},"bars":[`); - bars.forEach((bar, index) => digest.update((index ? ',' : '') + JSON.stringify(bar))); - const dataset = freeze({ - manifest: { ...manifest, hash: digest.update(']}').digest('hex') }, - bars, - }); - prepared.add(dataset); - return dataset; -} - -function create(input: unknown, parentDatasetHash: string | null): HistoricalDatasetV2 { - const parsed = z - .object({ metadata: metadataSchema, bars: z.array(sourceBarSchema).min(1) }) - .strict() - .parse(input); - const metadata = parseMetadata(parsed.metadata); - const index = indexMetadata(metadata); - const bars = parsed.bars.map(row => { - const series = index.series.get(row.seriesId); - const calendar = series && index.calendars.get(series.calendarId); - if (!series || !calendar) { - throw new Error('Unknown series/calendar mapping'); - } - if (series.availability === 'explicit' && row.availableAt === undefined) { - throw new Error('Explicit availability policy requires availableAt on every bar'); - } - let intervalStart: number, intervalEnd: number; - if (series.interval === '1d') { - const session = typeof row.timestamp === 'string' && calendar.byDate.get(row.timestamp); - if (!session) { - throw new Error('Unknown daily session mapping'); - } - intervalStart = session.open; - intervalEnd = session.close; - } else { - if (typeof row.timestamp !== 'number') { - throw new Error('Intraday timestamp requires an explicit instant'); - } - const duration = durations[series.interval]; - intervalStart = - series.timestamp === 'interval-start' ? row.timestamp : row.timestamp - duration; - intervalEnd = intervalStart + duration; - } - return { - seriesId: series.id, - instrumentId: series.instrumentId, - intervalStart, - intervalEnd, - eventTime: intervalEnd, - availableAt: row.availableAt ?? intervalEnd, - sourceSequence: row.sourceSequence, - open: row.open, - high: row.high, - low: row.low, - close: row.close, - volume: row.volume, - vwap: row.vwap ?? null, - }; - }); - return finish(metadata, validateBars(metadata, bars), parentDatasetHash); -} - -/** No storage/provider access or implicit v1 cutover. Tables and timestamp semantics are mandatory. */ -export function createDatasetV2(input: HistoricalDatasetInputV2): HistoricalDatasetV2 { - return create(input, null); -} - -/** Recompute constraints, eligibility and hash; untrusted values are detached before freezing. */ -export function validateDatasetV2(input: unknown): HistoricalDatasetV2 { - if (input && typeof input === 'object' && prepared.has(input)) { - return input as HistoricalDatasetV2; - } - const parsed = z - .object({ manifest: manifestSchema, bars: z.array(barSchema).min(1) }) - .strict() - .parse(input); - const { - version: _version, - hash: expectedHash, - normalizationRevision: _revision, - parentDatasetHash, - volumePolicy: _volume, - qualityPolicy: _quality, - intradayPolicy: _intraday, - eligibility, - limitations, - barCount, - ...rawMetadata - } = parsed.manifest; - const metadata = parseMetadata(rawMetadata); - const dataset = finish(metadata, validateBars(metadata, parsed.bars), parentDatasetHash); - if ( - dataset.manifest.hash !== expectedHash || - barCount !== dataset.bars.length || - eligibility !== dataset.manifest.eligibility || - JSON.stringify(limitations) !== JSON.stringify(dataset.manifest.limitations) || - (parentDatasetHash !== null && dataset.bars.some(bar => bar.vwap !== null)) - ) { - throw new Error('Dataset v2 hash/content or derived policy mismatch'); - } - return dataset; -} - -/** Exact retained v2 interval slice. V2 lineage belongs to the caller's manifest; - * parentDatasetHash continues to describe only the original legacy-v1 conversion. */ -export function sliceDatasetV2( - input: unknown, - boundsInput: HistoricalDatasetMetadataV2['bounds'] -): HistoricalDatasetV2 { - const source = validateDatasetV2(input); - const bounds = metadataSchema.shape.bounds.parse(boundsInput); - if ( - bounds.warmupStart < source.manifest.bounds.warmupStart || - bounds.tradeStart < source.manifest.bounds.tradeStart || - bounds.tradeEnd > source.manifest.bounds.tradeEnd - ) { - throw new Error('Slice bounds must remain within the source warmup and evaluation bounds'); - } - for (const boundary of [bounds.warmupStart, bounds.tradeStart, bounds.tradeEnd]) { - if (source.bars.some(bar => bar.intervalStart < boundary && boundary < bar.intervalEnd)) { - throw new Error('Slice boundaries cannot cut through a retained bar interval'); - } - } - const { - version: _version, - hash: _hash, - normalizationRevision: _revision, - parentDatasetHash, - volumePolicy: _volume, - qualityPolicy: _quality, - intradayPolicy: _intraday, - eligibility: _eligibility, - limitations: _limitations, - barCount: _count, - ...rawMetadata - } = source.manifest; - const metadata = parseMetadata({ ...rawMetadata, bounds }); - const bars = source.bars.filter( - bar => bar.intervalStart >= bounds.warmupStart && bar.intervalEnd <= bounds.tradeEnd - ); - return finish(metadata, validateBars(metadata, bars), parentDatasetHash); -} - -/** Unknown coverage remains exploratory; this assertion does not certify economic correctness. */ -export function assertDatasetV2Executable(input: unknown): HistoricalDatasetV2 { - const dataset = validateDatasetV2(input); - if (dataset.manifest.eligibility === 'ineligible') { - throw new Error(`Dataset is not executable: ${dataset.manifest.limitations.join('; ')}`); - } - return dataset; -} +/** Compatibility entrypoint; legacy conversion remains application-owned. */ +export * from '@stock-bot/research/datasets'; /** Explicit conversion keeps the original v1 hash and treats all legacy VWAP as unknown. */ export function convertDatasetV1ToV2( @@ -614,7 +14,7 @@ export function convertDatasetV1ToV2( metadata: HistoricalDatasetMetadataV2 ): HistoricalDatasetV2 { const legacy = validateDataset(input); - const normalized = parseMetadata(metadata); + const normalized = parseHistoricalDatasetMetadataV2(metadata); if ( normalized.series.length !== legacy.manifest.instruments.length || normalized.series.some( @@ -663,5 +63,5 @@ export function convertDatasetV1ToV2( vwap: null, }; }); - return create({ metadata: normalized, bars }, legacy.manifest.hash); + return createDatasetV2FromLegacy({ metadata: normalized, bars }, legacy.manifest.hash); } diff --git a/apps/stock/web-api/package.json b/apps/stock/web-api/package.json index 9cde905a..00fd1513 100644 --- a/apps/stock/web-api/package.json +++ b/apps/stock/web-api/package.json @@ -12,6 +12,7 @@ "clean": "rm -rf dist" }, "dependencies": { + "@stock-bot/research": "workspace:*", "@stock-bot/queue": "workspace:*", "@stock-bot/services": "workspace:*", "@stock-bot/config": "*", 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 a4a999ba..2c69f1c9 100644 --- a/apps/stock/web-api/src/services/backtest-v2.service.ts +++ b/apps/stock/web-api/src/services/backtest-v2.service.ts @@ -1,1071 +1,100 @@ -import { createHash, randomUUID as uuidv4 } from 'node:crypto'; -import type { PoolClient, QueryResultRow } from 'pg'; import { authenticatedServiceFetch } from '@stock-bot/di'; -import { at } from '@stock-bot/invariants'; -import { getLogger } from '@stock-bot/logger'; import { requireServices, type IServiceContainer } from '@stock-bot/services'; -import { - backtestRequestFromDefinition, - backtestSettingsFromDefinition, - CatalogBacktestDefinitionSchema, - datasetHashSchema, - parseBacktestRequest, - rejectCatalogVersionReferences, - type BacktestDefinitionInput, -} from '@stock-bot/stock-config/backtest'; -import { - canonicalRunRequestSchema, - canonicalStrategyExecution, - parseCanonicalFinancialResult, - type CanonicalReproductionComparison, - type CanonicalReproductionPreview, - 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, - ResearchActor, - 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 { canonicalReproductionHash } from './reproduction-comparison'; -import { RunReproductionError, verifyReproductionInputs } from './run-reproduction'; -import { StrategyCatalogError, StrategyCatalogService } from './strategy-catalog.service'; +import type { BacktestTransport } from './backtests/contracts'; +import { BacktestReproduction } from './backtests/reproduction'; +import { BacktestResults } from './backtests/results'; +import { BacktestRuns } from './backtests/runs'; +import { BacktestTemplates } from './backtests/templates'; -const logger = getLogger('backtest-v2-service'); +export { + BacktestRetentionError, + CatalogExecutionUnavailableError, + RunSubmissionConflictError, +} from './backtests/contracts'; +export type { + BacktestTransport, + BacktestResultQuery, + BacktestRequest, + Backtest, + Run, + RunRequest, + RunSubmission, +} from './backtests/contracts'; +export { datasetSelectionForRun } from './backtests/mapping'; -// Use environment variable or default -const ORCHESTRATOR_URL = process.env.ORCHESTRATOR_URL || 'http://localhost:2004'; - -export type BacktestTransport = (url: string, init?: RequestInit) => Promise; -/** Reads may share an existing transaction without acquiring another pool connection. */ -export interface BacktestResultQuery { - query( - text: string, - values?: unknown[] - ): Promise<{ rows: T[] }>; -} - -export interface BacktestRequest { - name: string; - strategy: string; - symbols: string[]; - startDate: string; - endDate: string; - initialCapital: number; - config?: Record; - strategyVersionId?: string | null; - strategyParameters?: Record | null; -} - -export interface Backtest { - id: string; - archivedAt: string | null; - strategyVersionId: string | null; - strategyParameters: Record | null; - name: string; - strategy: string; - symbols: string[]; - startDate: Date; - endDate: Date; - initialCapital: number; - config: Record; - createdAt: Date; - updatedAt: Date; -} - -export interface Run { - originalRunId: string | null; - dataset: BacktestRunDatasetSelection; - id: string; - backtestId: string; - runNumber: number; - status: 'pending' | 'running' | 'completed' | 'failed' | 'cancelled' | 'paused'; - speedMultiplier: number | null; - error?: string; - startedAt?: Date; - completedAt?: Date; - pausedAt?: Date; - progress: number; - cancelRequested: boolean; - attemptNumber: number; - currentDate?: Date; - createdAt: Date; - updatedAt: Date; -} - -export interface RunRequest { - backtestId: string; - speedMultiplier?: number | null; -} - -export interface RunSubmission { - principal: ResearchActor; - key: string; -} - -export class RunSubmissionConflictError extends Error { - constructor() { - super('This submission key was already used for a different run request'); - this.name = 'RunSubmissionConflictError'; - } -} -export class CatalogExecutionUnavailableError extends Error { - readonly code = 'catalog_execution_unavailable'; - constructor(reason?: string) { - super( - reason ?? - 'Configure an approved built-in, eligible v2 dataset and canonical policy before execution' - ); - } -} - -/** Strip only DTO metadata from legacy definitions; caller-supplied markers are rejected first. */ -function legacyDefinition(input: BacktestDefinitionInput): BacktestDefinitionInput { - return { - name: input.name, - strategy: input.strategy, - symbols: input.symbols, - startDate: input.startDate, - endDate: input.endDate, - initialCapital: input.initialCapital, - config: input.config, - }; -} - -export class BacktestRetentionError extends Error { - constructor( - public readonly code: 'backtest_archived' | 'retained_runs', - public readonly runCount?: number - ) { - super( - code === 'backtest_archived' - ? 'Backtest is archived; restore it before editing or submitting a new run' - : `Backtest has ${runCount} retained run(s); archive it to preserve results and reproducibility` - ); - } -} - -/** - * Application service for editable templates and immutable run inputs/results. - * Submission writes a PostgreSQL outbox row for BacktestDispatcher; execution - * belongs to the orchestrator. Historical result readers remain available even - * though new submissions require the canonical Rust research path. - */ +/** Compatible application facade; no financial simulation or accounting lives here. */ export class BacktestServiceV2 { - private container: IServiceContainer & { postgres: NonNullable }; - private wsHandler: WebSocketHandler | null = null; - + private readonly templates: BacktestTemplates; + private readonly runs: BacktestRuns; + private readonly results: BacktestResults; + private readonly reproduction: BacktestReproduction; constructor( container: IServiceContainer, - private readonly request: BacktestTransport = authenticatedServiceFetch + request: BacktestTransport = authenticatedServiceFetch ) { - this.container = requireServices(container, 'postgres'); - logger.info('BacktestServiceV2 initialized'); + const services = requireServices(container, 'postgres'); + this.runs = new BacktestRuns(services, request); + this.templates = new BacktestTemplates(services, input => this.runs.createRun(input)); + this.results = new BacktestResults(services); + this.reproduction = new BacktestReproduction(services, this.results); } - - // Backtest CRUD operations - async createBacktest( - request: BacktestRequest, - options: { autoStart?: boolean } = {} - ): Promise { - const catalog = request.strategy === 'catalog'; - if (catalog && options.autoStart !== false) { - throw new HistoricalDataRequestError('Catalog drafts require explicit autoStart:false'); - } - if (!catalog) { - rejectCatalogVersionReferences(request); - } - const backtestId = uuidv4(); - const result = await this.container.postgres.transaction(async client => { - const definition = catalog ? await this.validateCatalogDraft(client, request) : request; - if (!catalog) { - await assertSelectedDatasetMatchesRequest( - client, - backtestRequestFromDefinition(definition) - ); - } - return client.query( - `INSERT INTO backtests - (id, name, strategy, symbols, start_date, end_date, initial_capital, config, strategy_version_id, strategy_parameters) - VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10) - RETURNING *`, - [ - backtestId, - definition.name, - definition.strategy, - JSON.stringify(definition.symbols), - definition.startDate, - definition.endDate, - definition.initialCapital, - JSON.stringify(definition.config || {}), - definition.strategyVersionId ?? null, - definition.strategyParameters ? JSON.stringify(definition.strategyParameters) : null, - ] - ); - }); - - const backtest = this.mapBacktest(at(result.rows, 0)); - - // Automatically create and start a run for the new backtest - if (options.autoStart !== false) { - try { - await this.createRun({ - backtestId: backtest.id, - speedMultiplier: null, // Max speed (instant) - }); - } catch (error) { - logger.error('Failed to auto-create run for new backtest', { - backtestId: backtest.id, - error, - }); - // Don't fail the backtest creation if run creation fails - } - } - return backtest; + createBacktest(...args: Parameters) { + return this.templates.createBacktest(...args); } - - async getBacktest(id: string): Promise { - const result = await this.container.postgres.query('SELECT * FROM backtests WHERE id = $1', [ - id, - ]); - - if (result.rows.length === 0) { - return null; - } - - return this.mapBacktest(at(result.rows, 0)); + getBacktest(...args: Parameters) { + return this.templates.getBacktest(...args); } - - async updateBacktest(id: string, request: Partial): Promise { - return this.container.postgres.transaction(async client => { - const locked = await client.query('SELECT * FROM backtests WHERE id = $1 FOR UPDATE', [id]); - if (!locked.rows[0]) { - return null; - } - if (locked.rows[0].archived_at) { - throw new BacktestRetentionError('backtest_archived'); - } - const existing = this.mapBacktest(locked.rows[0]); - const catalog = existing.strategyVersionId !== null; - let next = { ...existing, ...request }; - if (catalog) { - CatalogBacktestDefinitionSchema.partial().parse(request); - if ( - request.strategyVersionId !== undefined && - request.strategyVersionId !== existing.strategyVersionId && - request.strategyParameters === undefined - ) { - throw new HistoricalDataRequestError( - 'Changing a selected version requires explicit strategyParameters' - ); - } - const normalized = await this.validateCatalogDraft( - client, - { - ...legacyDefinition(next), - strategyVersionId: next.strategyVersionId, - strategyParameters: next.strategyParameters, - }, - existing.strategyVersionId - ); - next = { ...next, ...normalized } as typeof next; - } else { - rejectCatalogVersionReferences(request); - await assertSelectedDatasetMatchesRequest( - client, - backtestRequestFromDefinition(legacyDefinition(next)) - ); - } - const updates: string[] = []; - const values: unknown[] = []; - let paramCount = 1; - - if (request.name !== undefined) { - updates.push(`name = $${paramCount++}`); - values.push(catalog ? next.name : request.name); - } - if (request.strategy !== undefined) { - updates.push(`strategy = $${paramCount++}`); - values.push(catalog ? next.strategy : request.strategy); - } - if (request.symbols !== undefined) { - updates.push(`symbols = $${paramCount++}`); - values.push(JSON.stringify(catalog ? next.symbols : request.symbols)); - } - if (request.startDate !== undefined) { - updates.push(`start_date = $${paramCount++}`); - values.push(catalog ? next.startDate : request.startDate); - } - if (request.endDate !== undefined) { - updates.push(`end_date = $${paramCount++}`); - values.push(catalog ? next.endDate : request.endDate); - } - if (request.initialCapital !== undefined) { - updates.push(`initial_capital = $${paramCount++}`); - values.push(catalog ? next.initialCapital : request.initialCapital); - } - if (request.config !== undefined) { - updates.push(`config = $${paramCount++}`); - values.push(JSON.stringify(catalog ? next.config : request.config)); - } - if (catalog) { - updates.push( - `strategy_version_id = $${paramCount++}`, - `strategy_parameters = $${paramCount++}` - ); - values.push(next.strategyVersionId, JSON.stringify(next.strategyParameters)); - } - - if (updates.length === 0) { - return existing; - } - - values.push(id); - const result = await client.query( - `UPDATE backtests - SET ${updates.join(', ')}, updated_at = NOW() - WHERE id = $${paramCount} - RETURNING *`, - values - ); - - if (result.rows.length === 0) { - return null; - } - - return this.mapBacktest(at(result.rows, 0)); - }); + updateBacktest(...args: Parameters) { + return this.templates.updateBacktest(...args); } - - async listBacktests(params: { - limit: number; - offset: number; - includeArchived?: boolean; - }): Promise { - const result = await this.container.postgres.query( - `SELECT * FROM backtests - WHERE ($3::boolean OR archived_at IS NULL) - ORDER BY created_at DESC - LIMIT $1 OFFSET $2`, - [params.limit, params.offset, params.includeArchived === true] - ); - - return result.rows.map(row => this.mapBacktest(row)); + listBacktests(...args: Parameters) { + return this.templates.listBacktests(...args); } - - async deleteBacktest(id: string): Promise { - await this.container.postgres.transaction(async client => { - const parent = await client.query('SELECT id FROM backtests WHERE id=$1 FOR UPDATE', [id]); - if (!parent.rows[0]) { - return; - } - const retained = await client.query( - 'SELECT count(*)::int AS count FROM runs WHERE backtest_id=$1', - [id] - ); - const count = Number(retained.rows[0]?.count ?? 0); - if (count > 0) { - throw new BacktestRetentionError('retained_runs', count); - } - await client.query('DELETE FROM backtests WHERE id=$1', [id]); - }); + deleteBacktest(...args: Parameters) { + return this.templates.deleteBacktest(...args); } - - async archiveBacktest(id: string, archived: boolean): Promise { - return this.container.postgres.transaction(async client => { - const parent = await client.query('SELECT id FROM backtests WHERE id=$1 FOR UPDATE', [id]); - if (!parent.rows[0]) { - return null; - } - const updated = await client.query( - `UPDATE backtests - SET archived_at=CASE WHEN $2::boolean THEN COALESCE(archived_at,NOW()) ELSE NULL END, - updated_at=NOW() WHERE id=$1 RETURNING *`, - [id, archived] - ); - return this.mapBacktest(at(updated.rows, 0)); - }); + archiveBacktest(...args: Parameters) { + return this.templates.archiveBacktest(...args); } - - /** - * Admit one logical run, saving its request and dispatch intent atomically. - * A principal/key identifies the submission, not the template's current contents: - * the same retry returns the original run even after a template edit. Conflicting - * reuse fails. No queue operation occurs inside this transaction. - */ - async createRun(request: RunRequest, submission?: RunSubmission): Promise { - const runId = uuidv4(); - const multiplier = request.speedMultiplier ?? null; - if (multiplier !== null && (!Number.isFinite(multiplier) || multiplier <= 0)) { - throw new HistoricalDataRequestError('Speed multiplier must be positive or null'); - } - // Hash submission intent, not the mutable definition or newly generated run ID. - // A retry after an edit must still return the original run and its frozen snapshot. - const submissionHash = submission - ? createHash('sha256') - .update( - JSON.stringify({ - version: 1, - backtestId: request.backtestId, - speedMultiplier: multiplier, - }) - ) - .digest('hex') - : null; - const row = await this.container.postgres.transaction(async client => { - const replay = async () => { - if (!submission) { - return undefined; - } - const existing = await client.query( - 'SELECT * FROM runs WHERE submission_principal = $1 AND submission_key = $2', - [submission.principal, submission.key] - ); - const saved = existing.rows[0]; - if (saved && saved.submission_hash !== submissionHash) { - throw new RunSubmissionConflictError(); - } - return saved; - }; - const previous = await replay(); - if (previous) { - return previous; - } - const parent = await client.query('SELECT * FROM backtests WHERE id = $1 FOR UPDATE', [ - request.backtestId, - ]); - if (!parent.rows.length) { - throw new Error('Backtest not found'); - } - const concurrent = await replay(); - if (concurrent) { - return concurrent; - } - if (at(parent.rows, 0).archived_at) { - throw new BacktestRetentionError('backtest_archived'); - } - const definition = this.mapBacktest(at(parent.rows, 0)); - const catalog = definition.strategyVersionId !== null || definition.strategy === 'catalog'; - if (!catalog) { - throw new CatalogExecutionUnavailableError( - 'Legacy backtest execution is retired. Select an approved strategy version and retained canonical dataset.' - ); - } - 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 result = await client.query( - `INSERT INTO runs - (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, $8, $5, $6, $7 - FROM runs WHERE backtest_id = $2 - ${submission ? 'ON CONFLICT (submission_principal, submission_key) DO NOTHING' : ''} - RETURNING *`, - [ - runId, - request.backtestId, - multiplier, - JSON.stringify(snapshot), - submission?.principal ?? null, - submission?.key ?? null, - submissionHash, - canonical?.datasetHash ?? null, - ] - ); - // Different parent locks can race for one principal/key. The unique index waits for - // the winner's transaction; this next READ COMMITTED query sees its committed row. - if (!result.rows.length) { - const winner = await replay(); - if (!winner) { - throw new Error('Concurrent submission disappeared; retry with the same key'); - } - return winner; - } - await client.query('INSERT INTO backtest_dispatch (run_id) VALUES ($1)', [runId]); - return at(result.rows, 0); - }); - return this.mapRun(row); + createRun(...args: Parameters) { + return this.runs.createRun(...args); } - - /** Preview validates retained inputs without admitting work or consulting current settings. */ - async getReproductionPreview(originalRunId: string): Promise { - return this.container.postgres.transaction(async client => { - const source = (await client.query('SELECT * FROM runs WHERE id=$1', [originalRunId])) - .rows[0]; - if (!source) { - throw new RunReproductionError(404, 'Original run not found'); - } - const preview: CanonicalReproductionPreview = { - originalRunId, - backtestId: source.backtest_id, - available: false, - reason: null, - request: null, - currentReviewId: null, - }; - try { - const request = await this.originalCanonicalRequest(client, source); - preview.request = request; - const parent = ( - await client.query('SELECT archived_at FROM backtests WHERE id=$1 FOR UPDATE', [ - source.backtest_id, - ]) - ).rows[0]; - if (!parent || parent.archived_at !== null) { - throw new RunReproductionError( - 409, - 'Backtest is archived; restore it before reproducing a run' - ); - } - preview.currentReviewId = await verifyReproductionInputs(client, this.container, request); - preview.available = true; - } catch (cause) { - if (!(cause instanceof RunReproductionError)) { - throw cause; - } - preview.reason = cause.message; - } - return preview; - }); + getRun(...args: Parameters) { + return this.runs.getRun(...args); } - - /** - * Create a new run from original retained inputs, not today's editable template. - * Current review and retained-build checks still apply. Only execution/account - * identity and the current review reference are rebound; economics stay pinned. - */ - async reproduceRun(originalRunId: string, submission: RunSubmission): Promise { - if ( - !submission || - !['operator', 'service'].includes(submission.principal) || - !/^[\x21-\x7e]{1,200}$/.test(submission.key) - ) { - throw new HistoricalDataRequestError('Reproduction requires a verified submission receipt'); - } - const submissionHash = createHash('sha256') - .update( - JSON.stringify({ - version: 1, - operation: 'reproduce-original', - originalRunId, - }) - ) - .digest('hex'); - const row = await this.container.postgres.transaction(async client => { - const replay = async () => { - const saved = ( - await client.query( - 'SELECT * FROM runs WHERE submission_principal=$1 AND submission_key=$2', - [submission.principal, submission.key] - ) - ).rows[0]; - if (saved && saved.submission_hash !== submissionHash) { - throw new RunSubmissionConflictError(); - } - return saved; - }; - const previous = await replay(); - if (previous) { - return previous; - } - const source = (await client.query('SELECT * FROM runs WHERE id=$1', [originalRunId])) - .rows[0]; - if (!source) { - throw new RunReproductionError(404, 'Original run not found'); - } - const parent = ( - await client.query('SELECT archived_at FROM backtests WHERE id=$1 FOR UPDATE', [ - source.backtest_id, - ]) - ).rows[0]; - const concurrent = await replay(); - if (concurrent) { - return concurrent; - } - if (!parent || parent.archived_at !== null) { - throw new BacktestRetentionError('backtest_archived'); - } - const original = await this.originalCanonicalRequest(client, source); - const reviewId = await verifyReproductionInputs(client, this.container, original); - const runId = uuidv4(); - const snapshot = structuredClone(original); - snapshot.runId = runId; - snapshot.policy.matching.risk.ledger.sessionId = runId; - snapshot.policy.matching.risk.ledger.accountId = `research:${runId}`; - snapshot.strategy.reviewId = reviewId; - canonicalRunRequestSchema.parse(snapshot); - const inserted = await client.query( - `INSERT INTO runs - (id,backtest_id,run_number,status,speed_multiplier,request_snapshot,dataset_hash, - submission_principal,submission_key,submission_hash,original_run_id) - SELECT $1,$2,COALESCE(MAX(run_number),0)+1,'pending'::run_status,NULL,$3::jsonb,$4,$5,$6,$7,$8 - FROM runs WHERE backtest_id=$2 - ON CONFLICT (submission_principal,submission_key) DO NOTHING RETURNING *`, - [ - runId, - source.backtest_id, - JSON.stringify(snapshot), - snapshot.datasetHash, - submission.principal, - submission.key, - submissionHash, - originalRunId, - ] - ); - if (!inserted.rows[0]) { - const winner = await replay(); - if (!winner) { - throw new Error('Concurrent reproduction disappeared; retry with the same key'); - } - return winner; - } - await client.query('INSERT INTO backtest_dispatch (run_id) VALUES ($1)', [runId]); - return inserted.rows[0]; - }); - return this.mapRun(row); + listRuns(...args: Parameters) { + return this.runs.listRuns(...args); } - - async getReproductionComparison(runId: string): Promise { - const current = (await this.container.postgres.query('SELECT * FROM runs WHERE id=$1', [runId])) - .rows[0]; - if (!current) { - throw new RunReproductionError(404, 'Run not found'); - } - const comparison: CanonicalReproductionComparison = { - version: 'canonical-reproduction/v1', - runId, - backtestId: current.backtest_id, - originalRunId: current.original_run_id ?? null, - status: 'not-reproduction', - reason: null, - originalHash: null, - reproducedHash: null, - }; - if (!comparison.originalRunId) { - return comparison; - } - if (['pending', 'running', 'paused'].includes(current.status)) { - return { ...comparison, status: 'pending', reason: 'The reproduction has not completed' }; - } - if (current.status !== 'completed') { - return { - ...comparison, - status: 'unavailable', - reason: 'The reproduction did not complete successfully', - }; - } - const source = ( - await this.container.postgres.query('SELECT * FROM runs WHERE id=$1', [ - comparison.originalRunId, - ]) - ).rows[0]; - if (!source || source.status !== 'completed' || source.backtest_id !== current.backtest_id) { - return { - ...comparison, - status: 'unavailable', - reason: 'The original completed run is unavailable', - }; - } - const original = await this.getRunResults(source.id); - const reproduced = await this.getRunResults(runId); - if (!original || !reproduced || !('kind' in original) || !('kind' in reproduced)) { - return { - ...comparison, - status: 'unavailable', - reason: 'Complete canonical results are unavailable', - }; - } - const originalHash = canonicalReproductionHash(original); - const reproducedHash = canonicalReproductionHash(reproduced); - return { - ...comparison, - originalHash, - reproducedHash, - status: originalHash === reproducedHash ? 'match' : 'mismatch', - }; + updateRunProgress(...args: Parameters) { + return this.runs.updateRunProgress(...args); } - - private async originalCanonicalRequest(client: PoolClient, source: QueryResultRow) { - if (source.status !== 'completed') { - throw new RunReproductionError(409, 'Only completed original runs can be reproduced'); - } - if (source.request_snapshot?.kind !== 'canonical-research/v1') { - throw new RunReproductionError( - 409, - 'The original run lacks compatible frozen canonical inputs' - ); - } - const request = canonicalRunRequestSchema.parse(source.request_snapshot); - if ( - request.runId !== source.id || - request.backtestId !== source.backtest_id || - request.datasetHash !== source.dataset_hash - ) { - throw new Error('The retained canonical source identity is inconsistent'); - } - const result = await this.getRunResults(source.id, client); - if (!result || !('kind' in result) || result.kind !== 'canonical-result/v1') { - throw new RunReproductionError(409, 'The original canonical result is unavailable'); - } - return request; + pauseRun(...args: Parameters) { + return this.runs.pauseRun(...args); } - - async getRun(id: string): Promise { - const result = await this.container.postgres.query('SELECT * FROM runs WHERE id = $1', [id]); - - if (result.rows.length === 0) { - return null; - } - - return this.mapRun(at(result.rows, 0)); + resumeRun(...args: Parameters) { + return this.runs.resumeRun(...args); } - - async listRuns(backtestId: string): Promise { - const result = await this.container.postgres.query( - `SELECT * FROM runs - WHERE backtest_id = $1 - ORDER BY run_number DESC`, - [backtestId] - ); - - return result.rows.map(row => this.mapRun(row)); + cancelRun(...args: Parameters) { + return this.runs.cancelRun(...args); } - - async updateRunProgress( - id: string, - updates: { progress?: number; currentDate?: Date; attemptId: string } - ): Promise { - const result = await this.container.postgres.transaction(async client => { - await client.query('SELECT id FROM runs WHERE id = $1 FOR UPDATE', [id]); - return client.query( - `UPDATE runs - SET progress = GREATEST(COALESCE($2::numeric, progress), progress), current_simulation_date = COALESCE($3, current_simulation_date), updated_at = NOW() - WHERE id = $1 AND status IN ('running', 'paused') AND attempt_id = $4 AND lease_expires_at > clock_timestamp() RETURNING status`, - [id, updates.progress ?? null, updates.currentDate ?? null, updates.attemptId] - ); - }); - const row = result.rows[0]; - if (row) { - this.getWebSocketHandler()?.broadcastRunUpdate(id, { - type: 'run_update', - runId: id, - data: { status: row.status, ...updates, timestamp: new Date().toISOString() }, - }); - } + updateRunSpeed(...args: Parameters) { + return this.runs.updateRunSpeed(...args); } - - async pauseRun(id: string): Promise { - await this.sendControl(id, 'pause'); + canonicalCapability(...args: Parameters) { + return this.runs.canonicalCapability(...args); } - async resumeRun(id: string): Promise { - await this.sendControl(id, 'resume'); + getRunResults(...args: Parameters) { + return this.results.getRunResults(...args); } - async cancelRun(id: string): Promise { - const result = await this.container.postgres.query( - `UPDATE runs SET cancel_requested = TRUE, - status = CASE WHEN status = 'pending' THEN 'cancelled'::run_status ELSE status END, - completed_at = CASE WHEN status = 'pending' THEN NOW() ELSE completed_at END, updated_at = NOW() - WHERE id = $1 AND status IN ('pending', 'running', 'paused', 'cancelled') RETURNING status`, - [id] - ); - const row = result.rows[0]; - if (!row) { - throw new Error('No cancellable run found'); - } - this.getWebSocketHandler()?.broadcastRunUpdate(id, { - type: 'run_update', - data: { status: row.status, cancelRequested: true, timestamp: new Date().toISOString() }, - }); + getReproductionPreview(...args: Parameters) { + return this.reproduction.getReproductionPreview(...args); } - async updateRunSpeed(id: string, speedMultiplier: number | null): Promise { - await this.sendControl(id, 'speed', { speed: speedMultiplier }); + reproduceRun(...args: Parameters) { + return this.reproduction.reproduceRun(...args); } - private async sendControl(runId: string, command: string, payload: object = {}): Promise { - const response = await this.request(`${ORCHESTRATOR_URL}/api/backtest/${command}`, { - method: 'POST', - headers: { 'Content-Type': 'application/json' }, - body: JSON.stringify({ ...payload, runId }), - }); - if (!response.ok) { - throw new Error(`Backtest ${command} was not acknowledged: ${await response.text()}`); - } - // The runner, not the API client, commits acknowledged state changes. - } - - /** - * Read saved results and verify canonical provenance and derived analytics - * against the frozen request. Recomputing statistics checks integrity; it does - * not simulate fills again. Missing canonical data must not fall back to a - * legacy result projection, which has different financial semantics. - */ - async getRunResults( - runId: string, - database: BacktestResultQuery = this.container.postgres - ): Promise { - const result = await database.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, - b.end_date, - b.initial_capital, - b.config as backtest_config - FROM backtest_results br - JOIN runs r ON r.id = br.run_id - JOIN backtests b ON b.id = r.backtest_id - WHERE br.run_id = $1`, - [runId] - ); - - if (result.rows.length === 0) { - return null; - } - - 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 !== canonicalStrategyExecution(request) || - !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); - } - - /** Preview admission for the UI without saving a run; submission must recheck it. */ - async canonicalCapability(id: string): Promise { - try { - const execution = 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'); - } - const request = await admitCanonicalRequest( - client, - this.container, - this.mapBacktest(row), - id - ); - return request.strategy.origin === 'candidate' ? request.strategy.execution : undefined; - }); - return { available: true, reason: null, ...(execution ? { execution } : {}) }; - } catch (error) { - return { - available: false, - reason: error instanceof Error ? error.message : 'Canonical execution unavailable', - }; - } - } - - // Private methods - private async validateCatalogDraft( - client: PoolClient, - input: unknown, - previousVersionId?: string | null - ): Promise { - try { - assertStrategyJsonText(input); - } catch (error) { - throw new HistoricalDataRequestError( - error instanceof Error ? error.message : 'Invalid catalog draft text' - ); - } - const draft = CatalogBacktestDefinitionSchema.parse(input); - let parameters: Record; - const pkg = await new StrategyCatalogService(this.container).getVersionArtifact( - draft.strategyVersionId, - client - ); - try { - assertStrategyJsonText(draft); - parameters = validateStrategyParameters(pkg, draft.strategyParameters); - } catch (error) { - throw new HistoricalDataRequestError( - error instanceof Error ? error.message : 'Invalid strategy parameters' - ); - } - const family = ( - await client.query( - `SELECT s.archived_at FROM strategy_versions v JOIN strategies s ON s.id=v.strategy_id WHERE v.id=$1 FOR UPDATE OF s`, - [draft.strategyVersionId] - ) - ).rows[0]; - if (!family) { - throw new StrategyCatalogError(404, 'Strategy version not found'); - } - if (previousVersionId !== draft.strategyVersionId && family.archived_at) { - throw new StrategyCatalogError( - 409, - '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 { - ...draft, - startDate: settings.startDate, - endDate: settings.endDate, - strategyParameters: parameters, - }; - } - private mapBacktest(row: QueryResultRow): Backtest { - return { - id: row.id, - archivedAt: row.archived_at ? new Date(row.archived_at).toISOString() : null, - strategyVersionId: row.strategy_version_id ?? null, - strategyParameters: row.strategy_parameters ?? null, - name: row.name, - strategy: row.strategy, - symbols: row.symbols, - startDate: row.start_date, - endDate: row.end_date, - initialCapital: parseFloat(row.initial_capital), - config: row.config, - createdAt: row.created_at, - updatedAt: row.updated_at, - }; - } - - private getWebSocketHandler(): WebSocketHandler | null { - // Try to get from global if not already set - this.wsHandler ??= getWebSocketHandler(); - return this.wsHandler; - } - - private mapRun(row: QueryResultRow): Run { - return { - originalRunId: row.original_run_id ?? null, - dataset: datasetSelectionForRun(row), - id: row.id, - backtestId: row.backtest_id, - runNumber: row.run_number, - status: row.status, - speedMultiplier: row.speed_multiplier === null ? null : parseFloat(row.speed_multiplier), - error: row.error, - startedAt: row.started_at, - completedAt: row.completed_at, - pausedAt: row.paused_at, - progress: parseFloat(row.progress), - cancelRequested: row.cancel_requested === true, - attemptNumber: Number(row.attempt_number ?? 0), - currentDate: row.current_simulation_date, - createdAt: row.created_at, - updatedAt: row.updated_at, - }; + getReproductionComparison( + ...args: Parameters + ) { + return this.reproduction.getReproductionComparison(...args); } } - -/** Provenance comes from the immutable request and bound dataset, never its template. */ -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); - } catch { - return { requestedHash: null, pinnedHash, source: null, state: 'unknown' }; - } - return { - requestedHash: snapshot.datasetHash ?? null, - pinnedHash, - source: snapshot.dataSource ?? 'auto', - state: pinnedHash - ? 'pinned' - : ['completed', 'failed', 'cancelled'].includes(row.status) - ? 'unavailable' - : ['running', 'paused'].includes(row.status) - ? 'preparing' - : 'requested', - }; -} diff --git a/apps/stock/web-api/src/services/backtests/contracts.ts b/apps/stock/web-api/src/services/backtests/contracts.ts new file mode 100644 index 00000000..1e3677c1 --- /dev/null +++ b/apps/stock/web-api/src/services/backtests/contracts.ts @@ -0,0 +1,128 @@ +import type { QueryResultRow } from 'pg'; +import type { IServiceContainer } from '@stock-bot/services'; +import type { BacktestDefinitionInput } from '@stock-bot/stock-config/backtest'; +import type { + BacktestRunDatasetSelection, + ResearchActor, + StrategyParameterValue, +} from '@stock-bot/types'; + +export type BacktestTransport = (url: string, init?: RequestInit) => Promise; +/** Reads may share an existing transaction without acquiring another pool connection. */ +export interface BacktestResultQuery { + query( + text: string, + values?: unknown[] + ): Promise<{ rows: T[] }>; +} + +export interface BacktestRequest { + name: string; + strategy: string; + symbols: string[]; + startDate: string; + endDate: string; + initialCapital: number; + config?: Record; + strategyVersionId?: string | null; + strategyParameters?: Record | null; +} + +export interface Backtest { + id: string; + archivedAt: string | null; + strategyVersionId: string | null; + strategyParameters: Record | null; + name: string; + strategy: string; + symbols: string[]; + startDate: Date; + endDate: Date; + initialCapital: number; + config: Record; + createdAt: Date; + updatedAt: Date; +} + +export interface Run { + originalRunId: string | null; + dataset: BacktestRunDatasetSelection; + id: string; + backtestId: string; + runNumber: number; + status: 'pending' | 'running' | 'completed' | 'failed' | 'cancelled' | 'paused'; + speedMultiplier: number | null; + error?: string; + startedAt?: Date; + completedAt?: Date; + pausedAt?: Date; + progress: number; + cancelRequested: boolean; + attemptNumber: number; + currentDate?: Date; + createdAt: Date; + updatedAt: Date; +} + +export interface RunRequest { + backtestId: string; + speedMultiplier?: number | null; +} + +export interface RunSubmission { + principal: ResearchActor; + key: string; +} + +export class RunSubmissionConflictError extends Error { + constructor() { + super('This submission key was already used for a different run request'); + this.name = 'RunSubmissionConflictError'; + } +} +export class CatalogExecutionUnavailableError extends Error { + readonly code = 'catalog_execution_unavailable'; + constructor(reason?: string) { + super( + reason ?? + 'Configure an approved built-in, eligible v2 dataset and canonical policy before execution' + ); + } +} + +/** Strip only DTO metadata from legacy definitions; caller-supplied markers are rejected first. */ +export function legacyDefinition(input: BacktestDefinitionInput): BacktestDefinitionInput { + return { + name: input.name, + strategy: input.strategy, + symbols: input.symbols, + startDate: input.startDate, + endDate: input.endDate, + initialCapital: input.initialCapital, + config: input.config, + }; +} + +export class BacktestRetentionError extends Error { + constructor( + public readonly code: 'backtest_archived' | 'retained_runs', + public readonly runCount?: number + ) { + super( + code === 'backtest_archived' + ? 'Backtest is archived; restore it before editing or submitting a new run' + : `Backtest has ${runCount} retained run(s); archive it to preserve results and reproducibility` + ); + } +} + +/** + * Application service for editable templates and immutable run inputs/results. + * Submission writes a PostgreSQL outbox row for BacktestDispatcher; execution + * belongs to the orchestrator. Historical result readers remain available even + * though new submissions require the canonical Rust research path. + */ + +export type BacktestContainer = IServiceContainer & { + postgres: NonNullable; +}; diff --git a/apps/stock/web-api/src/services/backtests/mapping.ts b/apps/stock/web-api/src/services/backtests/mapping.ts new file mode 100644 index 00000000..9746b95e --- /dev/null +++ b/apps/stock/web-api/src/services/backtests/mapping.ts @@ -0,0 +1,76 @@ +import type { QueryResultRow } from 'pg'; +import { datasetHashSchema, parseBacktestRequest } from '@stock-bot/stock-config/backtest'; +import { canonicalRunRequestSchema } from '@stock-bot/stock-config/canonical-research'; +import type { BacktestRunDatasetSelection } from '@stock-bot/types'; +import type { Backtest, Run } from './contracts'; + +export function mapBacktest(row: QueryResultRow): Backtest { + return { + id: row.id, + archivedAt: row.archived_at ? new Date(row.archived_at).toISOString() : null, + strategyVersionId: row.strategy_version_id ?? null, + strategyParameters: row.strategy_parameters ?? null, + name: row.name, + strategy: row.strategy, + symbols: row.symbols, + startDate: row.start_date, + endDate: row.end_date, + initialCapital: parseFloat(row.initial_capital), + config: row.config, + createdAt: row.created_at, + updatedAt: row.updated_at, + }; +} +export function mapRun(row: QueryResultRow): Run { + return { + originalRunId: row.original_run_id ?? null, + dataset: datasetSelectionForRun(row), + id: row.id, + backtestId: row.backtest_id, + runNumber: row.run_number, + status: row.status, + speedMultiplier: row.speed_multiplier === null ? null : parseFloat(row.speed_multiplier), + error: row.error, + startedAt: row.started_at, + completedAt: row.completed_at, + pausedAt: row.paused_at, + progress: parseFloat(row.progress), + cancelRequested: row.cancel_requested === true, + attemptNumber: Number(row.attempt_number ?? 0), + currentDate: row.current_simulation_date, + createdAt: row.created_at, + updatedAt: row.updated_at, + }; +} +/** Provenance comes from the immutable request and bound dataset, never its template. */ +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); + } catch { + return { requestedHash: null, pinnedHash, source: null, state: 'unknown' }; + } + return { + requestedHash: snapshot.datasetHash ?? null, + pinnedHash, + source: snapshot.dataSource ?? 'auto', + state: pinnedHash + ? 'pinned' + : ['completed', 'failed', 'cancelled'].includes(row.status) + ? 'unavailable' + : ['running', 'paused'].includes(row.status) + ? 'preparing' + : 'requested', + }; +} diff --git a/apps/stock/web-api/src/services/backtests/reproduction.ts b/apps/stock/web-api/src/services/backtests/reproduction.ts new file mode 100644 index 00000000..684ce0bf --- /dev/null +++ b/apps/stock/web-api/src/services/backtests/reproduction.ts @@ -0,0 +1,243 @@ +import { createHash, randomUUID as uuidv4 } from 'node:crypto'; +import type { PoolClient, QueryResultRow } from 'pg'; +import { + canonicalRunRequestSchema, + type CanonicalReproductionComparison, + type CanonicalReproductionPreview, +} from '@stock-bot/stock-config/canonical-research'; +import { HistoricalDataRequestError } from '@stock-bot/types'; +import { canonicalReproductionHash } from '../reproduction-comparison'; +import { RunReproductionError, verifyReproductionInputs } from '../run-reproduction'; +import { + BacktestRetentionError, + RunSubmissionConflictError, + type BacktestContainer, + type Run, + type RunSubmission, +} from './contracts'; +import { mapRun } from './mapping'; +import type { BacktestResults } from './results'; + +/** Focused reproduction operations; transaction order is preserved. */ +export class BacktestReproduction { + constructor( + private readonly container: BacktestContainer, + private readonly results: BacktestResults + ) {} + async getReproductionPreview(originalRunId: string): Promise { + return this.container.postgres.transaction(async client => { + const source = (await client.query('SELECT * FROM runs WHERE id=$1', [originalRunId])) + .rows[0]; + if (!source) { + throw new RunReproductionError(404, 'Original run not found'); + } + const preview: CanonicalReproductionPreview = { + originalRunId, + backtestId: source.backtest_id, + available: false, + reason: null, + request: null, + currentReviewId: null, + }; + try { + const request = await this.originalCanonicalRequest(client, source); + preview.request = request; + const parent = ( + await client.query('SELECT archived_at FROM backtests WHERE id=$1 FOR UPDATE', [ + source.backtest_id, + ]) + ).rows[0]; + if (!parent || parent.archived_at !== null) { + throw new RunReproductionError( + 409, + 'Backtest is archived; restore it before reproducing a run' + ); + } + preview.currentReviewId = await verifyReproductionInputs(client, this.container, request); + preview.available = true; + } catch (cause) { + if (!(cause instanceof RunReproductionError)) { + throw cause; + } + preview.reason = cause.message; + } + return preview; + }); + } + + async reproduceRun(originalRunId: string, submission: RunSubmission): Promise { + if ( + !submission || + !['operator', 'service'].includes(submission.principal) || + !/^[\x21-\x7e]{1,200}$/.test(submission.key) + ) { + throw new HistoricalDataRequestError('Reproduction requires a verified submission receipt'); + } + const submissionHash = createHash('sha256') + .update( + JSON.stringify({ + version: 1, + operation: 'reproduce-original', + originalRunId, + }) + ) + .digest('hex'); + const row = await this.container.postgres.transaction(async client => { + const replay = async () => { + const saved = ( + await client.query( + 'SELECT * FROM runs WHERE submission_principal=$1 AND submission_key=$2', + [submission.principal, submission.key] + ) + ).rows[0]; + if (saved && saved.submission_hash !== submissionHash) { + throw new RunSubmissionConflictError(); + } + return saved; + }; + const previous = await replay(); + if (previous) { + return previous; + } + const source = (await client.query('SELECT * FROM runs WHERE id=$1', [originalRunId])) + .rows[0]; + if (!source) { + throw new RunReproductionError(404, 'Original run not found'); + } + const parent = ( + await client.query('SELECT archived_at FROM backtests WHERE id=$1 FOR UPDATE', [ + source.backtest_id, + ]) + ).rows[0]; + const concurrent = await replay(); + if (concurrent) { + return concurrent; + } + if (!parent || parent.archived_at !== null) { + throw new BacktestRetentionError('backtest_archived'); + } + const original = await this.originalCanonicalRequest(client, source); + const reviewId = await verifyReproductionInputs(client, this.container, original); + const runId = uuidv4(); + const snapshot = structuredClone(original); + snapshot.runId = runId; + snapshot.policy.matching.risk.ledger.sessionId = runId; + snapshot.policy.matching.risk.ledger.accountId = `research:${runId}`; + snapshot.strategy.reviewId = reviewId; + canonicalRunRequestSchema.parse(snapshot); + const inserted = await client.query( + `INSERT INTO runs + (id,backtest_id,run_number,status,speed_multiplier,request_snapshot,dataset_hash, + submission_principal,submission_key,submission_hash,original_run_id) + SELECT $1,$2,COALESCE(MAX(run_number),0)+1,'pending'::run_status,NULL,$3::jsonb,$4,$5,$6,$7,$8 + FROM runs WHERE backtest_id=$2 + ON CONFLICT (submission_principal,submission_key) DO NOTHING RETURNING *`, + [ + runId, + source.backtest_id, + JSON.stringify(snapshot), + snapshot.datasetHash, + submission.principal, + submission.key, + submissionHash, + originalRunId, + ] + ); + if (!inserted.rows[0]) { + const winner = await replay(); + if (!winner) { + throw new Error('Concurrent reproduction disappeared; retry with the same key'); + } + return winner; + } + await client.query('INSERT INTO backtest_dispatch (run_id) VALUES ($1)', [runId]); + return inserted.rows[0]; + }); + return mapRun(row); + } + + async getReproductionComparison(runId: string): Promise { + const current = (await this.container.postgres.query('SELECT * FROM runs WHERE id=$1', [runId])) + .rows[0]; + if (!current) { + throw new RunReproductionError(404, 'Run not found'); + } + const comparison: CanonicalReproductionComparison = { + version: 'canonical-reproduction/v1', + runId, + backtestId: current.backtest_id, + originalRunId: current.original_run_id ?? null, + status: 'not-reproduction', + reason: null, + originalHash: null, + reproducedHash: null, + }; + if (!comparison.originalRunId) { + return comparison; + } + if (['pending', 'running', 'paused'].includes(current.status)) { + return { ...comparison, status: 'pending', reason: 'The reproduction has not completed' }; + } + if (current.status !== 'completed') { + return { + ...comparison, + status: 'unavailable', + reason: 'The reproduction did not complete successfully', + }; + } + const source = ( + await this.container.postgres.query('SELECT * FROM runs WHERE id=$1', [ + comparison.originalRunId, + ]) + ).rows[0]; + if (!source || source.status !== 'completed' || source.backtest_id !== current.backtest_id) { + return { + ...comparison, + status: 'unavailable', + reason: 'The original completed run is unavailable', + }; + } + const original = await this.results.getRunResults(source.id); + const reproduced = await this.results.getRunResults(runId); + if (!original || !reproduced || !('kind' in original) || !('kind' in reproduced)) { + return { + ...comparison, + status: 'unavailable', + reason: 'Complete canonical results are unavailable', + }; + } + const originalHash = canonicalReproductionHash(original); + const reproducedHash = canonicalReproductionHash(reproduced); + return { + ...comparison, + originalHash, + reproducedHash, + status: originalHash === reproducedHash ? 'match' : 'mismatch', + }; + } + + private async originalCanonicalRequest(client: PoolClient, source: QueryResultRow) { + if (source.status !== 'completed') { + throw new RunReproductionError(409, 'Only completed original runs can be reproduced'); + } + if (source.request_snapshot?.kind !== 'canonical-research/v1') { + throw new RunReproductionError( + 409, + 'The original run lacks compatible frozen canonical inputs' + ); + } + const request = canonicalRunRequestSchema.parse(source.request_snapshot); + if ( + request.runId !== source.id || + request.backtestId !== source.backtest_id || + request.datasetHash !== source.dataset_hash + ) { + throw new Error('The retained canonical source identity is inconsistent'); + } + const result = await this.results.getRunResults(source.id, client); + if (!result || !('kind' in result) || result.kind !== 'canonical-result/v1') { + throw new RunReproductionError(409, 'The original canonical result is unavailable'); + } + return request; + } +} diff --git a/apps/stock/web-api/src/services/backtests/results.ts b/apps/stock/web-api/src/services/backtests/results.ts new file mode 100644 index 00000000..2b9dc3d3 --- /dev/null +++ b/apps/stock/web-api/src/services/backtests/results.ts @@ -0,0 +1,79 @@ +import { at } from '@stock-bot/invariants'; +import { buildCanonicalBacktestReport } from '@stock-bot/research/results'; +import { + canonicalRunRequestSchema, + canonicalStrategyExecution, + parseCanonicalFinancialResult, + type CanonicalRunResult, + type ResearchRunResult, +} from '@stock-bot/stock-config/canonical-research'; +import { canonicalStrategyJson } from '@stock-bot/stock-config/strategy'; +import { mapStoredBacktestResult, type StoredBacktestResult } from '../backtest-result'; +import { type BacktestContainer, type BacktestResultQuery } from './contracts'; + +/** Focused results operations; transaction order is preserved. */ +export class BacktestResults { + constructor(private readonly container: BacktestContainer) {} + async getRunResults( + runId: string, + database: BacktestResultQuery = this.container.postgres + ): Promise { + const result = await database.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, + b.end_date, + b.initial_capital, + b.config as backtest_config + FROM backtest_results br + JOIN runs r ON r.id = br.run_id + JOIN backtests b ON b.id = r.backtest_id + WHERE br.run_id = $1`, + [runId] + ); + + if (result.rows.length === 0) { + return null; + } + + 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 !== canonicalStrategyExecution(request) || + !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); + } +} diff --git a/apps/stock/web-api/src/services/backtests/runs.ts b/apps/stock/web-api/src/services/backtests/runs.ts new file mode 100644 index 00000000..012d6d81 --- /dev/null +++ b/apps/stock/web-api/src/services/backtests/runs.ts @@ -0,0 +1,246 @@ +import { createHash, randomUUID as uuidv4 } from 'node:crypto'; +import { at } from '@stock-bot/invariants'; +import { type CanonicalRunCapability } from '@stock-bot/stock-config/canonical-research'; +import { HistoricalDataRequestError } from '@stock-bot/types'; +import { getWebSocketHandler } from '../../websocket/run-updates'; +import type { WebSocketHandler } from '../../websocket/run-updates'; +import { admitCanonicalRequest } from '../canonical-research.service'; +import { + BacktestRetentionError, + CatalogExecutionUnavailableError, + RunSubmissionConflictError, + type BacktestContainer, + type BacktestTransport, + type Run, + type RunRequest, + type RunSubmission, +} from './contracts'; +import { mapBacktest, mapRun } from './mapping'; + +const ORCHESTRATOR_URL = process.env.ORCHESTRATOR_URL || 'http://localhost:2004'; + +/** Focused runs operations; transaction order is preserved. */ +export class BacktestRuns { + private wsHandler: WebSocketHandler | null = null; + constructor( + private readonly container: BacktestContainer, + private readonly request: BacktestTransport + ) {} + async createRun(request: RunRequest, submission?: RunSubmission): Promise { + const runId = uuidv4(); + const multiplier = request.speedMultiplier ?? null; + if (multiplier !== null && (!Number.isFinite(multiplier) || multiplier <= 0)) { + throw new HistoricalDataRequestError('Speed multiplier must be positive or null'); + } + // Hash submission intent, not the mutable definition or newly generated run ID. + // A retry after an edit must still return the original run and its frozen snapshot. + const submissionHash = submission + ? createHash('sha256') + .update( + JSON.stringify({ + version: 1, + backtestId: request.backtestId, + speedMultiplier: multiplier, + }) + ) + .digest('hex') + : null; + const row = await this.container.postgres.transaction(async client => { + const replay = async () => { + if (!submission) { + return undefined; + } + const existing = await client.query( + 'SELECT * FROM runs WHERE submission_principal = $1 AND submission_key = $2', + [submission.principal, submission.key] + ); + const saved = existing.rows[0]; + if (saved && saved.submission_hash !== submissionHash) { + throw new RunSubmissionConflictError(); + } + return saved; + }; + const previous = await replay(); + if (previous) { + return previous; + } + const parent = await client.query('SELECT * FROM backtests WHERE id = $1 FOR UPDATE', [ + request.backtestId, + ]); + if (!parent.rows.length) { + throw new Error('Backtest not found'); + } + const concurrent = await replay(); + if (concurrent) { + return concurrent; + } + if (at(parent.rows, 0).archived_at) { + throw new BacktestRetentionError('backtest_archived'); + } + const definition = mapBacktest(at(parent.rows, 0)); + const catalog = definition.strategyVersionId !== null || definition.strategy === 'catalog'; + if (!catalog) { + throw new CatalogExecutionUnavailableError( + 'Legacy backtest execution is retired. Select an approved strategy version and retained canonical dataset.' + ); + } + if (multiplier !== null) { + throw new CatalogExecutionUnavailableError('Canonical research runs at maximum speed'); + } + const snapshot = await admitCanonicalRequest( + client, + this.container, + definition, + definition.id, + runId + ).catch((error: unknown) => { + throw new CatalogExecutionUnavailableError( + error instanceof Error ? error.message : 'Canonical execution unavailable' + ); + }); + const result = await client.query( + `INSERT INTO runs + (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, $8, $5, $6, $7 + FROM runs WHERE backtest_id = $2 + ${submission ? 'ON CONFLICT (submission_principal, submission_key) DO NOTHING' : ''} + RETURNING *`, + [ + runId, + request.backtestId, + multiplier, + JSON.stringify(snapshot), + submission?.principal ?? null, + submission?.key ?? null, + submissionHash, + snapshot.datasetHash, + ] + ); + // Different parent locks can race for one principal/key. The unique index waits for + // the winner's transaction; this next READ COMMITTED query sees its committed row. + if (!result.rows.length) { + const winner = await replay(); + if (!winner) { + throw new Error('Concurrent submission disappeared; retry with the same key'); + } + return winner; + } + await client.query('INSERT INTO backtest_dispatch (run_id) VALUES ($1)', [runId]); + return at(result.rows, 0); + }); + return mapRun(row); + } + + async getRun(id: string): Promise { + const result = await this.container.postgres.query('SELECT * FROM runs WHERE id = $1', [id]); + + if (result.rows.length === 0) { + return null; + } + + return mapRun(at(result.rows, 0)); + } + + async listRuns(backtestId: string): Promise { + const result = await this.container.postgres.query( + `SELECT * FROM runs + WHERE backtest_id = $1 + ORDER BY run_number DESC`, + [backtestId] + ); + + return result.rows.map(row => mapRun(row)); + } + + async updateRunProgress( + id: string, + updates: { progress?: number; currentDate?: Date; attemptId: string } + ): Promise { + const result = await this.container.postgres.transaction(async client => { + await client.query('SELECT id FROM runs WHERE id = $1 FOR UPDATE', [id]); + return client.query( + `UPDATE runs + SET progress = GREATEST(COALESCE($2::numeric, progress), progress), current_simulation_date = COALESCE($3, current_simulation_date), updated_at = NOW() + WHERE id = $1 AND status IN ('running', 'paused') AND attempt_id = $4 AND lease_expires_at > clock_timestamp() RETURNING status`, + [id, updates.progress ?? null, updates.currentDate ?? null, updates.attemptId] + ); + }); + const row = result.rows[0]; + if (row) { + this.getWebSocketHandler()?.broadcastRunUpdate(id, { + type: 'run_update', + runId: id, + data: { status: row.status, ...updates, timestamp: new Date().toISOString() }, + }); + } + } + + async pauseRun(id: string): Promise { + await this.sendControl(id, 'pause'); + } + + async resumeRun(id: string): Promise { + await this.sendControl(id, 'resume'); + } + + async cancelRun(id: string): Promise { + const result = await this.container.postgres.query( + `UPDATE runs SET cancel_requested = TRUE, + status = CASE WHEN status = 'pending' THEN 'cancelled'::run_status ELSE status END, + completed_at = CASE WHEN status = 'pending' THEN NOW() ELSE completed_at END, updated_at = NOW() + WHERE id = $1 AND status IN ('pending', 'running', 'paused', 'cancelled') RETURNING status`, + [id] + ); + const row = result.rows[0]; + if (!row) { + throw new Error('No cancellable run found'); + } + this.getWebSocketHandler()?.broadcastRunUpdate(id, { + type: 'run_update', + data: { status: row.status, cancelRequested: true, timestamp: new Date().toISOString() }, + }); + } + + async updateRunSpeed(id: string, speedMultiplier: number | null): Promise { + await this.sendControl(id, 'speed', { speed: speedMultiplier }); + } + + private async sendControl(runId: string, command: string, payload: object = {}): Promise { + const response = await this.request(`${ORCHESTRATOR_URL}/api/backtest/${command}`, { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ ...payload, runId }), + }); + if (!response.ok) { + throw new Error(`Backtest ${command} was not acknowledged: ${await response.text()}`); + } + // The runner, not the API client, commits acknowledged state changes. + } + + async canonicalCapability(id: string): Promise { + try { + const execution = 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'); + } + const request = await admitCanonicalRequest(client, this.container, mapBacktest(row), id); + return request.strategy.origin === 'candidate' ? request.strategy.execution : undefined; + }); + return { available: true, reason: null, ...(execution ? { execution } : {}) }; + } catch (error) { + return { + available: false, + reason: error instanceof Error ? error.message : 'Canonical execution unavailable', + }; + } + } + + private getWebSocketHandler(): WebSocketHandler | null { + // Try to get from global if not already set + this.wsHandler ??= getWebSocketHandler(); + return this.wsHandler; + } +} diff --git a/apps/stock/web-api/src/services/backtests/templates.ts b/apps/stock/web-api/src/services/backtests/templates.ts new file mode 100644 index 00000000..f25acde3 --- /dev/null +++ b/apps/stock/web-api/src/services/backtests/templates.ts @@ -0,0 +1,321 @@ +import { randomUUID as uuidv4 } from 'node:crypto'; +import type { PoolClient } from 'pg'; +import { at } from '@stock-bot/invariants'; +import { getLogger } from '@stock-bot/logger'; +import { + backtestRequestFromDefinition, + backtestSettingsFromDefinition, + CatalogBacktestDefinitionSchema, + rejectCatalogVersionReferences, +} from '@stock-bot/stock-config/backtest'; +import { + assertStrategyJsonText, + validateStrategyParameters, +} from '@stock-bot/stock-config/strategy'; +import type { StrategyParameterValue } from '@stock-bot/types'; +import { HistoricalDataRequestError } from '@stock-bot/types'; +import { validateCanonicalSetup } from '../canonical-research.service'; +import { assertSelectedDatasetMatchesRequest } from '../dataset-catalog.service'; +import { StrategyCatalogError, StrategyCatalogService } from '../strategy-catalog.service'; +import { + BacktestRetentionError, + legacyDefinition, + type Backtest, + type BacktestContainer, + type BacktestRequest, + type Run, + type RunRequest, +} from './contracts'; +import { mapBacktest } from './mapping'; + +const logger = getLogger('backtest-v2-service'); + +/** Focused templates operations; transaction order is preserved. */ +export class BacktestTemplates { + constructor( + private readonly container: BacktestContainer, + private readonly startRun: (request: RunRequest) => Promise + ) {} + async createBacktest( + request: BacktestRequest, + options: { autoStart?: boolean } = {} + ): Promise { + const catalog = request.strategy === 'catalog'; + if (catalog && options.autoStart !== false) { + throw new HistoricalDataRequestError('Catalog drafts require explicit autoStart:false'); + } + if (!catalog) { + rejectCatalogVersionReferences(request); + } + const backtestId = uuidv4(); + const result = await this.container.postgres.transaction(async client => { + const definition = catalog ? await this.validateCatalogDraft(client, request) : request; + if (!catalog) { + await assertSelectedDatasetMatchesRequest( + client, + backtestRequestFromDefinition(definition) + ); + } + return client.query( + `INSERT INTO backtests + (id, name, strategy, symbols, start_date, end_date, initial_capital, config, strategy_version_id, strategy_parameters) + VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10) + RETURNING *`, + [ + backtestId, + definition.name, + definition.strategy, + JSON.stringify(definition.symbols), + definition.startDate, + definition.endDate, + definition.initialCapital, + JSON.stringify(definition.config || {}), + definition.strategyVersionId ?? null, + definition.strategyParameters ? JSON.stringify(definition.strategyParameters) : null, + ] + ); + }); + + const backtest = mapBacktest(at(result.rows, 0)); + + // Automatically create and start a run for the new backtest + if (options.autoStart !== false) { + try { + await this.startRun({ + backtestId: backtest.id, + speedMultiplier: null, // Max speed (instant) + }); + } catch (error) { + logger.error('Failed to auto-create run for new backtest', { + backtestId: backtest.id, + error, + }); + // Don't fail the backtest creation if run creation fails + } + } + return backtest; + } + + async getBacktest(id: string): Promise { + const result = await this.container.postgres.query('SELECT * FROM backtests WHERE id = $1', [ + id, + ]); + + if (result.rows.length === 0) { + return null; + } + + return mapBacktest(at(result.rows, 0)); + } + + async updateBacktest(id: string, request: Partial): Promise { + return this.container.postgres.transaction(async client => { + const locked = await client.query('SELECT * FROM backtests WHERE id = $1 FOR UPDATE', [id]); + if (!locked.rows[0]) { + return null; + } + if (locked.rows[0].archived_at) { + throw new BacktestRetentionError('backtest_archived'); + } + const existing = mapBacktest(locked.rows[0]); + const catalog = existing.strategyVersionId !== null; + let next = { ...existing, ...request }; + if (catalog) { + CatalogBacktestDefinitionSchema.partial().parse(request); + if ( + request.strategyVersionId !== undefined && + request.strategyVersionId !== existing.strategyVersionId && + request.strategyParameters === undefined + ) { + throw new HistoricalDataRequestError( + 'Changing a selected version requires explicit strategyParameters' + ); + } + const normalized = await this.validateCatalogDraft( + client, + { + ...legacyDefinition(next), + strategyVersionId: next.strategyVersionId, + strategyParameters: next.strategyParameters, + }, + existing.strategyVersionId + ); + next = { ...next, ...normalized } as typeof next; + } else { + rejectCatalogVersionReferences(request); + await assertSelectedDatasetMatchesRequest( + client, + backtestRequestFromDefinition(legacyDefinition(next)) + ); + } + const updates: string[] = []; + const values: unknown[] = []; + let paramCount = 1; + + if (request.name !== undefined) { + updates.push(`name = $${paramCount++}`); + values.push(catalog ? next.name : request.name); + } + if (request.strategy !== undefined) { + updates.push(`strategy = $${paramCount++}`); + values.push(catalog ? next.strategy : request.strategy); + } + if (request.symbols !== undefined) { + updates.push(`symbols = $${paramCount++}`); + values.push(JSON.stringify(catalog ? next.symbols : request.symbols)); + } + if (request.startDate !== undefined) { + updates.push(`start_date = $${paramCount++}`); + values.push(catalog ? next.startDate : request.startDate); + } + if (request.endDate !== undefined) { + updates.push(`end_date = $${paramCount++}`); + values.push(catalog ? next.endDate : request.endDate); + } + if (request.initialCapital !== undefined) { + updates.push(`initial_capital = $${paramCount++}`); + values.push(catalog ? next.initialCapital : request.initialCapital); + } + if (request.config !== undefined) { + updates.push(`config = $${paramCount++}`); + values.push(JSON.stringify(catalog ? next.config : request.config)); + } + if (catalog) { + updates.push( + `strategy_version_id = $${paramCount++}`, + `strategy_parameters = $${paramCount++}` + ); + values.push(next.strategyVersionId, JSON.stringify(next.strategyParameters)); + } + + if (updates.length === 0) { + return existing; + } + + values.push(id); + const result = await client.query( + `UPDATE backtests + SET ${updates.join(', ')}, updated_at = NOW() + WHERE id = $${paramCount} + RETURNING *`, + values + ); + + if (result.rows.length === 0) { + return null; + } + + return mapBacktest(at(result.rows, 0)); + }); + } + + async listBacktests(params: { + limit: number; + offset: number; + includeArchived?: boolean; + }): Promise { + const result = await this.container.postgres.query( + `SELECT * FROM backtests + WHERE ($3::boolean OR archived_at IS NULL) + ORDER BY created_at DESC + LIMIT $1 OFFSET $2`, + [params.limit, params.offset, params.includeArchived === true] + ); + + return result.rows.map(row => mapBacktest(row)); + } + + async deleteBacktest(id: string): Promise { + await this.container.postgres.transaction(async client => { + const parent = await client.query('SELECT id FROM backtests WHERE id=$1 FOR UPDATE', [id]); + if (!parent.rows[0]) { + return; + } + const retained = await client.query( + 'SELECT count(*)::int AS count FROM runs WHERE backtest_id=$1', + [id] + ); + const count = Number(retained.rows[0]?.count ?? 0); + if (count > 0) { + throw new BacktestRetentionError('retained_runs', count); + } + await client.query('DELETE FROM backtests WHERE id=$1', [id]); + }); + } + + async archiveBacktest(id: string, archived: boolean): Promise { + return this.container.postgres.transaction(async client => { + const parent = await client.query('SELECT id FROM backtests WHERE id=$1 FOR UPDATE', [id]); + if (!parent.rows[0]) { + return null; + } + const updated = await client.query( + `UPDATE backtests + SET archived_at=CASE WHEN $2::boolean THEN COALESCE(archived_at,NOW()) ELSE NULL END, + updated_at=NOW() WHERE id=$1 RETURNING *`, + [id, archived] + ); + return mapBacktest(at(updated.rows, 0)); + }); + } + + private async validateCatalogDraft( + client: PoolClient, + input: unknown, + previousVersionId?: string | null + ): Promise { + try { + assertStrategyJsonText(input); + } catch (error) { + throw new HistoricalDataRequestError( + error instanceof Error ? error.message : 'Invalid catalog draft text' + ); + } + const draft = CatalogBacktestDefinitionSchema.parse(input); + let parameters: Record; + const pkg = await new StrategyCatalogService(this.container).getVersionArtifact( + draft.strategyVersionId, + client + ); + try { + assertStrategyJsonText(draft); + parameters = validateStrategyParameters(pkg, draft.strategyParameters); + } catch (error) { + throw new HistoricalDataRequestError( + error instanceof Error ? error.message : 'Invalid strategy parameters' + ); + } + const family = ( + await client.query( + `SELECT s.archived_at FROM strategy_versions v JOIN strategies s ON s.id=v.strategy_id WHERE v.id=$1 FOR UPDATE OF s`, + [draft.strategyVersionId] + ) + ).rows[0]; + if (!family) { + throw new StrategyCatalogError(404, 'Strategy version not found'); + } + if (previousVersionId !== draft.strategyVersionId && family.archived_at) { + throw new StrategyCatalogError( + 409, + '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 { + ...draft, + startDate: settings.startDate, + endDate: settings.endDate, + strategyParameters: parameters, + }; + } +} diff --git a/apps/stock/web-api/src/services/canonical-research.service.ts b/apps/stock/web-api/src/services/canonical-research.service.ts index ebb7f38e..b4614f20 100644 --- a/apps/stock/web-api/src/services/canonical-research.service.ts +++ b/apps/stock/web-api/src/services/canonical-research.service.ts @@ -7,6 +7,8 @@ */ import { randomUUID } from 'node:crypto'; import type { PoolClient } from 'pg'; +import { datasetUnavailableReason } from '@stock-bot/research/dataset-contracts'; +import { validateDatasetV2 } from '@stock-bot/research/datasets'; import type { IServiceContainer } from '@stock-bot/services'; import { retainedProgramSelectionSchema, @@ -30,7 +32,6 @@ import { } from '@stock-bot/types'; import { readCandidateExecution } from '../../../orchestrator/src/backtest/candidate-sandbox'; import { readCanonicalBuildIdentity } from '../../../orchestrator/src/backtest/canonical-build'; -import { validateDatasetV2 } from '../../../orchestrator/src/data/historical-dataset-v2'; import { canonicalRiskSessionClock } from './canonical-risk-clock'; import type { DatasetCatalogQuery } from './dataset-catalog.service'; import { StrategyCatalogService } from './strategy-catalog.service'; @@ -51,17 +52,7 @@ const invalid = (message: string): never => { /** The existing workbench gate, shared by retained selection and source preview. */ export function canonicalDatasetUnavailableReason(dataset: HistoricalDatasetV2): string | null { - if (dataset.manifest.eligibility !== 'eligible') { - return '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 'Canonical workbench currently supports one execution asset and one retained series'; - } - return null; + return datasetUnavailableReason(dataset.manifest); } /** diff --git a/apps/stock/web-api/src/services/chronological-validation.service.ts b/apps/stock/web-api/src/services/chronological-validation.service.ts index 0d90d270..f0a46d16 100644 --- a/apps/stock/web-api/src/services/chronological-validation.service.ts +++ b/apps/stock/web-api/src/services/chronological-validation.service.ts @@ -2,6 +2,7 @@ import { randomUUID } from 'node:crypto'; import type { PoolClient, QueryResultRow } from 'pg'; import { z } from 'zod'; import { at } from '@stock-bot/invariants'; +import { validateDatasetV2 } from '@stock-bot/research/datasets'; import { requireServices, type IServiceContainer } from '@stock-bot/services'; import type { CanonicalRunResult } from '@stock-bot/stock-config/canonical-research'; import type { @@ -18,7 +19,6 @@ import type { import type { ExperimentPreview } from '@stock-bot/stock-config/experiments'; import type { ResearchActor } from '@stock-bot/types'; import { HistoricalDataRequestError } from '@stock-bot/types'; -import { validateDatasetV2 } from '../../../orchestrator/src/data/historical-dataset-v2'; import { BacktestServiceV2 } from './backtest-v2.service'; import { readCanonicalDataset } from './canonical-research.service'; import { diff --git a/apps/stock/web-api/src/services/dataset-preparation.service.ts b/apps/stock/web-api/src/services/dataset-preparation.service.ts index a426179c..5659c506 100644 --- a/apps/stock/web-api/src/services/dataset-preparation.service.ts +++ b/apps/stock/web-api/src/services/dataset-preparation.service.ts @@ -1,7 +1,7 @@ import { z } from 'zod'; +import { createDatasetV2 } from '@stock-bot/research/datasets'; import type { CanonicalDatasetPreparation } from '@stock-bot/stock-config/canonical-research'; import type { HistoricalDatasetInputV2, HistoricalDatasetV2 } from '@stock-bot/types'; -import { createDatasetV2 } from '../../../orchestrator/src/data/historical-dataset-v2'; import { retainResearchDataset, type RetainedDatasetStore, diff --git a/apps/stock/web-api/src/services/stored-dataset-preparation.ts b/apps/stock/web-api/src/services/stored-dataset-preparation.ts index a24f40f6..90220e58 100644 --- a/apps/stock/web-api/src/services/stored-dataset-preparation.ts +++ b/apps/stock/web-api/src/services/stored-dataset-preparation.ts @@ -1,7 +1,7 @@ import { z } from 'zod'; +import { parseHistoricalDatasetMetadataV2 } from '@stock-bot/research/datasets'; import type { CanonicalStoredSourcePreparation } from '@stock-bot/stock-config/canonical-research'; import type { HistoricalDatasetInputV2, HistoricalDatasetMetadataV2 } from '@stock-bot/types'; -import { parseHistoricalDatasetMetadataV2 } from '../../../orchestrator/src/data/historical-dataset-v2'; import { HistoricalStorageError, type StorageService, diff --git a/apps/stock/web-api/src/services/validation-preview.ts b/apps/stock/web-api/src/services/validation-preview.ts index 55af2591..a95c52fd 100644 --- a/apps/stock/web-api/src/services/validation-preview.ts +++ b/apps/stock/web-api/src/services/validation-preview.ts @@ -1,3 +1,4 @@ +import { sliceDatasetV2, validateDatasetV2 } from '@stock-bot/research/datasets'; import { canonicalRunRequestSchema } from '@stock-bot/stock-config/canonical-research'; import { chronologicalPolicyForOrigin, @@ -14,10 +15,6 @@ import { canonicalStrategyJson, } from '@stock-bot/stock-config/strategy'; import type { HistoricalDatasetV2 } from '@stock-bot/types'; -import { - sliceDatasetV2, - validateDatasetV2, -} from '../../../orchestrator/src/data/historical-dataset-v2'; import { canonicalRiskSessionClock } from './canonical-risk-clock'; import { ExperimentError, experimentHash, retainedExperimentPreview } from './experiment-input'; diff --git a/apps/stock/web-app/README.md b/apps/stock/web-app/README.md index e6e66b1e..39c3eea9 100644 --- a/apps/stock/web-app/README.md +++ b/apps/stock/web-app/README.md @@ -57,3 +57,7 @@ Browser authentication uses HttpOnly session cookies. `VITE_API_BASE_URL` is a p The [workbench browser test](../../../test/e2e/workbench.test.ts) exercises the authenticated API and durable workflow using disposable infrastructure. [Canonical workbench tests](../../../test/integration/canonical-workbench.test.tsx) cover retained-input configuration and results. Follow the [root test setup](../../../README.md#build-and-verify) for prerequisites rather than using a regular trading database as a test fixture. Keep loading, empty, failed, cancelled and completed states distinct. Reopening a saved run should read the recorded result, not silently start a new simulation. + +Primary navigation lists implemented workflows. Standalone Portfolio, Analytics and Settings +remain unavailable at their existing URLs and are hidden from the menu. Saved backtest and +experiment pages continue to provide performance, trade and risk analysis. diff --git a/apps/stock/web-app/package.json b/apps/stock/web-app/package.json index 6923ac23..c12e0369 100644 --- a/apps/stock/web-app/package.json +++ b/apps/stock/web-app/package.json @@ -10,6 +10,7 @@ "type-check": "tsc --noEmit" }, "dependencies": { + "@stock-bot/research": "workspace:*", "@stock-bot/calculations": "workspace:*", "@headlessui/react": "^1.7.17", "@heroicons/react": "^2.0.18", diff --git a/apps/stock/web-app/src/app/App.tsx b/apps/stock/web-app/src/app/App.tsx index 7e59f2ed..a0a1d0a5 100644 --- a/apps/stock/web-app/src/app/App.tsx +++ b/apps/stock/web-app/src/app/App.tsx @@ -17,6 +17,7 @@ import { ResearchAgentsPage, ResearchListPage, ResearchProjectPage } from '@/fea import { StrategyDetailPage, StrategyListPage, StrategyVersionPage } from '@/features/strategies'; import { SymbolDetailPage, SymbolsPage } from '@/features/symbols'; import { AuthGate } from './AuthGate'; +import { UnavailablePage } from './UnavailablePage'; export function App() { return ( @@ -31,20 +32,14 @@ export function App() { } /> } /> - Portfolio Page - Coming Soon} - /> + } /> } /> } /> } /> } /> - Analytics Page - Coming Soon} - /> + } /> } /> @@ -71,10 +66,7 @@ export function App() { } /> } /> - Settings Page - Coming Soon} - /> + } /> } /> } /> diff --git a/apps/stock/web-app/src/app/UnavailablePage.tsx b/apps/stock/web-app/src/app/UnavailablePage.tsx new file mode 100644 index 00000000..4c3bf3cf --- /dev/null +++ b/apps/stock/web-app/src/app/UnavailablePage.tsx @@ -0,0 +1,12 @@ +import { Link } from 'react-router-dom'; + +/** Retain old URLs without advertising unfinished workflows in navigation. */ +export function UnavailablePage({ name }: { name: string }) { + return ( +
+

{name} is not available

+

Inspect saved performance, trades and risk metrics in backtests and experiments.

+ Open backtests Open experiments +
+ ); +} 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 0a6827f8..f6bfc13a 100644 --- a/apps/stock/web-app/src/features/backtest/hooks/useBacktestV2.ts +++ b/apps/stock/web-app/src/features/backtest/hooks/useBacktestV2.ts @@ -5,29 +5,10 @@ */ import { useCallback, useEffect, useRef, useState } from 'react'; import type { CanonicalRunCapability } from '@stock-bot/stock-config/canonical-research'; -import { catalogExecutionReason } from '@/features/strategies/components/StrategySelection'; -import { backtestApiV2, RunResultsUnavailableError } from '../services/backtestApiV2'; -import type { - Backtest, - CreateBacktestRequest, - ResearchRunResult, - Run, -} from '../services/backtestApiV2'; - -/** Object identity is the ownership token for one status/result request chain. */ -interface RunSelection { - id: string; - backtestId: string | null; - controller: AbortController; - timer?: ReturnType; - request?: Promise; - refreshRequested: boolean; - results: ResearchRunResult | null; -} - -const isActive = (run: Run) => ['pending', 'running', 'paused'].includes(run.status); -const messageOf = (error: unknown, fallback: string) => - error instanceof Error ? error.message : fallback; +import { backtestApiV2 } from '../services/backtestApiV2'; +import type { Backtest, CreateBacktestRequest, Run } from '../services/backtestApiV2'; +import { messageOf, useRunMonitoring } from './useRunMonitoring'; +import { useRunSubmission } from './useRunSubmission'; /** * Connects BacktestDetailPageV2 to backtestApiV2. Template loading, run monitoring @@ -37,32 +18,14 @@ const messageOf = (error: unknown, fallback: string) => export function useBacktestV2() { const [backtest, setBacktest] = useState(null); const [runs, setRuns] = useState([]); - const [currentRun, setCurrentRun] = useState(null); - const [runResults, setRunResults] = useState(null); const [isBacktestLoading, setIsBacktestLoading] = useState(false); - const [isRunLoading, setIsRunLoading] = useState(false); const [error, setError] = useState(null); - const [runError, setRunError] = useState(null); - const [submissionError, setSubmissionError] = useState(null); - const [isSubmitting, setIsSubmitting] = useState(false); - const [cancelRequested, setCancelRequested] = useState(false); // Generations reject late responses even when an earlier request cannot be // aborted. The selection generation also prevents submission from taking the // user away from a different run they selected while admission was pending. const mounted = useRef(true); const backtestGeneration = useRef(0); const loadedBacktestId = useRef(null); - const selectionGeneration = useRef(0); - // The intent survives an ambiguous response and configuration edits. Only an - // acknowledged submission (or leaving this definition) releases its key. - const submission = useRef<{ - backtestId: string; - key: string; - body: { speedMultiplier: number | null }; - pending: boolean; - } | null>(null); - const selection = useRef(null); - const cancellation = useRef(null); const [capabilityRetry, setCapabilityRetry] = useState(0); const [capabilityState, setCapabilityState] = useState<{ definition: Backtest; @@ -119,172 +82,36 @@ export function useBacktestV2() { catalog && !backtest?.archivedAt && !capabilityError && canonicalCapability === null; const refreshCanonicalCapability = useCallback(() => setCapabilityRetry(value => value + 1), []); - const isSelected = useCallback( - (selected: RunSelection) => - mounted.current && - selection.current === selected && - selected.backtestId === loadedBacktestId.current, - [] - ); - - /** Stop browser observation only; cancelling server execution is cancelRun's job. */ - const stopMonitoring = useCallback(() => { - selectionGeneration.current++; - const selected = selection.current; - selection.current = null; - cancellation.current = null; - if (selected) { - clearTimeout(selected.timer); - selected.controller.abort(); - } - }, []); - - // A selection owns one request chain (status, then results) and one timer. - // Polls, websocket invalidations and cancel acknowledgements all use this path. - const refreshSelection = useCallback( - function refresh(selected: RunSelection): Promise { - if (!isSelected(selected)) { - return Promise.resolve(); - } - if (selected.request) { - selected.refreshRequested = true; - return selected.request; - } - clearTimeout(selected.timer); - let monitorAgain = true; - selected.request = (async () => { - try { - const run = await backtestApiV2.getRun(selected.id, selected.controller.signal); - 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 => - previous.some(item => item.id === run.id) - ? previous.map(item => (item.id === run.id ? run : item)) - : [run, ...previous] - ); - setRunError(null); - monitorAgain = isActive(run); - if (!monitorAgain) { - cancellation.current = null; - setCancelRequested(false); - } else if (run.cancelRequested) { - setCancelRequested(true); - } - - if (run.status === 'completed') { - if (!selected.results) { - const results = await backtestApiV2.getRunResults( - selected.id, - selected.controller.signal - ); - if (!isSelected(selected)) { - return; - } - 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); - } - } else { - selected.results = null; - setRunResults(null); - } - } catch (err) { - if (!isSelected(selected)) { - return; - } - setRunError( - err instanceof RunResultsUnavailableError - ? null - : messageOf(err, 'Failed to refresh run') - ); - } finally { - if (isSelected(selected)) { - selected.request = undefined; - setIsRunLoading(false); - if (selected.refreshRequested) { - selected.refreshRequested = false; - void refresh(selected); - } else if (monitorAgain) { - selected.timer = setTimeout(() => void refresh(selected), 1000); - } - } - } - })(); - return selected.request; - }, - [isSelected] - ); - - const refreshRun = useCallback( - (runId?: string) => { - const selected = selection.current; - return selected && (!runId || selected.id === runId) - ? refreshSelection(selected) - : Promise.resolve(); - }, - [refreshSelection] - ); - - /** Reopening a run reads its recorded state; it never submits another backtest. */ - const selectRun = useCallback( - (runId: string | undefined) => { - if ( - runId && - selection.current?.id === runId && - selection.current.backtestId === loadedBacktestId.current - ) { - return refreshSelection(selection.current); - } - stopMonitoring(); - setCurrentRun(null); - setRunResults(null); - setRunError(null); - setCancelRequested(false); - setIsRunLoading(Boolean(runId)); - if (!runId) { - return Promise.resolve(); - } - - const selected: RunSelection = { - id: runId, - backtestId: loadedBacktestId.current, - controller: new AbortController(), - refreshRequested: false, - results: null, - }; - selection.current = selected; - return refreshSelection(selected); - }, - [refreshSelection, stopMonitoring] - ); + const { + currentRun, + runResults, + isRunLoading, + runError, + cancelRequested, + selection, + selectionGeneration, + stopMonitoring, + refreshRun, + selectRun, + cancelRun, + } = useRunMonitoring({ mounted, loadedBacktestId, setRuns }); + const { createRun, submissionError, isSubmitting, hasPendingSubmission, resetSubmission } = + useRunSubmission({ + backtest, + loadedBacktestId, + mounted, + selectionGeneration, + catalog, + canonicalCapability, + capabilityError, + setRuns, + }); const loadBacktest = useCallback( async (id: string) => { const generation = ++backtestGeneration.current; if (loadedBacktestId.current !== id) { - submission.current = null; - setSubmissionError(null); - setIsSubmitting(false); + resetSubmission(); // 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; @@ -325,7 +152,7 @@ export function useBacktestV2() { } } }, - [selectRun] + [selectRun, resetSubmission] ); const createBacktest = useCallback( @@ -337,9 +164,7 @@ export function useBacktestV2() { const created = await backtestApiV2.createBacktest(request); if (mounted.current && generation === backtestGeneration.current) { loadedBacktestId.current = created.id; - submission.current = null; - setSubmissionError(null); - setIsSubmitting(false); + resetSubmission(); setBacktest(created); setRuns([]); await selectRun(undefined); @@ -356,7 +181,7 @@ export function useBacktestV2() { } } }, - [selectRun] + [selectRun, resetSubmission] ); const updateBacktest = useCallback( @@ -395,9 +220,7 @@ export function useBacktestV2() { await backtestApiV2.deleteBacktest(id); if (mounted.current && generation === backtestGeneration.current) { loadedBacktestId.current = null; - submission.current = null; - setSubmissionError(null); - setIsSubmitting(false); + resetSubmission(); setBacktest(null); setRuns([]); await selectRun(undefined); @@ -413,7 +236,7 @@ export function useBacktestV2() { } } }, - [selectRun] + [selectRun, resetSubmission] ); const setBacktestArchived = useCallback(async (id: string, archived: boolean) => { @@ -437,103 +260,6 @@ export function useBacktestV2() { } }, []); - /** - * Retain the same key/body after an ambiguous response so Retry can recover - * the accepted run. This receipt is in memory for this mounted hook; it is not - * a persistent browser recovery journal. New admissions recheck eligibility; - * receipt retries recover the original run before current eligibility checks. - */ - const createRun = useCallback( - async (_speedMultiplier: number | null = null) => { - if (!backtest || backtest.id !== loadedBacktestId.current || submission.current?.pending) { - return undefined; - } - if (backtest.archivedAt && !submission.current) { - setSubmissionError('Restore this archived backtest before starting a new run.'); - return undefined; - } - if (catalog && !canonicalCapability?.available && !submission.current) { - setSubmissionError( - capabilityError ?? canonicalCapability?.reason ?? catalogExecutionReason - ); - return undefined; - } - if (!catalog && !submission.current) { - setSubmissionError( - 'Legacy execution is retired. Create a catalog backtest to run with retained canonical inputs.' - ); - return undefined; - } - const intent = (submission.current ??= { - backtestId: backtest.id, - key: crypto.randomUUID(), - body: { speedMultiplier: null }, - pending: false, - }); - intent.pending = true; - const selectedGeneration = selectionGeneration.current; - const ownsSubmission = () => mounted.current && submission.current === intent; - const ownsSelection = () => - ownsSubmission() && selectionGeneration.current === selectedGeneration; - setIsSubmitting(true); - setSubmissionError(null); - try { - const created = await backtestApiV2.createRun(intent.backtestId, intent.body, intent.key); - if (!ownsSubmission()) { - return undefined; - } - const selected = ownsSelection(); - submission.current = null; - setIsSubmitting(false); - if (!selected) { - return undefined; - } - setRuns(previous => [created, ...previous.filter(run => run.id !== created.id)]); - return created; - } catch (err) { - if (ownsSubmission()) { - setSubmissionError(messageOf(err, 'Failed to submit run')); - } - return undefined; - } finally { - intent.pending = false; - if (ownsSubmission()) { - setIsSubmitting(false); - } - } - }, - [backtest, catalog, canonicalCapability, capabilityError] - ); - - /** Record a cancellation request, then monitor until the server reports a terminal state. */ - const cancelRun = useCallback(async () => { - const selected = selection.current; - if ( - !selected || - !currentRun || - currentRun.id !== selected.id || - !isActive(currentRun) || - cancellation.current === selected - ) { - return; - } - cancellation.current = selected; - setCancelRequested(true); - setRunError(null); - try { - await backtestApiV2.cancelRun(selected.id, selected.controller.signal); - if (isSelected(selected)) { - await refreshSelection(selected); - } - } catch (err) { - if (isSelected(selected)) { - cancellation.current = null; - setCancelRequested(Boolean(currentRun.cancelRequested)); - setRunError(messageOf(err, 'Failed to request cancellation')); - } - } - }, [currentRun, isSelected, refreshSelection]); - useEffect(() => { mounted.current = true; return () => { @@ -556,7 +282,7 @@ export function useBacktestV2() { error: runError ?? error, submissionError, isSubmitting, - hasPendingSubmission: submission.current !== null, + hasPendingSubmission, cancelRequested, loadBacktest, createBacktest, diff --git a/apps/stock/web-app/src/features/backtest/hooks/useRunMonitoring.ts b/apps/stock/web-app/src/features/backtest/hooks/useRunMonitoring.ts new file mode 100644 index 00000000..df18c7c9 --- /dev/null +++ b/apps/stock/web-app/src/features/backtest/hooks/useRunMonitoring.ts @@ -0,0 +1,250 @@ +import { + useCallback, + useRef, + useState, + type Dispatch, + type MutableRefObject, + type SetStateAction, +} from 'react'; +import { + backtestApiV2, + RunResultsUnavailableError, + type ResearchRunResult, + type Run, +} from '../services/backtestApiV2'; + +/** Object identity is the ownership token for one status/result request chain. */ +export interface RunSelection { + id: string; + backtestId: string | null; + controller: AbortController; + timer?: ReturnType; + request?: Promise; + refreshRequested: boolean; + results: ResearchRunResult | null; +} + +const isActive = (run: Run) => ['pending', 'running', 'paused'].includes(run.status); +export const messageOf = (error: unknown, fallback: string) => + error instanceof Error ? error.message : fallback; + +/** One selection owns status, results, polling, refresh and cancellation. */ +export function useRunMonitoring({ + mounted, + loadedBacktestId, + setRuns, +}: { + mounted: MutableRefObject; + loadedBacktestId: MutableRefObject; + setRuns: Dispatch>; +}) { + const [currentRun, setCurrentRun] = useState(null); + const [runResults, setRunResults] = useState(null); + const [isRunLoading, setIsRunLoading] = useState(false); + const [runError, setRunError] = useState(null); + const [cancelRequested, setCancelRequested] = useState(false); + const selectionGeneration = useRef(0); + const selection = useRef(null); + const cancellation = useRef(null); + const isSelected = useCallback( + (selected: RunSelection) => + mounted.current && + selection.current === selected && + selected.backtestId === loadedBacktestId.current, + [] + ); + + /** Stop browser observation only; cancelling server execution is cancelRun's job. */ + const stopMonitoring = useCallback(() => { + selectionGeneration.current++; + const selected = selection.current; + selection.current = null; + cancellation.current = null; + if (selected) { + clearTimeout(selected.timer); + selected.controller.abort(); + } + }, []); + + // A selection owns one request chain (status, then results) and one timer. + // Polls, websocket invalidations and cancel acknowledgements all use this path. + const refreshSelection = useCallback( + function refresh(selected: RunSelection): Promise { + if (!isSelected(selected)) { + return Promise.resolve(); + } + if (selected.request) { + selected.refreshRequested = true; + return selected.request; + } + clearTimeout(selected.timer); + let monitorAgain = true; + selected.request = (async () => { + try { + const run = await backtestApiV2.getRun(selected.id, selected.controller.signal); + 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 => + previous.some(item => item.id === run.id) + ? previous.map(item => (item.id === run.id ? run : item)) + : [run, ...previous] + ); + setRunError(null); + monitorAgain = isActive(run); + if (!monitorAgain) { + cancellation.current = null; + setCancelRequested(false); + } else if (run.cancelRequested) { + setCancelRequested(true); + } + + if (run.status === 'completed') { + if (!selected.results) { + const results = await backtestApiV2.getRunResults( + selected.id, + selected.controller.signal + ); + if (!isSelected(selected)) { + return; + } + 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); + } + } else { + selected.results = null; + setRunResults(null); + } + } catch (err) { + if (!isSelected(selected)) { + return; + } + setRunError( + err instanceof RunResultsUnavailableError + ? null + : messageOf(err, 'Failed to refresh run') + ); + } finally { + if (isSelected(selected)) { + selected.request = undefined; + setIsRunLoading(false); + if (selected.refreshRequested) { + selected.refreshRequested = false; + void refresh(selected); + } else if (monitorAgain) { + selected.timer = setTimeout(() => void refresh(selected), 1000); + } + } + } + })(); + return selected.request; + }, + [isSelected] + ); + + const refreshRun = useCallback( + (runId?: string) => { + const selected = selection.current; + return selected && (!runId || selected.id === runId) + ? refreshSelection(selected) + : Promise.resolve(); + }, + [refreshSelection] + ); + + /** Reopening a run reads its recorded state; it never submits another backtest. */ + const selectRun = useCallback( + (runId: string | undefined) => { + if ( + runId && + selection.current?.id === runId && + selection.current.backtestId === loadedBacktestId.current + ) { + return refreshSelection(selection.current); + } + stopMonitoring(); + setCurrentRun(null); + setRunResults(null); + setRunError(null); + setCancelRequested(false); + setIsRunLoading(Boolean(runId)); + if (!runId) { + return Promise.resolve(); + } + + const selected: RunSelection = { + id: runId, + backtestId: loadedBacktestId.current, + controller: new AbortController(), + refreshRequested: false, + results: null, + }; + selection.current = selected; + return refreshSelection(selected); + }, + [refreshSelection, stopMonitoring] + ); + + /** Record a cancellation request, then monitor until the server reports a terminal state. */ + const cancelRun = useCallback(async () => { + const selected = selection.current; + if ( + !selected || + !currentRun || + currentRun.id !== selected.id || + !isActive(currentRun) || + cancellation.current === selected + ) { + return; + } + cancellation.current = selected; + setCancelRequested(true); + setRunError(null); + try { + await backtestApiV2.cancelRun(selected.id, selected.controller.signal); + if (isSelected(selected)) { + await refreshSelection(selected); + } + } catch (err) { + if (isSelected(selected)) { + cancellation.current = null; + setCancelRequested(Boolean(currentRun.cancelRequested)); + setRunError(messageOf(err, 'Failed to request cancellation')); + } + } + }, [currentRun, isSelected, refreshSelection]); + + return { + currentRun, + runResults, + isRunLoading, + runError, + cancelRequested, + selection, + selectionGeneration, + stopMonitoring, + refreshRun, + selectRun, + cancelRun, + }; +} diff --git a/apps/stock/web-app/src/features/backtest/hooks/useRunSubmission.ts b/apps/stock/web-app/src/features/backtest/hooks/useRunSubmission.ts new file mode 100644 index 00000000..53a7bd8d --- /dev/null +++ b/apps/stock/web-app/src/features/backtest/hooks/useRunSubmission.ts @@ -0,0 +1,123 @@ +import { + useCallback, + useRef, + useState, + type Dispatch, + type MutableRefObject, + type SetStateAction, +} from 'react'; +import type { CanonicalRunCapability } from '@stock-bot/stock-config/canonical-research'; +import { catalogExecutionReason } from '@/features/strategies/components/StrategySelection'; +import { backtestApiV2, type Backtest, type Run } from '../services/backtestApiV2'; +import { messageOf } from './useRunMonitoring'; + +export function useRunSubmission({ + backtest, + loadedBacktestId, + mounted, + selectionGeneration, + catalog, + canonicalCapability, + capabilityError, + setRuns, +}: { + backtest: Backtest | null; + loadedBacktestId: MutableRefObject; + mounted: MutableRefObject; + selectionGeneration: MutableRefObject; + catalog: boolean; + canonicalCapability: CanonicalRunCapability | null; + capabilityError: string | null; + setRuns: Dispatch>; +}) { + const [submissionError, setSubmissionError] = useState(null); + const [isSubmitting, setIsSubmitting] = useState(false); + // The intent survives an ambiguous response and configuration edits. Only an + // acknowledged submission (or leaving this definition) releases its key. + const submission = useRef<{ + backtestId: string; + key: string; + body: { speedMultiplier: number | null }; + pending: boolean; + } | null>(null); + /** + * Retain the same key/body after an ambiguous response so Retry can recover + * the accepted run. This receipt is in memory for this mounted hook; it is not + * a persistent browser recovery journal. New admissions recheck eligibility; + * receipt retries recover the original run before current eligibility checks. + */ + const createRun = useCallback( + async (_speedMultiplier: number | null = null) => { + if (!backtest || backtest.id !== loadedBacktestId.current || submission.current?.pending) { + return undefined; + } + if (backtest.archivedAt && !submission.current) { + setSubmissionError('Restore this archived backtest before starting a new run.'); + return undefined; + } + if (catalog && !canonicalCapability?.available && !submission.current) { + setSubmissionError( + capabilityError ?? canonicalCapability?.reason ?? catalogExecutionReason + ); + return undefined; + } + if (!catalog && !submission.current) { + setSubmissionError( + 'Legacy execution is retired. Create a catalog backtest to run with retained canonical inputs.' + ); + return undefined; + } + const intent = (submission.current ??= { + backtestId: backtest.id, + key: crypto.randomUUID(), + body: { speedMultiplier: null }, + pending: false, + }); + intent.pending = true; + const selectedGeneration = selectionGeneration.current; + const ownsSubmission = () => mounted.current && submission.current === intent; + const ownsSelection = () => + ownsSubmission() && selectionGeneration.current === selectedGeneration; + setIsSubmitting(true); + setSubmissionError(null); + try { + const created = await backtestApiV2.createRun(intent.backtestId, intent.body, intent.key); + if (!ownsSubmission()) { + return undefined; + } + const selected = ownsSelection(); + submission.current = null; + setIsSubmitting(false); + if (!selected) { + return undefined; + } + setRuns(previous => [created, ...previous.filter(run => run.id !== created.id)]); + return created; + } catch (err) { + if (ownsSubmission()) { + setSubmissionError(messageOf(err, 'Failed to submit run')); + } + return undefined; + } finally { + intent.pending = false; + if (ownsSubmission()) { + setIsSubmitting(false); + } + } + }, + [backtest, catalog, canonicalCapability, capabilityError] + ); + + const resetSubmission = useCallback(() => { + submission.current = null; + setSubmissionError(null); + setIsSubmitting(false); + }, []); + return { + createRun, + submissionError, + isSubmitting, + hasPendingSubmission: submission.current !== null, + resetSubmission, + }; +} 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 23141efd..c9026275 100644 --- a/apps/stock/web-app/src/features/backtest/services/backtestApiV2.ts +++ b/apps/stock/web-app/src/features/backtest/services/backtestApiV2.ts @@ -1,4 +1,8 @@ import { z } from 'zod'; +import { + datasetUnavailableReason, + preparationManifestSchema, +} from '@stock-bot/research/dataset-contracts'; import { candidateExecutionSchema } from '@stock-bot/stock-config/candidate-execution'; import { canonicalRunRequestSchema } from '@stock-bot/stock-config/canonical-research'; import type { @@ -113,112 +117,7 @@ const hashOrNull = (value: unknown) => const preparationText = z.string().min(1); const preparationHash = z.string().regex(/^[a-f0-9]{64}$/); const preparationInstant = z.number().int().nonnegative().max(8_640_000_000_000_000); -const preparationDay = z - .string() - .regex(/^\d{4}-\d{2}-\d{2}$/) - .refine( - value => - Number.isFinite(Date.parse(value)) && new Date(value).toISOString().slice(0, 10) === value - ); -const preparationManifest = z - .object({ - version: z.literal(2), - hash: preparationHash, - normalizationRevision: z.literal('historical-normalization-v2'), - parentDatasetHash: z.null(), - volumePolicy: z.literal('reported'), - qualityPolicy: z.literal('reject-invalid-no-interpolation'), - intradayPolicy: z.literal('full-duration-session-contained'), - eligibility: z.enum(['eligible', 'exploratory', 'ineligible']), - limitations: z.array(preparationText), - barCount: z.number().int().positive().safe(), - calendars: z - .array( - z - .object({ - id: preparationText, - venue: preparationText, - timeZone: preparationText, - source: preparationText, - revision: preparationText, - startDate: preparationDay, - endDate: preparationDay, - sessions: z - .array( - z - .object({ - date: preparationDay, - open: preparationInstant, - close: preparationInstant, - }) - .strict() - .refine(value => value.open < value.close) - ) - .min(1), - }) - .strict() - ) - .min(1), - series: z - .array( - z - .object({ - id: preparationText, - instrumentId: preparationText, - interval: z.enum(['1m', '5m', '15m', '1h', '1d']), - calendarId: preparationText, - venue: preparationText, - source: z.object({ provider: preparationText, revision: preparationText }).strict(), - timestamp: z.enum(['session-date', 'interval-start', 'interval-end']), - availability: z.enum(['explicit', 'interval-end-assumption']), - adjustment: z.enum(['raw', 'provider-adjusted']), - }) - .strict() - ) - .min(1), - executionSeries: z - .array(z.object({ instrumentId: preparationText, seriesId: preparationText }).strict()) - .min(1), - bounds: z - .object({ - warmupStart: preparationInstant, - tradeStart: preparationInstant, - tradeEnd: preparationInstant, - }) - .strict() - .refine(value => value.warmupStart <= value.tradeStart && value.tradeStart < value.tradeEnd), - universe: z - .object({ - selection: z.enum(['point-in-time', 'current-constituents', 'unknown']), - asOf: preparationInstant.nullable(), - revision: preparationText, - instrumentIds: z.array(preparationText).min(1), - }) - .strict(), - corporateActions: z - .array( - z - .object({ - instrumentId: preparationText, - status: z.enum(['unknown', 'action-free', 'known-actions']), - start: preparationInstant, - end: preparationInstant, - revision: preparationText, - actions: z.array( - z - .object({ - effectiveAt: preparationInstant, - kind: z.enum(['split', 'dividend', 'other']), - reference: preparationText, - }) - .strict() - ), - }) - .strict() - ) - .min(1), - }) - .strict(); +const preparationManifest = preparationManifestSchema; const datasetPreparationSchema = z .object({ version: z.literal('canonical-dataset-preparation/v1'), @@ -234,11 +133,7 @@ export function parseDatasetPreparation( ): CanonicalDatasetPreparation { const value = datasetPreparationSchema.parse(raw), manifest = value.manifest; - const available = - manifest.eligibility === 'eligible' && - manifest.executionSeries.length === 1 && - manifest.series.length === 1 && - manifest.universe.instrumentIds.length === 1; + const available = datasetUnavailableReason(manifest) === null; if ( value.hash !== manifest.hash || (expectedHash !== undefined && value.hash !== expectedHash) || diff --git a/apps/stock/web-app/src/features/experiments/components/ExperimentEditor.tsx b/apps/stock/web-app/src/features/experiments/components/ExperimentEditor.tsx index cf312ea4..3df497ff 100644 --- a/apps/stock/web-app/src/features/experiments/components/ExperimentEditor.tsx +++ b/apps/stock/web-app/src/features/experiments/components/ExperimentEditor.tsx @@ -1,51 +1,21 @@ -import { useCallback, useEffect, useRef, useState } from 'react'; +import { useEffect, useRef, useState } from 'react'; import { Link, useNavigate } from 'react-router-dom'; -import { z } from 'zod'; -import { - costSensitivityInputSchema, - type CostScenario, - type CostSensitivitySubmission, -} from '@stock-bot/stock-config/cost-sensitivity'; -import { - experimentInputSchema, - MAX_EXPERIMENT_TRIALS, - type ExperimentSubmission, -} from '@stock-bot/stock-config/experiments'; +import { type CostScenario } from '@stock-bot/stock-config/cost-sensitivity'; +import { MAX_EXPERIMENT_TRIALS } from '@stock-bot/stock-config/experiments'; import { Button } from '@/components/ui/Button'; -import { backtestApiV2, type Backtest } from '@/features/backtest/services/backtestApiV2'; import { StrategySelection, type CatalogSelection, } from '@/features/strategies/components/StrategySelection'; import { useUnsavedWarning } from '@/features/strategies/components/useUnsavedWarning'; -import { - experimentApi, - ExperimentApiError, - type WorkbenchExperimentPreviewView, -} from '../services/experimentApi'; +import { useExperimentSubmission } from '../hooks/useExperimentSubmission'; +import { useExperimentTemplates } from '../hooks/useExperimentTemplates'; import { ChronologicalValidationPreflight } from './ChronologicalValidationPreflight'; import { ExperimentInputs } from './ExperimentInputs'; import { WalkForwardPreflight } from './WalkForwardPreflight'; const fieldClass = 'mt-1 w-full rounded-md border border-border bg-background px-3 py-2 text-text-primary disabled:opacity-60'; -const message = (cause: unknown) => - cause instanceof z.ZodError - ? cause.issues.map(issue => `${issue.path.join('.') || 'Input'}: ${issue.message}`).join('; ') - : cause instanceof Error - ? cause.message - : 'Could not prepare the experiment'; -const canonical = (value: Backtest) => - value && - typeof value.id === 'string' && - typeof value.name === 'string' && - !value.archivedAt && - value.strategyVersionId && - value.config && - typeof value.config.canonical === 'object' && - value.config.canonical !== null && - typeof value.config.datasetHash === 'string'; - export function ExperimentEditor({ initialBacktestId, onDirty, @@ -54,47 +24,9 @@ export function ExperimentEditor({ onDirty: (dirty: boolean) => void; }) { const navigate = useNavigate(); - const alive = useRef(false); - const generation = useRef(0); - const previewRevision = useRef(null); - const previewRequest = useRef(null); - const pending = useRef(false); - type Intent = - | { kind: 'parameters'; body: ExperimentSubmission; key: string } - | { kind: 'cost-sensitivity'; body: CostSensitivitySubmission; key: string }; - const intent = useRef(null); const [mode, setMode] = useState<'parameters' | 'cost-sensitivity'>('parameters'); const modeRef = useRef(mode); const [scenarios, setScenarios] = useState([{ feeRate: '', slippageRate: '' }]); - const submissionOwner = useRef<'ordinary' | 'chronological' | 'walk-forward' | null>(null); - const [lockedBy, setLockedBy] = useState<'ordinary' | 'chronological' | 'walk-forward' | null>( - null - ); - const claimSubmission = useCallback((owner: 'ordinary' | 'chronological' | 'walk-forward') => { - if ( - (owner !== 'ordinary' && modeRef.current === 'cost-sensitivity') || - (submissionOwner.current && submissionOwner.current !== owner) - ) { - return false; - } - submissionOwner.current = owner; - setLockedBy(owner); - if (owner !== 'ordinary') { - generation.current++; - previewRequest.current?.abort(); - previewRevision.current = null; - setPreview(null); - setPreviewLoading(false); - } - return true; - }, []); - const releaseSubmission = useCallback((owner: 'ordinary' | 'chronological' | 'walk-forward') => { - if (submissionOwner.current === owner) { - submissionOwner.current = null; - setLockedBy(null); - } - }, []); - const [hasIntent, setHasIntent] = useState(false); const [backtestId, setBacktestId] = useState(initialBacktestId); const [name, setName] = useState(''); const [grid, setGrid] = useState('{}'); @@ -111,19 +43,38 @@ export function ExperimentEditor({ parameters: candidateSelection.strategyParameters ?? {}, } : undefined; - const [backtests, setBacktests] = useState([]); - const [templateLoading, setTemplateLoading] = useState(true); - const [templateError, setTemplateError] = useState(''); - const [templateReload, setTemplateReload] = useState(0); - const [limit, setLimit] = useState(50); - const [moreTemplates, setMoreTemplates] = useState(false); - const [preview, setPreview] = useState(null); - const [previewLoading, setPreviewLoading] = useState(false); - const [error, setError] = useState(''); - const [submitting, setSubmitting] = useState(false); - const [ambiguous, setAmbiguous] = useState(false); const [validationDirty, setValidationDirty] = useState(false); const [walkForwardDirty, setWalkForwardDirty] = useState(false); + const { backtests, templateLoading, templateError, setTemplateReload, moreTemplates, setLimit } = + useExperimentTemplates(initialBacktestId); + const { + submissionOwner, + lockedBy, + claimSubmission, + releaseSubmission, + preview, + previewLoading, + error, + hasIntent, + submitting, + ambiguous, + invalidate, + prepare, + submit, + newIntent, + } = useExperimentSubmission({ + backtestId, + name, + grid, + modeRef, + scenarios, + candidate, + candidateRevision, + renderedCandidateRevision, + useCandidate, + candidateValid, + onAccepted: id => navigate(`/experiments/${encodeURIComponent(id)}`), + }); const dirty = hasIntent || validationDirty || @@ -141,183 +92,7 @@ export function ExperimentEditor({ useEffect(() => { onDirty(dirty); }, [dirty, onDirty]); - useEffect(() => { - alive.current = true; - return () => { - alive.current = false; - generation.current++; - previewRequest.current?.abort(); - }; - }, []); - useEffect(() => { - let current = true; - const controller = new AbortController(); - setTemplateLoading(true); - setTemplateError(''); - void (async () => { - const rows = await backtestApiV2.listBacktests(limit, 0, false, controller.signal); - if (!Array.isArray(rows)) { - throw new Error('The saved backtest list could not be read'); - } - const selected = - initialBacktestId && !rows.some(item => item?.id === initialBacktestId) - ? await backtestApiV2.getBacktest(initialBacktestId) - : null; - if (current) { - setMoreTemplates(rows.length === limit); - setBacktests((selected ? [...rows, selected] : rows).filter(canonical)); - } - })() - .catch(cause => { - if (current) { - setTemplateError(message(cause)); - } - }) - .finally(() => { - if (current) { - setTemplateLoading(false); - } - }); - return () => { - current = false; - controller.abort(); - }; - }, [initialBacktestId, templateReload, limit]); - const invalidate = (change: () => void) => { - if (submissionOwner.current) { - return; - } - generation.current++; - previewRequest.current?.abort(); - previewRevision.current = null; - setPreview(null); - setPreviewLoading(false); - setError(''); - change(); - }; - const prepare = async () => { - if ( - submissionOwner.current || - previewLoading || - candidateRevision.current !== renderedCandidateRevision || - (useCandidate && !candidateValid) - ) { - return; - } - const current = ++generation.current; - previewRequest.current?.abort(); - const controller = new AbortController(); - previewRequest.current = controller; - previewRevision.current = null; - setPreview(null); - setError(''); - setPreviewLoading(true); - try { - const value = - modeRef.current === 'cost-sensitivity' - ? await experimentApi.costPreview( - costSensitivityInputSchema.parse({ - backtestId, - name, - scenarios, - ...(candidate ? { candidate } : {}), - }), - controller.signal - ) - : await experimentApi.preview( - experimentInputSchema.parse({ - backtestId, - name, - grid: JSON.parse(grid), - ...(candidate ? { candidate } : {}), - }), - controller.signal - ); - if (alive.current && current === generation.current) { - previewRevision.current = current; - setPreview(value); - } - } catch (cause) { - if (alive.current && current === generation.current) { - setError(message(cause)); - } - } finally { - if (alive.current && current === generation.current) { - setPreviewLoading(false); - } - } - }; - const submit = async () => { - if ( - pending.current || - (!intent.current && (!preview || previewRevision.current !== generation.current)) || - !claimSubmission('ordinary') - ) { - return; - } - if (!intent.current) { - if (!preview) { - return; - } - intent.current = - preview.version === 'cost-sensitivity-preview/v1' - ? { - kind: 'cost-sensitivity', - key: crypto.randomUUID(), - body: { ...preview.input, previewHash: preview.previewHash }, - } - : { - kind: 'parameters', - key: crypto.randomUUID(), - body: { ...preview.input, previewHash: preview.previewHash }, - }; - } - const captured = intent.current; - pending.current = true; - setHasIntent(true); - setSubmitting(true); - setError(''); - try { - const accepted = - captured.kind === 'cost-sensitivity' - ? await experimentApi.costSubmit(captured.body, captured.key) - : await experimentApi.create(captured.body, captured.key); - if (alive.current) { - intent.current = null; - setHasIntent(false); - releaseSubmission('ordinary'); - navigate(`/experiments/${encodeURIComponent(accepted.id)}`); - } - } catch (cause) { - if (alive.current) { - setError(message(cause)); - setAmbiguous(!(cause instanceof ExperimentApiError) || cause.ambiguous); - } - } finally { - pending.current = false; - if (alive.current) { - setSubmitting(false); - } - } - }; - const newIntent = () => { - if ( - pending.current || - !window.confirm( - 'Release this submission? If its response was lost, it may already exist. Check the experiment list before creating another.' - ) - ) { - return; - } - intent.current = null; - setHasIntent(false); - releaseSubmission('ordinary'); - setAmbiguous(false); - previewRevision.current = null; - setPreview(null); - setError(''); - }; return (
; + scenarios: CostScenario[]; + candidate: { versionId: string; parameters: Record } | undefined; + candidateRevision: MutableRefObject; + renderedCandidateRevision: number; + useCandidate: boolean; + candidateValid: boolean; + onAccepted: (id: string) => void; +} +export const message = (cause: unknown) => + cause instanceof z.ZodError + ? cause.issues.map(issue => `${issue.path.join('.') || 'Input'}: ${issue.message}`).join('; ') + : cause instanceof Error + ? cause.message + : 'Could not prepare the experiment'; + +/** One coordinator owns all submission modes and ordinary receipt recovery. */ +export function useExperimentSubmission({ + backtestId, + name, + grid, + modeRef, + scenarios, + candidate, + candidateRevision, + renderedCandidateRevision, + useCandidate, + candidateValid, + onAccepted, +}: Inputs) { + const alive = useRef(false); + const generation = useRef(0); + const previewRevision = useRef(null); + const previewRequest = useRef(null); + const pending = useRef(false); + type Intent = + | { kind: 'parameters'; body: ExperimentSubmission; key: string } + | { kind: 'cost-sensitivity'; body: CostSensitivitySubmission; key: string }; + const intent = useRef(null); + const [preview, setPreview] = useState(null); + const [previewLoading, setPreviewLoading] = useState(false); + const [error, setError] = useState(''); + const [phase, setPhase] = useState<'idle' | 'submitting' | 'uncertain' | 'rejected'>('idle'); + const hasIntent = phase !== 'idle'; + const submitting = phase === 'submitting'; + const ambiguous = phase === 'uncertain'; + const submissionOwner = useRef<'ordinary' | 'chronological' | 'walk-forward' | null>(null); + const [lockedBy, setLockedBy] = useState<'ordinary' | 'chronological' | 'walk-forward' | null>( + null + ); + const claimSubmission = useCallback((owner: 'ordinary' | 'chronological' | 'walk-forward') => { + if ( + (owner !== 'ordinary' && modeRef.current === 'cost-sensitivity') || + (submissionOwner.current && submissionOwner.current !== owner) + ) { + return false; + } + submissionOwner.current = owner; + setLockedBy(owner); + if (owner !== 'ordinary') { + generation.current++; + previewRequest.current?.abort(); + previewRevision.current = null; + setPreview(null); + setPreviewLoading(false); + } + return true; + }, []); + const releaseSubmission = useCallback((owner: 'ordinary' | 'chronological' | 'walk-forward') => { + if (submissionOwner.current === owner) { + submissionOwner.current = null; + setLockedBy(null); + } + }, []); + useEffect(() => { + alive.current = true; + return () => { + alive.current = false; + generation.current++; + previewRequest.current?.abort(); + }; + }, []); + const invalidate = (change: () => void) => { + if (submissionOwner.current) { + return; + } + generation.current++; + previewRequest.current?.abort(); + previewRevision.current = null; + setPreview(null); + setPreviewLoading(false); + setError(''); + change(); + }; + const prepare = async () => { + if ( + submissionOwner.current || + previewLoading || + candidateRevision.current !== renderedCandidateRevision || + (useCandidate && !candidateValid) + ) { + return; + } + const current = ++generation.current; + previewRequest.current?.abort(); + const controller = new AbortController(); + previewRequest.current = controller; + previewRevision.current = null; + setPreview(null); + setError(''); + setPreviewLoading(true); + try { + const value = + modeRef.current === 'cost-sensitivity' + ? await experimentApi.costPreview( + costSensitivityInputSchema.parse({ + backtestId, + name, + scenarios, + ...(candidate ? { candidate } : {}), + }), + controller.signal + ) + : await experimentApi.preview( + experimentInputSchema.parse({ + backtestId, + name, + grid: JSON.parse(grid), + ...(candidate ? { candidate } : {}), + }), + controller.signal + ); + if (alive.current && current === generation.current) { + previewRevision.current = current; + setPreview(value); + } + } catch (cause) { + if (alive.current && current === generation.current) { + setError(message(cause)); + } + } finally { + if (alive.current && current === generation.current) { + setPreviewLoading(false); + } + } + }; + const submit = async () => { + if ( + pending.current || + (!intent.current && (!preview || previewRevision.current !== generation.current)) || + !claimSubmission('ordinary') + ) { + return; + } + if (!intent.current) { + if (!preview) { + return; + } + intent.current = + preview.version === 'cost-sensitivity-preview/v1' + ? { + kind: 'cost-sensitivity', + key: crypto.randomUUID(), + body: { ...preview.input, previewHash: preview.previewHash }, + } + : { + kind: 'parameters', + key: crypto.randomUUID(), + body: { ...preview.input, previewHash: preview.previewHash }, + }; + } + const captured = intent.current; + pending.current = true; + setPhase('submitting'); + setError(''); + try { + const accepted = + captured.kind === 'cost-sensitivity' + ? await experimentApi.costSubmit(captured.body, captured.key) + : await experimentApi.create(captured.body, captured.key); + if (alive.current) { + intent.current = null; + setPhase('idle'); + releaseSubmission('ordinary'); + onAccepted(accepted.id); + } + } catch (cause) { + if (alive.current) { + setError(message(cause)); + setPhase( + !(cause instanceof ExperimentApiError) || cause.ambiguous ? 'uncertain' : 'rejected' + ); + } + } finally { + pending.current = false; + } + }; + const newIntent = () => { + if ( + pending.current || + !window.confirm( + 'Release this submission? If its response was lost, it may already exist. Check the experiment list before creating another.' + ) + ) { + return; + } + intent.current = null; + setPhase('idle'); + releaseSubmission('ordinary'); + previewRevision.current = null; + setPreview(null); + setError(''); + }; + return { + submissionOwner, + lockedBy, + claimSubmission, + releaseSubmission, + preview, + previewLoading, + error, + hasIntent, + submitting, + ambiguous, + invalidate, + prepare, + submit, + newIntent, + }; +} diff --git a/apps/stock/web-app/src/features/experiments/hooks/useExperimentTemplates.ts b/apps/stock/web-app/src/features/experiments/hooks/useExperimentTemplates.ts new file mode 100644 index 00000000..f325d74a --- /dev/null +++ b/apps/stock/web-app/src/features/experiments/hooks/useExperimentTemplates.ts @@ -0,0 +1,59 @@ +import { useEffect, useState } from 'react'; +import { backtestApiV2, type Backtest } from '@/features/backtest/services/backtestApiV2'; +import { message } from './useExperimentSubmission'; + +const canonical = (value: Backtest) => + value && + typeof value.id === 'string' && + typeof value.name === 'string' && + !value.archivedAt && + value.strategyVersionId && + value.config && + typeof value.config.canonical === 'object' && + value.config.canonical !== null && + typeof value.config.datasetHash === 'string'; + +export function useExperimentTemplates(initialBacktestId: string) { + const [backtests, setBacktests] = useState([]); + const [templateLoading, setTemplateLoading] = useState(true); + const [templateError, setTemplateError] = useState(''); + const [templateReload, setTemplateReload] = useState(0); + const [limit, setLimit] = useState(50); + const [moreTemplates, setMoreTemplates] = useState(false); + useEffect(() => { + let current = true; + const controller = new AbortController(); + setTemplateLoading(true); + setTemplateError(''); + void (async () => { + const rows = await backtestApiV2.listBacktests(limit, 0, false, controller.signal); + if (!Array.isArray(rows)) { + throw new Error('The saved backtest list could not be read'); + } + const selected = + initialBacktestId && !rows.some(item => item?.id === initialBacktestId) + ? await backtestApiV2.getBacktest(initialBacktestId) + : null; + if (current) { + setMoreTemplates(rows.length === limit); + setBacktests((selected ? [...rows, selected] : rows).filter(canonical)); + } + })() + .catch(cause => { + if (current) { + setTemplateError(message(cause)); + } + }) + .finally(() => { + if (current) { + setTemplateLoading(false); + } + }); + return () => { + current = false; + controller.abort(); + }; + }, [initialBacktestId, templateReload, limit]); + + return { backtests, templateLoading, templateError, setTemplateReload, moreTemplates, setLimit }; +} diff --git a/apps/stock/web-app/src/features/experiments/services/chronologicalValidationDurableApi.ts b/apps/stock/web-app/src/features/experiments/services/chronologicalValidationDurableApi.ts index ccfcb4e6..67770ba3 100644 --- a/apps/stock/web-app/src/features/experiments/services/chronologicalValidationDurableApi.ts +++ b/apps/stock/web-app/src/features/experiments/services/chronologicalValidationDurableApi.ts @@ -15,7 +15,8 @@ import { validationSummarySchema as summary, ValidationApiError, } from '@stock-bot/stock-config/research-responses'; -import { API_BASE_URL, apiFetch } from '@/lib/api'; +import { API_BASE_URL } from '@/lib/api'; +import { requestJson } from '@/lib/requestJson'; export { parseValidationDetail, @@ -26,41 +27,20 @@ export { export type { ValidationResultEvidence }; const envelope = (body: unknown, key: string) => z.record(z.unknown()).parse(body)[key]; -async function request( +function request( path: string, init: RequestInit, status: number, parse: (body: unknown) => T ): Promise { - let response: Response; - try { - response = await apiFetch(`${API_BASE_URL}/api/v2/experiments/validation${path}`, init); - } catch (cause) { - if (init.signal?.aborted) { - throw cause; - } - throw new ValidationApiError( - 'The validation response was lost. Retry the same request to recover its receipt.', - null - ); - } - const body: unknown = await response.json().catch(() => null); - if (!response.ok) { - const error = z.object({ error: z.string() }).safeParse(body); - throw new ValidationApiError( - error.success ? error.data.error : `Validation request failed (${response.status})`, - response.status - ); - } - try { - if (response.status !== status) { - throw invalid(); - } - return parse(body); - } catch { - throw invalid(); - } + return requestJson(`${API_BASE_URL}/api/v2/experiments/validation${path}`, init, status, parse, { + create: (message, code) => new ValidationApiError(message, code), + invalid, + lostMessage: 'The validation response was lost. Retry the same request to recover its receipt.', + failureLabel: 'Validation request failed', + }); } + const post = (body: unknown, key?: string): RequestInit => ({ method: 'POST', body: JSON.stringify(body), diff --git a/apps/stock/web-app/src/features/experiments/services/experimentApi.ts b/apps/stock/web-app/src/features/experiments/services/experimentApi.ts index 375ae9e8..a07f9e50 100644 --- a/apps/stock/web-app/src/features/experiments/services/experimentApi.ts +++ b/apps/stock/web-app/src/features/experiments/services/experimentApi.ts @@ -23,7 +23,8 @@ import { sameExperimentInput as same, type ExperimentRetryTarget, } from '@stock-bot/stock-config/research-responses'; -import { API_BASE_URL, apiFetch } from '@/lib/api'; +import { API_BASE_URL } from '@/lib/api'; +import { requestJson } from '@/lib/requestJson'; export { ExperimentApiError, @@ -41,41 +42,21 @@ export { type WorkbenchExperimentPreviewView, } from '@stock-bot/stock-config/research-responses'; -async function request( +function request( path: string, init: RequestInit, - expectedStatus: number, + status: number, parse: (body: unknown) => T ): Promise { - let response: Response; - try { - response = await apiFetch(`${API_BASE_URL}/api/v2/experiments${path}`, init); - } catch (cause) { - if (init.signal?.aborted) { - throw cause; - } - throw new ExperimentApiError( + return requestJson(`${API_BASE_URL}/api/v2/experiments${path}`, init, status, parse, { + create: (message, code) => new ExperimentApiError(message, code), + invalid, + lostMessage: 'The experiment response was lost. Retry the same submission to check whether it was accepted.', - null - ); - } - const body: unknown = await response.json().catch(() => null); - if (!response.ok) { - const parsed = z.object({ error: z.string() }).safeParse(body); - throw new ExperimentApiError( - parsed.success ? parsed.data.error : `Experiment request failed (${response.status})`, - response.status - ); - } - try { - if (response.status !== expectedStatus) { - throw invalid(); - } - return parse(body); - } catch { - throw invalid(); - } + failureLabel: 'Experiment request failed', + }); } + const envelope = (body: unknown, field: string): unknown => z.record(z.unknown()).parse(body)[field]; const json = (body: unknown): RequestInit => ({ diff --git a/apps/stock/web-app/src/features/experiments/services/walkForwardApi.ts b/apps/stock/web-app/src/features/experiments/services/walkForwardApi.ts index 9a9f514b..ac0110c9 100644 --- a/apps/stock/web-app/src/features/experiments/services/walkForwardApi.ts +++ b/apps/stock/web-app/src/features/experiments/services/walkForwardApi.ts @@ -16,7 +16,8 @@ import { type WalkForwardSubmission, type WalkForwardSummary, } from '@stock-bot/stock-config/walk-forward'; -import { API_BASE_URL, apiFetch } from '@/lib/api'; +import { API_BASE_URL } from '@/lib/api'; +import { requestJson } from '@/lib/requestJson'; export { WalkForwardApiError, @@ -27,41 +28,27 @@ export { } from '@stock-bot/stock-config/research-responses'; const envelope = (body: unknown, key: string) => z.record(z.unknown()).parse(body)[key]; -async function request( +function request( path: string, init: RequestInit, status: number, parse: (body: unknown) => T ): Promise { - let response: Response; - try { - response = await apiFetch(`${API_BASE_URL}/api/v2/experiments/walk-forward${path}`, init); - } catch (cause) { - if (init.signal?.aborted) { - throw cause; + return requestJson( + `${API_BASE_URL}/api/v2/experiments/walk-forward${path}`, + init, + status, + parse, + { + create: (message, code) => new WalkForwardApiError(message, code), + invalid, + lostMessage: + 'The walk-forward response was lost. Retry the same request to recover its receipt.', + failureLabel: 'Walk-forward request failed', } - throw new WalkForwardApiError( - 'The walk-forward response was lost. Retry the same request to recover its receipt.', - null - ); - } - const body: unknown = await response.json().catch(() => null); - if (!response.ok) { - const error = z.object({ error: z.string() }).safeParse(body); - throw new WalkForwardApiError( - error.success ? error.data.error : `Walk-forward request failed (${response.status})`, - response.status - ); - } - try { - if (response.status !== status) { - throw invalid(); - } - return parse(body); - } catch { - throw invalid(); - } + ); } + const post = (body: unknown, key?: string): RequestInit => ({ method: 'POST', body: JSON.stringify(body), diff --git a/apps/stock/web-app/src/features/strategies/StrategyDetailPage.tsx b/apps/stock/web-app/src/features/strategies/StrategyDetailPage.tsx index 03840c2d..849323b9 100644 --- a/apps/stock/web-app/src/features/strategies/StrategyDetailPage.tsx +++ b/apps/stock/web-app/src/features/strategies/StrategyDetailPage.tsx @@ -1,15 +1,14 @@ import { useEffect, useRef, useState } from 'react'; import { Link, Navigate, useNavigate, useParams } from 'react-router-dom'; -import type { - StrategyRecord, - StrategyVersionPackage, - StrategyVersionSummary, -} from '@stock-bot/types'; +import type { StrategyRecord, StrategyVersionSummary } from '@stock-bot/types'; import { BuiltinReview } from './components/BuiltinReview'; import { CandidatePublication } from './components/CandidatePublication'; +import { StrategyMetadataForm } from './components/StrategyMetadataForm'; import { actionClass, fieldClass, StrategyParameterForm } from './components/StrategyParameterForm'; import { versionPath } from './components/StrategySelection'; +import { VersionComparison, VersionIdentity } from './components/StrategyVersionPanel'; import { confirmDiscard, useUnsavedWarning } from './components/useUnsavedWarning'; +import { useStrategyClone } from './hooks/useStrategyClone'; import { strategyApi, type Parameters } from './services/strategyApi'; export function StrategyDetailPage() { @@ -35,21 +34,24 @@ function StrategyDetail({ strategyId, versionId }: { strategyId: string; version const [validParameters, setValidParameters] = useState(false); const [parameterEdits, setParameterEdits] = useState(false); const [publicationDirty, setPublicationDirty] = useState(false); - const [cloneOpen, setCloneOpen] = useState(false); - const [cloneName, setCloneName] = useState(''); - const [cloneDescription, setCloneDescription] = useState(''); - const [cloning, setCloning] = useState(false); - const [cloneError, setCloneError] = useState(null); - const cloneIntent = useRef<{ - versionId: string; - versionOrdinal: number; - body: { name: string; description: string }; - key: string; - } | null>(null); - const [cloneFrozen, setCloneFrozen] = useState(false); const mounted = useRef(true); const selectedVersionId = useRef(versionId); selectedVersionId.current = versionId; + const { + cloneOpen, + setCloneOpen, + cloneName, + setCloneName, + cloneDescription, + setCloneDescription, + cloning, + cloneError, + setCloneError, + cloneIntent, + cloneFrozen, + setCloneFrozen, + clone, + } = useStrategyClone(version, versionId, navigate); const metadataDirty = Boolean( strategy && (name !== strategy.name || description !== strategy.description) ); @@ -150,37 +152,7 @@ function StrategyDetail({ strategyId, versionId }: { strategyId: string; version } } }; - const clone = async (event: React.FormEvent) => { - event.preventDefault(); - if (!version || cloning || !cloneName.trim()) { - return; - } - const intent = (cloneIntent.current ??= { - versionId: version.id, - versionOrdinal: version.ordinal, - body: { name: cloneName, description: cloneDescription }, - key: crypto.randomUUID(), - }); - setCloneFrozen(true); - setCloning(true); - setCloneError(null); - try { - const result = await strategyApi.clone(intent.versionId, intent.body, intent.key); - if (mounted.current && selectedVersionId.current === intent.versionId) { - navigate(versionPath(result.version)); - } - } catch (cause) { - if (mounted.current && selectedVersionId.current === intent.versionId) { - setCloneError( - `${cause instanceof Error ? cause.message : 'Clone failed'}. Retry clone to recover the same immutable version.` - ); - } - } finally { - if (mounted.current) { - setCloning(false); - } - } - }; + return (
-
{ - event.preventDefault(); - void update({ name, description }); - }} - > - -