refactor: share research domain and simplify application workflows
This commit is contained in:
parent
805a9f8fd4
commit
8c39ccf7ea
58 changed files with 3805 additions and 3081 deletions
|
|
@ -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": "*",
|
||||
|
|
|
|||
|
|
@ -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';
|
||||
|
|
|
|||
|
|
@ -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<object>();
|
||||
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<string>(),
|
||||
sequences = new Set<string>(),
|
||||
seen = new Set<string>();
|
||||
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<T>(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<typeof parseMetadata>,
|
||||
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);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -12,6 +12,7 @@
|
|||
"clean": "rm -rf dist"
|
||||
},
|
||||
"dependencies": {
|
||||
"@stock-bot/research": "workspace:*",
|
||||
"@stock-bot/queue": "workspace:*",
|
||||
"@stock-bot/services": "workspace:*",
|
||||
"@stock-bot/config": "*",
|
||||
|
|
|
|||
File diff suppressed because it is too large
Load diff
128
apps/stock/web-api/src/services/backtests/contracts.ts
Normal file
128
apps/stock/web-api/src/services/backtests/contracts.ts
Normal file
|
|
@ -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<Response>;
|
||||
/** Reads may share an existing transaction without acquiring another pool connection. */
|
||||
export interface BacktestResultQuery {
|
||||
query<T extends QueryResultRow = QueryResultRow>(
|
||||
text: string,
|
||||
values?: unknown[]
|
||||
): Promise<{ rows: T[] }>;
|
||||
}
|
||||
|
||||
export interface BacktestRequest {
|
||||
name: string;
|
||||
strategy: string;
|
||||
symbols: string[];
|
||||
startDate: string;
|
||||
endDate: string;
|
||||
initialCapital: number;
|
||||
config?: Record<string, unknown>;
|
||||
strategyVersionId?: string | null;
|
||||
strategyParameters?: Record<string, StrategyParameterValue> | null;
|
||||
}
|
||||
|
||||
export interface Backtest {
|
||||
id: string;
|
||||
archivedAt: string | null;
|
||||
strategyVersionId: string | null;
|
||||
strategyParameters: Record<string, StrategyParameterValue> | null;
|
||||
name: string;
|
||||
strategy: string;
|
||||
symbols: string[];
|
||||
startDate: Date;
|
||||
endDate: Date;
|
||||
initialCapital: number;
|
||||
config: Record<string, unknown>;
|
||||
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<IServiceContainer['postgres']>;
|
||||
};
|
||||
76
apps/stock/web-api/src/services/backtests/mapping.ts
Normal file
76
apps/stock/web-api/src/services/backtests/mapping.ts
Normal file
|
|
@ -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',
|
||||
};
|
||||
}
|
||||
243
apps/stock/web-api/src/services/backtests/reproduction.ts
Normal file
243
apps/stock/web-api/src/services/backtests/reproduction.ts
Normal file
|
|
@ -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<CanonicalReproductionPreview> {
|
||||
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<Run> {
|
||||
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<CanonicalReproductionComparison> {
|
||||
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;
|
||||
}
|
||||
}
|
||||
79
apps/stock/web-api/src/services/backtests/results.ts
Normal file
79
apps/stock/web-api/src/services/backtests/results.ts
Normal file
|
|
@ -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<ResearchRunResult | null> {
|
||||
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);
|
||||
}
|
||||
}
|
||||
246
apps/stock/web-api/src/services/backtests/runs.ts
Normal file
246
apps/stock/web-api/src/services/backtests/runs.ts
Normal file
|
|
@ -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<Run> {
|
||||
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<Run | null> {
|
||||
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<Run[]> {
|
||||
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<void> {
|
||||
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<void> {
|
||||
await this.sendControl(id, 'pause');
|
||||
}
|
||||
|
||||
async resumeRun(id: string): Promise<void> {
|
||||
await this.sendControl(id, 'resume');
|
||||
}
|
||||
|
||||
async cancelRun(id: string): Promise<void> {
|
||||
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<void> {
|
||||
await this.sendControl(id, 'speed', { speed: speedMultiplier });
|
||||
}
|
||||
|
||||
private async sendControl(runId: string, command: string, payload: object = {}): Promise<void> {
|
||||
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<CanonicalRunCapability> {
|
||||
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;
|
||||
}
|
||||
}
|
||||
321
apps/stock/web-api/src/services/backtests/templates.ts
Normal file
321
apps/stock/web-api/src/services/backtests/templates.ts
Normal file
|
|
@ -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<Run>
|
||||
) {}
|
||||
async createBacktest(
|
||||
request: BacktestRequest,
|
||||
options: { autoStart?: boolean } = {}
|
||||
): Promise<Backtest> {
|
||||
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<Backtest | null> {
|
||||
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<BacktestRequest>): Promise<Backtest | null> {
|
||||
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<Backtest[]> {
|
||||
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<void> {
|
||||
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<Backtest | null> {
|
||||
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<BacktestRequest> {
|
||||
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<string, StrategyParameterValue>;
|
||||
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,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
|
@ -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);
|
||||
}
|
||||
|
||||
/**
|
||||
|
|
|
|||
|
|
@ -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 {
|
||||
|
|
|
|||
|
|
@ -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,
|
||||
|
|
|
|||
|
|
@ -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,
|
||||
|
|
|
|||
|
|
@ -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';
|
||||
|
||||
|
|
|
|||
|
|
@ -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.
|
||||
|
|
|
|||
|
|
@ -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",
|
||||
|
|
|
|||
|
|
@ -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() {
|
|||
<Route path=":symbol" element={<SymbolDetailPage />} />
|
||||
</Route>
|
||||
<Route path="exchanges" element={<ExchangesPage />} />
|
||||
<Route
|
||||
path="portfolio"
|
||||
element={<div className="p-4">Portfolio Page - Coming Soon</div>}
|
||||
/>
|
||||
<Route path="portfolio" element={<UnavailablePage name="Portfolio" />} />
|
||||
<Route path="strategies">
|
||||
<Route index element={<StrategyListPage />} />
|
||||
<Route path="versions/:versionId" element={<StrategyVersionPage />} />
|
||||
<Route path=":strategyId" element={<StrategyDetailPage />} />
|
||||
<Route path=":strategyId/versions/:versionId" element={<StrategyDetailPage />} />
|
||||
</Route>
|
||||
<Route
|
||||
path="analytics"
|
||||
element={<div className="p-4">Analytics Page - Coming Soon</div>}
|
||||
/>
|
||||
<Route path="analytics" element={<UnavailablePage name="Analytics" />} />
|
||||
<Route path="backtests">
|
||||
<Route index element={<BacktestListPageV2 />} />
|
||||
<Route path=":id">
|
||||
|
|
@ -71,10 +66,7 @@ export function App() {
|
|||
<Route path="walk-forward/:walkForwardId" element={<WalkForwardDetailPage />} />
|
||||
<Route path=":experimentId" element={<ExperimentDetailPage />} />
|
||||
</Route>
|
||||
<Route
|
||||
path="settings"
|
||||
element={<div className="p-4">Settings Page - Coming Soon</div>}
|
||||
/>
|
||||
<Route path="settings" element={<UnavailablePage name="Settings" />} />
|
||||
<Route path="system/monitoring" element={<MonitoringPage />} />
|
||||
<Route path="system/pipeline" element={<PipelinePage />} />
|
||||
</Route>
|
||||
|
|
|
|||
12
apps/stock/web-app/src/app/UnavailablePage.tsx
Normal file
12
apps/stock/web-app/src/app/UnavailablePage.tsx
Normal file
|
|
@ -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 (
|
||||
<section className="p-4 space-y-3">
|
||||
<h1 className="font-semibold">{name} is not available</h1>
|
||||
<p>Inspect saved performance, trades and risk metrics in backtests and experiments.</p>
|
||||
<Link to="/backtests">Open backtests</Link> <Link to="/experiments">Open experiments</Link>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
|
@ -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<typeof setTimeout>;
|
||||
request?: Promise<void>;
|
||||
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<Backtest | null>(null);
|
||||
const [runs, setRuns] = useState<Run[]>([]);
|
||||
const [currentRun, setCurrentRun] = useState<Run | null>(null);
|
||||
const [runResults, setRunResults] = useState<ResearchRunResult | null>(null);
|
||||
const [isBacktestLoading, setIsBacktestLoading] = useState(false);
|
||||
const [isRunLoading, setIsRunLoading] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [runError, setRunError] = useState<string | null>(null);
|
||||
const [submissionError, setSubmissionError] = useState<string | null>(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<string | null>(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<RunSelection | null>(null);
|
||||
const cancellation = useRef<RunSelection | null>(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<void> {
|
||||
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,
|
||||
|
|
|
|||
|
|
@ -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<typeof setTimeout>;
|
||||
request?: Promise<void>;
|
||||
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<boolean>;
|
||||
loadedBacktestId: MutableRefObject<string | null>;
|
||||
setRuns: Dispatch<SetStateAction<Run[]>>;
|
||||
}) {
|
||||
const [currentRun, setCurrentRun] = useState<Run | null>(null);
|
||||
const [runResults, setRunResults] = useState<ResearchRunResult | null>(null);
|
||||
const [isRunLoading, setIsRunLoading] = useState(false);
|
||||
const [runError, setRunError] = useState<string | null>(null);
|
||||
const [cancelRequested, setCancelRequested] = useState(false);
|
||||
const selectionGeneration = useRef(0);
|
||||
const selection = useRef<RunSelection | null>(null);
|
||||
const cancellation = useRef<RunSelection | null>(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<void> {
|
||||
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,
|
||||
};
|
||||
}
|
||||
|
|
@ -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<string | null>;
|
||||
mounted: MutableRefObject<boolean>;
|
||||
selectionGeneration: MutableRefObject<number>;
|
||||
catalog: boolean;
|
||||
canonicalCapability: CanonicalRunCapability | null;
|
||||
capabilityError: string | null;
|
||||
setRuns: Dispatch<SetStateAction<Run[]>>;
|
||||
}) {
|
||||
const [submissionError, setSubmissionError] = useState<string | null>(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,
|
||||
};
|
||||
}
|
||||
|
|
@ -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) ||
|
||||
|
|
|
|||
|
|
@ -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<number | null>(null);
|
||||
const previewRequest = useRef<AbortController | null>(null);
|
||||
const pending = useRef(false);
|
||||
type Intent =
|
||||
| { kind: 'parameters'; body: ExperimentSubmission; key: string }
|
||||
| { kind: 'cost-sensitivity'; body: CostSensitivitySubmission; key: string };
|
||||
const intent = useRef<Intent | null>(null);
|
||||
const [mode, setMode] = useState<'parameters' | 'cost-sensitivity'>('parameters');
|
||||
const modeRef = useRef(mode);
|
||||
const [scenarios, setScenarios] = useState<CostScenario[]>([{ 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<Backtest[]>([]);
|
||||
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<WorkbenchExperimentPreviewView | null>(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 (
|
||||
<section
|
||||
aria-label="Create experiment"
|
||||
|
|
|
|||
|
|
@ -0,0 +1,252 @@
|
|||
import { useCallback, useEffect, useRef, useState, type MutableRefObject } from 'react';
|
||||
import { z } from 'zod';
|
||||
import {
|
||||
costSensitivityInputSchema,
|
||||
type CostScenario,
|
||||
type CostSensitivitySubmission,
|
||||
} from '@stock-bot/stock-config/cost-sensitivity';
|
||||
import {
|
||||
experimentInputSchema,
|
||||
type ExperimentSubmission,
|
||||
} from '@stock-bot/stock-config/experiments';
|
||||
import type { StrategyParameterValue } from '@stock-bot/types';
|
||||
import {
|
||||
experimentApi,
|
||||
ExperimentApiError,
|
||||
type WorkbenchExperimentPreviewView,
|
||||
} from '../services/experimentApi';
|
||||
|
||||
interface Inputs {
|
||||
backtestId: string;
|
||||
name: string;
|
||||
grid: string;
|
||||
modeRef: MutableRefObject<'parameters' | 'cost-sensitivity'>;
|
||||
scenarios: CostScenario[];
|
||||
candidate: { versionId: string; parameters: Record<string, StrategyParameterValue> } | undefined;
|
||||
candidateRevision: MutableRefObject<number>;
|
||||
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<number | null>(null);
|
||||
const previewRequest = useRef<AbortController | null>(null);
|
||||
const pending = useRef(false);
|
||||
type Intent =
|
||||
| { kind: 'parameters'; body: ExperimentSubmission; key: string }
|
||||
| { kind: 'cost-sensitivity'; body: CostSensitivitySubmission; key: string };
|
||||
const intent = useRef<Intent | null>(null);
|
||||
const [preview, setPreview] = useState<WorkbenchExperimentPreviewView | null>(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,
|
||||
};
|
||||
}
|
||||
|
|
@ -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<Backtest[]>([]);
|
||||
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 };
|
||||
}
|
||||
|
|
@ -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<T>(
|
||||
function request<T>(
|
||||
path: string,
|
||||
init: RequestInit,
|
||||
status: number,
|
||||
parse: (body: unknown) => T
|
||||
): Promise<T> {
|
||||
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),
|
||||
|
|
|
|||
|
|
@ -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<T>(
|
||||
function request<T>(
|
||||
path: string,
|
||||
init: RequestInit,
|
||||
expectedStatus: number,
|
||||
status: number,
|
||||
parse: (body: unknown) => T
|
||||
): Promise<T> {
|
||||
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 => ({
|
||||
|
|
|
|||
|
|
@ -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<T>(
|
||||
function request<T>(
|
||||
path: string,
|
||||
init: RequestInit,
|
||||
status: number,
|
||||
parse: (body: unknown) => T
|
||||
): Promise<T> {
|
||||
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),
|
||||
|
|
|
|||
|
|
@ -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<string | null>(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 (
|
||||
<div className="space-y-5 text-text-primary">
|
||||
<Link
|
||||
|
|
@ -218,84 +190,17 @@ function StrategyDetail({ strategyId, versionId }: { strategyId: string; version
|
|||
{strategy.name}
|
||||
{strategy.archived ? ' — Archived' : ''}
|
||||
</h1>
|
||||
<form
|
||||
className="space-y-3 border border-border rounded-md p-4"
|
||||
onSubmit={event => {
|
||||
event.preventDefault();
|
||||
void update({ name, description });
|
||||
}}
|
||||
>
|
||||
<label className="block text-sm">
|
||||
Strategy name
|
||||
<input
|
||||
aria-label="Strategy name"
|
||||
className={fieldClass}
|
||||
required
|
||||
disabled={saving}
|
||||
value={name}
|
||||
onChange={event => setName(event.target.value)}
|
||||
/>
|
||||
</label>
|
||||
<label className="block text-sm">
|
||||
Strategy description
|
||||
<textarea
|
||||
aria-label="Strategy description"
|
||||
className={fieldClass}
|
||||
disabled={saving}
|
||||
value={description}
|
||||
onChange={event => setDescription(event.target.value)}
|
||||
/>
|
||||
</label>
|
||||
{metadataDirty && (
|
||||
<p role="status" className="text-sm text-text-secondary">
|
||||
Unsaved strategy metadata. Save or discard before leaving.
|
||||
</p>
|
||||
)}
|
||||
{saveError && (
|
||||
<p role="alert" className="text-error text-sm">
|
||||
{saveError}
|
||||
</p>
|
||||
)}
|
||||
<button
|
||||
type="submit"
|
||||
className={actionClass}
|
||||
disabled={saving || !metadataDirty || !name.trim()}
|
||||
>
|
||||
Save metadata
|
||||
</button>{' '}
|
||||
<button
|
||||
type="button"
|
||||
className={actionClass}
|
||||
disabled={saving || !metadataDirty}
|
||||
onClick={() => {
|
||||
if (confirmDiscard(metadataDirty)) {
|
||||
setName(strategy.name);
|
||||
setDescription(strategy.description);
|
||||
}
|
||||
}}
|
||||
>
|
||||
Discard metadata changes
|
||||
</button>{' '}
|
||||
<button
|
||||
type="button"
|
||||
className={actionClass}
|
||||
disabled={saving}
|
||||
onClick={() => {
|
||||
if (
|
||||
confirmDiscard(metadataDirty) &&
|
||||
window.confirm(
|
||||
strategy.archived
|
||||
? 'Restore this strategy family?'
|
||||
: 'Archive this strategy family? Saved versions and history remain available.'
|
||||
)
|
||||
) {
|
||||
void update({ archived: !strategy.archived });
|
||||
}
|
||||
}}
|
||||
>
|
||||
{strategy.archived ? 'Restore strategy' : 'Archive strategy'}
|
||||
</button>
|
||||
</form>
|
||||
<StrategyMetadataForm
|
||||
strategy={strategy}
|
||||
name={name}
|
||||
description={description}
|
||||
saving={saving}
|
||||
metadataDirty={metadataDirty}
|
||||
saveError={saveError}
|
||||
update={update}
|
||||
setName={setName}
|
||||
setDescription={setDescription}
|
||||
/>
|
||||
<CandidatePublication
|
||||
key={`publication:${strategyId}:${versionId ?? ''}`}
|
||||
strategyId={strategyId}
|
||||
|
|
@ -524,234 +429,6 @@ function StrategyDetail({ strategyId, versionId }: { strategyId: string; version
|
|||
</div>
|
||||
);
|
||||
}
|
||||
function VersionIdentity({ version }: { version: StrategyVersionSummary }) {
|
||||
const pkg = version.package;
|
||||
return (
|
||||
<div className="space-y-2 text-sm border border-border rounded-md p-4">
|
||||
<h3 className="font-medium">Version {version.ordinal}</h3>
|
||||
<p>
|
||||
Immutable version ID: <code>{version.id}</code>
|
||||
</p>
|
||||
<p>
|
||||
Origin: {version.origin} · Review: {version.reviewStatus}
|
||||
</p>
|
||||
<p role="status">
|
||||
{version.origin === 'candidate'
|
||||
? 'Candidate research uses the isolated runtime. Eligibility is checked against the retained package, dataset and financial policy.'
|
||||
: 'Canonical execution requires approval, a matching executable build, a supported dataset and an explicit simulation policy.'}
|
||||
</p>
|
||||
<p>
|
||||
Program: {pkg.program.strategyId} / {pkg.program.strategyVersion}
|
||||
</p>
|
||||
<p>
|
||||
API: {pkg.program.apiVersion} · Checkpoint: {pkg.program.checkpointVersion}
|
||||
</p>
|
||||
<p className="break-all">Artifact SHA256: {pkg.artifact.sha256}</p>
|
||||
<p className="break-all">Dependency lock SHA256: {pkg.dependencyLock.sha256}</p>
|
||||
<p className="break-all">
|
||||
Source revision: {pkg.source.revision} (
|
||||
{pkg.source.dirty ? 'dirty working tree' : 'clean working tree'})
|
||||
</p>
|
||||
<p>
|
||||
Build: {pkg.build.tool} {pkg.build.version} / {pkg.build.target}
|
||||
</p>
|
||||
{version.parentVersionId && <p>Parent version: {version.parentVersionId}</p>}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
function VersionComparison({
|
||||
version,
|
||||
versions,
|
||||
}: {
|
||||
version: StrategyVersionSummary;
|
||||
versions: StrategyVersionSummary[];
|
||||
}) {
|
||||
const [showArtifact, setShowArtifact] = useState(false);
|
||||
const [compareId, setCompareId] = useState('');
|
||||
const [artifact, setArtifact] = useState<StrategyVersionPackage | null>(null);
|
||||
const [comparison, setComparison] = useState<StrategyVersionPackage | null>(null);
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [retry, setRetry] = useState(0);
|
||||
useEffect(() => {
|
||||
const controller = new AbortController();
|
||||
setComparison(null);
|
||||
setError(null);
|
||||
if (!showArtifact && !compareId) {
|
||||
setLoading(false);
|
||||
return () => controller.abort();
|
||||
}
|
||||
setLoading(true);
|
||||
void Promise.all([
|
||||
strategyApi.artifact(version.id, controller.signal),
|
||||
compareId ? strategyApi.artifact(compareId, controller.signal) : Promise.resolve(null),
|
||||
])
|
||||
.then(([current, other]) => {
|
||||
if (!controller.signal.aborted) {
|
||||
setArtifact(current.package);
|
||||
setComparison(other?.package ?? null);
|
||||
}
|
||||
})
|
||||
.catch(cause => {
|
||||
if (!controller.signal.aborted) {
|
||||
setError(cause.message);
|
||||
}
|
||||
})
|
||||
.finally(() => {
|
||||
if (!controller.signal.aborted) {
|
||||
setLoading(false);
|
||||
}
|
||||
});
|
||||
return () => controller.abort();
|
||||
}, [version.id, showArtifact, compareId, retry]);
|
||||
const options = versions.filter(item => item.id !== version.id);
|
||||
return (
|
||||
<section className="space-y-3">
|
||||
<button className={actionClass} onClick={() => setShowArtifact(value => !value)}>
|
||||
{showArtifact ? 'Hide bundled JavaScript' : 'View bundled JavaScript'}
|
||||
</button>
|
||||
<label className="block text-sm">
|
||||
Compare with version
|
||||
<select
|
||||
aria-label="Compare with version"
|
||||
className={fieldClass}
|
||||
value={compareId}
|
||||
onChange={event => setCompareId(event.target.value)}
|
||||
>
|
||||
<option value="">No comparison</option>
|
||||
{options.map(item => (
|
||||
<option key={item.id} value={item.id}>
|
||||
Version {item.ordinal} — {item.id}
|
||||
</option>
|
||||
))}
|
||||
{version.parentVersionId &&
|
||||
!options.some(item => item.id === version.parentVersionId) && (
|
||||
<option value={version.parentVersionId}>
|
||||
Parent version — {version.parentVersionId}
|
||||
</option>
|
||||
)}
|
||||
</select>
|
||||
</label>
|
||||
{(showArtifact || compareId) && (
|
||||
<p className="text-sm text-text-secondary">
|
||||
Retained bundled JavaScript, not original TypeScript. Displayed as text; never executed in
|
||||
the browser.
|
||||
</p>
|
||||
)}
|
||||
{loading && <p role="status">Loading retained artifacts...</p>}
|
||||
{error && (
|
||||
<div>
|
||||
<p role="alert" className="text-error">
|
||||
{error}
|
||||
</p>
|
||||
<button className={actionClass} onClick={() => setRetry(value => value + 1)}>
|
||||
Retry artifacts
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
{!loading && !error && artifact && (showArtifact || compareId) && (
|
||||
<>
|
||||
{comparison && (
|
||||
<>
|
||||
<h3 className="font-medium">Version comparison</h3>
|
||||
<table className="w-full text-sm">
|
||||
<thead>
|
||||
<tr>
|
||||
<th className="text-left">Retained field</th>
|
||||
<th className="text-left">Comparison</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{(['program', 'parameterSchema', 'source', 'build'] as const).map(key => (
|
||||
<tr key={key}>
|
||||
<td>{key}</td>
|
||||
<td>
|
||||
{JSON.stringify(artifact[key]) === JSON.stringify(comparison[key])
|
||||
? 'Unchanged'
|
||||
: 'Changed'}
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
<tr>
|
||||
<td>Artifact SHA256</td>
|
||||
<td>
|
||||
{artifact.artifact.sha256 === comparison.artifact.sha256
|
||||
? 'Identical artifact bytes'
|
||||
: 'Different artifact bytes'}
|
||||
</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>Dependency lock SHA256</td>
|
||||
<td>
|
||||
{artifact.dependencyLock.sha256 === comparison.dependencyLock.sha256
|
||||
? 'Unchanged'
|
||||
: 'Changed'}
|
||||
</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
<div className="grid gap-4 md:grid-cols-2">
|
||||
<div>
|
||||
<h4>Selected version metadata</h4>
|
||||
<pre className="overflow-auto text-xs max-h-64">
|
||||
{JSON.stringify(
|
||||
{
|
||||
program: artifact.program,
|
||||
parameterSchema: artifact.parameterSchema,
|
||||
source: artifact.source,
|
||||
build: artifact.build,
|
||||
},
|
||||
null,
|
||||
2
|
||||
)}
|
||||
</pre>
|
||||
</div>
|
||||
<div>
|
||||
<h4>Compared version metadata</h4>
|
||||
<pre className="overflow-auto text-xs max-h-64">
|
||||
{JSON.stringify(
|
||||
{
|
||||
program: comparison.program,
|
||||
parameterSchema: comparison.parameterSchema,
|
||||
source: comparison.source,
|
||||
build: comparison.build,
|
||||
},
|
||||
null,
|
||||
2
|
||||
)}
|
||||
</pre>
|
||||
</div>
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
<div className={comparison ? 'grid gap-4 md:grid-cols-2' : ''}>
|
||||
<div>
|
||||
<h4>Selected bundled JavaScript</h4>
|
||||
<pre
|
||||
aria-label="Selected bundled JavaScript"
|
||||
className="overflow-auto max-h-96 text-xs p-3 border border-border rounded-md"
|
||||
>
|
||||
{artifact.artifact.content}
|
||||
</pre>
|
||||
</div>
|
||||
{comparison && (
|
||||
<div>
|
||||
<h4>Compared bundled JavaScript</h4>
|
||||
<pre
|
||||
aria-label="Compared bundled JavaScript"
|
||||
className="overflow-auto max-h-96 text-xs p-3 border border-border rounded-md"
|
||||
>
|
||||
{comparison.artifact.content}
|
||||
</pre>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
||||
/** Saved backtests retain version identity without duplicating the mutable family metadata. */
|
||||
export function StrategyVersionPage() {
|
||||
const { versionId = '' } = useParams<{ versionId: string }>();
|
||||
|
|
|
|||
|
|
@ -0,0 +1,107 @@
|
|||
import type { StrategyRecord } from '@stock-bot/types';
|
||||
import { actionClass, fieldClass } from './StrategyParameterForm';
|
||||
import { confirmDiscard } from './useUnsavedWarning';
|
||||
|
||||
interface Props {
|
||||
strategy: StrategyRecord;
|
||||
name: string;
|
||||
description: string;
|
||||
saving: boolean;
|
||||
metadataDirty: boolean;
|
||||
saveError: string | null;
|
||||
update: (body: { name?: string; description?: string; archived?: boolean }) => Promise<void>;
|
||||
setName: (value: string) => void;
|
||||
setDescription: (value: string) => void;
|
||||
}
|
||||
export function StrategyMetadataForm({
|
||||
strategy,
|
||||
name,
|
||||
description,
|
||||
saving,
|
||||
metadataDirty,
|
||||
saveError,
|
||||
update,
|
||||
setName,
|
||||
setDescription,
|
||||
}: Props) {
|
||||
return (
|
||||
<form
|
||||
className="space-y-3 border border-border rounded-md p-4"
|
||||
onSubmit={event => {
|
||||
event.preventDefault();
|
||||
void update({ name, description });
|
||||
}}
|
||||
>
|
||||
<label className="block text-sm">
|
||||
Strategy name
|
||||
<input
|
||||
aria-label="Strategy name"
|
||||
className={fieldClass}
|
||||
required
|
||||
disabled={saving}
|
||||
value={name}
|
||||
onChange={event => setName(event.target.value)}
|
||||
/>
|
||||
</label>
|
||||
<label className="block text-sm">
|
||||
Strategy description
|
||||
<textarea
|
||||
aria-label="Strategy description"
|
||||
className={fieldClass}
|
||||
disabled={saving}
|
||||
value={description}
|
||||
onChange={event => setDescription(event.target.value)}
|
||||
/>
|
||||
</label>
|
||||
{metadataDirty && (
|
||||
<p role="status" className="text-sm text-text-secondary">
|
||||
Unsaved strategy metadata. Save or discard before leaving.
|
||||
</p>
|
||||
)}
|
||||
{saveError && (
|
||||
<p role="alert" className="text-error text-sm">
|
||||
{saveError}
|
||||
</p>
|
||||
)}
|
||||
<button
|
||||
type="submit"
|
||||
className={actionClass}
|
||||
disabled={saving || !metadataDirty || !name.trim()}
|
||||
>
|
||||
Save metadata
|
||||
</button>{' '}
|
||||
<button
|
||||
type="button"
|
||||
className={actionClass}
|
||||
disabled={saving || !metadataDirty}
|
||||
onClick={() => {
|
||||
if (confirmDiscard(metadataDirty)) {
|
||||
setName(strategy.name);
|
||||
setDescription(strategy.description);
|
||||
}
|
||||
}}
|
||||
>
|
||||
Discard metadata changes
|
||||
</button>{' '}
|
||||
<button
|
||||
type="button"
|
||||
className={actionClass}
|
||||
disabled={saving}
|
||||
onClick={() => {
|
||||
if (
|
||||
confirmDiscard(metadataDirty) &&
|
||||
window.confirm(
|
||||
strategy.archived
|
||||
? 'Restore this strategy family?'
|
||||
: 'Archive this strategy family? Saved versions and history remain available.'
|
||||
)
|
||||
) {
|
||||
void update({ archived: !strategy.archived });
|
||||
}
|
||||
}}
|
||||
>
|
||||
{strategy.archived ? 'Restore strategy' : 'Archive strategy'}
|
||||
</button>
|
||||
</form>
|
||||
);
|
||||
}
|
||||
|
|
@ -0,0 +1,232 @@
|
|||
import { useEffect, useState } from 'react';
|
||||
import type { StrategyVersionPackage, StrategyVersionSummary } from '@stock-bot/types';
|
||||
import { strategyApi } from '../services/strategyApi';
|
||||
import { actionClass, fieldClass } from './StrategyParameterForm';
|
||||
|
||||
export function VersionIdentity({ version }: { version: StrategyVersionSummary }) {
|
||||
const pkg = version.package;
|
||||
return (
|
||||
<div className="space-y-2 text-sm border border-border rounded-md p-4">
|
||||
<h3 className="font-medium">Version {version.ordinal}</h3>
|
||||
<p>
|
||||
Immutable version ID: <code>{version.id}</code>
|
||||
</p>
|
||||
<p>
|
||||
Origin: {version.origin} · Review: {version.reviewStatus}
|
||||
</p>
|
||||
<p role="status">
|
||||
{version.origin === 'candidate'
|
||||
? 'Candidate research uses the isolated runtime. Eligibility is checked against the retained package, dataset and financial policy.'
|
||||
: 'Canonical execution requires approval, a matching executable build, a supported dataset and an explicit simulation policy.'}
|
||||
</p>
|
||||
<p>
|
||||
Program: {pkg.program.strategyId} / {pkg.program.strategyVersion}
|
||||
</p>
|
||||
<p>
|
||||
API: {pkg.program.apiVersion} · Checkpoint: {pkg.program.checkpointVersion}
|
||||
</p>
|
||||
<p className="break-all">Artifact SHA256: {pkg.artifact.sha256}</p>
|
||||
<p className="break-all">Dependency lock SHA256: {pkg.dependencyLock.sha256}</p>
|
||||
<p className="break-all">
|
||||
Source revision: {pkg.source.revision} (
|
||||
{pkg.source.dirty ? 'dirty working tree' : 'clean working tree'})
|
||||
</p>
|
||||
<p>
|
||||
Build: {pkg.build.tool} {pkg.build.version} / {pkg.build.target}
|
||||
</p>
|
||||
{version.parentVersionId && <p>Parent version: {version.parentVersionId}</p>}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
export function VersionComparison({
|
||||
version,
|
||||
versions,
|
||||
}: {
|
||||
version: StrategyVersionSummary;
|
||||
versions: StrategyVersionSummary[];
|
||||
}) {
|
||||
const [showArtifact, setShowArtifact] = useState(false);
|
||||
const [compareId, setCompareId] = useState('');
|
||||
const [artifact, setArtifact] = useState<StrategyVersionPackage | null>(null);
|
||||
const [comparison, setComparison] = useState<StrategyVersionPackage | null>(null);
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [retry, setRetry] = useState(0);
|
||||
useEffect(() => {
|
||||
const controller = new AbortController();
|
||||
setComparison(null);
|
||||
setError(null);
|
||||
if (!showArtifact && !compareId) {
|
||||
setLoading(false);
|
||||
return () => controller.abort();
|
||||
}
|
||||
setLoading(true);
|
||||
void Promise.all([
|
||||
strategyApi.artifact(version.id, controller.signal),
|
||||
compareId ? strategyApi.artifact(compareId, controller.signal) : Promise.resolve(null),
|
||||
])
|
||||
.then(([current, other]) => {
|
||||
if (!controller.signal.aborted) {
|
||||
setArtifact(current.package);
|
||||
setComparison(other?.package ?? null);
|
||||
}
|
||||
})
|
||||
.catch(cause => {
|
||||
if (!controller.signal.aborted) {
|
||||
setError(cause.message);
|
||||
}
|
||||
})
|
||||
.finally(() => {
|
||||
if (!controller.signal.aborted) {
|
||||
setLoading(false);
|
||||
}
|
||||
});
|
||||
return () => controller.abort();
|
||||
}, [version.id, showArtifact, compareId, retry]);
|
||||
const options = versions.filter(item => item.id !== version.id);
|
||||
return (
|
||||
<section className="space-y-3">
|
||||
<button className={actionClass} onClick={() => setShowArtifact(value => !value)}>
|
||||
{showArtifact ? 'Hide bundled JavaScript' : 'View bundled JavaScript'}
|
||||
</button>
|
||||
<label className="block text-sm">
|
||||
Compare with version
|
||||
<select
|
||||
aria-label="Compare with version"
|
||||
className={fieldClass}
|
||||
value={compareId}
|
||||
onChange={event => setCompareId(event.target.value)}
|
||||
>
|
||||
<option value="">No comparison</option>
|
||||
{options.map(item => (
|
||||
<option key={item.id} value={item.id}>
|
||||
Version {item.ordinal} — {item.id}
|
||||
</option>
|
||||
))}
|
||||
{version.parentVersionId &&
|
||||
!options.some(item => item.id === version.parentVersionId) && (
|
||||
<option value={version.parentVersionId}>
|
||||
Parent version — {version.parentVersionId}
|
||||
</option>
|
||||
)}
|
||||
</select>
|
||||
</label>
|
||||
{(showArtifact || compareId) && (
|
||||
<p className="text-sm text-text-secondary">
|
||||
Retained bundled JavaScript, not original TypeScript. Displayed as text; never executed in
|
||||
the browser.
|
||||
</p>
|
||||
)}
|
||||
{loading && <p role="status">Loading retained artifacts...</p>}
|
||||
{error && (
|
||||
<div>
|
||||
<p role="alert" className="text-error">
|
||||
{error}
|
||||
</p>
|
||||
<button className={actionClass} onClick={() => setRetry(value => value + 1)}>
|
||||
Retry artifacts
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
{!loading && !error && artifact && (showArtifact || compareId) && (
|
||||
<>
|
||||
{comparison && (
|
||||
<>
|
||||
<h3 className="font-medium">Version comparison</h3>
|
||||
<table className="w-full text-sm">
|
||||
<thead>
|
||||
<tr>
|
||||
<th className="text-left">Retained field</th>
|
||||
<th className="text-left">Comparison</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{(['program', 'parameterSchema', 'source', 'build'] as const).map(key => (
|
||||
<tr key={key}>
|
||||
<td>{key}</td>
|
||||
<td>
|
||||
{JSON.stringify(artifact[key]) === JSON.stringify(comparison[key])
|
||||
? 'Unchanged'
|
||||
: 'Changed'}
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
<tr>
|
||||
<td>Artifact SHA256</td>
|
||||
<td>
|
||||
{artifact.artifact.sha256 === comparison.artifact.sha256
|
||||
? 'Identical artifact bytes'
|
||||
: 'Different artifact bytes'}
|
||||
</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>Dependency lock SHA256</td>
|
||||
<td>
|
||||
{artifact.dependencyLock.sha256 === comparison.dependencyLock.sha256
|
||||
? 'Unchanged'
|
||||
: 'Changed'}
|
||||
</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
<div className="grid gap-4 md:grid-cols-2">
|
||||
<div>
|
||||
<h4>Selected version metadata</h4>
|
||||
<pre className="overflow-auto text-xs max-h-64">
|
||||
{JSON.stringify(
|
||||
{
|
||||
program: artifact.program,
|
||||
parameterSchema: artifact.parameterSchema,
|
||||
source: artifact.source,
|
||||
build: artifact.build,
|
||||
},
|
||||
null,
|
||||
2
|
||||
)}
|
||||
</pre>
|
||||
</div>
|
||||
<div>
|
||||
<h4>Compared version metadata</h4>
|
||||
<pre className="overflow-auto text-xs max-h-64">
|
||||
{JSON.stringify(
|
||||
{
|
||||
program: comparison.program,
|
||||
parameterSchema: comparison.parameterSchema,
|
||||
source: comparison.source,
|
||||
build: comparison.build,
|
||||
},
|
||||
null,
|
||||
2
|
||||
)}
|
||||
</pre>
|
||||
</div>
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
<div className={comparison ? 'grid gap-4 md:grid-cols-2' : ''}>
|
||||
<div>
|
||||
<h4>Selected bundled JavaScript</h4>
|
||||
<pre
|
||||
aria-label="Selected bundled JavaScript"
|
||||
className="overflow-auto max-h-96 text-xs p-3 border border-border rounded-md"
|
||||
>
|
||||
{artifact.artifact.content}
|
||||
</pre>
|
||||
</div>
|
||||
{comparison && (
|
||||
<div>
|
||||
<h4>Compared bundled JavaScript</h4>
|
||||
<pre
|
||||
aria-label="Compared bundled JavaScript"
|
||||
className="overflow-auto max-h-96 text-xs p-3 border border-border rounded-md"
|
||||
>
|
||||
{comparison.artifact.content}
|
||||
</pre>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
|
@ -0,0 +1,80 @@
|
|||
import { useEffect, useRef, useState } from 'react';
|
||||
import type { NavigateFunction } from 'react-router-dom';
|
||||
import type { StrategyVersionSummary } from '@stock-bot/types';
|
||||
import { versionPath } from '../components/StrategySelection';
|
||||
import { strategyApi } from '../services/strategyApi';
|
||||
|
||||
/** Own the immutable clone receipt for the lifetime of the strategy route. */
|
||||
export function useStrategyClone(
|
||||
version: StrategyVersionSummary | null,
|
||||
versionId: string | undefined,
|
||||
navigate: NavigateFunction
|
||||
) {
|
||||
const [cloneOpen, setCloneOpen] = useState(false);
|
||||
const [cloneName, setCloneName] = useState('');
|
||||
const [cloneDescription, setCloneDescription] = useState('');
|
||||
const [cloning, setCloning] = useState(false);
|
||||
const [cloneError, setCloneError] = useState<string | null>(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;
|
||||
useEffect(() => {
|
||||
mounted.current = true;
|
||||
return () => {
|
||||
mounted.current = false;
|
||||
};
|
||||
}, []);
|
||||
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 {
|
||||
cloneOpen,
|
||||
setCloneOpen,
|
||||
cloneName,
|
||||
setCloneName,
|
||||
cloneDescription,
|
||||
setCloneDescription,
|
||||
cloning,
|
||||
cloneError,
|
||||
setCloneError,
|
||||
cloneIntent,
|
||||
cloneFrozen,
|
||||
setCloneFrozen,
|
||||
clone,
|
||||
};
|
||||
}
|
||||
|
|
@ -4,11 +4,9 @@ import {
|
|||
ChartBarIcon,
|
||||
ChartPieIcon,
|
||||
CircleStackIcon,
|
||||
CogIcon,
|
||||
CurrencyDollarIcon,
|
||||
DocumentTextIcon,
|
||||
HomeIcon,
|
||||
PresentationChartLineIcon,
|
||||
ServerStackIcon,
|
||||
} from '@heroicons/react/24/outline';
|
||||
|
||||
|
|
@ -29,9 +27,7 @@ export const navigation: NavigationItem[] = [
|
|||
{ name: 'Symbols', href: '/symbols', icon: ChartBarIcon },
|
||||
],
|
||||
},
|
||||
{ name: 'Portfolio', href: '/portfolio', icon: ChartBarIcon },
|
||||
{ name: 'Strategies', href: '/strategies', icon: DocumentTextIcon },
|
||||
{ name: 'Analytics', href: '/analytics', icon: PresentationChartLineIcon },
|
||||
{ name: 'Backtests', href: '/backtests', icon: BeakerIcon },
|
||||
{ name: 'Research', href: '/research', icon: BeakerIcon },
|
||||
{ name: 'Experiments', href: '/experiments', icon: BeakerIcon },
|
||||
|
|
@ -44,5 +40,4 @@ export const navigation: NavigationItem[] = [
|
|||
{ name: 'Pipeline', href: '/system/pipeline', icon: CircleStackIcon },
|
||||
],
|
||||
},
|
||||
{ name: 'Settings', href: '/settings', icon: CogIcon },
|
||||
];
|
||||
|
|
|
|||
44
apps/stock/web-app/src/lib/requestJson.ts
Normal file
44
apps/stock/web-app/src/lib/requestJson.ts
Normal file
|
|
@ -0,0 +1,44 @@
|
|||
import { apiFetch } from './api';
|
||||
|
||||
interface RequestErrors {
|
||||
create: (message: string, status: number | null) => Error;
|
||||
invalid: () => Error;
|
||||
lostMessage: string;
|
||||
failureLabel: string;
|
||||
}
|
||||
|
||||
/** Transport only. Domain clients retain identity checks and receipt policy.
|
||||
* Never retry a write here: a lost response may already have been accepted. */
|
||||
export async function requestJson<T>(
|
||||
url: string,
|
||||
init: RequestInit,
|
||||
expectedStatus: number,
|
||||
parse: (body: unknown) => T,
|
||||
errors: RequestErrors
|
||||
): Promise<T> {
|
||||
let response: Response;
|
||||
try {
|
||||
response = await apiFetch(url, init);
|
||||
} catch (cause) {
|
||||
if (init.signal?.aborted) {
|
||||
throw cause;
|
||||
}
|
||||
throw errors.create(errors.lostMessage, null);
|
||||
}
|
||||
const body: unknown = await response.json().catch(() => null);
|
||||
if (!response.ok) {
|
||||
const message =
|
||||
body && typeof body === 'object' && 'error' in body && typeof body.error === 'string'
|
||||
? body.error
|
||||
: `${errors.failureLabel} (${response.status})`;
|
||||
throw errors.create(message, response.status);
|
||||
}
|
||||
try {
|
||||
if (response.status !== expectedStatus) {
|
||||
throw errors.invalid();
|
||||
}
|
||||
return parse(body);
|
||||
} catch {
|
||||
throw errors.invalid();
|
||||
}
|
||||
}
|
||||
15
bun.lock
15
bun.lock
|
|
@ -139,6 +139,7 @@
|
|||
"@stock-bot/postgres": "workspace:*",
|
||||
"@stock-bot/questdb": "*",
|
||||
"@stock-bot/queue": "*",
|
||||
"@stock-bot/research": "workspace:*",
|
||||
"@stock-bot/services": "workspace:*",
|
||||
"@stock-bot/shutdown": "*",
|
||||
"@stock-bot/stock-config": "*",
|
||||
|
|
@ -175,6 +176,7 @@
|
|||
"@stock-bot/mongodb": "*",
|
||||
"@stock-bot/postgres": "*",
|
||||
"@stock-bot/queue": "workspace:*",
|
||||
"@stock-bot/research": "workspace:*",
|
||||
"@stock-bot/services": "workspace:*",
|
||||
"@stock-bot/shutdown": "*",
|
||||
"@stock-bot/stock-config": "*",
|
||||
|
|
@ -195,6 +197,7 @@
|
|||
"@hookform/resolvers": "^3.3.4",
|
||||
"@stock-bot/calculations": "workspace:*",
|
||||
"@stock-bot/invariants": "workspace:*",
|
||||
"@stock-bot/research": "workspace:*",
|
||||
"@stock-bot/types": "workspace:*",
|
||||
"@tanstack/react-table": "^8.21.3",
|
||||
"clsx": "^2.1.1",
|
||||
|
|
@ -470,6 +473,16 @@
|
|||
"typescript": "^5.3.0",
|
||||
},
|
||||
},
|
||||
"libs/research": {
|
||||
"name": "@stock-bot/research",
|
||||
"version": "1.0.0",
|
||||
"dependencies": {
|
||||
"@stock-bot/calculations": "workspace:*",
|
||||
"@stock-bot/stock-config": "workspace:*",
|
||||
"@stock-bot/types": "workspace:*",
|
||||
"zod": "^3.22.4",
|
||||
},
|
||||
},
|
||||
"libs/services/browser": {
|
||||
"name": "@stock-bot/browser",
|
||||
"version": "1.0.0",
|
||||
|
|
@ -1001,6 +1014,8 @@
|
|||
|
||||
"@stock-bot/queue": ["@stock-bot/queue@workspace:libs/core/queue"],
|
||||
|
||||
"@stock-bot/research": ["@stock-bot/research@workspace:libs/research"],
|
||||
|
||||
"@stock-bot/services": ["@stock-bot/services@workspace:libs/core/services"],
|
||||
|
||||
"@stock-bot/shutdown": ["@stock-bot/shutdown@workspace:libs/core/shutdown"],
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
# Cleanup and maintainability plan
|
||||
|
||||
Baseline: `fbf2eb9e`, inspected October 26, 2026. This extends the existing development backlog. The original 45 scheduled tasks remain complete; these 13 cleanup stories are new work. The owner subsequently authorized implementation and validated commits; progress and checks are recorded in [cleanup-execution.md](cleanup-execution.md). No additional agents have been launched.
|
||||
Baseline: `fbf2eb9e`, inspected October 26, 2026. This extends the existing development backlog. The original 45 scheduled tasks remain complete; these 13 cleanup stories are new work. The owner subsequently authorized implementation and validated commits; progress and checks are recorded in [cleanup-execution.md](cleanup-execution.md). All 13 stories are implemented and validated. They remain in `review` until an independent reviewer signs off; no additional agents have been launched.
|
||||
|
||||
[manifest.json](backlog/manifest.json) remains the scheduling source of truth. It records task states, prerequisites, priorities and write locks. This page explains the execution contract and recommended order; it is not a second status tracker. Current evidence is appended to [findings.md](backlog/findings.md#cleanup-audit-2026-10-26).
|
||||
|
||||
|
|
|
|||
|
|
@ -1,10 +1,10 @@
|
|||
# Revised development roadmap
|
||||
|
||||
## Current planning — October 26, 2026
|
||||
## Cleanup implementation — October 26, 2026
|
||||
|
||||
The [cleanup plan](CLEANUP.md) adds 13 scoped stories under E10, grounded in the current code audit. The original completion record below remains historical evidence. Current task IDs, states, dependencies and locks are in the [manifest](backlog/manifest.json); the six conditional tasks remain deferred.
|
||||
|
||||
**Planning only:** implementation has not been requested. Current `execution_authorized` is false; old continuation instructions do not authorize these new stories. First independent assignments: **CL01 (DI tests), CL03 (startup rollback), CL04 (developer commands)**. Then complete configuration normalization and the shared research/domain boundary before their dependent cleanup.
|
||||
The owner authorized implementation and validated commits after planning. All 13 cleanup stories are implemented and validated, pending independent review; [execution evidence](cleanup-execution.md) records exact checks and limitations. The historical first wave was CL01/CL03/CL04, followed by configuration, shared research code, backend and frontend cleanup.
|
||||
|
||||
**The original 45/45 scheduled tasks are complete.** The canonical Rust engine, TypeScript research/workbench, bounded worker pool, isolated candidates, AI evidence workflow and human-reviewed paper promotion are validated. Implementation commits: `bbf0dd4`, `26b9726`, `25b5cbf` (R07 measurement `ab08db8`). Six conditional tasks remain deferred; four merged IDs remain redirects. This is scheduled-backlog completion, not live-trading activation.
|
||||
|
||||
|
|
|
|||
|
|
@ -2,13 +2,13 @@
|
|||
|
||||
**The original 45/45 scheduled tasks are complete.** The canonical Rust engine, TypeScript research/workbench, bounded worker pool, isolated candidates, AI evidence workflow and human-reviewed paper promotion are validated. Implementation commits: `bbf0dd4`, `26b9726`, `25b5cbf` (R07 measurement `ab08db8`). Six conditional tasks remain deferred; four merged IDs remain redirects. This is scheduled-backlog completion, not live-trading activation.
|
||||
|
||||
**New work:** [13 cleanup stories](../CLEANUP.md) were proposed on October 26, 2026. The owner subsequently authorized implementation and commits; see [execution evidence](../cleanup-execution.md). The first independent group is CL01, CL03 and CL04.
|
||||
**New work:** [13 cleanup stories](../CLEANUP.md) were proposed on October 26, 2026. The owner subsequently authorized implementation and commits; see [execution evidence](../cleanup-execution.md). All 13 are implemented and validated; independent review is the remaining completion gate.
|
||||
|
||||
## One source of truth
|
||||
|
||||
[manifest.json](manifest.json) owns scheduling metadata: status, priorities, dependencies, ADR approvals, assignments and write locks. Task Markdown owns implementation scope/evidence/acceptance. This index and the [graph](dependencies.mmd) are derived views. Only the planning/integration owner updates scheduling state.
|
||||
|
||||
**Current total: 45 completed original tasks + 13 proposed cleanup tasks + 6 deferred + 4 merged IDs = 68 retained IDs.** The original backlog accounted for 55 IDs. F09/P07 added projection/profiling work; the owner deferred P08's TypeScript optimization. Merged records preserve traceability; never execute them separately. Deferred work requires its stated trigger and explicit activation.
|
||||
**Current total: 45 completed original tasks + 13 implemented cleanup tasks pending independent review + 6 deferred + 4 merged IDs = 68 retained IDs.** The original backlog accounted for 55 IDs. F09/P07 added projection/profiling work; the owner deferred P08's TypeScript optimization. Merged records preserve traceability; never execute them separately. Deferred work requires its stated trigger and explicit activation.
|
||||
|
||||
States: ready, claimed, in_progress, review, done, blocked, deferred, merged. “Ready” means no code/ADR prerequisite, not execution authority. Implementation dependencies require accepted integration. `release_gates` govern enabling an end-to-end feature, not component coding or integration; conditional gates apply only to the named capability. F05 may integrate before F06, but its replay behavior is not released until F06 proves it.
|
||||
|
||||
|
|
@ -118,23 +118,23 @@ Relative size: S narrow correction, M coherent boundary, L sensitive owner-contr
|
|||
|
||||
### E10 — Cleanup and maintainability foundations
|
||||
|
||||
Scope and first execution wave: [CLEANUP.md](../CLEANUP.md). Ready is code readiness only; all new implementation is planning-only until requested.
|
||||
Scope and first execution wave: [CLEANUP.md](../CLEANUP.md). The owner has authorized implementation and commits. Current completion evidence is in [cleanup-execution.md](../cleanup-execution.md); the manifest owns task state.
|
||||
|
||||
| Task | Priority / status | Implementation prerequisites | Release gate | Specialist / size |
|
||||
| --- | --- | --- | --- | --- |
|
||||
| [CL01 Replace permissive DI configuration tests with production-path assertions](tasks/CL01.md) | P1 / ready | None | — | TypeScript infrastructure testing / M |
|
||||
| [CL02 Normalize database configuration once and enforce consistent service switches](tasks/CL02.md) | P1 / blocked | CL01 | — | TypeScript configuration and database adapters / M |
|
||||
| [CL03 Roll back failed shared-service startup and clear initialization timers](tasks/CL03.md) | P1 / ready | None | — | TypeScript resource lifecycle and concurrency / M |
|
||||
| [CL04 Provide one consistent research startup path and repair stale commands](tasks/CL04.md) | P1 / ready | None | — | Bun/Turbo developer tooling / S |
|
||||
| [CL05 Extract shared dataset and reporting logic behind a research library boundary](tasks/CL05.md) | P2 / ready | D01, F08, R05 | — | TypeScript domain boundaries and package migration / M |
|
||||
| [CL06 Use shared dataset response schemas and eligibility checks in the workbench](tasks/CL06.md) | P2 / blocked | CL05 | — | Shared contracts and frontend validation / M |
|
||||
| [CL07 Share JSON transport handling across experiment and validation clients](tasks/CL07.md) | P2 / ready | None | — | Frontend HTTP contracts and retry semantics / M |
|
||||
| [CL08 Split backtest template, run and reproduction responsibilities behind the existing service](tasks/CL08.md) | P2 / blocked | CL05 | — | TypeScript application services and PostgreSQL transactions / M |
|
||||
| [CL09 Separate strategy metadata, version inspection and publication UI](tasks/CL09.md) | P2 / ready | None | — | React strategy workflows / M |
|
||||
| [CL10 Separate experiment modes and make draft/submission state explicit](tasks/CL10.md) | P2 / ready | None | — | React experiment workflow state / M |
|
||||
| [CL11 Separate backtest template loading, run monitoring and submission state](tasks/CL11.md) | P2 / ready | None | — | React asynchronous state and durable-run UX / M |
|
||||
| [CL12 Simplify retired execution seams while preserving historical reads](tasks/CL12.md) | P2 / blocked | CL08 | — | Compatibility cleanup and execution boundaries / M |
|
||||
| [CL13 Hide placeholder navigation while preserving useful product routes](tasks/CL13.md) | P2 / ready | None | — | React navigation and product clarity / S |
|
||||
| [CL01 Replace permissive DI configuration tests with production-path assertions](tasks/CL01.md) | P1 / review | None | — | TypeScript infrastructure testing / M |
|
||||
| [CL02 Normalize database configuration once and enforce consistent service switches](tasks/CL02.md) | P1 / review | CL01 | — | TypeScript configuration and database adapters / M |
|
||||
| [CL03 Roll back failed shared-service startup and clear initialization timers](tasks/CL03.md) | P1 / review | None | — | TypeScript resource lifecycle and concurrency / M |
|
||||
| [CL04 Provide one consistent research startup path and repair stale commands](tasks/CL04.md) | P1 / review | None | — | Bun/Turbo developer tooling / S |
|
||||
| [CL05 Extract shared dataset and reporting logic behind a research library boundary](tasks/CL05.md) | P2 / review | D01, F08, R05 | — | TypeScript domain boundaries and package migration / M |
|
||||
| [CL06 Use shared dataset response schemas and eligibility checks in the workbench](tasks/CL06.md) | P2 / review | CL05 | — | Shared contracts and frontend validation / M |
|
||||
| [CL07 Share JSON transport handling across experiment and validation clients](tasks/CL07.md) | P2 / review | None | — | Frontend HTTP contracts and retry semantics / M |
|
||||
| [CL08 Split backtest template, run and reproduction responsibilities behind the existing service](tasks/CL08.md) | P2 / review | CL05 | — | TypeScript application services and PostgreSQL transactions / M |
|
||||
| [CL09 Separate strategy metadata, version inspection and publication UI](tasks/CL09.md) | P2 / review | None | — | React strategy workflows / M |
|
||||
| [CL10 Separate experiment modes and make draft/submission state explicit](tasks/CL10.md) | P2 / review | None | — | React experiment workflow state / M |
|
||||
| [CL11 Separate backtest template loading, run monitoring and submission state](tasks/CL11.md) | P2 / review | None | — | React asynchronous state and durable-run UX / M |
|
||||
| [CL12 Simplify retired execution seams while preserving historical reads](tasks/CL12.md) | P2 / review | CL08 | — | Compatibility cleanup and execution boundaries / M |
|
||||
| [CL13 Hide placeholder navigation while preserving useful product routes](tasks/CL13.md) | P2 / review | None | — | React navigation and product clarity / S |
|
||||
|
||||
## Scheduling checks
|
||||
|
||||
|
|
|
|||
|
|
@ -2,7 +2,7 @@
|
|||
"schema_version": 1,
|
||||
"plan_revision": "2026-10-26.79",
|
||||
"repository_base": "b7aeca4",
|
||||
"plan_status": "cleanup_backlog_in_progress",
|
||||
"plan_status": "cleanup_implemented_pending_review",
|
||||
"execution_authorized": true,
|
||||
"execution_scope": {
|
||||
"authorized_by": "Owner: commit and continue with the rest of the tasks till 100%",
|
||||
|
|
@ -2086,7 +2086,7 @@
|
|||
"epic": "E10",
|
||||
"priority": "P1",
|
||||
"severity": "High",
|
||||
"status": "done",
|
||||
"status": "review",
|
||||
"dependencies": [],
|
||||
"decision_dependencies": [],
|
||||
"task_file": "backlog/tasks/CL01.md",
|
||||
|
|
@ -2105,9 +2105,9 @@
|
|||
"completed_commit": null,
|
||||
"blocker": null,
|
||||
"release_gates": [],
|
||||
"integration_state": "validated",
|
||||
"integration_state": "validated_pending_independent_review",
|
||||
"integration_base": "fbf2eb9e",
|
||||
"review_notes": "Focused implementation and integration checks recorded in cleanup-execution.md; no separate reviewer agent was launched.",
|
||||
"review_notes": "Implementation and relevant checks are complete. Separate self-review performed; independent reviewer sign-off remains pending. No reviewer agent was launched.",
|
||||
"concrete_write_scope": [
|
||||
"libs/core/di/test/container-builder.test.ts",
|
||||
"libs/core/di/test/di.test.ts"
|
||||
|
|
@ -2120,7 +2120,7 @@
|
|||
"epic": "E10",
|
||||
"priority": "P1",
|
||||
"severity": "High",
|
||||
"status": "done",
|
||||
"status": "review",
|
||||
"dependencies": [
|
||||
"CL01"
|
||||
],
|
||||
|
|
@ -2143,9 +2143,9 @@
|
|||
"completed_commit": null,
|
||||
"blocker": null,
|
||||
"release_gates": [],
|
||||
"integration_state": "validated",
|
||||
"integration_state": "validated_pending_independent_review",
|
||||
"integration_base": "fbf2eb9e",
|
||||
"review_notes": "Focused implementation and integration checks recorded in cleanup-execution.md; no separate reviewer agent was launched.",
|
||||
"review_notes": "Implementation and relevant checks are complete. Separate self-review performed; independent reviewer sign-off remains pending. No reviewer agent was launched.",
|
||||
"concrete_write_scope": [
|
||||
"libs/core/config/src/schemas/database.schema.ts",
|
||||
"libs/core/config/src/schemas/unified-app.schema.ts",
|
||||
|
|
@ -2165,7 +2165,7 @@
|
|||
"epic": "E10",
|
||||
"priority": "P1",
|
||||
"severity": "High",
|
||||
"status": "done",
|
||||
"status": "review",
|
||||
"dependencies": [],
|
||||
"decision_dependencies": [],
|
||||
"task_file": "backlog/tasks/CL03.md",
|
||||
|
|
@ -2185,9 +2185,9 @@
|
|||
"completed_commit": null,
|
||||
"blocker": null,
|
||||
"release_gates": [],
|
||||
"integration_state": "validated",
|
||||
"integration_state": "validated_pending_independent_review",
|
||||
"integration_base": "fbf2eb9e",
|
||||
"review_notes": "Focused implementation and integration checks recorded in cleanup-execution.md; no separate reviewer agent was launched.",
|
||||
"review_notes": "Implementation and relevant checks are complete. Separate self-review performed; independent reviewer sign-off remains pending. No reviewer agent was launched.",
|
||||
"concrete_write_scope": [
|
||||
"libs/core/di/src/utils/lifecycle.ts",
|
||||
"libs/core/di/src/container/builder.ts",
|
||||
|
|
@ -2202,7 +2202,7 @@
|
|||
"epic": "E10",
|
||||
"priority": "P1",
|
||||
"severity": "Medium",
|
||||
"status": "done",
|
||||
"status": "review",
|
||||
"dependencies": [],
|
||||
"decision_dependencies": [],
|
||||
"task_file": "backlog/tasks/CL04.md",
|
||||
|
|
@ -2223,9 +2223,9 @@
|
|||
"completed_commit": null,
|
||||
"blocker": null,
|
||||
"release_gates": [],
|
||||
"integration_state": "validated",
|
||||
"integration_state": "validated_pending_independent_review",
|
||||
"integration_base": "fbf2eb9e",
|
||||
"review_notes": "Focused implementation and integration checks recorded in cleanup-execution.md; no separate reviewer agent was launched.",
|
||||
"review_notes": "Implementation and relevant checks are complete. Separate self-review performed; independent reviewer sign-off remains pending. No reviewer agent was launched.",
|
||||
"concrete_write_scope": [
|
||||
"package.json",
|
||||
"scripts/docker.sh",
|
||||
|
|
@ -2242,7 +2242,7 @@
|
|||
"epic": "E10",
|
||||
"priority": "P2",
|
||||
"severity": "High",
|
||||
"status": "ready",
|
||||
"status": "review",
|
||||
"dependencies": [
|
||||
"D01",
|
||||
"F08",
|
||||
|
|
@ -2271,9 +2271,9 @@
|
|||
"completed_commit": null,
|
||||
"blocker": null,
|
||||
"release_gates": [],
|
||||
"integration_state": "planned",
|
||||
"integration_state": "validated_pending_independent_review",
|
||||
"integration_base": "fbf2eb9e",
|
||||
"review_notes": "Planning-only cleanup story requested 2026-10-26. Current implementation authorization is false. No implementation, tests or completion are claimed by this entry.",
|
||||
"review_notes": "Implementation and relevant checks are complete. Separate self-review performed; independent reviewer sign-off remains pending. No reviewer agent was launched.",
|
||||
"concrete_write_scope": [
|
||||
"apps/stock/orchestrator/src/data/historical-dataset-v2.ts",
|
||||
"apps/stock/orchestrator/src/backtest/canonical-result.ts",
|
||||
|
|
@ -2289,7 +2289,8 @@
|
|||
"libs/research/src/dataset-contracts.ts",
|
||||
"libs/research/src/datasets.ts",
|
||||
"libs/research/src/results.ts"
|
||||
]
|
||||
],
|
||||
"completion_evidence": "docs/development/cleanup-execution.md"
|
||||
},
|
||||
{
|
||||
"id": "CL06",
|
||||
|
|
@ -2297,7 +2298,7 @@
|
|||
"epic": "E10",
|
||||
"priority": "P2",
|
||||
"severity": "Medium",
|
||||
"status": "blocked",
|
||||
"status": "review",
|
||||
"dependencies": [
|
||||
"CL05"
|
||||
],
|
||||
|
|
@ -2317,11 +2318,11 @@
|
|||
"branch": null,
|
||||
"pull_request": null,
|
||||
"completed_commit": null,
|
||||
"blocker": "Waiting for implementation prerequisites: CL05.",
|
||||
"blocker": null,
|
||||
"release_gates": [],
|
||||
"integration_state": "planned",
|
||||
"integration_state": "validated_pending_independent_review",
|
||||
"integration_base": "fbf2eb9e",
|
||||
"review_notes": "Planning-only cleanup story requested 2026-10-26. Current implementation authorization is false. No implementation, tests or completion are claimed by this entry.",
|
||||
"review_notes": "Implementation and relevant checks are complete. Separate self-review performed; independent reviewer sign-off remains pending. No reviewer agent was launched.",
|
||||
"concrete_write_scope": [
|
||||
"apps/stock/web-app/src/features/backtest/services/backtestApiV2.ts",
|
||||
"apps/stock/web-api/src/services/canonical-research.service.ts",
|
||||
|
|
@ -2329,7 +2330,8 @@
|
|||
"libs/research/src/dataset-contracts.ts",
|
||||
"test/integration/dataset-source-preparation-ui.test.tsx",
|
||||
"test/integration/canonical-workbench.test.tsx"
|
||||
]
|
||||
],
|
||||
"completion_evidence": "docs/development/cleanup-execution.md"
|
||||
},
|
||||
{
|
||||
"id": "CL07",
|
||||
|
|
@ -2337,7 +2339,7 @@
|
|||
"epic": "E10",
|
||||
"priority": "P2",
|
||||
"severity": "Medium",
|
||||
"status": "ready",
|
||||
"status": "review",
|
||||
"dependencies": [],
|
||||
"decision_dependencies": [],
|
||||
"task_file": "backlog/tasks/CL07.md",
|
||||
|
|
@ -2356,9 +2358,9 @@
|
|||
"completed_commit": null,
|
||||
"blocker": null,
|
||||
"release_gates": [],
|
||||
"integration_state": "planned",
|
||||
"integration_state": "validated_pending_independent_review",
|
||||
"integration_base": "fbf2eb9e",
|
||||
"review_notes": "Planning-only cleanup story requested 2026-10-26. Current implementation authorization is false. No implementation, tests or completion are claimed by this entry.",
|
||||
"review_notes": "Implementation and relevant checks are complete. Separate self-review performed; independent reviewer sign-off remains pending. No reviewer agent was launched.",
|
||||
"concrete_write_scope": [
|
||||
"apps/stock/web-app/src/lib/api.ts",
|
||||
"apps/stock/web-app/src/features/experiments/services/experimentApi.ts",
|
||||
|
|
@ -2366,7 +2368,8 @@
|
|||
"apps/stock/web-app/src/features/experiments/services/walkForwardApi.ts",
|
||||
"apps/stock/web-app/src/lib/requestJson.ts",
|
||||
"test/integration/research-http-transport.test.ts"
|
||||
]
|
||||
],
|
||||
"completion_evidence": "docs/development/cleanup-execution.md"
|
||||
},
|
||||
{
|
||||
"id": "CL08",
|
||||
|
|
@ -2374,7 +2377,7 @@
|
|||
"epic": "E10",
|
||||
"priority": "P2",
|
||||
"severity": "Medium",
|
||||
"status": "blocked",
|
||||
"status": "review",
|
||||
"dependencies": [
|
||||
"CL05"
|
||||
],
|
||||
|
|
@ -2397,11 +2400,11 @@
|
|||
"branch": null,
|
||||
"pull_request": null,
|
||||
"completed_commit": null,
|
||||
"blocker": "Waiting for implementation prerequisites: CL05.",
|
||||
"blocker": null,
|
||||
"release_gates": [],
|
||||
"integration_state": "planned",
|
||||
"integration_state": "validated_pending_independent_review",
|
||||
"integration_base": "fbf2eb9e",
|
||||
"review_notes": "Planning-only cleanup story requested 2026-10-26. Current implementation authorization is false. No implementation, tests or completion are claimed by this entry.",
|
||||
"review_notes": "Implementation and relevant checks are complete. Separate self-review performed; independent reviewer sign-off remains pending. No reviewer agent was launched.",
|
||||
"concrete_write_scope": [
|
||||
"apps/stock/web-api/src/services/backtest-v2.service.ts",
|
||||
"apps/stock/web-api/src/services/run-reproduction.ts",
|
||||
|
|
@ -2411,7 +2414,8 @@
|
|||
"apps/stock/web-api/src/services/backtests/runs.ts",
|
||||
"apps/stock/web-api/src/services/backtests/reproduction.ts",
|
||||
"apps/stock/web-api/src/services/backtests/results.ts"
|
||||
]
|
||||
],
|
||||
"completion_evidence": "docs/development/cleanup-execution.md"
|
||||
},
|
||||
{
|
||||
"id": "CL09",
|
||||
|
|
@ -2419,7 +2423,7 @@
|
|||
"epic": "E10",
|
||||
"priority": "P2",
|
||||
"severity": "Medium",
|
||||
"status": "ready",
|
||||
"status": "review",
|
||||
"dependencies": [],
|
||||
"decision_dependencies": [],
|
||||
"task_file": "backlog/tasks/CL09.md",
|
||||
|
|
@ -2438,9 +2442,9 @@
|
|||
"completed_commit": null,
|
||||
"blocker": null,
|
||||
"release_gates": [],
|
||||
"integration_state": "planned",
|
||||
"integration_state": "validated_pending_independent_review",
|
||||
"integration_base": "fbf2eb9e",
|
||||
"review_notes": "Planning-only cleanup story requested 2026-10-26. Current implementation authorization is false. No implementation, tests or completion are claimed by this entry.",
|
||||
"review_notes": "Implementation and relevant checks are complete. Separate self-review performed; independent reviewer sign-off remains pending. No reviewer agent was launched.",
|
||||
"concrete_write_scope": [
|
||||
"apps/stock/web-app/src/features/strategies/StrategyDetailPage.tsx",
|
||||
"apps/stock/web-app/src/features/strategies/components/",
|
||||
|
|
@ -2448,7 +2452,8 @@
|
|||
"test/integration/strategy-workbench.test.tsx",
|
||||
"apps/stock/web-app/src/features/strategies/components/StrategyVersionPanel.tsx",
|
||||
"apps/stock/web-app/src/features/strategies/hooks/useStrategyClone.ts"
|
||||
]
|
||||
],
|
||||
"completion_evidence": "docs/development/cleanup-execution.md"
|
||||
},
|
||||
{
|
||||
"id": "CL10",
|
||||
|
|
@ -2456,7 +2461,7 @@
|
|||
"epic": "E10",
|
||||
"priority": "P2",
|
||||
"severity": "Medium",
|
||||
"status": "ready",
|
||||
"status": "review",
|
||||
"dependencies": [],
|
||||
"decision_dependencies": [],
|
||||
"task_file": "backlog/tasks/CL10.md",
|
||||
|
|
@ -2475,9 +2480,9 @@
|
|||
"completed_commit": null,
|
||||
"blocker": null,
|
||||
"release_gates": [],
|
||||
"integration_state": "planned",
|
||||
"integration_state": "validated_pending_independent_review",
|
||||
"integration_base": "fbf2eb9e",
|
||||
"review_notes": "Planning-only cleanup story requested 2026-10-26. Current implementation authorization is false. No implementation, tests or completion are claimed by this entry.",
|
||||
"review_notes": "Implementation and relevant checks are complete. Separate self-review performed; independent reviewer sign-off remains pending. No reviewer agent was launched.",
|
||||
"concrete_write_scope": [
|
||||
"apps/stock/web-app/src/features/experiments/components/ExperimentEditor.tsx",
|
||||
"apps/stock/web-app/src/features/experiments/components/ChronologicalValidationPreflight.tsx",
|
||||
|
|
@ -2485,7 +2490,8 @@
|
|||
"test/integration/experiments-ui.test.tsx",
|
||||
"apps/stock/web-app/src/features/experiments/hooks/useExperimentSubmission.ts",
|
||||
"apps/stock/web-app/src/features/experiments/components/ExperimentDraftForm.tsx"
|
||||
]
|
||||
],
|
||||
"completion_evidence": "docs/development/cleanup-execution.md"
|
||||
},
|
||||
{
|
||||
"id": "CL11",
|
||||
|
|
@ -2493,7 +2499,7 @@
|
|||
"epic": "E10",
|
||||
"priority": "P2",
|
||||
"severity": "Medium",
|
||||
"status": "ready",
|
||||
"status": "review",
|
||||
"dependencies": [],
|
||||
"decision_dependencies": [],
|
||||
"task_file": "backlog/tasks/CL11.md",
|
||||
|
|
@ -2512,9 +2518,9 @@
|
|||
"completed_commit": null,
|
||||
"blocker": null,
|
||||
"release_gates": [],
|
||||
"integration_state": "planned",
|
||||
"integration_state": "validated_pending_independent_review",
|
||||
"integration_base": "fbf2eb9e",
|
||||
"review_notes": "Planning-only cleanup story requested 2026-10-26. Current implementation authorization is false. No implementation, tests or completion are claimed by this entry.",
|
||||
"review_notes": "Implementation and relevant checks are complete. Separate self-review performed; independent reviewer sign-off remains pending. No reviewer agent was launched.",
|
||||
"concrete_write_scope": [
|
||||
"apps/stock/web-app/src/features/backtest/hooks/useBacktestV2.ts",
|
||||
"apps/stock/web-app/src/features/backtest/BacktestDetailPageV2.tsx",
|
||||
|
|
@ -2522,7 +2528,8 @@
|
|||
"test/integration/canonical-workbench.test.tsx",
|
||||
"apps/stock/web-app/src/features/backtest/hooks/useRunMonitoring.ts",
|
||||
"apps/stock/web-app/src/features/backtest/hooks/useRunSubmission.ts"
|
||||
]
|
||||
],
|
||||
"completion_evidence": "docs/development/cleanup-execution.md"
|
||||
},
|
||||
{
|
||||
"id": "CL12",
|
||||
|
|
@ -2530,7 +2537,7 @@
|
|||
"epic": "E10",
|
||||
"priority": "P2",
|
||||
"severity": "Medium",
|
||||
"status": "blocked",
|
||||
"status": "review",
|
||||
"dependencies": [
|
||||
"CL08"
|
||||
],
|
||||
|
|
@ -2552,11 +2559,11 @@
|
|||
"branch": null,
|
||||
"pull_request": null,
|
||||
"completed_commit": null,
|
||||
"blocker": "Waiting for implementation prerequisites: CL08.",
|
||||
"blocker": null,
|
||||
"release_gates": [],
|
||||
"integration_state": "planned",
|
||||
"integration_state": "validated_pending_independent_review",
|
||||
"integration_base": "fbf2eb9e",
|
||||
"review_notes": "Planning-only cleanup story requested 2026-10-26. Current implementation authorization is false. No implementation, tests or completion are claimed by this entry.",
|
||||
"review_notes": "Implementation and relevant checks are complete. Separate self-review performed; independent reviewer sign-off remains pending. No reviewer agent was launched.",
|
||||
"concrete_write_scope": [
|
||||
"apps/stock/web-api/src/services/backtest-v2.service.ts",
|
||||
"apps/stock/web-api/src/services/backtest-result.ts",
|
||||
|
|
@ -2564,7 +2571,8 @@
|
|||
"apps/stock/orchestrator/src/backtest/execution-engine.ts",
|
||||
"apps/stock/orchestrator/src/api/rest/backtest.ts",
|
||||
"scripts/test/architecture.test.ts"
|
||||
]
|
||||
],
|
||||
"completion_evidence": "docs/development/cleanup-execution.md"
|
||||
},
|
||||
{
|
||||
"id": "CL13",
|
||||
|
|
@ -2572,7 +2580,7 @@
|
|||
"epic": "E10",
|
||||
"priority": "P2",
|
||||
"severity": "Low",
|
||||
"status": "ready",
|
||||
"status": "review",
|
||||
"dependencies": [],
|
||||
"decision_dependencies": [],
|
||||
"task_file": "backlog/tasks/CL13.md",
|
||||
|
|
@ -2591,16 +2599,17 @@
|
|||
"completed_commit": null,
|
||||
"blocker": null,
|
||||
"release_gates": [],
|
||||
"integration_state": "planned",
|
||||
"integration_state": "validated_pending_independent_review",
|
||||
"integration_base": "fbf2eb9e",
|
||||
"review_notes": "Planning-only cleanup story requested 2026-10-26. Current implementation authorization is false. No implementation, tests or completion are claimed by this entry.",
|
||||
"review_notes": "Implementation and relevant checks are complete. Separate self-review performed; independent reviewer sign-off remains pending. No reviewer agent was launched.",
|
||||
"concrete_write_scope": [
|
||||
"apps/stock/web-app/src/lib/constants.ts",
|
||||
"apps/stock/web-app/src/app/App.tsx",
|
||||
"apps/stock/web-app/README.md",
|
||||
"docs/guide/README.md",
|
||||
"test/integration/navigation.test.tsx"
|
||||
]
|
||||
],
|
||||
"completion_evidence": "docs/development/cleanup-execution.md"
|
||||
}
|
||||
],
|
||||
"review_note": "Independent skeptical revision: four superseded tasks retain stable IDs; deferred work is not a dependency of scheduled tasks. Release gates are distinct from implementation prerequisites.",
|
||||
|
|
|
|||
|
|
@ -31,3 +31,77 @@ intentionally owns DB1 and its service/global namespace; core `db`/`keyPrefix` d
|
|||
that isolation policy. Core `ttl`, retry hints and QuestDB buffer/flush metadata are not
|
||||
claims that the shared DI client supports writer/cache tuning; those adapter APIs remain
|
||||
unchanged. Financial inputs, hashes and accounting were not modified.
|
||||
|
||||
## CL05–CL13 — Shared domain and application cleanup
|
||||
|
||||
- CL05 adds one `@stock-bot/research` workspace with browser-safe contracts, server
|
||||
normalization/hashing and statistical reports. Orchestrator paths re-export the one
|
||||
implementation. Legacy V1 adaptation stays application-owned and calls an explicit
|
||||
parent-hash factory; existing pure stock-config contracts are reused.
|
||||
- CL06 reuses shared manifest structures and structural eligibility policy in API/browser
|
||||
admission. Preparation-specific parent-hash/null and response refinements remain explicit;
|
||||
server content validation and client expected-identity checks remain separate.
|
||||
- CL07 shares cookie JSON transport for experiment, chronological and walk-forward clients.
|
||||
Domain parsing, uncertain acceptance, receipt identities and endpoint errors remain local.
|
||||
No automatic retry or research-token/browser credential mixing is introduced.
|
||||
- CL08 retains BacktestServiceV2 as a compatible facade over template, run/control,
|
||||
reproduction and result operations. Row mapping and contracts are shared locally. SQL
|
||||
transactions retain their original ordering and pass the same connection into result reads.
|
||||
- CL09 separates metadata presentation, version/artifact comparison and clone-receipt state
|
||||
from the strategy route. Publication continues using the existing CandidatePublication.
|
||||
- CL10 separates saved-template loading and the preview/submission coordinator. One phase
|
||||
replaces coupled ordinary-submission flags; the immediate submission lock/ref and exact
|
||||
frozen receipt remain necessary across ordinary/chronological/walk-forward modes.
|
||||
- CL11 separates run selection/polling/results/cancellation and submission receipt lifetime
|
||||
from editable-template state. The useBacktestV2 public return contract is preserved.
|
||||
- CL12 removes the impossible legacy snapshot fallback after canonical admission. Current
|
||||
run writes use the admitted canonical request/hash. Legacy template adapters, saved result
|
||||
readers, historical provenance parsing, retired REST/runner rejection and native exports
|
||||
remain. No algorithms, calculation library or retained executable artifacts were deleted.
|
||||
- CL13 hides only the three verified placeholder menu items; their URLs show explicit
|
||||
availability messages and links to existing backtest/experiment analytics. AuthGate and
|
||||
all working route identities remain unchanged.
|
||||
|
||||
Review focused on receipt lifetime and navigation races, original request/result identity,
|
||||
transaction ordering, single-connection reads, hash/property-order preservation, client
|
||||
bundle boundaries, and avoiding additional framework layers. The public facade re-exports
|
||||
its original contracts; internal helper/container types are not new public API.
|
||||
|
||||
Intermediate verification:
|
||||
|
||||
- Workspace build — 28/28 tasks pass.
|
||||
- Domain/native/UI group — 174 pass; one initial architecture allowlist failed on the
|
||||
newly shared **pure** report subpath. Added the narrow allowlist plus tests verifying the
|
||||
new package has no application/service imports and browser contracts bundle successfully.
|
||||
- Strategy/publication/experiment/transport group — 218 pass / 931 assertions.
|
||||
- Run-control/workbench/reproduction UI group — 83 pass / 472 assertions.
|
||||
- Backend/reproduction/result/navigation group — 28 pass / 184 assertions.
|
||||
- First full check found the missing-config disabled MongoDB URI regression; corrected
|
||||
the schema-valid default instead of weakening validation. Store/offline/paper-composition
|
||||
focused group then passed 22 tests / 129 assertions.
|
||||
- Final `CARGO_BUILD_JOBS=2 bun run check` — pass: 132 tooling, 43 utility, 44 calculation,
|
||||
1,221 integration tests (14 explicitly skipped), 150 Rust tests (4 ignored), plus build,
|
||||
type/contract checks, secret audit and lint. Conditional OS-isolation tests remain skipped
|
||||
under their existing explicit runtime gate; this cleanup does not certify live trading.
|
||||
- DI builder/general/lifecycle focused group — 32 pass; root integration separately covers
|
||||
startup rollback and store configuration.
|
||||
|
||||
The first disposable PostgreSQL suite ran concurrently with the first repository check,
|
||||
encountered the same pre-fix disabled-Mongo default, then Bun 1.2.17 segfaulted. That attempt
|
||||
is not a pass. A fresh full suite runs after the successful repository check on the corrected
|
||||
build; final PostgreSQL/browser outcomes are recorded below. Sandbox-restricted native
|
||||
worker spawning also failed initially; its rerun outside the sandbox used the assigned
|
||||
checkout and correctly built addon rather than weakening worker checks.
|
||||
|
||||
Final integration evidence:
|
||||
|
||||
- `PIPELINE_TEST_DATABASE_URL=<disposable PostgreSQL>/stock_bot_safety BACKTEST_TEST_REDIS_URL=<disposable Redis>/15 bun run test:postgres` — **273 pass, 0 fail, 2,617 assertions, 34 files**. Fresh run completed after the runtime crash noted above; it includes single-connection reproduction, concurrent receipts/outbox transactions, recovery, ownership and unchanged native economics.
|
||||
- The same fixture URLs with `bun run test:e2e` — **18 pass, 0 fail, 655 assertions** using installed Chromium and a freshly built frontend. Includes native smoke, version clone, archived history, experiments/validation and research evidence workflows.
|
||||
- Final review added an explicit unknown-VWAP guard to `createDatasetV2FromLegacy`: the former private application adapter guaranteed this invariant before normalization. Its shared entrypoint now rejects contradictory provenance before returning a prepared dataset. Dataset/report focused suites passed **25 tests / 515 assertions**, including detached validation, golden hashes and malformed parent hashes. Typecheck/lint passed again.
|
||||
- Temporary PostgreSQL and Redis fixture containers were removed after both suites. Existing development stores and environment files were preserved.
|
||||
- After the final boundary guard, `CARGO_BUILD_JOBS=2 bun run check` passed again on the final application tree: **1,222 integration tests** (14 existing skips), **150 Rust tests** (4 ignored), plus all build/type/contract/tooling/utility/calculation/secret/lint gates. No application edits followed that pass.
|
||||
|
||||
All 13 implementations are validated. Their manifest status is `review`, because these
|
||||
stories define independent review as part of done and this execution used one agent.
|
||||
The earlier first-four `done` entries were corrected to `review` for consistency; this is
|
||||
an outstanding reviewer sign-off, not unfinished implementation or a failing test gate.
|
||||
|
|
|
|||
|
|
@ -81,3 +81,7 @@ This fixture does not need a provider connection or running databases. For initi
|
|||
- [Backlog](../development/backlog/README.md) and [roadmap](../development/ROADMAP.md): work history, completion evidence and conditional future tasks.
|
||||
|
||||
When documentation and an implementation disagree, follow the current entrypoint, contract and focused regression test. Historical plans explain the direction; these guides explain how the current pieces fit together.
|
||||
|
||||
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.
|
||||
|
|
|
|||
|
|
@ -1,5 +1,14 @@
|
|||
# Reading the implementation
|
||||
|
||||
The cleanup keeps old dataset/report paths as compatibility entrypoints. Read
|
||||
`libs/research/src/datasets.ts` for V2 normalization and hashes, and
|
||||
`libs/research/src/results.ts` for statistical reporting. The backtest API facade now delegates
|
||||
to `apps/stock/web-api/src/services/backtests/{templates,runs,reproduction,results}.ts`.
|
||||
Frontend run observation/submission, strategy cloning/version inspection and experiment
|
||||
submission each have focused hooks/components beside their existing pages. These moves
|
||||
preserve the Rust financial engine and saved-run contracts described below.
|
||||
|
||||
|
||||
[Guide home](README.md) · [System map](system-map.md) · [Backtest walkthrough](backtest-walkthrough.md) · [Strategy authoring](strategy-development.md)
|
||||
|
||||
This guide follows **functions and state**, rather than application boxes. The linked TypeScript files now have explanatory TSDoc comments, and the Rust financial modules have module and method documentation. Read these beside the implementation; you can hover documented symbols in your editor.
|
||||
|
|
|
|||
|
|
@ -114,7 +114,7 @@ export class ServiceContainerBuilder {
|
|||
mongodb: {
|
||||
...(config.mongodb || {
|
||||
enabled: this.options.enableMongoDB ?? true,
|
||||
uri: '',
|
||||
uri: 'mongodb://localhost:27017',
|
||||
database: '',
|
||||
}),
|
||||
enabled: this.options.enableMongoDB !== false && (config.mongodb?.enabled ?? true),
|
||||
|
|
|
|||
|
|
@ -31,14 +31,18 @@ export class ServiceLifecycleManager {
|
|||
try {
|
||||
const work = this.services.map(async ({ name, key }) => {
|
||||
const service = container.cradle[key] as ServiceWithLifecycle | null;
|
||||
if (!service) {return Promise.resolve();}
|
||||
if (!service) {
|
||||
return Promise.resolve();
|
||||
}
|
||||
const entry = { name, service, settled: false };
|
||||
started.push(entry);
|
||||
// A timeout cannot cancel connect(). Keep ownership until it settles,
|
||||
// including resources allocated by an initializer that later rejects.
|
||||
const initialization = this.initializeService(name, service).finally(async () => {
|
||||
entry.settled = true;
|
||||
if (failed) {await this.cleanupOnce(name, service);}
|
||||
if (failed) {
|
||||
await this.cleanupOnce(name, service);
|
||||
}
|
||||
});
|
||||
let timer: ReturnType<typeof setTimeout>;
|
||||
const expired = new Promise<never>((_, reject) => {
|
||||
|
|
@ -65,7 +69,9 @@ export class ServiceLifecycleManager {
|
|||
);
|
||||
throw error;
|
||||
} finally {
|
||||
for (const clear of cancelTimers) {clear();}
|
||||
for (const clear of cancelTimers) {
|
||||
clear();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -86,7 +92,9 @@ export class ServiceLifecycleManager {
|
|||
for (const { name, key } of [...this.services].reverse()) {
|
||||
try {
|
||||
const service = container.cradle[key] as ServiceWithLifecycle | null;
|
||||
if (service) {await this.cleanupOnce(name, service);}
|
||||
if (service) {
|
||||
await this.cleanupOnce(name, service);
|
||||
}
|
||||
} catch (error) {
|
||||
this.logger.error(`Error resolving ${name} during shutdown:`, error);
|
||||
}
|
||||
|
|
|
|||
24
libs/research/package.json
Normal file
24
libs/research/package.json
Normal file
|
|
@ -0,0 +1,24 @@
|
|||
{
|
||||
"name": "@stock-bot/research",
|
||||
"version": "1.0.0",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"description": "Shared historical dataset contracts, normalization and statistical reports",
|
||||
"main": "./src/index.ts",
|
||||
"types": "./src/index.ts",
|
||||
"exports": {
|
||||
".": "./src/index.ts",
|
||||
"./dataset-contracts": "./src/dataset-contracts.ts",
|
||||
"./datasets": "./src/datasets.ts",
|
||||
"./results": "./src/results.ts"
|
||||
},
|
||||
"scripts": {
|
||||
"build": "tsc"
|
||||
},
|
||||
"dependencies": {
|
||||
"@stock-bot/types": "workspace:*",
|
||||
"@stock-bot/calculations": "workspace:*",
|
||||
"@stock-bot/stock-config": "workspace:*",
|
||||
"zod": "^3.22.4"
|
||||
}
|
||||
}
|
||||
152
libs/research/src/dataset-contracts.ts
Normal file
152
libs/research/src/dataset-contracts.ts
Normal file
|
|
@ -0,0 +1,152 @@
|
|||
import { z } from 'zod';
|
||||
|
||||
export const text = z.string().min(1);
|
||||
export const instant = z.number().int().nonnegative().max(8_640_000_000_000_000);
|
||||
export const sequence = z.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER);
|
||||
export const price = z.number().finite().positive();
|
||||
export 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');
|
||||
export const hash = z
|
||||
.string()
|
||||
.length(64)
|
||||
.regex(/^[a-f0-9]{64}$/);
|
||||
export 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();
|
||||
export 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();
|
||||
|
||||
/** Response shapes add cheap consistency checks; content/hash validation stays server-side. */
|
||||
export const responseMetadataSchema = metadataSchema.extend({
|
||||
calendars: metadataSchema.shape.calendars.element
|
||||
.extend({
|
||||
sessions: metadataSchema.shape.calendars.element.shape.sessions.element
|
||||
.refine(value => value.open < value.close)
|
||||
.array()
|
||||
.min(1),
|
||||
})
|
||||
.array()
|
||||
.min(1),
|
||||
bounds: metadataSchema.shape.bounds.refine(
|
||||
value => value.warmupStart <= value.tradeStart && value.tradeStart < value.tradeEnd
|
||||
),
|
||||
});
|
||||
export const preparationManifestSchema = responseMetadataSchema
|
||||
.extend({
|
||||
...manifestSchema.omit({
|
||||
calendars: true,
|
||||
series: true,
|
||||
executionSeries: true,
|
||||
bounds: true,
|
||||
universe: true,
|
||||
corporateActions: true,
|
||||
}).shape,
|
||||
parentDatasetHash: z.null(),
|
||||
barCount: z.number().int().positive().safe(),
|
||||
})
|
||||
.strict();
|
||||
|
||||
/** Structural workbench policy, not authentication of retained dataset bytes. */
|
||||
export function datasetUnavailableReason(manifest: {
|
||||
eligibility: string;
|
||||
executionSeries: readonly unknown[];
|
||||
series: readonly unknown[];
|
||||
universe: { instrumentIds: readonly string[] };
|
||||
}): string | null {
|
||||
if (manifest.eligibility !== 'eligible') {
|
||||
return 'Canonical research requires an eligible dataset with known timing and action coverage';
|
||||
}
|
||||
if (
|
||||
manifest.executionSeries.length !== 1 ||
|
||||
manifest.series.length !== 1 ||
|
||||
manifest.universe.instrumentIds.length !== 1
|
||||
) {
|
||||
return 'Canonical workbench currently supports one execution asset and one retained series';
|
||||
}
|
||||
return null;
|
||||
}
|
||||
532
libs/research/src/datasets.ts
Normal file
532
libs/research/src/datasets.ts
Normal file
|
|
@ -0,0 +1,532 @@
|
|||
import { createHash } from 'node:crypto';
|
||||
import { z } from 'zod';
|
||||
import {
|
||||
parseInstrumentId,
|
||||
type HistoricalBarV2,
|
||||
type HistoricalDatasetInputV2,
|
||||
type HistoricalDatasetMetadataV2,
|
||||
type HistoricalDatasetV2,
|
||||
} from '@stock-bot/types';
|
||||
import {
|
||||
day,
|
||||
hash,
|
||||
instant,
|
||||
manifestSchema,
|
||||
metadataSchema,
|
||||
price,
|
||||
sequence,
|
||||
text,
|
||||
} from './dataset-contracts';
|
||||
|
||||
const prices = {
|
||||
open: price,
|
||||
high: price,
|
||||
low: price,
|
||||
close: price,
|
||||
volume: z.number().finite().nonnegative(),
|
||||
};
|
||||
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 durations = { '1m': 60_000, '5m': 300_000, '15m': 900_000, '1h': 3_600_000 };
|
||||
const prepared = new WeakSet<object>();
|
||||
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<string>(),
|
||||
sequences = new Set<string>(),
|
||||
seen = new Set<string>();
|
||||
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<T>(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<typeof parseMetadata>,
|
||||
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;
|
||||
}
|
||||
|
||||
/** Explicit legacy adapter only: retain the validated original-v1 hash. */
|
||||
export function createDatasetV2FromLegacy(
|
||||
input: HistoricalDatasetInputV2,
|
||||
parentHash: string
|
||||
): HistoricalDatasetV2 {
|
||||
const dataset = create(input, hash.parse(parentHash));
|
||||
// The old application adapter guaranteed this before calling private create().
|
||||
// Preserve that invariant at the new exported boundary, including prepared objects.
|
||||
if (dataset.bars.some(bar => bar.vwap !== null)) {
|
||||
throw new Error('Legacy v1 conversion requires unknown VWAP');
|
||||
}
|
||||
return dataset;
|
||||
}
|
||||
2
libs/research/src/index.ts
Normal file
2
libs/research/src/index.ts
Normal file
|
|
@ -0,0 +1,2 @@
|
|||
// The default entrypoint is browser safe; server validation is an explicit subpath.
|
||||
export * from './dataset-contracts';
|
||||
195
libs/research/src/results.ts
Normal file
195
libs/research/src/results.ts
Normal file
|
|
@ -0,0 +1,195 @@
|
|||
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 { ReplayReportResult } from '@stock-bot/stock-config/canonical-replay';
|
||||
import type {
|
||||
CanonicalBacktestAnalytics,
|
||||
CanonicalMetrics,
|
||||
CanonicalMetricsInput,
|
||||
CanonicalMetricUnavailableReason,
|
||||
CanonicalSessionReturn,
|
||||
} from '@stock-bot/types';
|
||||
|
||||
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,
|
||||
},
|
||||
};
|
||||
}
|
||||
20
libs/research/tsconfig.json
Normal file
20
libs/research/tsconfig.json
Normal file
|
|
@ -0,0 +1,20 @@
|
|||
{
|
||||
"extends": "../../tsconfig.lib.json",
|
||||
"compilerOptions": {
|
||||
"rootDir": "src",
|
||||
"outDir": "dist",
|
||||
"composite": true
|
||||
},
|
||||
"include": ["src/**/*.ts"],
|
||||
"references": [
|
||||
{
|
||||
"path": "../core/types"
|
||||
},
|
||||
{
|
||||
"path": "../calculations"
|
||||
},
|
||||
{
|
||||
"path": "../../apps/stock/config"
|
||||
}
|
||||
]
|
||||
}
|
||||
|
|
@ -93,6 +93,7 @@ describe('orchestrator architecture boundaries', () => {
|
|||
'@stock-bot/stock-config/paper-deployments',
|
||||
'@stock-bot/calculations/analytics',
|
||||
'@stock-bot/calculations/returns',
|
||||
'@stock-bot/research/results',
|
||||
].includes(specifier)
|
||||
).toBe(true);
|
||||
}
|
||||
|
|
@ -417,3 +418,36 @@ describe('orchestrator architecture boundaries', () => {
|
|||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe('shared research boundary', () => {
|
||||
const repository = fileURLToPath(new URL('../../', import.meta.url));
|
||||
const research = join(repository, 'libs/research/src');
|
||||
it('shared domain files have no application implementation or service imports', () => {
|
||||
for (const name of new Bun.Glob('**/*.ts').scanSync({ cwd: research })) {
|
||||
const source = readFileSync(join(research, name), 'utf8');
|
||||
const sourceFile = ts.createSourceFile(name, source, ts.ScriptTarget.Latest, true);
|
||||
for (const statement of sourceFile.statements) {
|
||||
if ((ts.isImportDeclaration(statement) || ts.isExportDeclaration(statement)) && statement.moduleSpecifier && ts.isStringLiteral(statement.moduleSpecifier)) {
|
||||
const dependency = statement.moduleSpecifier.text;
|
||||
expect(dependency).not.toMatch(/apps\/|orchestrator|@stock-bot\/(?:di|postgres|mongodb|questdb|engine|queue)(?:\/|$)/);
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
it('the shared response contract bundles for browsers without server dependencies', async () => {
|
||||
const result = await Bun.build({ entrypoints: [join(research, 'dataset-contracts.ts')], target: 'browser', write: false });
|
||||
expect(result.success).toBe(true);
|
||||
expect(await result.outputs[0]!.text()).not.toMatch(/node:crypto|node:fs|engine\.node/);
|
||||
});
|
||||
});
|
||||
|
||||
describe('canonical admission boundary', () => {
|
||||
it('new run operations cannot construct legacy snapshots or invoke legacy execution', () => {
|
||||
const path = fileURLToPath(new URL('../../apps/stock/web-api/src/services/backtests/runs.ts', import.meta.url));
|
||||
const dependencies = runtimeImports(path);
|
||||
expect(dependencies.some(value => /execution-engine|BacktestRunner|strategy-manager/.test(value))).toBe(false);
|
||||
const source = readFileSync(path, 'utf8');
|
||||
expect(source).not.toContain('backtestRequestFromDefinition');
|
||||
expect(source).not.toContain('legacyDefinition');
|
||||
});
|
||||
});
|
||||
|
|
|
|||
|
|
@ -1,5 +1,6 @@
|
|||
import { describe, expect, test } from 'bun:test';
|
||||
import { createHash } from 'node:crypto';
|
||||
import { describe, expect, test } from 'bun:test';
|
||||
import { createDatasetV2FromLegacy } from '@stock-bot/research/datasets';
|
||||
import { validateDataset } from '../../apps/stock/orchestrator/src/data/historical-dataset';
|
||||
import {
|
||||
assertDatasetV2Executable,
|
||||
|
|
@ -372,3 +373,14 @@ describe('availability-aware dataset v2', () => {
|
|||
}
|
||||
});
|
||||
});
|
||||
|
||||
test('shared legacy factory preserves the adapter invariant before returning a prepared dataset', () => {
|
||||
const source = input();
|
||||
expect(() => createDatasetV2FromLegacy(source, 'a'.repeat(64))).toThrow('unknown VWAP');
|
||||
source.bars.forEach(bar => {
|
||||
bar.vwap = null;
|
||||
});
|
||||
const dataset = createDatasetV2FromLegacy(source, 'a'.repeat(64));
|
||||
expect(validateDatasetV2(structuredClone(dataset))).toEqual(dataset);
|
||||
expect(() => createDatasetV2FromLegacy(source, 'not-a-hash')).toThrow();
|
||||
});
|
||||
|
|
|
|||
35
test/integration/navigation.test.tsx
Normal file
35
test/integration/navigation.test.tsx
Normal file
|
|
@ -0,0 +1,35 @@
|
|||
import { expect, test } from 'bun:test';
|
||||
import { createElement } from 'react';
|
||||
import { renderToStaticMarkup } from 'react-dom/server';
|
||||
import { MemoryRouter } from 'react-router-dom';
|
||||
import { UnavailablePage } from '../../apps/stock/web-app/src/app/UnavailablePage';
|
||||
import { navigation } from '../../apps/stock/web-app/src/lib/constants';
|
||||
|
||||
test('the shared desktop/mobile menu advertises working workflows only', () => {
|
||||
const hrefs = navigation.flatMap(item => [
|
||||
item.href,
|
||||
...(item.children?.map(child => child.href) ?? []),
|
||||
]);
|
||||
for (const href of ['/portfolio', '/analytics', '/settings']) expect(hrefs).not.toContain(href);
|
||||
for (const href of [
|
||||
'/strategies',
|
||||
'/backtests',
|
||||
'/research',
|
||||
'/experiments',
|
||||
'/paper',
|
||||
'/symbols',
|
||||
'/system/monitoring',
|
||||
])
|
||||
expect(hrefs).toContain(href);
|
||||
});
|
||||
for (const name of ['Portfolio', 'Analytics', 'Settings']) {
|
||||
test(`${name} direct-page fallback explains availability and links to existing analytics`, () => {
|
||||
const html = renderToStaticMarkup(
|
||||
createElement(MemoryRouter, {}, createElement(UnavailablePage, { name }))
|
||||
);
|
||||
expect(html).toContain(`${name} is not available`);
|
||||
expect(html).toContain('href="/backtests"');
|
||||
expect(html).toContain('href="/experiments"');
|
||||
expect(html).not.toContain('Coming Soon');
|
||||
});
|
||||
}
|
||||
86
test/integration/research-http-transport.test.ts
Normal file
86
test/integration/research-http-transport.test.ts
Normal file
|
|
@ -0,0 +1,86 @@
|
|||
import { afterAll, beforeAll, beforeEach, expect, mock, test } from 'bun:test';
|
||||
import { GlobalWindow } from 'happy-dom';
|
||||
|
||||
const browser = new GlobalWindow({ url: 'http://localhost:5173' });
|
||||
const original = Object.getOwnPropertyDescriptor(globalThis, 'window');
|
||||
let requestJson: typeof import('../../apps/stock/web-app/src/lib/requestJson').requestJson;
|
||||
beforeEach(() => {
|
||||
Object.defineProperty(globalThis, 'window', { value: browser, configurable: true });
|
||||
});
|
||||
beforeAll(async () => {
|
||||
Object.defineProperty(globalThis, 'window', { value: browser, configurable: true });
|
||||
({ requestJson } = await import('../../apps/stock/web-app/src/lib/requestJson'));
|
||||
});
|
||||
afterAll(() => {
|
||||
if (original) Object.defineProperty(globalThis, 'window', original);
|
||||
else Reflect.deleteProperty(globalThis, 'window');
|
||||
browser.happyDOM.abort();
|
||||
});
|
||||
const errors = {
|
||||
create: (message: string, status: number | null) => Object.assign(new Error(message), { status }),
|
||||
invalid: () => new Error('invalid domain response'),
|
||||
lostMessage: 'uncertain',
|
||||
failureLabel: 'failed',
|
||||
};
|
||||
const parse = (body: unknown) => {
|
||||
if (body !== 42) throw new Error('wrong identity');
|
||||
return body;
|
||||
};
|
||||
function respond(body: string, status = 200) {
|
||||
const fetch = mock(async () => new Response(body, { status }));
|
||||
browser.fetch = fetch as unknown as typeof browser.fetch;
|
||||
return fetch;
|
||||
}
|
||||
test('JSON transport includes session cookies, preserves headers and never retries writes', async () => {
|
||||
const fetch = respond('42');
|
||||
expect(
|
||||
await requestJson(
|
||||
'/test',
|
||||
{ method: 'POST', headers: { 'Idempotency-Key': 'original' } },
|
||||
200,
|
||||
parse,
|
||||
errors
|
||||
)
|
||||
).toBe(42);
|
||||
expect(fetch).toHaveBeenCalledTimes(1);
|
||||
expect(fetch.mock.calls[0]![1]).toMatchObject({
|
||||
credentials: 'include',
|
||||
headers: { 'Idempotency-Key': 'original' },
|
||||
});
|
||||
});
|
||||
for (const [body, status] of [
|
||||
['not json', 200],
|
||||
['41', 200],
|
||||
['42', 202],
|
||||
] as const) {
|
||||
test(`rejects invalid response ${body}/${status}`, async () => {
|
||||
respond(body, status);
|
||||
await expect(requestJson('/test', {}, 200, parse, errors)).rejects.toThrow(
|
||||
'invalid domain response'
|
||||
);
|
||||
});
|
||||
}
|
||||
test('HTTP errors preserve status and messages', async () => {
|
||||
respond('{"error":"rejected"}', 409);
|
||||
await expect(requestJson('/test', {}, 200, parse, errors)).rejects.toMatchObject({
|
||||
message: 'rejected',
|
||||
status: 409,
|
||||
});
|
||||
});
|
||||
test('network failures remain uncertain and abort retains its cause', async () => {
|
||||
const failure = new Error('connection lost');
|
||||
const fetch = mock(async () => {
|
||||
throw failure;
|
||||
});
|
||||
browser.fetch = fetch as unknown as typeof browser.fetch;
|
||||
await expect(requestJson('/test', { method: 'POST' }, 202, parse, errors)).rejects.toMatchObject({
|
||||
message: 'uncertain',
|
||||
status: null,
|
||||
});
|
||||
expect(fetch).toHaveBeenCalledTimes(1);
|
||||
const abort = new AbortController();
|
||||
abort.abort();
|
||||
await expect(requestJson('/test', { signal: abort.signal }, 200, parse, errors)).rejects.toBe(
|
||||
failure
|
||||
);
|
||||
});
|
||||
|
|
@ -127,3 +127,24 @@ test('flat QuestDB alias takes precedence without discarding credentials or sche
|
|||
await c.dispose();
|
||||
}
|
||||
});
|
||||
|
||||
// Existing offline examples compose the shared graph without an application config.
|
||||
test('all-disabled default composition needs neither store settings nor connections', async () => {
|
||||
const c = await new ServiceContainerBuilder()
|
||||
.withOptions({
|
||||
enableCache: false,
|
||||
enableQueue: false,
|
||||
enableMongoDB: false,
|
||||
enablePostgres: false,
|
||||
enableQuestDB: false,
|
||||
enableBrowser: false,
|
||||
enableProxy: false,
|
||||
})
|
||||
.build();
|
||||
try {
|
||||
for (const name of ['cache', 'mongoClient', 'postgresClient', 'questdbClient'])
|
||||
expect(c.resolve(name)).toBeNull();
|
||||
} finally {
|
||||
await c.dispose();
|
||||
}
|
||||
});
|
||||
|
|
|
|||
|
|
@ -8,6 +8,7 @@
|
|||
"declarationMap": false,
|
||||
"allowImportingTsExtensions": true,
|
||||
"paths": {
|
||||
"@stock-bot/research/*": ["libs/research/src/*"],
|
||||
"@/*": ["apps/stock/web-app/src/*"],
|
||||
"@stock-bot/stock-config": ["apps/stock/config/src/index.ts"],
|
||||
"@stock-bot/stock-config/backtest": ["apps/stock/config/src/contracts/backtest.ts"],
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue