diff --git a/apps/stock/config/src/contracts/backtest.ts b/apps/stock/config/src/contracts/backtest.ts index 338b5205..5b9aba09 100644 --- a/apps/stock/config/src/contracts/backtest.ts +++ b/apps/stock/config/src/contracts/backtest.ts @@ -3,6 +3,7 @@ import { HistoricalDataRequestError, parseInstrumentId, validateHistoricalDataRequest, + type HistoricalDatasetManifest, } from '@stock-bot/types'; /** Pure execution configuration; importing this subpath starts no configuration services. */ @@ -26,6 +27,96 @@ export const historicalDataPolicySchema = z }) .strict(); export const datasetHashSchema = z.string().regex(/^[a-f0-9]{64}$/); +export const datasetManifestSchema = z + .object({ + version: z.literal(1), + hash: datasetHashSchema, + instruments: z + .array( + z.object({ id: instrumentIdSchema, symbol: z.string(), exchange: z.string() }).strict() + ) + .min(1), + startDate: z.string().datetime(), + endDate: z.string().datetime(), + interval: z.enum(['1m', '5m', '15m', '1h', '1d']), + policy: historicalDataPolicySchema, + volumePolicy: z.literal('reported'), + qualityPolicy: z.literal('reject-invalid-no-interpolation'), + sources: z.array( + z + .object({ + instrumentId: instrumentIdSchema, + provider: z.enum(['eod', 'questdb', 'synthetic']), + revision: z.string().min(1), + }) + .strict() + ), + barCount: z.number().int().positive(), + }) + .strict(); +/** Validate retained v1 metadata without loading or claiming to verify bar content. */ +export function validateDatasetManifestMetadata(input: unknown): HistoricalDatasetManifest { + const m = datasetManifestSchema.parse(input); + const ids = m.instruments.map(i => i.id); + validateHistoricalDataRequest({ + symbols: ids, + startDate: m.startDate, + endDate: m.endDate, + dataFrequency: m.interval, + dataPolicy: m.policy, + datasetHash: m.hash, + }); + if ( + ids.some((id, index) => id !== [...ids].sort()[index]) || + m.instruments.some(i => { + const expected = parseInstrumentId(i.id); + return i.symbol !== expected.symbol || i.exchange !== expected.exchange; + }) || + m.sources.length !== ids.length || + m.sources.some((source, index) => source.instrumentId !== ids[index]) + ) { + throw new HistoricalDataRequestError('Invalid dataset manifest'); + } + return m; +} + +/** Exact reuse only: a retained dataset is not an implicit subrange or provider fallback. */ +export function assertDatasetMatchesRequest( + manifest: HistoricalDatasetManifest, + request: Pick< + BacktestConfig, + | 'symbols' + | 'startDate' + | 'endDate' + | 'dataFrequency' + | 'dataPolicy' + | 'datasetHash' + | 'dataSource' + > +): void { + const policy = request.dataPolicy ?? { + adjustment: 'raw', + timestamp: request.dataFrequency === '1d' ? 'utc-session-date' : 'utc-instant', + }; + if ( + JSON.stringify([...request.symbols].sort()) !== + JSON.stringify(manifest.instruments.map(i => i.id)) || + new Date(request.startDate).toISOString() !== manifest.startDate || + new Date(request.endDate).toISOString() !== manifest.endDate || + request.dataFrequency !== manifest.interval || + policy.adjustment !== manifest.policy.adjustment || + policy.timestamp !== manifest.policy.timestamp || + (request.datasetHash !== undefined && request.datasetHash !== manifest.hash) || + (request.dataSource !== undefined && + request.dataSource !== 'auto' && + manifest.sources.some(s => s.provider !== request.dataSource)) + ) { + throw new HistoricalDataRequestError( + 'Frozen dataset does not match the backtest request (assets, exact range, interval, policy or source)' + ); + } +} + export const RiskLimitsSchema = z.object({ maxPositionSize: z.number().finite().positive(), maxOrderSize: z.number().finite().positive(), @@ -47,6 +138,7 @@ export const BacktestExecutionSettingsSchema = z.object({ .refine(ids => new Set(ids).size === ids.length, 'Duplicate instruments'), dataPolicy: historicalDataPolicySchema.optional(), datasetHash: datasetHashSchema.optional(), + dataSource: z.enum(['auto', 'questdb', 'eod']).optional(), initialCapital: z.number().finite().positive(), dataFrequency: z.enum(['1m', '5m', '15m', '1h', '1d']), commission: z.number().finite().min(0).max(0.1).optional(), @@ -141,6 +233,7 @@ export function backtestRequestFromDefinition( dataFrequency: parameters.dataFrequency ?? BACKTEST_DEFAULTS.dataFrequency, dataPolicy: parameters.dataPolicy, datasetHash: parameters.datasetHash, + dataSource: parameters.dataSource, }; // Validate timezone/session intent before canonicalizing date strings to UTC. validateHistoricalDataRequest(historical); diff --git a/apps/stock/orchestrator/src/contracts/historical.ts b/apps/stock/orchestrator/src/contracts/historical.ts index afce59bb..e2ff12cc 100644 --- a/apps/stock/orchestrator/src/contracts/historical.ts +++ b/apps/stock/orchestrator/src/contracts/historical.ts @@ -1,11 +1,12 @@ import { z } from 'zod'; import { datasetHashSchema, + datasetManifestSchema, historicalDataPolicySchema, instrumentIdSchema, } from '@stock-bot/stock-config/backtest'; -export { datasetHashSchema, historicalDataPolicySchema, instrumentIdSchema }; +export { datasetHashSchema, datasetManifestSchema, historicalDataPolicySchema, instrumentIdSchema }; const positive = z.number().finite().positive(); export const datasetBarSchema = z .object({ @@ -19,33 +20,6 @@ export const datasetBarSchema = z vwap: positive, }) .strict(); -export const datasetManifestSchema = z - .object({ - version: z.literal(1), - hash: datasetHashSchema, - instruments: z - .array( - z.object({ id: instrumentIdSchema, symbol: z.string(), exchange: z.string() }).strict() - ) - .min(1), - startDate: z.string().datetime(), - endDate: z.string().datetime(), - interval: z.enum(['1m', '5m', '15m', '1h', '1d']), - policy: historicalDataPolicySchema, - volumePolicy: z.literal('reported'), - qualityPolicy: z.literal('reject-invalid-no-interpolation'), - sources: z.array( - z - .object({ - instrumentId: instrumentIdSchema, - provider: z.enum(['eod', 'questdb', 'synthetic']), - revision: z.string().min(1), - }) - .strict() - ), - barCount: z.number().int().positive(), - }) - .strict(); export const datasetSchema = z .object({ manifest: datasetManifestSchema, bars: z.array(datasetBarSchema).min(1) }) .strict(); diff --git a/apps/stock/orchestrator/src/data/historical-dataset.ts b/apps/stock/orchestrator/src/data/historical-dataset.ts index 84d986fa..a0689335 100644 --- a/apps/stock/orchestrator/src/data/historical-dataset.ts +++ b/apps/stock/orchestrator/src/data/historical-dataset.ts @@ -1,11 +1,15 @@ import { createHash } from 'node:crypto'; +import { + assertDatasetMatchesRequest, + validateDatasetManifestMetadata, +} from '@stock-bot/stock-config/backtest'; import { parseInstrumentId, validateHistoricalDataRequest, type HistoricalDataPolicy, type HistoricalDataset, } from '@stock-bot/types'; -import { datasetBarSchema, datasetManifestSchema } from '../contracts/historical'; +import { datasetBarSchema } from '../contracts/historical'; import type { StorageService } from '../services/StorageService'; import type { BacktestConfig } from '../types'; import { PREPARATION_BATCH_SIZE, preparationCheckpoint } from './preparation'; @@ -31,17 +35,8 @@ export function dataPolicy( } function matchRequest(dataset: HistoricalDataset, config?: BacktestConfig): void { - const m = dataset.manifest; - if ( - config && - (JSON.stringify([...config.symbols].sort()) !== JSON.stringify(m.instruments.map(i => i.id)) || - new Date(config.startDate).toISOString() !== m.startDate || - new Date(config.endDate).toISOString() !== m.endDate || - config.dataFrequency !== m.interval || - JSON.stringify(dataPolicy(config)) !== JSON.stringify(m.policy) || - (config.datasetHash && config.datasetHash !== m.hash)) - ) { - throw new Error('Frozen dataset does not match the backtest request'); + if (config) { + assertDatasetMatchesRequest(dataset.manifest, config); } } @@ -70,27 +65,12 @@ function* canonicalize( ) { throw new Error('Invalid historical dataset'); } - const m = datasetManifestSchema.parse(input.manifest); + const m = validateDatasetManifestMetadata(input.manifest); const ids = m.instruments.map(i => i.id); const idSet = new Set(ids); - const sortedIds = [...ids].sort(); const start = Date.parse(m.startDate), end = Date.parse(m.endDate); - validateHistoricalDataRequest({ - symbols: ids, - startDate: m.startDate, - endDate: m.endDate, - dataFrequency: m.interval, - dataPolicy: m.policy, - datasetHash: m.hash, - }); - if ( - ids.some((id, i) => id !== sortedIds[i]) || - m.instruments.some(i => JSON.stringify(i) !== JSON.stringify(parseInstrumentId(i.id))) || - m.sources.length !== ids.length || - m.sources.some((s, i) => s.instrumentId !== ids[i]) || - m.barCount !== input.bars.length - ) { + if (m.barCount !== input.bars.length) { throw new Error('Invalid dataset manifest'); } const dataset: HistoricalDataset = { manifest: m, bars: [] }; @@ -203,7 +183,8 @@ export async function loadDataset( new Date(config.endDate), config.dataFrequency, policy, - signal + signal, + config.dataSource ?? 'auto' ); signal?.throwIfAborted(); const source = rows[0]?.source; diff --git a/apps/stock/web-api/src/routes/create-routes.ts b/apps/stock/web-api/src/routes/create-routes.ts index f6dd6132..9eecb581 100644 --- a/apps/stock/web-api/src/routes/create-routes.ts +++ b/apps/stock/web-api/src/routes/create-routes.ts @@ -9,6 +9,7 @@ import { createHttpSecurity, httpSecurityOptions, type HttpSecurity } from '@sto import type { IServiceContainer } from '@stock-bot/handlers'; import { createBacktestRoutes } from './backtest.routes'; import { createBacktestV2Routes } from './backtests-v2.routes'; +import { createDatasetRoutes } from './datasets.routes'; import { createExchangeRoutes } from './exchange.routes'; import { createHealthRoutes } from './health.routes'; import { createMonitoringRoutes } from './monitoring.routes'; @@ -47,6 +48,7 @@ export function createRoutes( app.route('/api/pipeline', pipelineRoutes); app.route('/', backtestRoutes); // Mounted at root since routes already have /api prefix app.route('/', backtestV2Routes); // V2 routes also mounted at root + app.route('/', createDatasetRoutes(container)); return app; } diff --git a/apps/stock/web-api/src/routes/datasets.routes.ts b/apps/stock/web-api/src/routes/datasets.routes.ts new file mode 100644 index 00000000..be1547eb --- /dev/null +++ b/apps/stock/web-api/src/routes/datasets.routes.ts @@ -0,0 +1,43 @@ +import { Hono } from 'hono'; +import { getLogger } from '@stock-bot/logger'; +import { requireServices, type IServiceContainer } from '@stock-bot/services'; +import { HistoricalDataRequestError } from '@stock-bot/types'; +import { DatasetCatalogService } from '../services/dataset-catalog.service'; + +const logger = getLogger('dataset-catalog-routes'); + +export function createDatasetRoutes(container: IServiceContainer) { + const app = new Hono(); + const catalog = new DatasetCatalogService(requireServices(container, 'postgres').postgres); + app.get('/api/v2/datasets', async c => { + try { + const limit = c.req.query('limit') ?? '50'; + const offset = c.req.query('offset') ?? '0'; + if (!/^\d+$/.test(limit) || !/^\d+$/.test(offset)) { + throw new HistoricalDataRequestError('Dataset limit and offset must be integers'); + } + return c.json({ + datasets: await catalog.list({ limit: Number(limit), offset: Number(offset) }), + }); + } catch (error) { + if (error instanceof HistoricalDataRequestError) { + return c.json({ error: error.message }, 400); + } + logger.error('Failed to list datasets', error); + return c.json({ error: 'Failed to list datasets' }, 500); + } + }); + app.get('/api/v2/datasets/:hash', async c => { + try { + const dataset = await catalog.get(c.req.param('hash')); + return dataset ? c.json({ dataset }) : c.json({ error: 'Dataset not found' }, 404); + } catch (error) { + if (error instanceof HistoricalDataRequestError) { + return c.json({ error: error.message }, 400); + } + logger.error('Failed to get dataset', error); + return c.json({ error: 'Failed to get dataset' }, 500); + } + }); + return app; +} diff --git a/apps/stock/web-api/src/services/backtest-v2.service.ts b/apps/stock/web-api/src/services/backtest-v2.service.ts index 5caaa182..cd2e0956 100644 --- a/apps/stock/web-api/src/services/backtest-v2.service.ts +++ b/apps/stock/web-api/src/services/backtest-v2.service.ts @@ -4,12 +4,17 @@ import { authenticatedServiceFetch } from '@stock-bot/di'; import { at } from '@stock-bot/invariants'; import { getLogger } from '@stock-bot/logger'; import { requireServices, type IServiceContainer } from '@stock-bot/services'; -import { backtestRequestFromDefinition } from '@stock-bot/stock-config/backtest'; -import type { BacktestRunResult } from '@stock-bot/types'; +import { + backtestRequestFromDefinition, + datasetHashSchema, + parseBacktestRequest, +} from '@stock-bot/stock-config/backtest'; +import type { BacktestRunDatasetSelection, BacktestRunResult } from '@stock-bot/types'; import { HistoricalDataRequestError } from '@stock-bot/types'; import { getWebSocketHandler } from '../websocket/run-updates'; import type { WebSocketHandler } from '../websocket/run-updates'; import { mapStoredBacktestResult, type StoredBacktestResult } from './backtest-result'; +import { assertSelectedDatasetMatchesRequest } from './dataset-catalog.service'; const logger = getLogger('backtest-v2-service'); @@ -42,6 +47,7 @@ export interface Backtest { } export interface Run { + dataset: BacktestRunDatasetSelection; id: string; backtestId: string; runNumber: number; @@ -93,7 +99,10 @@ export class BacktestServiceV2 { request: BacktestRequest, options: { autoStart?: boolean } = {} ): Promise { - backtestRequestFromDefinition(request); + await assertSelectedDatasetMatchesRequest( + this.container.postgres, + backtestRequestFromDefinition(request) + ); const backtestId = uuidv4(); const result = await this.container.postgres.query( @@ -146,63 +155,66 @@ export class BacktestServiceV2 { } async updateBacktest(id: string, request: Partial): Promise { - const existing = await this.getBacktest(id); - if (!existing) { - return null; - } - const next = { ...existing, ...request }; - backtestRequestFromDefinition(next); - const updates: string[] = []; - const values: unknown[] = []; - let paramCount = 1; + 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; + } + const existing = this.mapBacktest(locked.rows[0]); + const next = { ...existing, ...request }; + await assertSelectedDatasetMatchesRequest(client, backtestRequestFromDefinition(next)); + const updates: string[] = []; + const values: unknown[] = []; + let paramCount = 1; - if (request.name !== undefined) { - updates.push(`name = $${paramCount++}`); - values.push(request.name); - } - if (request.strategy !== undefined) { - updates.push(`strategy = $${paramCount++}`); - values.push(request.strategy); - } - if (request.symbols !== undefined) { - updates.push(`symbols = $${paramCount++}`); - values.push(JSON.stringify(request.symbols)); - } - if (request.startDate !== undefined) { - updates.push(`start_date = $${paramCount++}`); - values.push(request.startDate); - } - if (request.endDate !== undefined) { - updates.push(`end_date = $${paramCount++}`); - values.push(request.endDate); - } - if (request.initialCapital !== undefined) { - updates.push(`initial_capital = $${paramCount++}`); - values.push(request.initialCapital); - } - if (request.config !== undefined) { - updates.push(`config = $${paramCount++}`); - values.push(JSON.stringify(request.config)); - } + if (request.name !== undefined) { + updates.push(`name = $${paramCount++}`); + values.push(request.name); + } + if (request.strategy !== undefined) { + updates.push(`strategy = $${paramCount++}`); + values.push(request.strategy); + } + if (request.symbols !== undefined) { + updates.push(`symbols = $${paramCount++}`); + values.push(JSON.stringify(request.symbols)); + } + if (request.startDate !== undefined) { + updates.push(`start_date = $${paramCount++}`); + values.push(request.startDate); + } + if (request.endDate !== undefined) { + updates.push(`end_date = $${paramCount++}`); + values.push(request.endDate); + } + if (request.initialCapital !== undefined) { + updates.push(`initial_capital = $${paramCount++}`); + values.push(request.initialCapital); + } + if (request.config !== undefined) { + updates.push(`config = $${paramCount++}`); + values.push(JSON.stringify(request.config)); + } - if (updates.length === 0) { - return this.getBacktest(id); - } + if (updates.length === 0) { + return existing; + } - values.push(id); - const result = await this.container.postgres.query( - `UPDATE backtests + values.push(id); + const result = await client.query( + `UPDATE backtests SET ${updates.join(', ')}, updated_at = NOW() WHERE id = $${paramCount} RETURNING *`, - values - ); + values + ); - if (result.rows.length === 0) { - return null; - } + if (result.rows.length === 0) { + return null; + } - return this.mapBacktest(at(result.rows, 0)); + return this.mapBacktest(at(result.rows, 0)); + }); } async listBacktests(params: { limit: number; offset: number }): Promise { @@ -275,6 +287,7 @@ export class BacktestServiceV2 { backtestId: definition.id, speedMultiplier: multiplier, }); + await assertSelectedDatasetMatchesRequest(client, snapshot); const result = await client.query( `INSERT INTO runs (id, backtest_id, run_number, speed_multiplier, status, request_snapshot, @@ -441,6 +454,7 @@ export class BacktestServiceV2 { private mapRun(row: QueryResultRow): Run { return { + dataset: datasetSelectionForRun(row), id: row.id, backtestId: row.backtest_id, runNumber: row.run_number, @@ -459,3 +473,27 @@ export class BacktestServiceV2 { }; } } + +/** 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; + let snapshot; + try { + snapshot = parseBacktestRequest(row.request_snapshot); + } catch { + return { requestedHash: null, pinnedHash, source: null, state: 'unknown' }; + } + return { + requestedHash: snapshot.datasetHash ?? null, + pinnedHash, + source: snapshot.dataSource ?? 'auto', + state: pinnedHash + ? 'pinned' + : ['completed', 'failed', 'cancelled'].includes(row.status) + ? 'unavailable' + : ['running', 'paused'].includes(row.status) + ? 'preparing' + : 'requested', + }; +} diff --git a/apps/stock/web-api/src/services/dataset-catalog.service.ts b/apps/stock/web-api/src/services/dataset-catalog.service.ts new file mode 100644 index 00000000..e65af79c --- /dev/null +++ b/apps/stock/web-api/src/services/dataset-catalog.service.ts @@ -0,0 +1,130 @@ +import type { QueryResultRow } from 'pg'; +import { + assertDatasetMatchesRequest, + datasetHashSchema, + validateDatasetManifestMetadata, + type BacktestConfig, +} from '@stock-bot/stock-config/backtest'; +import { HistoricalDataRequestError, type HistoricalDatasetCatalogEntry } from '@stock-bot/types'; + +/** Accept either the pool or the already locked run transaction. */ +export interface DatasetCatalogQuery { + query(text: string, values?: unknown[]): Promise<{ rows: QueryResultRow[] }>; +} + +// Never transfer the bar payload to the API process. CASE guards PostgreSQL's +// array/object functions so malformed retained JSON becomes a diagnostic row. +const metadataProjection = `SELECT hash, created_at, payload->'manifest' AS manifest, + jsonb_typeof(payload) AS payload_type, + jsonb_typeof(payload->'manifest') AS manifest_type, + jsonb_typeof(payload->'bars') AS bars_type, + CASE WHEN jsonb_typeof(payload->'bars') = 'array' + THEN jsonb_array_length(payload->'bars') ELSE NULL END AS bar_count, + CASE WHEN jsonb_typeof(payload) = 'object' + THEN ARRAY(SELECT key FROM jsonb_object_keys(payload) AS key ORDER BY key) + ELSE NULL END AS root_keys + FROM backtest_datasets`; + +function entry(row: QueryResultRow): HistoricalDatasetCatalogEntry { + const raw = row.manifest; + const version = + raw && typeof raw === 'object' && !Array.isArray(raw) && Number.isSafeInteger(raw.version) + ? (raw.version as number) + : null; + const result: HistoricalDatasetCatalogEntry = { + hash: row.hash, + version, + createdAt: new Date(row.created_at).toISOString(), + manifest: null, + status: 'invalid', + reason: null, + coverage: 'unknown', + integrity: 'not-verified', + }; + if (version !== null && version !== 1) { + return { + ...result, + status: 'unsupported', + reason: + version === 2 + ? 'Dataset v2 requires canonical workbench support (R05); choose a v1 dataset or prepare source data.' + : `Dataset version ${version} is unsupported; choose a supported dataset or prepare source data.`, + }; + } + if ( + row.payload_type !== 'object' || + row.manifest_type !== 'object' || + row.bars_type !== 'array' || + JSON.stringify(row.root_keys) !== JSON.stringify(['bars', 'manifest']) + ) { + return { ...result, reason: 'Retained dataset structure is invalid; prepare a new dataset.' }; + } + try { + const manifest = validateDatasetManifestMetadata(raw); + if (manifest.hash !== row.hash) { + return { ...result, reason: 'Dataset key and manifest hash differ; prepare a new dataset.' }; + } + if (manifest.barCount !== row.bar_count) { + return { + ...result, + reason: 'Dataset manifest bar count differs from retained data; prepare a new dataset.', + }; + } + return { ...result, manifest, status: 'available' }; + } catch { + return { + ...result, + reason: 'Retained dataset manifest metadata is invalid; prepare a new dataset.', + }; + } +} + +export class DatasetCatalogService { + constructor(private readonly database: DatasetCatalogQuery) {} + + async list(params: { limit: number; offset: number }): Promise { + if ( + !Number.isSafeInteger(params.limit) || + params.limit <= 0 || + !Number.isSafeInteger(params.offset) || + params.offset < 0 + ) { + throw new HistoricalDataRequestError( + 'Dataset pagination requires a positive limit and nonnegative offset' + ); + } + const result = await this.database.query( + `${metadataProjection} ORDER BY created_at DESC, hash ASC LIMIT $1 OFFSET $2`, + [params.limit, params.offset] + ); + return result.rows.map(entry); + } + + async get(hash: string): Promise { + if (!datasetHashSchema.safeParse(hash).success) { + throw new HistoricalDataRequestError('Invalid dataset hash'); + } + const result = await this.database.query(`${metadataProjection} WHERE hash = $1`, [hash]); + return result.rows[0] ? entry(result.rows[0]) : null; + } +} + +/** Acceptance uses metadata only. The existing runner still verifies full content. */ +export async function assertSelectedDatasetMatchesRequest( + database: DatasetCatalogQuery, + config: BacktestConfig +): Promise { + if (config.datasetHash === undefined) { + return; + } + const selected = await new DatasetCatalogService(database).get(config.datasetHash); + if (!selected) { + throw new HistoricalDataRequestError('Selected frozen dataset was not found'); + } + if (selected.status !== 'available' || !selected.manifest) { + throw new HistoricalDataRequestError( + selected.reason ?? 'Selected frozen dataset is unavailable' + ); + } + assertDatasetMatchesRequest(selected.manifest, config); +} diff --git a/apps/stock/web-app/src/features/backtest/BacktestDetailPageV2.tsx b/apps/stock/web-app/src/features/backtest/BacktestDetailPageV2.tsx index fcf8aebf..6c6d2aa9 100644 --- a/apps/stock/web-app/src/features/backtest/BacktestDetailPageV2.tsx +++ b/apps/stock/web-app/src/features/backtest/BacktestDetailPageV2.tsx @@ -1,11 +1,12 @@ import { ArrowLeftIcon, PlusIcon } from '@heroicons/react/24/outline'; -import { useCallback, useEffect, useRef, useState } from 'react'; +import { useCallback, useEffect, useMemo, useRef, useState } from 'react'; import { useNavigate, useParams } from 'react-router-dom'; import { useWebSocket } from '@/hooks/useWebSocket'; import { BacktestConfiguration } from './components/BacktestConfiguration'; import { BacktestPlayback } from './components/BacktestPlayback'; import { BacktestTrades } from './components/BacktestTrades'; import { RunControlsCompact } from './components/RunControlsCompact'; +import { RunDataset } from './components/RunDataset'; import { RunsListWithMetrics } from './components/RunsListWithMetrics'; import { useBacktestV2 } from './hooks/useBacktestV2'; import type { BacktestConfig } from './types/backtest.types'; @@ -90,18 +91,21 @@ export function BacktestDetailPageV2() { name: config.name, strategy: config.strategy, symbols: config.symbols, - startDate: config.startDate.toISOString().split('T')[0], - endDate: config.endDate.toISOString().split('T')[0], + startDate: config.startDate, + endDate: config.endDate, initialCapital: config.initialCapital, config: { ...backtest?.config, commission: config.commission, slippage: config.slippage, speedMultiplier: config.speedMultiplier, + dataFrequency: config.dataFrequency, + dataSource: config.dataSource, + datasetHash: config.datasetHash, dataPolicy: { adjustment: config.priceAdjustment ?? 'raw', timestamp: - !backtest?.config?.dataFrequency || backtest.config.dataFrequency === '1d' + !config.dataFrequency || config.dataFrequency === '1d' ? 'utc-session-date' : 'utc-instant', }, @@ -134,26 +138,37 @@ export function BacktestDetailPageV2() { ); // Convert backtest to config format for the form - const backtestConfig: BacktestConfig | undefined = backtest - ? { - name: backtest.name, - startDate: new Date(backtest.startDate), - endDate: new Date(backtest.endDate), - initialCapital: backtest.initialCapital, - symbols: backtest.symbols, - strategy: backtest.strategy, - speedMultiplier: 1, - commission: Number(backtest.config?.commission ?? 0.001), - slippage: Number(backtest.config?.slippage ?? 0.0001), - priceAdjustment: - backtest.config?.dataPolicy && - typeof backtest.config.dataPolicy === 'object' && - 'adjustment' in backtest.config.dataPolicy && - backtest.config.dataPolicy.adjustment === 'provider-adjusted' - ? 'provider-adjusted' - : 'raw', - } - : undefined; + const backtestConfig = useMemo( + () => + backtest + ? { + name: backtest.name, + startDate: backtest.startDate, + endDate: backtest.endDate, + initialCapital: backtest.initialCapital, + symbols: backtest.symbols, + strategy: backtest.strategy, + speedMultiplier: 1, + dataFrequency: (backtest.config?.dataFrequency ?? + '1d') as BacktestConfig['dataFrequency'], + dataSource: (backtest.config?.dataSource ?? 'auto') as BacktestConfig['dataSource'], + datasetHash: + typeof backtest.config?.datasetHash === 'string' + ? backtest.config.datasetHash + : undefined, + commission: Number(backtest.config?.commission ?? 0.001), + slippage: Number(backtest.config?.slippage ?? 0.0001), + priceAdjustment: + backtest.config?.dataPolicy && + typeof backtest.config.dataPolicy === 'object' && + 'adjustment' in backtest.config.dataPolicy && + backtest.config.dataPolicy.adjustment === 'provider-adjusted' + ? 'provider-adjusted' + : 'raw', + } + : undefined, + [backtest] + ); const renderTabContent = () => { if (['details', 'trades'].includes(activeTab)) { @@ -393,7 +408,7 @@ export function BacktestDetailPageV2() { {/* Tab Content */} -
+
{submissionError && (

@@ -422,7 +437,8 @@ export function BacktestDetailPageV2() { )}

)} - {renderTabContent()} + {currentRun && } +
{renderTabContent()}
); diff --git a/apps/stock/web-app/src/features/backtest/components/BacktestConfiguration.tsx b/apps/stock/web-app/src/features/backtest/components/BacktestConfiguration.tsx index 13f85353..cdf8b47f 100644 --- a/apps/stock/web-app/src/features/backtest/components/BacktestConfiguration.tsx +++ b/apps/stock/web-app/src/features/backtest/components/BacktestConfiguration.tsx @@ -1,9 +1,9 @@ import { useEffect, useState } from 'react'; -import { parseInstrumentId } from '@stock-bot/types'; import type { BacktestConfig } from '../types'; +import { HistoricalDataSelection } from './HistoricalDataSelection'; interface BacktestConfigurationProps { - onSubmit: (config: BacktestConfig) => void; + onSubmit: (config: BacktestConfig) => void | Promise; disabled?: boolean; initialConfig?: BacktestConfig; } @@ -16,8 +16,12 @@ export function BacktestConfiguration({ const [formData, setFormData] = useState( initialConfig || { name: '', - startDate: new Date(new Date().setMonth(new Date().getMonth() - 6)), // 6 months ago - endDate: new Date(), + startDate: new Date(new Date().setMonth(new Date().getMonth() - 6)) + .toISOString() + .slice(0, 10), // 6 months ago + endDate: new Date().toISOString().slice(0, 10), + dataFrequency: '1d', + dataSource: 'auto', initialCapital: 100000, symbols: [], strategy: 'sma-crossover', @@ -27,7 +31,10 @@ export function BacktestConfiguration({ } ); - const [symbolInput, setSymbolInput] = useState(''); + const [historicalValid, setHistoricalValid] = useState(false); + const [saving, setSaving] = useState(false); + const [saveError, setSaveError] = useState(null); + const locked = disabled || saving; useEffect(() => { if (initialConfig) { @@ -35,53 +42,32 @@ export function BacktestConfiguration({ } }, [initialConfig]); - const handleSubmit = (e: React.FormEvent) => { + const handleSubmit = async (e: React.FormEvent) => { e.preventDefault(); - if (formData.symbols.length === 0) { - alert('Please add at least one symbol'); + if (!historicalValid || locked) { return; } - onSubmit(formData); + setSaving(true); + setSaveError(null); + try { + await onSubmit(formData); + } catch (error) { + setSaveError(error instanceof Error ? error.message : 'Could not save configuration'); + } finally { + setSaving(false); + } }; const handleChange = (e: React.ChangeEvent) => { const { name, value, type } = e.target; setFormData(prev => ({ ...prev, - [name]: type === 'number' ? parseFloat(value) : type === 'date' ? new Date(value) : value, + [name]: type === 'number' ? parseFloat(value) : value, })); }; - const handleAddSymbol = () => { - const symbol = symbolInput.trim().toUpperCase(); - try { - parseInstrumentId(symbol); - } catch { - alert('Enter an exchange-qualified ID, for example AAPL.US'); - return; - } - if (symbol && !formData.symbols.includes(symbol)) { - setFormData(prev => ({ - ...prev, - symbols: [...prev.symbols, symbol], - })); - setSymbolInput(''); - } - }; - - const handleRemoveSymbol = (symbol: string) => { - setFormData(prev => ({ - ...prev, - symbols: prev.symbols.filter(s => s !== symbol), - })); - }; - - const formatDate = (date: Date) => { - return date.toISOString().split('T')[0]; - }; - return ( -
+ void handleSubmit(event)} className="space-y-4">
-
- - -
- -
-
- - -
- -
- - -
-
+ setFormData(previous => ({ ...previous, ...selection }))} + onValidityChange={setHistoricalValid} + disabled={locked} + /> + {saveError && ( +

+ {saveError} +

+ )}
-
- -
- setSymbolInput(e.target.value)} - onKeyPress={e => e.key === 'Enter' && (e.preventDefault(), handleAddSymbol())} - placeholder="AAPL.US" - className="flex-1 px-3 py-2 bg-background border border-border rounded-md text-sm text-text-primary focus:outline-none focus:ring-1 focus:ring-primary-500" - disabled={disabled} - /> - -
-
- {formData.symbols.map(symbol => ( - - {symbol} - - - ))} -
-
-
-
- -
- setSymbolInput(e.target.value)} - onKeyPress={e => e.key === 'Enter' && (e.preventDefault(), addSymbol())} - className="flex-1 px-3 py-2 bg-background border border-border rounded-md text-text-primary focus:outline-none focus:ring-1 focus:ring-primary-500" - placeholder="Instrument ID (e.g., AAPL.US)" - /> - -
-
- {formData.symbols.map(symbol => ( - - {symbol} - - - ))} -
-
- -
- - -
- -
-
- - setFormData({ ...formData, startDate: e.target.value })} - className="w-full px-3 py-2 bg-background border border-border rounded-md text-text-primary focus:outline-none focus:ring-1 focus:ring-primary-500" - required - /> -
-
- - setFormData({ ...formData, endDate: e.target.value })} - className="w-full px-3 py-2 bg-background border border-border rounded-md text-text-primary focus:outline-none focus:ring-1 focus:ring-primary-500" - required - /> -
-
+ setFormData(previous => ({ ...previous, ...selection }))} + onValidityChange={setHistoricalValid} + disabled={isSubmitting || saved.current !== null} + />
+ ) : ( + <> +

+ Source request — unpinned. Historical data will be prepared asynchronously and frozen + before execution; this request is not yet a reproducible dataset. +

+ + + )} +
+
+ + +
+
+ {(['startDate', 'endDate'] as const).map(key => { + const label = `${key === 'startDate' ? 'Start' : 'End'} ${frequency === '1d' ? 'date' : 'instant'} (UTC)`; + return ( + + ); + })} +
+

+ End is exclusive. Intraday instants require an explicit UTC offset; milliseconds are + preserved. +

+
+ + + {symbolError && ( +

+ {symbolError} +

+ )} +
+ {value.symbols.map(id => ( + + {id}{' '} + + + ))} +
+
+
+ {validation && !(frozen && (loading || detailLoading || detailError)) && ( +

+ {validation} +

+ )} + + ); +} diff --git a/apps/stock/web-app/src/features/backtest/components/RunDataset.tsx b/apps/stock/web-app/src/features/backtest/components/RunDataset.tsx new file mode 100644 index 00000000..75c5d2db --- /dev/null +++ b/apps/stock/web-app/src/features/backtest/components/RunDataset.tsx @@ -0,0 +1,39 @@ +import type { BacktestRunDatasetSelection } from '@stock-bot/types'; + +/** This binding belongs to the accepted run, never the editable backtest form. */ +export function RunDataset({ dataset }: { dataset?: BacktestRunDatasetSelection }) { + return ( +
+ {dataset?.pinnedHash ? ( +

+ Pinned dataset hash: {dataset.pinnedHash} +

+ ) : dataset?.requestedHash ? ( + <> +

+ Requested frozen dataset hash: {dataset.requestedHash} +

+

+ {dataset.state === 'unavailable' + ? 'Dataset preparation is unavailable for this run.' + : 'Waiting for dataset preparation and binding.'} +

+ + ) : dataset?.state === 'requested' ? ( +

+ Source request ({dataset.source ?? 'auto'}) — unpinned. Historical data will be prepared + asynchronously. +

+ ) : dataset?.state === 'preparing' ? ( +

Source request ({dataset.source ?? 'auto'}) — unpinned. Historical data is preparing.

+ ) : dataset?.state === 'unavailable' ? ( +

No dataset was pinned. Historical data preparation is unavailable for this run.

+ ) : ( +

Dataset provenance is unavailable for this run.

+ )} +
+ ); +} diff --git a/apps/stock/web-app/src/features/backtest/services/backtestApiV2.ts b/apps/stock/web-app/src/features/backtest/services/backtestApiV2.ts index b53feced..8a185209 100644 --- a/apps/stock/web-app/src/features/backtest/services/backtestApiV2.ts +++ b/apps/stock/web-app/src/features/backtest/services/backtestApiV2.ts @@ -1,6 +1,9 @@ -import type { BacktestRunResult } from '@stock-bot/types'; +import type { + BacktestRunDatasetSelection, + BacktestRunResult, + HistoricalDatasetCatalogEntry, +} from '@stock-bot/types'; import { API_BASE_URL, apiFetch as fetch } from '@/lib/api'; -import { browserLog } from '@/utils/browserLog'; export interface Backtest { id: string; @@ -31,6 +34,7 @@ export interface Run { currentSimulationDate?: string; createdAt: string; updatedAt: string; + dataset?: BacktestRunDatasetSelection; } export interface CreateBacktestRequest { @@ -56,7 +60,43 @@ export class RunResultsUnavailableError extends Error { } } +async function requestError(response: Response, fallback: string): Promise { + const payload: unknown = await response.json().catch(() => null); + const message = + payload && + typeof payload === 'object' && + 'error' in payload && + typeof payload.error === 'string' + ? payload.error + : `${fallback}: ${response.status} ${response.statusText}`; + return new Error(message); +} + export const backtestApiV2 = { + async listDatasets( + limit = 50, + offset = 0, + signal?: AbortSignal + ): Promise { + const response = await fetch( + `${API_BASE_URL}/api/v2/datasets?limit=${limit}&offset=${offset}`, + { signal } + ); + if (!response.ok) { + throw await requestError(response, 'Failed to load frozen datasets'); + } + return (await response.json()).datasets; + }, + + async getDataset(hash: string, signal?: AbortSignal): Promise { + const response = await fetch(`${API_BASE_URL}/api/v2/datasets/${encodeURIComponent(hash)}`, { + signal, + }); + if (!response.ok) { + throw await requestError(response, 'Failed to load frozen dataset'); + } + return (await response.json()).dataset; + }, // Backtest operations async createBacktest(request: CreateBacktestRequest): Promise { const response = await fetch(`${API_BASE_URL}/api/v2/backtests`, { @@ -69,7 +109,7 @@ export const backtestApiV2 = { }); if (!response.ok) { - throw new Error(`Failed to create backtest: ${response.statusText}`); + throw await requestError(response, 'Failed to create backtest'); } return response.json(); @@ -107,7 +147,7 @@ export const backtestApiV2 = { }); if (!response.ok) { - throw new Error(`Failed to update backtest: ${response.statusText}`); + throw await requestError(response, 'Failed to update backtest'); } return response.json(); @@ -139,9 +179,7 @@ export const backtestApiV2 = { }); if (!response.ok) { - const errorText = await response.text(); - browserLog.error(`Failed to create run:`, response.status, errorText); - throw new Error(`Failed to create run: ${response.statusText}`); + throw await requestError(response, 'Failed to create run'); } return response.json(); diff --git a/apps/stock/web-app/src/features/backtest/services/historical-selection.ts b/apps/stock/web-app/src/features/backtest/services/historical-selection.ts new file mode 100644 index 00000000..4df7ca53 --- /dev/null +++ b/apps/stock/web-app/src/features/backtest/services/historical-selection.ts @@ -0,0 +1,86 @@ +import { + validateHistoricalDataRequest, + type HistoricalDatasetCatalogEntry, +} from '@stock-bot/types'; + +export const historicalIntervals = ['1m', '5m', '15m', '1h', '1d'] as const; +export interface HistoricalSelection { + symbols: string[]; + startDate: string; + endDate: string; + dataFrequency?: (typeof historicalIntervals)[number]; + dataSource?: 'auto' | 'questdb' | 'eod'; + priceAdjustment?: 'raw' | 'provider-adjusted'; + datasetHash?: string; +} + +/** Selecting a retained snapshot adopts its exact request, never a cropped range. */ +export function retainedDatasetSelection( + entry: HistoricalDatasetCatalogEntry +): HistoricalSelection { + const manifest = entry.manifest; + if (entry.status !== 'available' || manifest?.version !== 1 || manifest.hash !== entry.hash) { + throw new Error(entry.reason ?? 'This dataset is unavailable in the current workbench'); + } + const interval = historicalIntervals.find(value => value === manifest.interval); + if (!interval) { + throw new Error('This dataset timeframe is unsupported'); + } + return { + symbols: manifest.instruments.map(instrument => instrument.id), + startDate: manifest.startDate, + endDate: manifest.endDate, + dataFrequency: interval, + dataSource: 'auto', + priceAdjustment: manifest.policy.adjustment, + datasetHash: entry.hash, + }; +} + +export function historicalSelectionError( + value: HistoricalSelection, + retained?: HistoricalDatasetCatalogEntry | null +): string | null { + try { + const frequency = value.dataFrequency ?? '1d'; + if (!['auto', 'questdb', 'eod'].includes(value.dataSource ?? 'auto')) { + return 'Choose a supported historical source'; + } + validateHistoricalDataRequest({ + symbols: value.symbols, + startDate: value.startDate, + endDate: value.endDate, + dataFrequency: frequency, + dataPolicy: { + adjustment: value.priceAdjustment ?? 'raw', + timestamp: frequency === '1d' ? 'utc-session-date' : 'utc-instant', + }, + datasetHash: value.datasetHash, + }); + if (value.datasetHash !== undefined) { + if (!retained || retained.hash !== value.datasetHash) { + return 'Select an available frozen dataset and wait for its metadata'; + } + const exact = retainedDatasetSelection(retained); + if ( + JSON.stringify([...value.symbols].sort()) !== JSON.stringify([...exact.symbols].sort()) || + new Date(value.startDate).toISOString() !== exact.startDate || + new Date(value.endDate).toISOString() !== exact.endDate || + frequency !== exact.dataFrequency || + (value.priceAdjustment ?? 'raw') !== exact.priceAdjustment || + (value.dataSource ?? 'auto') !== 'auto' + ) { + return 'These settings do not match the frozen dataset. Apply its exact settings or switch to a source request.'; + } + } + return null; + } catch (error) { + return error instanceof Error ? error.message : 'Invalid historical data settings'; + } +} + +/** A daily control displays the UTC session date; intraday controls retain the + * complete explicit-offset string, including milliseconds. */ +export function historicalDateInput(value: string, frequency: string): string { + return frequency === '1d' ? value.slice(0, 10) : value; +} diff --git a/apps/stock/web-app/src/features/backtest/types/backtest.types.ts b/apps/stock/web-app/src/features/backtest/types/backtest.types.ts index 8f589efa..234df415 100644 --- a/apps/stock/web-app/src/features/backtest/types/backtest.types.ts +++ b/apps/stock/web-app/src/features/backtest/types/backtest.types.ts @@ -1,3 +1,5 @@ +import type { HistoricalSelection } from '../services/historical-selection'; + export type BacktestStatus = | 'idle' | 'configured' @@ -7,17 +9,13 @@ export type BacktestStatus = | 'completed' | 'error'; -export interface BacktestConfig { +export interface BacktestConfig extends HistoricalSelection { name: string; - startDate: Date; - endDate: Date; initialCapital: number; - symbols: string[]; strategy: string; speedMultiplier: number; commission: number; slippage: number; - priceAdjustment?: 'raw' | 'provider-adjusted'; } export interface BacktestMetrics { diff --git a/docs/development/ROADMAP.md b/docs/development/ROADMAP.md index 4f3f9edf..2a82262a 100644 --- a/docs/development/ROADMAP.md +++ b/docs/development/ROADMAP.md @@ -467,3 +467,17 @@ The [comparison example](../../apps/stock/orchestrator/examples/canonical-regime Validation: `bun run check` passed build/source/contracts, 82 tooling, 43 utility, 44 calculation, 479 integration and 150 Rust tests (four manual ignored), plus lint. The final added public-schema matrix passed separately. Full disposable PostgreSQL/Redis suite: **105 tests / 728 assertions**. Final strict new-test types, scoped lint/format and diff checks passed. **98 tests / 580 assertions** passed against the final release addon, including the added matrix, worker reports, SMA regressions and durable recovery. Exact commands, hashes and logs are recorded in `manifest.json` → `eighteenth_wave_validation` and `/tmp/stock-bot-wave18.V1G17v/`. Only the two exact disposable test containers and identified sandbox-stalled verifier test processes were stopped; development resources, worktrees and logs remain. No S05 commit, push, PR, optimization, benchmark measurement, default cutover or trading activation occurred. Next after acceptance/commit: **R01 immutable strategy versions and R11 dataset workbench integration**, subject to the pending [ADR-006 research-product decision](architecture/decisions/006-research-product.md). Performance work remains deferred. + + +## Nineteenth-wave execution — 2026-10-23 + +S05 is accepted and committed as `6a67ae8`, superseding its uncommitted handoff above. Owner continuation approves the explicitly linked ADR-006 research-product direction. R11 is the next focused vertical slice; R01 is ready but outside this wave. Backend and frontend worktrees under `/tmp/stock-bot-wave19.do4GnG/` reserve disjoint files. Root owns contracts, composition, source forwarding and browser integration; review is independent. + +The workbench will select exact retained v1 datasets or explicit source requests through the existing durable runner. Metadata listing does not certify bar integrity or calendar coverage. V2 datasets remain visibly unsupported until R05; existing economics warnings remain. No new service, default engine cutover, trading activation, profiling or benchmark work. + + +**Validated handoff:** R11 is `review` / `validated_uncommitted`. Twenty-four source/test files add a metadata-only retained dataset catalog, exact hash selection shared by creation and Settings, explicit source forwarding through the existing runner, and run-specific preparation/pinned status. Intraday UTC milliseconds survive save/reopen. Missing/unsupported metadata stays visible; source mode remains independent of catalog availability. Save and submit validate exact compatibility; concurrent partial updates serialize under the existing backtest row lock. Accepted idempotent submissions still return their original receipt before checking current templates/catalog state. + +Independent G1/G2 review accepted the final changes. Repository checks passed 498 integration and 150 Rust tests (four manual ignored), plus build/source/contracts, 82 tooling, 43 utility, 44 calculation and lint gates. The final row-lock fix passed the full disposable PostgreSQL/Redis suite: **111 tests / 792 assertions**. Final release-addon focused coverage: **94 tests / 596 assertions**. Final browser coverage: **6 workflows / 66 assertions**, including real native frozen-hash reuse/reopen/trades, exact intraday save/reopen, mismatch rejection before dispatch and source unpinned-to-pinned display. Strict changed-test types and scoped lint/format/diff checks passed. Exact commands, source hashes and logs are in `manifest.json` → `nineteenth_wave_validation` and `/tmp/stock-bot-wave19.do4GnG/`. + +The catalog does not certify full content integrity or calendar coverage. Current web economics remain legacy/qualified; v2 entries remain unsupported until R05. No financial Rust change, schema migration, new service, performance measurement, default cutover or trading activation. The final release addon matches this checkout's release library. Both exact disposable fixtures were stopped; development resources, logs and worktrees remain. No R11 commit, push or PR. **Next after acceptance/commit: R01 immutable strategy versions**, now ready under approved ADR-006. diff --git a/docs/development/architecture/decisions/006-research-product.md b/docs/development/architecture/decisions/006-research-product.md index 48a9c1cb..b40fc2a3 100644 --- a/docs/development/architecture/decisions/006-research-product.md +++ b/docs/development/architecture/decisions/006-research-product.md @@ -1,6 +1,6 @@ # ADR-006 — Web-first research product and minimal persistence -Status: **proposed for plan approval**; web as primary product is user-mandated. +Status: **approved by owner continuation on 2026-10-23**, after the S05 handoff explicitly linked this decision for the next research-product work. Web as primary product is user-mandated. Approval covers direction; engine cutover and trading activation remain separate release gates. ## Selected approach diff --git a/docs/development/architecture/research-product.md b/docs/development/architecture/research-product.md index d0bde189..ff7bf6d0 100644 --- a/docs/development/architecture/research-product.md +++ b/docs/development/architecture/research-product.md @@ -1,6 +1,6 @@ # Integrated research product contracts -Status: proposed under ADR-006. This is the minimum product model, not a general laboratory system. +Status: approved under ADR-006 on 2026-10-23. This is the minimum product model, not a general laboratory system. ## Existing paths to preserve @@ -94,7 +94,9 @@ No extra AI database, simulator or agent framework is needed for this workflow. Reuse current Card/Dialog/DataTable/layout/chart/metric components and responsive layouts. Add only research/strategy/experiment navigation. Preserve draft input on errors, show loading separate from empty, label incomplete/cancelled/legacy/ungated results, and allow reopening exact saved URLs. Do not replace working components for cosmetic consistency. -Existing [analytics-ui tests](../../../test/integration/analytics-ui.test.tsx#L1) use server rendering; there is no declared browser harness in [web package](../../../apps/stock/web-app/package.json). W01 adds narrowly scoped interaction tests; W04 adds real navigation E2E, preferably Playwright. Dependency installation is an explicit task step requiring the usual approval, not an assumed existing capability. +Existing [analytics-ui tests](../../../test/integration/analytics-ui.test.tsx#L1) use server rendering. W04 now supplies the shared [Playwright workflow harness](../../../test/e2e/workbench.test.ts), real authenticated Hono routes, disposable SQL/Redis, durable dispatch and native smoke coverage. Extend it for research-product flows instead of creating a second harness. + +R11 exposes retained v1 metadata and exact hash selection in both backtest forms. Catalog coverage is unknown and full content integrity is not verified by metadata inspection; the runner validates retained bytes before binding/execution. The current web runner remains legacy/v1, so v2 entries are visibly unsupported until R05. Source requests remain unpinned until prepared asynchronously. These product capabilities do not remove the existing economics qualifications. ## Review clarifications diff --git a/docs/development/backlog/manifest.json b/docs/development/backlog/manifest.json index 705599a9..46809de1 100644 --- a/docs/development/backlog/manifest.json +++ b/docs/development/backlog/manifest.json @@ -1,16 +1,16 @@ { "schema_version": 1, - "plan_revision": "2026-10-23.40", + "plan_revision": "2026-10-23.42", "repository_base": "b7aeca4", - "plan_status": "eighteenth_wave_review", + "plan_status": "nineteenth_wave_review", "execution_authorized": true, "execution_scope": { - "authorized_by": "User: commit and continue after validated S03 handoff (2026-10-23). S03 accepted/committed c01e96e; S04 prerequisites satisfied. Performance work remains deferred.", + "authorized_by": "User: commit and continue after validated S05 handoff explicitly linked ADR-006 as next research product direction (2026-10-23). S05 accepted and committed 6a67ae868327eebc46872ab58e492933f582b7fd. ADR-006 direction approved by continuation; R11 chosen as next scoped vertical slice. Performance remains deferred.", "tasks": [ - "S05" + "R11" ], "permissions": [ - "S05 isolated implementation, correctness tests, independent review and planning updates; S04 commit authorized and completed" + "R11 isolated implementation, correctness/browser tests, independent review and planning updates; prior S05 commit authorized/completed" ], "excluded": [ "performance_profiling_or_optimization", @@ -23,15 +23,8 @@ "other_backlog_tasks" ], "pending_policy_decisions": [ - "ADR-006", "ADR-007", "ADR-008" - ], - "exclusions": [ - "Performance profiling/optimization/benchmarks", - "New-wave commits, push, PR or trading activation", - "Default cutover or unapproved ADR policies", - "Other backlog tasks" ] }, "canonical_metadata": "This manifest alone owns task status, dependency edges, approvals, assignments and write locks. Task Markdown owns scope and acceptance criteria. Index/roadmap are derived views.", @@ -72,7 +65,9 @@ { "id": "ADR-006", "file": "architecture/decisions/006-research-product.md", - "status": "proposed_for_plan_approval" + "status": "approved", + "approved_by": "User instructed commit and continue after handoff explicitly linked pending ADR-006 for next research-product work. Direction approved; no engine/default/paper/live activation.", + "approved_on": "2026-10-23" }, { "id": "ADR-007", @@ -1144,7 +1139,7 @@ "epic": "E4", "priority": "P2", "severity": "Medium", - "status": "review", + "status": "done", "dependencies": [ "S02", "F08" @@ -1165,14 +1160,14 @@ "assignment": "/root/s04_controls_audit", "branch": "wave18/s05-strategy", "pull_request": null, - "completed_commit": null, + "completed_commit": "6a67ae868327eebc46872ab58e492933f582b7fd", "blocker": null, "release_gates": [ "R08" ], "worktree": "/tmp/stock-bot-wave18.V1G17v/strategy", "integration_base": "75abae2cfc65229f65273bebc2ea9ef3148cce60", - "integration_state": "validated_uncommitted", + "integration_state": "accepted_committed", "implementation_slices": [ { "owner": "/root/s04_controls_audit", @@ -1395,7 +1390,7 @@ "epic": "E6", "priority": "P1", "severity": "High", - "status": "blocked", + "status": "ready", "dependencies": [ "O01" ], @@ -1750,7 +1745,7 @@ "epic": "E6", "priority": "P1", "severity": "High", - "status": "blocked", + "status": "review", "dependencies": [ "D01", "O01" @@ -1772,14 +1767,33 @@ "web-backtest-detail", "web-backtest-service" ], - "parallel_policy": "Allowed only with satisfied dependencies/approvals and disjoint write locks AND actual files; see agents/integration.md.", - "assignment": null, + "parallel_policy": "Root owns shared contracts, source plumbing, composition, browser harness and planning. Backend and frontend worktrees reserve disjoint actual files; independent reviewer is read-only.", + "assignment": "/root", "branch": null, "pull_request": null, "completed_commit": null, "blocker": null, "release_gates": [ "W04" + ], + "integration_base": "6a67ae868327eebc46872ab58e492933f582b7fd", + "integration_state": "validated_uncommitted", + "worktree": "/home/boki/repos/stock-bot", + "implementation_slices": [ + { + "owner": "/root/s04_controls_audit", + "scope": "Dataset metadata API, admission compatibility and run projection; focused integration/PostgreSQL tests", + "worktree": "/tmp/stock-bot-wave19.do4GnG/backend" + }, + { + "owner": "/root/s04_feed_audit", + "scope": "Shared dataset selection UI, both configuration forms, API client and run status", + "worktree": "/tmp/stock-bot-wave19.do4GnG/frontend" + }, + { + "owner": "/root", + "scope": "Shared contracts/metadata validation, source forwarding, route mount, browser tests, integration/planning" + } ] }, { @@ -2462,6 +2476,39 @@ "commit_authorized_by": "User: commit and continue (2026-10-22), after W04 validated handoff", "continuation": "Requested; no remaining scheduled task has satisfied code AND ADR prerequisites. Explicit ADR-002/003/004 approval requested before F01/D01. No policy decision or deferred activation inferred." } + }, + { + "wave": "eighteenth_wave", + "scope": { + "authorized_by": "User: commit and continue after validated S03 handoff (2026-10-23). S03 accepted/committed c01e96e; S04 prerequisites satisfied. Performance work remains deferred.", + "tasks": [ + "S05" + ], + "permissions": [ + "S05 isolated implementation, correctness tests, independent review and planning updates; S04 commit authorized and completed" + ], + "excluded": [ + "performance_profiling_or_optimization", + "performance_benchmarks", + "new_wave_commits_without_further_approval", + "push", + "pull_requests", + "live_or_paper_operations", + "default_engine_cutover", + "other_backlog_tasks" + ], + "pending_policy_decisions": [ + "ADR-006", + "ADR-007", + "ADR-008" + ], + "exclusions": [ + "Performance profiling/optimization/benchmarks", + "New-wave commits, push, PR or trading activation", + "Default cutover or unapproved ADR policies", + "Other backlog tasks" + ] + } } ], "second_wave": [ @@ -6398,5 +6445,121 @@ ] }, "next": "Accept/commit S05; next product work R01/R11 requires pending ADR-006. Performance remains deferred; no other code/ADR-ready execution task is authorized by this handoff." + }, + "nineteenth_wave": [ + "R11" + ], + "nineteenth_wave_base": "6a67ae868327eebc46872ab58e492933f582b7fd", + "nineteenth_wave_notes": [ + "ADR-006 approved by continuation of explicitly linked direction. R01 is ready but outside this wave.", + "Current durable web runner remains v1/legacy. Retained v2 datasets are visible as unsupported pending R05, with no adaptation or default cutover.", + "Metadata catalog does not prove full content integrity or calendar coverage; exact v1 reuse and full runner validation remain authoritative.", + "Performance engineering and benchmarks remain deferred." + ], + "nineteenth_wave_validation": { + "state": "validated_uncommitted", + "task": "R11", + "base": "6a67ae868327eebc46872ab58e492933f582b7fd", + "evidence_directory": "/tmp/stock-bot-wave19.do4GnG", + "source_archive": "/tmp/stock-bot-wave19.do4GnG/r11-integrated-source.tar", + "source_archive_sha256": "4757798a17c9216bf67daf0efb6b29bbddbc47677f2782243a031c31eaf4c78f", + "source_hashes": { + "apps/stock/config/src/contracts/backtest.ts": "8a1dfea4ffce69834692ffc9049bc0d755f27f4ce4a82032b1e3d47d4c00dd50", + "apps/stock/orchestrator/src/contracts/historical.ts": "5c0c613a87dec4d22c5999b25fa5d9425832a1b95db5b85fc94baff74bb131cc", + "apps/stock/orchestrator/src/data/historical-dataset.ts": "7b1c279aa0f031282b6b725b9f50dee5362f588eb0e913e42609370ad8583dd4", + "apps/stock/web-api/src/routes/create-routes.ts": "bb87b71c237510b638d5bcff8edb766a2976f57cf85f111d85816d1934cc519b", + "apps/stock/web-api/src/routes/datasets.routes.ts": "001f99b321e2444c359543ad36aef8a531432898763e57395cdd7b080e50c436", + "apps/stock/web-api/src/services/backtest-v2.service.ts": "8199972cc0b3cad9f35317b994350221b648327d48d0ef69f14ae218777e6541", + "apps/stock/web-api/src/services/dataset-catalog.service.ts": "d7808120300922eaea2b269481ff3771ee9b3da632dfa152dfe9022640a2fadc", + "apps/stock/web-app/src/features/backtest/BacktestDetailPageV2.tsx": "46d39c64478f0e100378b89e005cb87817cf1e1dd6f10104f3faf855b32377ca", + "apps/stock/web-app/src/features/backtest/components/BacktestConfiguration.tsx": "b6bfc0b0609692c1316c40449468c5b239bc60499f474d9607ac43703a068635", + "apps/stock/web-app/src/features/backtest/components/CreateBacktestDialog.tsx": "a6e1b76777ce0ba20b44be96fbe1d430e49a4bd1e5241a63d7eb87441ce74a5d", + "apps/stock/web-app/src/features/backtest/components/HistoricalDataSelection.tsx": "63af2d46c77a766db86d73eceea5d60ecc5a3d118256fdd3a5197fa3b11b1a01", + "apps/stock/web-app/src/features/backtest/components/RunDataset.tsx": "ee6c3cbb5e4b4beb7b6274afedc78a376847cb8c4634edc44817c61ef5f46f6d", + "apps/stock/web-app/src/features/backtest/services/backtestApiV2.ts": "84250aa382bb71de6575ff23e63a04b1e6a8b903221add2f8c52cf21c993a43a", + "apps/stock/web-app/src/features/backtest/services/historical-selection.ts": "ee16badd8cd3721f045b23a3666493a9dd8204b8ca447e681e0edb925a82f497", + "apps/stock/web-app/src/features/backtest/types/backtest.types.ts": "9b6eb37fa30a43c063f27f7ecbf84d997caee4be3e0892dc5b3e5ed6eb24cc90", + "libs/core/types/src/dataset-catalog.ts": "9f0ab029be94ec502dc4ea797e441ed075a32662048c7c141282eb99da7bd969", + "libs/core/types/src/index.ts": "600ee1bd084b8d50ce97bbcd632ac27abba741d5a00b4e2e00562e92a7a098a0", + "test/e2e/fixture.ts": "09fae4adcf9af66fac200b451ccfc76b9135f0e5255b47c7a98a715d5060ab51", + "test/e2e/workbench.test.ts": "43731027c547c3529391f28d76093919b1c7b9b32856d77623b21b707e62adc0", + "test/integration/backtest-request-contract.test.ts": "52d669e44e478070a4a0c6a4998f5e6cd4503def061393ed5de74c1c89da2a84", + "test/integration/dataset-catalog.test.ts": "a13c14310263e46a944b0814a2aa9ffe0db9487a0a11d75f76f86c0501a55900", + "test/integration/dataset-workbench.test.ts": "a2e2a02e3d00595b7f4bf90aa0f163ea536a709141cabd68a67c72959265e817", + "test/integration/ingestion-backtest.test.ts": "ddfee95759278434a33db035f04680b81c42b0348ba920189fb112d1c3739784", + "test/postgres/dataset-catalog.test.ts": "ba8388007383bd7109c56ce20028e976138d9e282249e80946f9f78d820e2866" + }, + "independent_review": { + "owner": "/root/s03_review", + "outcome": "Accepted G1/G2 after concurrent-update fix and pending-source presentation fix; post-fix verification gates passed. No remaining must-fix findings.", + "reviewed_fixes": [ + "94ca8edc5ab316d9c6a56d88b930359db477b4c8ffa5bb9044cfcad1666163ca", + "fcec404fb706f65b6370b1f5c0e1e4cf6680c9015330e57d09cf727fad84d453" + ], + "root_test_adjustments": "Strict happy-dom fetch mock uses browser.Response and its actual response type; existing ingestion fixture if/else expanded for scoped lint. Browser source case additionally checks pending unpinned to running pinned." + }, + "checks": [ + { + "command": "CARGO_BUILD_JOBS=2 bun run check", + "log": "/tmp/stock-bot-wave19.do4GnG/check.log", + "outcome": "Passed all repository gates: build/source/contracts, 82 tooling, 43 utility, 44 calculation, 498 integration, 150 Rust (4 manual ignored), lint. Before final backend row-lock fix; affected source/tests rechecked below." + }, + { + "command": "PIPELINE_TEST_DATABASE_URL=postgres://fixture:fixture@127.0.0.1:32821/stock_bot_safety BACKTEST_TEST_REDIS_URL=redis://127.0.0.1:32822/15 bun run test:postgres", + "log": "/tmp/stock-bot-wave19.do4GnG/postgres.log", + "outcome": "111 tests / 792 assertions passed after row-lock fix, including deterministic concurrent partial-update regression and durable freeze/retry/recovery tests." + }, + { + "command": "CARGO_BUILD_JOBS=2 bun run --cwd apps/stock/engine build:release", + "log": "/tmp/stock-bot-wave19.do4GnG/native-release-build.log", + "outcome": "Release addon restored and byte-identical to checkout release library." + }, + { + "command": "bun test test/integration/dataset-catalog.test.ts test/integration/dataset-workbench.test.ts test/integration/backtest-request-contract.test.ts test/integration/ingestion-backtest.test.ts test/integration/dataset-preparation.test.ts test/integration/backtest-workflow.test.ts test/integration/native-terminal-equity.test.ts", + "log": "/tmp/stock-bot-wave19.do4GnG/release-focused.log", + "outcome": "94 tests / 596 assertions passed against final release addon and backend row-lock fix. Subsequent test-only type annotation/brace formatting does not change runtime behavior." + }, + { + "command": "PIPELINE_TEST_DATABASE_URL=postgres://fixture:fixture@127.0.0.1:32821/stock_bot_safety BACKTEST_TEST_REDIS_URL=redis://127.0.0.1:32822/15 bun run test:e2e", + "log": "/tmp/stock-bot-wave19.do4GnG/e2e-final.log", + "outcome": "6 browser workflows / 66 assertions passed after row-lock fix and release restoration. Includes native frozen-hash run/reopen/trades, exact intraday milliseconds save/reopen, mismatch400/no dispatch, source unpinned-to-pinned, existing retry/switch/cancel flows." + }, + { + "command": "bun run typecheck", + "log": "/tmp/stock-bot-wave19.do4GnG/typecheck-final.log", + "outcome": "Passed after row-lock fix." + }, + { + "command": "bunx tsc --project /tmp/stock-bot-wave19.do4GnG/tests-tsconfig.json --noEmit", + "log": "/tmp/stock-bot-wave19.do4GnG/strict-tests-final.log", + "outcome": "Passed all new/changed integration, PostgreSQL and browser test types." + }, + { + "command": "bunx eslint <24 source-files.json paths> --max-warnings 0; bunx prettier --check ; git diff --check", + "logs": [ + "/tmp/stock-bot-wave19.do4GnG/scoped-lint-final.log", + "/tmp/stock-bot-wave19.do4GnG/scoped-format-final.log" + ], + "outcome": "Passed." + } + ], + "native_release_sha256": "ef00eed556f5c32332d36a9a00ef710682e90deb00b54552e4b5c8bfdfbe8103", + "scope": "24 source/test files; five planning files. No database migration, Rust financial source, new services or trading/default activation.", + "limitations": [ + "Current web runner remains v1/legacy with existing unverified-economics qualification; v2 is listed unsupported until R05.", + "Catalog validates structure/count/key metadata but cannot certify payload hash integrity or complete calendar coverage. Runner retains full validation.", + "Exact full dataset reuse only; no implicit slicing or coverage guarantee. Source preparation uses existing configured storage." + ], + "environment_notes": [ + "Initial sandbox-focused native worker run failed under process restrictions and was stopped via its exact exec session; escalated rerun passed34/211.", + "Two exact disposable containers stopped after verification; development services untouched.", + "Worktrees/logs retained. No performance profiling, optimization or benchmark measurements.", + "No new-wave commit, push or PR." + ], + "stopped_fixture_ids": [ + "100a9b5627d5fc80ade256f99ddbe7f88f2df1e24218c4b67baae8ae66f70d63", + "b90c3964498805a5d69bc68540c53b85cef5b9729010d0681a2292d1aff679f8" + ], + "next": "R01 immutable strategy versions is ADR/code-ready; performance remains deferred." } } diff --git a/docs/development/backlog/tasks/R11.md b/docs/development/backlog/tasks/R11.md index a0c552cb..5e9f4922 100644 --- a/docs/development/backlog/tasks/R11.md +++ b/docs/development/backlog/tasks/R11.md @@ -28,7 +28,7 @@ No new storage service, arbitrary truncation, full corporate-action feed, or syn - apps/stock/web-app/src/features/backtest/components/CreateBacktestDialog.tsx - apps/stock/orchestrator/src/backtest/BacktestRunner.ts -Write locks: dataset-contract, web-backtest-detail, web-backtest-service. One agent owns this change. Lock names do not override actual overlapping files. +Write locks: dataset-contract, web-backtest-detail, web-backtest-service. Root coordinates shared contracts; backend and frontend owners may use isolated worktrees with disjoint actual files. Lock names do not override actual overlapping files. ## Dependencies and blockers @@ -68,3 +68,18 @@ Keep migrations additive and previous results readable. Do not add a switch that ## Handoff Report scope changes (if any), fixture expectations, API/schema changes, measurements, remaining limitations and commit/PR references once authorized. Request independent review; only the integration/planning owner may mark the manifest done. + +## Execution contract — 2026-10-23 + +- Existing web execution remains v1/legacy. Catalog v2 entries are unsupported pending R05; do not adapt them or switch engine defaults. +- Metadata-only list/detail includes the v1 manifest, storage key, version, creation time and actionable status. No bar arrays enter API memory. Validate structure/count/key agreement; describe coverage as unknown and full content integrity as not verified by catalog. The durable runner retains full content validation. +- Reuse is exact: sorted instruments, full UTC bounds (including intraday milliseconds), interval, adjustment/timestamp policy and hash. No implicit slicing. An explicit source conflicting with retained provenance rejects; omitted/auto allows exact retained reuse. +- Optional `dataSource: auto | questdb | eod` reaches existing asynchronous storage loading. Definitions and accepted snapshots retain it. No synchronous provider access in API. +- Save/update/new submission checks selected metadata before execution. Idempotent submission receipts are returned before revalidating mutable definitions or current catalog state. +- Run dataset projection reads only immutable request snapshot and atomic binding. Pending/source preparation is visibly unpinned; failed runs never become successful merely because a hash is bound. +- Reuse one picker in creation and Settings; preserve exact intraday bounds and missing hash selections. Source mode works when catalog is empty/unavailable. Keep existing economics warnings. +- Root owns shared contracts/source plumbing/route mount/browser tests/planning; backend and frontend slices own disjoint files. No Rust financial changes, extra storage/queue service, strategy catalog or performance work. + +## Validated handoff — 2026-10-23 + +Integrated exact v1 catalog/selection/source/run-binding flow with unchanged durable content validation and engine defaults. Concurrent definition edits now lock before merge/validation. Independent review accepted; all required metadata/compatibility/source/retry cases and shared browser flows passed. Full PostgreSQL suite: 111 tests / 792 assertions; final browser: 6 / 66; final release-addon focused suite: 94 / 596. Strict test types, scoped lint/format and repository gates passed (see manifest for exact sequencing and evidence). Status, hashes, commands, limitations and acceptance state remain canonical in `manifest.json` → `nineteenth_wave_validation`. R01 is next; performance remains deferred. diff --git a/libs/core/types/src/dataset-catalog.ts b/libs/core/types/src/dataset-catalog.ts new file mode 100644 index 00000000..b6d0b3ee --- /dev/null +++ b/libs/core/types/src/dataset-catalog.ts @@ -0,0 +1,21 @@ +import type { HistoricalDatasetManifest } from './historical-data'; + +/** Metadata only. Availability here never certifies bar content or calendar coverage. */ +export interface HistoricalDatasetCatalogEntry { + hash: string; + version: number | null; + createdAt: string; + manifest: HistoricalDatasetManifest | null; + status: 'available' | 'unsupported' | 'invalid'; + reason: string | null; + coverage: 'unknown'; + integrity: 'not-verified'; +} + +/** Derived from the accepted run snapshot and its atomic dataset binding. */ +export interface BacktestRunDatasetSelection { + requestedHash: string | null; + pinnedHash: string | null; + source: 'auto' | 'questdb' | 'eod' | null; + state: 'requested' | 'preparing' | 'pinned' | 'unavailable' | 'unknown'; +} diff --git a/libs/core/types/src/index.ts b/libs/core/types/src/index.ts index 70040217..4068fc14 100644 --- a/libs/core/types/src/index.ts +++ b/libs/core/types/src/index.ts @@ -128,6 +128,7 @@ export { HistoricalDataRequestError, validateHistoricalDataRequest, } from './historical-data'; +export type { HistoricalDatasetCatalogEntry, BacktestRunDatasetSelection } from './dataset-catalog'; export type { InstrumentIdentity, HistoricalDataPolicy, diff --git a/test/e2e/fixture.ts b/test/e2e/fixture.ts index 40480b4c..a35fc852 100644 --- a/test/e2e/fixture.ts +++ b/test/e2e/fixture.ts @@ -103,6 +103,26 @@ const storage: Pick = { }, }; +/** Retain a real hash-validated v1 fixture through the same preparation function as a run. */ +export async function retainDataset(pool: Pool, overrides: Partial = {}) { + const dataset = await loadDataset(storage, { + mode: 'backtest', + strategy: 'moving-average', + symbols: ['AAPL.US'], + startDate: '2024-01-01T00:00:00.000Z', + endDate: '2024-03-15T00:00:00.000Z', + dataFrequency: '1d', + initialCapital: 100000, + speed: 'max', + ...overrides, + }); + await pool.query('INSERT INTO backtest_datasets(hash,payload) VALUES ($1,$2)', [ + dataset.manifest.hash, + JSON.stringify(dataset), + ]); + return dataset; +} + /** Fixed UI lifecycle data, NOT a financial simulator or correctness oracle. */ class FixtureEngine extends EventEmitter { completion = gate(); @@ -377,6 +397,7 @@ export async function fixture(native = false) { if ( (!pathname.startsWith('/api/v2/backtests') && !pathname.startsWith('/api/v2/runs') && + !pathname.startsWith('/api/v2/datasets') && pathname !== '/api/auth/session') || /\/(pause|resume|speed)$/.test(pathname) ) { diff --git a/test/e2e/workbench.test.ts b/test/e2e/workbench.test.ts index 63a45db9..0f88079c 100644 --- a/test/e2e/workbench.test.ts +++ b/test/e2e/workbench.test.ts @@ -1,7 +1,15 @@ import { randomUUID } from 'node:crypto'; import { expect, test } from 'bun:test'; import type { Request } from 'playwright'; -import { createInBrowser, fixture, gate, submitInBrowser, until, visible } from './fixture'; +import { + createInBrowser, + fixture, + gate, + retainDataset, + submitInBrowser, + until, + visible, +} from './fixture'; // Serial by design: the production WebSocket projection has a process-local handler. test('browser_saved_run_lifecycle', async () => { @@ -24,6 +32,7 @@ test('browser_saved_run_lifecycle', async () => { expect(response.headers().location).toBe(`/api/v2/runs/${run.id}`); expect(response.request().headers()['idempotency-key']).toBeTruthy(); await visible(f.page, 'Pending'); + await visible(f.page, /Source request \(auto\) — unpinned/); expect((await f.pool.query('SELECT * FROM runs')).rowCount).toBe(1); expect((await f.pool.query('SELECT * FROM backtest_dispatch')).rowCount).toBe(1); expect(await f.page.getByRole('button', { name: /pause|resume/i }).count()).toBe(0); @@ -31,6 +40,9 @@ test('browser_saved_run_lifecycle', async () => { f.dispatcher.start(); await visible(f.page, 'Running'); await visible(f.page, '25%'); + expect( + await f.page.getByRole('region', { name: 'Run dataset', exact: true }).textContent() + ).toContain('Pinned dataset hash'); await until( () => f.frames.some( @@ -278,3 +290,117 @@ test('native_smoke', async () => { await f.close(); } }); + +test('browser_frozen_dataset_native_run_and_reopen', async () => { + const f = await fixture(true); + try { + const dataset = await retainDataset(f.pool); + const hash = dataset.manifest.hash; + await f.login(); + await f.page.getByRole('button', { name: 'New Backtest', exact: true }).click(); + await f.page.getByPlaceholder('My Strategy Backtest').fill('Frozen dataset browser run'); + await f.page.getByLabel('Historical data input', { exact: true }).selectOption('frozen'); + await f.page.getByLabel('Frozen dataset', { exact: true }).selectOption(hash); + expect(await f.page.getByLabel('Start date (UTC)', { exact: true }).inputValue()).toBe( + '2024-01-01' + ); + expect(await f.page.getByLabel('Start date (UTC)', { exact: true }).isDisabled()).toBe(true); + await f.page.getByRole('button', { name: 'Save and run', exact: true }).click(); + await f.page.waitForURL(/\/backtests\/[^/]+\/run\/[^/]+$/); + const runId = f.page.url().split('/').at(-1)!; + await visible(f.page, 'Pending'); + const pending = await f.request(`/api/v2/runs/${runId}`); + expect(pending.dataset).toMatchObject({ + requestedHash: hash, + pinnedHash: null, + state: 'requested', + }); + expect( + await f.page.getByRole('region', { name: 'Run dataset', exact: true }).textContent() + ).toContain(hash); + f.dispatcher.start(); + await visible(f.page, 'Completed'); + const result = await f.request(`/api/v2/runs/${runId}/results`); + expect(result.config.dataset.hash).toBe(hash); + expect(result.engine).toBe('native'); + expect(result.trades.length).toBeGreaterThan(0); + expect((await f.pool.query('SELECT count(*) FROM backtest_datasets')).rows[0].count).toBe('1'); + await visible(f.page, 'Research only · Unverified economics'); + const runDataset = f.page.getByRole('region', { name: 'Run dataset', exact: true }); + expect(await runDataset.textContent()).toContain('Pinned dataset hash'); + await f.page.reload(); + await visible(f.page, 'Completed'); + expect(await runDataset.textContent()).toContain(hash); + await f.page.getByRole('button', { name: 'Trades', exact: true }).click(); + await visible(f.page, result.trades[0].side.toUpperCase()); + expect(f.unexpectedNetwork).toEqual([]); + } finally { + await f.close(); + } +}); + +test('browser_intraday_dataset_exact_settings_and_incompatible_submission', async () => { + const f = await fixture(); + try { + const startDate = '2024-01-02T13:30:00.123Z'; + const endDate = '2024-01-02T15:30:00.456Z'; + const dataset = await retainDataset(f.pool, { startDate, endDate, dataFrequency: '1m' }); + const hash = dataset.manifest.hash; + await f.login(); + await f.page.getByRole('button', { name: 'New Backtest', exact: true }).click(); + await f.page.getByPlaceholder('My Strategy Backtest').fill('Exact intraday frozen settings'); + await f.page.getByLabel('Historical data input', { exact: true }).selectOption('frozen'); + await f.page.getByLabel('Frozen dataset', { exact: true }).selectOption(hash); + await f.page.getByRole('button', { name: 'Save', exact: true }).click(); + await f.page.waitForURL(/\/backtests\/[^/]+$/); + const backtestId = f.page.url().split('/').at(-1)!; + await f.page.getByRole('button', { name: 'Settings', exact: true }).click(); + expect(await f.page.getByLabel('Start instant (UTC)', { exact: true }).inputValue()).toBe( + startDate + ); + expect(await f.page.getByLabel('End instant (UTC)', { exact: true }).inputValue()).toBe( + endDate + ); + const saved = f.page.waitForResponse( + response => + response.request().method() === 'PUT' && + response.url().endsWith(`/api/v2/backtests/${backtestId}`) + ); + await f.page.getByRole('button', { name: 'Save', exact: true }).click(); + expect((await saved).status()).toBe(200); + const stored = ( + await f.pool.query('SELECT start_date,end_date,config FROM backtests WHERE id=$1', [ + backtestId, + ]) + ).rows[0]; + expect(stored.start_date.toISOString()).toBe(startDate); + expect(stored.end_date.toISOString()).toBe(endDate); + expect(stored.config.datasetHash).toBe(hash); + expect(stored.config.dataFrequency).toBe('1m'); + await f.page.reload(); + await f.page.getByRole('button', { name: 'Settings', exact: true }).click(); + expect(await f.page.getByLabel('Start instant (UTC)', { exact: true }).inputValue()).toBe( + startDate + ); + // Simulate a template changed outside this browser; API must reject before durable dispatch. + await f.pool.query( + "UPDATE backtests SET config=jsonb_set(config,'{dataFrequency}','\"5m\"') WHERE id=$1", + [backtestId] + ); + await f.page.getByRole('button', { name: 'Runs', exact: true }).click(); + await f.page.getByRole('button', { name: 'New Run', exact: true }).click(); + const rejected = f.page.waitForResponse( + response => + response.request().method() === 'POST' && + response.url().endsWith(`/api/v2/backtests/${backtestId}/runs`) + ); + await f.page.getByRole('button', { name: 'Run current settings', exact: true }).click(); + expect((await rejected).status()).toBe(400); + await visible(f.page, /Frozen dataset does not match/); + expect((await f.pool.query('SELECT count(*) FROM runs')).rows[0].count).toBe('0'); + expect((await f.pool.query('SELECT count(*) FROM backtest_dispatch')).rows[0].count).toBe('0'); + expect(f.unexpectedNetwork).toEqual([]); + } finally { + await f.close(); + } +}); diff --git a/test/integration/backtest-request-contract.test.ts b/test/integration/backtest-request-contract.test.ts index 436eb93d..2b986857 100644 --- a/test/integration/backtest-request-contract.test.ts +++ b/test/integration/backtest-request-contract.test.ts @@ -63,6 +63,23 @@ describe('shared backtest request contract', () => { expect(runnerParser).toBe(parseBacktestRequest); }); + test('historical provider selection is retained as execution configuration', () => { + for (const dataSource of ['auto', 'questdb', 'eod'] as const) { + const snapshot = backtestRequestFromDefinition({ + ...definition, + config: { ...definition.config, dataSource }, + }); + expect(snapshot.dataSource).toBe(dataSource); + expect(parseBacktestRequest(snapshot).dataSource).toBe(dataSource); + expect(normalizeBacktestStrategyConfig(snapshot.config ?? {}).parameters).toEqual( + definition.config + ); + } + expect(() => + backtestRequestFromDefinition({ ...definition, config: { dataSource: 'unknown' } }) + ).toThrow(); + }); + test('definition snapshots and direct requests share defaults without mutating their inputs', () => { const input = structuredClone(request); const parsed = parseBacktestRequest(input); diff --git a/test/integration/dataset-catalog.test.ts b/test/integration/dataset-catalog.test.ts new file mode 100644 index 00000000..4368a785 --- /dev/null +++ b/test/integration/dataset-catalog.test.ts @@ -0,0 +1,85 @@ +import { expect, test } from 'bun:test'; +import { Hono } from 'hono'; +import { getLogger, setLoggerConfig } from '@stock-bot/logger'; +import type { PostgresClient } from '@stock-bot/services'; +import { parseBacktestRequest } from '@stock-bot/stock-config/backtest'; +import { createDatasetRoutes } from '../../apps/stock/web-api/src/routes/datasets.routes'; +import { datasetSelectionForRun } from '../../apps/stock/web-api/src/services/backtest-v2.service'; + +setLoggerConfig({ logLevel: 'fatal', logConsole: false }); +const hash = 'a'.repeat(64); +const logger = getLogger('dataset-catalog-http-test'); +test('dataset endpoints return explicit empty/missing states and reject invalid query inputs before database reads', async () => { + const calls: { text: string; values?: unknown[] }[] = []; + const postgres = { + async query(text: string, values?: unknown[]) { + calls.push({ text, values }); + return { rows: [] }; + }, + } as unknown as PostgresClient; + const app = new Hono().route('/', createDatasetRoutes({ postgres, logger })); + const list = await app.request('/api/v2/datasets'); + expect(list.status).toBe(200); + expect(await list.json()).toEqual({ datasets: [] }); + expect(calls[0]!.values).toEqual([50, 0]); + expect((await app.request(`/api/v2/datasets/${hash}`)).status).toBe(404); + const count = calls.length; + for (const path of [ + '/api/v2/datasets/bad', + '/api/v2/datasets?limit=1x', + '/api/v2/datasets?limit=0', + '/api/v2/datasets?offset=-1', + '/api/v2/datasets?offset=1.5', + ]) { + expect((await app.request(path)).status).toBe(400); + } + expect(calls).toHaveLength(count); +}); + +test('catalog database errors are failures, never an empty success or leaked internal diagnostic', async () => { + const postgres = { + async query() { + throw new Error('private database detail'); + }, + } as unknown as PostgresClient; + const app = new Hono().route('/', createDatasetRoutes({ postgres, logger })); + for (const path of ['/api/v2/datasets', `/api/v2/datasets/${hash}`]) { + const response = await app.request(path); + expect(response.status).toBe(500); + expect(await response.text()).not.toContain('private database detail'); + } +}); + +test('run dataset provenance distinguishes accepted request, active preparation, terminal failure and actual binding', () => { + const snapshot = parseBacktestRequest({ + mode: 'backtest', + strategy: 'sma-crossover', + symbols: ['A.US'], + startDate: '2024-01-01T00:00:00.000Z', + endDate: '2024-01-02T00:00:00.000Z', + initialCapital: 1000, + dataFrequency: '1d', + datasetHash: hash, + }); + const row = { + request_snapshot: snapshot, + dataset_hash: null, + status: 'pending', + config: { dataSource: 'questdb', datasetHash: 'b'.repeat(64) }, + }; + expect(datasetSelectionForRun(row)).toEqual({ + requestedHash: hash, + pinnedHash: null, + source: 'auto', + state: 'requested', + }); + for (const status of ['running', 'paused']) { + expect(datasetSelectionForRun({ ...row, status }).state).toBe('preparing'); + } + for (const status of ['completed', 'failed', 'cancelled']) { + expect(datasetSelectionForRun({ ...row, status }).state).toBe('unavailable'); + expect(datasetSelectionForRun({ ...row, status, dataset_hash: hash }).state).toBe('pinned'); + } + expect(datasetSelectionForRun({ ...row, request_snapshot: null }).state).toBe('unknown'); + expect(datasetSelectionForRun({ ...row, request_snapshot: {} }).state).toBe('unknown'); +}); diff --git a/test/integration/dataset-workbench.test.ts b/test/integration/dataset-workbench.test.ts new file mode 100644 index 00000000..599132a7 --- /dev/null +++ b/test/integration/dataset-workbench.test.ts @@ -0,0 +1,373 @@ +import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, test } from 'bun:test'; +import { GlobalWindow } from 'happy-dom'; +import { act, createElement, useState } from 'react'; +import type { Root } from 'react-dom/client'; +import { renderToStaticMarkup } from 'react-dom/server'; +import type { HistoricalDatasetCatalogEntry } from '@stock-bot/types'; +import { RunDataset } from '../../apps/stock/web-app/src/features/backtest/components/RunDataset'; +import { + historicalDateInput, + historicalSelectionError, + retainedDatasetSelection, + type HistoricalSelection, +} from '../../apps/stock/web-app/src/features/backtest/services/historical-selection'; + +const hash = 'a'.repeat(64); +const retained: HistoricalDatasetCatalogEntry = { + hash, + version: 1, + createdAt: '2024-01-03T00:00:00.000Z', + status: 'available', + reason: null, + coverage: 'unknown', + integrity: 'not-verified', + manifest: { + version: 1, + hash, + instruments: [ + { id: 'AAPL.US', symbol: 'AAPL', exchange: 'US' }, + { id: 'MSFT.US', symbol: 'MSFT', exchange: 'US' }, + ], + startDate: '2024-01-02T14:30:00.123Z', + endDate: '2024-01-02T20:59:59.999Z', + interval: '1m', + policy: { adjustment: 'provider-adjusted', timestamp: 'utc-instant' }, + volumePolicy: 'reported', + qualityPolicy: 'reject-invalid-no-interpolation', + sources: [ + { instrumentId: 'AAPL.US', provider: 'eod', revision: 'fixture-a' }, + { instrumentId: 'MSFT.US', provider: 'questdb', revision: 'fixture-b' }, + ], + barCount: 2, + }, +}; + +describe('dataset workbench selection', () => { + test('select_hash_compatibility adopts exact manifest settings and UTC milliseconds', () => { + const selected = retainedDatasetSelection(retained); + expect(selected).toEqual({ + symbols: ['AAPL.US', 'MSFT.US'], + startDate: '2024-01-02T14:30:00.123Z', + endDate: '2024-01-02T20:59:59.999Z', + dataFrequency: '1m', + dataSource: 'auto', + priceAdjustment: 'provider-adjusted', + datasetHash: hash, + }); + expect(historicalSelectionError(selected, retained)).toBeNull(); + expect(historicalDateInput(selected.startDate, '1m')).toBe(selected.startDate); + expect(historicalDateInput('2024-01-02T00:00:00.000Z', '1d')).toBe('2024-01-02'); + }); + + test('equivalent explicit offsets and reordered instrument sets preserve exact identity', () => { + const selected = retainedDatasetSelection(retained); + expect( + historicalSelectionError( + { + ...selected, + symbols: [...selected.symbols].reverse(), + startDate: '2024-01-02T09:30:00.123-05:00', + }, + retained + ) + ).toBeNull(); + }); + + test('subsets, cropped bounds, different policies, intervals and explicit providers cannot reuse a hash', () => { + const selected = retainedDatasetSelection(retained); + for (const change of [ + { symbols: ['AAPL.US'] }, + { startDate: '2024-01-02T14:30:00.124Z' }, + { endDate: '2024-01-02T20:59:59.998Z' }, + { priceAdjustment: 'raw' as const }, + { dataFrequency: '5m' as const }, + { dataSource: 'eod' as const }, + ]) { + expect(historicalSelectionError({ ...selected, ...change }, retained)).toContain( + 'do not match' + ); + } + }); + + test('unresolved, missing, unsupported and invalid retained selections remain blocked', () => { + const selected = retainedDatasetSelection(retained); + expect(historicalSelectionError(selected)).toContain('wait for its metadata'); + expect(historicalSelectionError(selected, { ...retained, hash: 'b'.repeat(64) })).toContain( + 'wait for its metadata' + ); + expect( + historicalSelectionError(selected, { + ...retained, + status: 'invalid', + reason: 'Invalid metadata', + }) + ).toBe('Invalid metadata'); + expect( + historicalSelectionError(selected, { + ...retained, + status: 'unsupported', + version: 2, + manifest: null, + reason: 'Version 2 is unsupported', + }) + ).toBe('Version 2 is unsupported'); + expect(selected.datasetHash).toBe(hash); + }); + + test('source requests need no catalog and retain the selected source and exact range', () => { + const selected = { + ...retainedDatasetSelection(retained), + datasetHash: undefined, + dataSource: 'questdb' as const, + }; + expect(historicalSelectionError(selected)).toBeNull(); + expect(selected.startDate).toBe(retained.manifest!.startDate); + expect(historicalSelectionError({ ...selected, symbols: [] })).toContain('one or more'); + expect(historicalSelectionError({ ...selected, startDate: '2024-01-02T14:30:00' })).toContain( + 'explicit UTC offset' + ); + }); +}); + +describe('historical picker interactions', () => { + const browser = new GlobalWindow({ url: 'http://localhost:5173' }); + const globals = ['window', 'document', 'IS_REACT_ACT_ENVIRONMENT'] as const; + const originalGlobals = new Map( + globals.map(key => [key, Object.getOwnPropertyDescriptor(globalThis, key)]) + ); + let createRoot: typeof import('react-dom/client').createRoot; + let HistoricalDataSelection: typeof import('../../apps/stock/web-app/src/features/backtest/components/HistoricalDataSelection').HistoricalDataSelection; + let root: Root; + let host: HTMLDivElement; + let current: HistoricalSelection; + let valid = false; + type BrowserResponse = Awaited>; + const requests: { path: string; done: boolean; reply: (response: BrowserResponse) => void }[] = + []; + + const flush = async (action: () => void) => { + await act(async () => { + action(); + await Promise.resolve(); + }); + }; + const respond = async (path: string, body: object, status = 200) => { + const request = requests.find(item => item.path === path && !item.done); + if (!request) { + throw new Error(`No pending request for ${path}`); + } + await flush(() => { + request.done = true; + request.reply(browser.Response.json(body, { status })); + }); + }; + const select = async (label: string, value: string) => { + const element = host.querySelector(`select[aria-label="${label}"]`) as HTMLSelectElement; + await flush(() => { + element.value = value; + element.dispatchEvent(new browser.Event('change', { bubbles: true }) as unknown as Event); + }); + }; + function Picker({ initial }: { initial: HistoricalSelection }) { + const [selection, setSelection] = useState(initial); + current = selection; + return createElement(HistoricalDataSelection, { + value: selection, + onChange: setSelection, + onValidityChange: value => { + valid = value; + }, + }); + } + async function mount(initial: HistoricalSelection) { + await flush(() => root.render(createElement(Picker, { initial }))); + } + + beforeAll(async () => { + for (const [key, value] of Object.entries({ + window: browser, + document: browser.document, + IS_REACT_ACT_ENVIRONMENT: true, + })) { + Object.defineProperty(globalThis, key, { configurable: true, writable: true, value }); + } + ({ createRoot } = await import('react-dom/client')); + ({ HistoricalDataSelection } = await import( + '../../apps/stock/web-app/src/features/backtest/components/HistoricalDataSelection' + )); + }); + beforeEach(() => { + requests.length = 0; + valid = false; + host = browser.document.createElement('div') as unknown as HTMLDivElement; + browser.document.body.append(host as never); + root = createRoot(host); + browser.fetch = input => + new Promise(reply => { + const url = new URL(String(input)); + requests.push({ path: `${url.pathname}${url.search}`, done: false, reply }); + }); + }); + afterEach(async () => { + await flush(() => root.unmount()); + host.remove(); + }); + afterAll(() => { + for (const key of globals) { + const original = originalGlobals.get(key); + if (original) { + Object.defineProperty(globalThis, key, original); + } else { + Reflect.deleteProperty(globalThis, key); + } + } + void browser.happyDOM.abort(); + }); + + test('choosing a snapshot applies its exact settings and locks data fields', async () => { + await mount({ + ...retainedDatasetSelection(retained), + datasetHash: undefined, + dataSource: 'eod', + }); + await respond('/api/v2/datasets?limit=50&offset=0', { datasets: [retained] }); + await select('Historical data input', 'frozen'); + expect(valid).toBe(false); + await select('Frozen dataset', hash); + expect(valid).toBe(true); + expect(current).toEqual(retainedDatasetSelection(retained)); + expect(host.querySelector('fieldset')?.disabled).toBe(true); + expect(host.textContent).toContain('Coverage: unknown'); + expect(host.textContent).toContain('not verified by this catalog'); + await select('Historical data input', 'source'); + expect(current.datasetHash).toBeUndefined(); + expect(host.querySelector('fieldset')?.disabled).toBe(false); + expect(valid).toBe(true); + }); + + test('a saved selection outside the catalog page loads by hash and remains blocked until resolved', async () => { + await mount(retainedDatasetSelection(retained)); + expect(valid).toBe(false); + await respond('/api/v2/datasets?limit=50&offset=0', { datasets: [] }); + // Replacing the catalog aborts/restarts any earlier detail lookup. A stale + // reply must not make the selected dataset eligible. + await respond(`/api/v2/datasets/${hash}`, { dataset: retained }); + expect(valid).toBe(false); + await respond(`/api/v2/datasets/${hash}`, { dataset: retained }); + expect(valid).toBe(true); + expect(current.datasetHash).toBe(hash); + expect(host.querySelector('select[aria-label="Frozen dataset"]')?.textContent).toContain(hash); + }); + + test('missing selected metadata never clears the hash and a successful retry restores eligibility', async () => { + await mount(retainedDatasetSelection(retained)); + await respond(`/api/v2/datasets/${hash}`, { error: 'Frozen dataset not found' }, 404); + expect(valid).toBe(false); + expect(current.datasetHash).toBe(hash); + expect(host.textContent).toContain('Frozen dataset not found'); + await respond('/api/v2/datasets?limit=50&offset=0', { datasets: [] }); + await respond(`/api/v2/datasets/${hash}`, { error: 'Frozen dataset not found' }, 404); + const retry = [...host.querySelectorAll('button')].find( + button => button.textContent === 'Retry datasets' + )!; + await flush(() => retry.click()); + await respond(`/api/v2/datasets/${hash}`, { dataset: retained }); + expect(valid).toBe(true); + expect(current.datasetHash).toBe(hash); + }); + + test('catalog failure and late lookup failure cannot prevent a source request', async () => { + await mount(retainedDatasetSelection(retained)); + await select('Historical data input', 'source'); + await respond('/api/v2/datasets?limit=50&offset=0', { error: 'Catalog unavailable' }, 503); + await respond(`/api/v2/datasets/${hash}`, { error: 'Late missing dataset' }, 404); + expect(valid).toBe(true); + expect(current.datasetHash).toBeUndefined(); + expect(host.textContent).not.toContain('Late missing dataset'); + await select('Historical source', 'questdb'); + expect(current.dataSource).toBe('questdb'); + expect(valid).toBe(true); + }); + + test('unsupported catalog versions are visible but not selectable', async () => { + await mount({ ...retainedDatasetSelection(retained), datasetHash: '' }); + const unsupported = { + ...retained, + hash: 'b'.repeat(64), + status: 'unsupported', + version: 2, + manifest: null, + reason: 'Version 2 needs a canonical run', + }; + await respond('/api/v2/datasets?limit=50&offset=0', { datasets: [unsupported] }); + const option = host.querySelector(`option[value="${unsupported.hash}"]`) as HTMLOptionElement; + expect(option.disabled).toBe(true); + expect(option.textContent).toContain('Version 2 needs a canonical run'); + expect(valid).toBe(false); + }); +}); + +describe('persisted run dataset presentation', () => { + test('pending source requests are unpinned and awaiting asynchronous preparation', () => { + for (const source of ['eod', 'auto'] as const) { + const requested = renderToStaticMarkup( + createElement(RunDataset, { + dataset: { requestedHash: null, pinnedHash: null, source, state: 'requested' }, + }) + ); + expect(requested).toContain(`Source request (${source})`); + expect(requested).toContain('unpinned'); + expect(requested).toContain('will be prepared asynchronously'); + expect(requested).not.toContain('is preparing'); + expect(requested).not.toContain('provenance is unavailable'); + expect(requested).not.toContain('Pinned dataset hash'); + } + }); + + test('source_request_freeze_status differentiates preparation from a bound hash', () => { + const preparing = renderToStaticMarkup( + createElement(RunDataset, { + dataset: { + requestedHash: null, + pinnedHash: null, + source: 'questdb', + state: 'preparing', + }, + }) + ); + expect(preparing).toContain('unpinned'); + expect(preparing).toContain('questdb'); + expect(preparing).not.toContain('Pinned dataset hash'); + const pinned = renderToStaticMarkup( + createElement(RunDataset, { + dataset: { + requestedHash: null, + pinnedHash: hash, + source: 'questdb', + state: 'pinned', + }, + }) + ); + expect(pinned).toContain(`Pinned dataset hash: ${hash}`); + expect(pinned).not.toContain('succeeded'); + }); + + test('requested, failed preparation and legacy unknown provenance are never presented as pinned', () => { + for (const state of ['requested', 'unavailable'] as const) { + const html = renderToStaticMarkup( + createElement(RunDataset, { + dataset: { + requestedHash: hash, + pinnedHash: null, + source: 'auto', + state, + }, + }) + ); + expect(html).toContain('Requested frozen dataset hash'); + expect(html).not.toContain('Pinned dataset hash'); + expect(html).toContain(state === 'unavailable' ? 'unavailable' : 'Waiting'); + } + expect(renderToStaticMarkup(createElement(RunDataset))).toContain('provenance is unavailable'); + }); +}); diff --git a/test/integration/ingestion-backtest.test.ts b/test/integration/ingestion-backtest.test.ts index b1630cf5..7f630e62 100644 --- a/test/integration/ingestion-backtest.test.ts +++ b/test/integration/ingestion-backtest.test.ts @@ -40,8 +40,11 @@ function memoryStore() { const index = documents.findIndex( old => old.date === row.date && old.eodSearchCode === row.eodSearchCode ); - if (index >= 0) documents[index] = row; - else documents.push(row); + if (index >= 0) { + documents[index] = row; + } else { + documents.push(row); + } } return { insertedCount: rows.length, @@ -175,6 +178,30 @@ describe('deterministic ingestion → storage → native backtest', () => { expect(a.manifest.hash).not.toBe(b.manifest.hash); }); + test('explicit source requests reach storage and cannot silently reuse another provider', async () => { + const { mongodb } = memoryStore(); + await persistEodPrices(mongodb, identity, fixture); + const storage = new StorageService({ logger }, mongodb, null, null); + const providers: unknown[] = []; + const selected = await loadDataset( + { + getHistoricalBars: (...args: Parameters) => { + providers.push(args[6]); + return storage.getHistoricalBars(...args); + }, + }, + { ...datasetConfig(), dataSource: 'eod' } + ); + expect(providers).toEqual(['eod']); + expect(selected.manifest.sources.map(source => source.provider)).toEqual(['eod']); + expect(() => validateDataset(selected, { ...datasetConfig(), dataSource: 'questdb' })).toThrow( + 'does not match' + ); + await expect( + loadDataset(storage, { ...datasetConfig(), dataSource: 'questdb' }) + ).rejects.toThrow(); + }); + test('missing provider factors cannot silently turn adjusted requests into raw data', async () => { const { mongodb } = memoryStore(); await persistEodPrices(mongodb, identity, [fixture[0]!]); diff --git a/test/postgres/dataset-catalog.test.ts b/test/postgres/dataset-catalog.test.ts new file mode 100644 index 00000000..af122e1a --- /dev/null +++ b/test/postgres/dataset-catalog.test.ts @@ -0,0 +1,346 @@ +import { randomUUID } from 'node:crypto'; +import { readFileSync } from 'node:fs'; +import { afterEach, describe, expect, test } from 'bun:test'; +import { Hono } from 'hono'; +import { Pool } from 'pg'; +import { getLogger, setLoggerConfig } from '@stock-bot/logger'; +import { PostgreSQLClient } from '@stock-bot/postgres'; +import type { HistoricalDatasetManifest } from '@stock-bot/types'; +import { createDatasetRoutes } from '../../apps/stock/web-api/src/routes/datasets.routes'; +import { + BacktestServiceV2, + type BacktestRequest, +} from '../../apps/stock/web-api/src/services/backtest-v2.service'; +import { DatasetCatalogService } from '../../apps/stock/web-api/src/services/dataset-catalog.service'; + +setLoggerConfig({ logLevel: 'fatal', logConsole: false }); +const logger = getLogger('dataset-catalog-test'); +const url = process.env.PIPELINE_TEST_DATABASE_URL; +const cleanup: (() => Promise)[] = []; +afterEach(async () => { + for (const close of cleanup.splice(0).reverse()) { + await close(); + } +}); +const hash = '1'.repeat(64); +const manifest = (key = hash): HistoricalDatasetManifest => ({ + version: 1, + hash: key, + instruments: [{ id: 'FIXTURE.TEST', symbol: 'FIXTURE', exchange: 'TEST' }], + startDate: '2024-01-01T00:00:00.000Z', + endDate: '2024-01-03T00:00:00.000Z', + interval: '1d', + policy: { adjustment: 'raw', timestamp: 'utc-session-date' }, + volumePolicy: 'reported', + qualityPolicy: 'reject-invalid-no-interpolation', + sources: [{ instrumentId: 'FIXTURE.TEST', provider: 'eod', revision: 'fixture-v1' }], + barCount: 1, +}); +const request = (): BacktestRequest => ({ + name: 'Dataset choice', + strategy: 'sma-crossover', + symbols: ['FIXTURE.TEST'], + startDate: manifest().startDate, + endDate: manifest().endDate, + initialCapital: 1000, + config: { fastPeriod: 2, slowPeriod: 3, datasetHash: hash, dataFrequency: '1d' }, +}); +async function fixture() { + if (!url || !new URL(url).pathname.startsWith('/stock_bot_safety')) { + throw new Error('Dedicated stock_bot_safety database required'); + } + const schema = 'stock_bot_safety_' + randomUUID().replaceAll('-', ''); + const admin = new Pool({ connectionString: url }); + await admin.query(`CREATE SCHEMA ${schema}`); + const pool = new Pool({ + connectionString: url, + application_name: schema, + options: `-c search_path=${schema} -c statement_timeout=10000`, + }); + cleanup.push(async () => { + await pool.end(); + await admin.query(`DROP SCHEMA ${schema} CASCADE`); + await admin.end(); + }); + for (const name of [ + '06-create-backtest-tables.sql', + '08-create-runs-table.sql', + '09-backtest-run-contract.sql', + '10-durable-backtest-dispatch.sql', + '12-historical-datasets.sql', + '14-backtest-submission.sql', + ]) { + await pool.query( + readFileSync(new URL(`../../database/postgres/init/${name}`, import.meta.url), 'utf8') + ); + } + const postgres = new PostgreSQLClient( + { host: 'unused', port: 5432, database: 'unused', username: 'unused', password: 'unused' }, + logger + ); + Object.defineProperty(postgres, 'connectionPool', { get: () => pool }); + Object.defineProperty(postgres, 'query', { value: pool.query.bind(pool) }); + const insert = async (key: string, payload: unknown) => + pool.query( + "INSERT INTO backtest_datasets(hash,payload,created_at) VALUES($1,$2::jsonb,'2024-02-01T00:00:00Z')", + [key, JSON.stringify(payload)] + ); + const api = new BacktestServiceV2({ postgres, logger }, async () => { + throw new Error('Catalog must not fetch source data'); + }); + return { + pool, + schema, + postgres, + api, + insert, + catalog: new DatasetCatalogService(postgres), + routes: new Hono().route('/', createDatasetRoutes({ postgres, logger })), + }; +} + +describe.skipIf(!url)('dataset catalog and selected-run submission on real PostgreSQL', () => { + test('dataset_list_metadata_only projects no bars and diagnoses malformed shapes without SQL errors', async () => { + const f = await fixture(); + await f.insert(hash, { + manifest: manifest(), + bars: [{ payloadMustStayInPostgres: 'SECRET_BAR_CONTENT' }], + }); + const cases = [ + null, + [], + 'malformed', + { manifest: manifest('2'.repeat(64)), bars: {} }, + { manifest: manifest('3'.repeat(64)), bars: [] }, + { manifest: manifest('4'.repeat(64)), bars: [1], extra: true }, + { manifest: { version: 2 }, bars: [] }, + ]; + for (let index = 0; index < cases.length; index++) { + await f.insert(String(index + 2).repeat(64), cases[index]); + } + const result = await f.routes.request('/api/v2/datasets'); + expect(result.status).toBe(200); + const body = await result.json(); + expect(body.datasets).toHaveLength(8); + expect(body.datasets[0]).toMatchObject({ + hash, + status: 'available', + coverage: 'unknown', + integrity: 'not-verified', + manifest: { barCount: 1 }, + }); + expect(body.datasets.at(-1)).toMatchObject({ + version: 2, + status: 'unsupported', + manifest: null, + }); + expect(body.datasets.at(-1).reason).toContain('R05'); + expect(JSON.stringify(body)).not.toContain('SECRET_BAR_CONTENT'); + expect(JSON.stringify(body)).not.toContain('"bars"'); + for (const item of body.datasets.slice(1, -1)) { + expect(item.status).toBe('invalid'); + } + const queries: string[] = []; + const projected = new DatasetCatalogService({ + async query(text, values) { + queries.push(text); + const rows = await f.pool.query(text, values); + expect(rows.rows[0]).not.toHaveProperty('payload'); + expect(rows.rows[0]).not.toHaveProperty('bars'); + expect(rows.rows[0].bar_count).toBe(1); + return rows; + }, + }); + await projected.get(hash); + expect(queries[0]).not.toContain('SELECT *'); + expect(queries[0]).toContain("payload->'manifest' AS manifest"); + expect((await f.routes.request('/api/v2/datasets?limit=1&offset=1')).status).toBe(200); + expect((await f.routes.request(`/api/v2/datasets/${'f'.repeat(64)}`)).status).toBe(404); + expect((await f.routes.request('/api/v2/datasets/not-a-hash')).status).toBe(400); + }); + + test('select_hash_compatibility validates exact assets, interval, range, policy and explicit source on create and update', async () => { + const f = await fixture(); + await f.insert(hash, { manifest: manifest(), bars: [{}] }); + const saved = await f.api.createBacktest(request(), { autoStart: false }); + for (const changed of [ + { symbols: ['OTHER.TEST'] }, + { startDate: '2024-01-02T00:00:00.000Z' }, + { endDate: '2024-01-04T00:00:00.000Z' }, + { config: { ...request().config, dataFrequency: '1h' } }, + { + config: { + ...request().config, + dataPolicy: { adjustment: 'provider-adjusted', timestamp: 'utc-session-date' }, + }, + }, + { config: { ...request().config, dataSource: 'questdb' } }, + ]) { + await expect( + f.api.createBacktest({ ...request(), ...changed }, { autoStart: false }) + ).rejects.toThrow('does not match'); + await expect(f.api.updateBacktest(saved.id, changed)).rejects.toThrow('does not match'); + } + expect((await f.api.getBacktest(saved.id))!.config).toEqual(request().config!); + expect((await f.pool.query('SELECT count(*)::int AS n FROM backtests')).rows[0].n).toBe(1); + for (const dataSource of ['eod', 'auto']) { + await expect( + f.api.updateBacktest(saved.id, { config: { ...request().config, dataSource } }) + ).resolves.not.toBeNull(); + } + }); + + test('missing, inconsistent, malformed and unsupported selected snapshots reject before any run/outbox is inserted', async () => { + const f = await fixture(); + const saved = await f.api.createBacktest( + { ...request(), config: { fastPeriod: 2, slowPeriod: 3 } }, + { autoStart: false } + ); + const payloads = [ + { manifest: manifest('f'.repeat(64)), bars: [{}] }, + { manifest: { ...manifest(), barCount: 2 }, bars: [{}] }, + { manifest: { ...manifest(), sources: [] }, bars: [{}] }, + { manifest: { version: 2 }, bars: [] }, + ]; + for (const payload of payloads) { + await f.pool.query('DELETE FROM backtest_datasets'); + await f.insert(hash, payload); + await f.pool.query('UPDATE backtests SET config=$2 WHERE id=$1', [ + saved.id, + JSON.stringify(request().config), + ]); + await expect(f.api.createRun({ backtestId: saved.id })).rejects.toThrow(); + } + await f.pool.query('DELETE FROM backtest_datasets'); + await expect(f.api.createRun({ backtestId: saved.id })).rejects.toThrow('not found'); + expect((await f.pool.query('SELECT count(*)::int AS n FROM runs')).rows[0].n).toBe(0); + expect((await f.pool.query('SELECT count(*)::int AS n FROM backtest_dispatch')).rows[0].n).toBe( + 0 + ); + }); + + test('concurrent partial definition edits lock, merge and validate one committed definition', async () => { + const f = await fixture(); + await f.insert(hash, { manifest: manifest(), bars: [{}] }); + const saved = await f.api.createBacktest({ ...request(), config: {} }, { autoStart: false }); + const blocker = await f.pool.connect(); + await blocker.query('BEGIN'); + await blocker.query('LOCK TABLE backtest_datasets IN ACCESS EXCLUSIVE MODE'); + const selected = f.api.updateBacktest(saved.id, { config: request().config }).then( + value => ({ value, error: null }), + error => ({ value: null, error }) + ); + const isWaiting = async (pattern: string) => { + for (let attempt = 0; attempt < 100; attempt++) { + const result = await f.pool.query( + "SELECT 1 FROM pg_stat_activity WHERE application_name=$1 AND wait_event_type='Lock' AND query LIKE $2", + [f.schema, pattern] + ); + if (result.rowCount) { + return true; + } + await new Promise(resolve => setTimeout(resolve, 5)); + } + return false; + }; + let catalogWait = false; + let definitionWait = false; + let changed: typeof selected | undefined; + try { + catalogWait = await isWaiting('%FROM backtest_datasets%'); + changed = f.api.updateBacktest(saved.id, { endDate: '2024-01-04T00:00:00.000Z' }).then( + value => ({ value, error: null }), + error => ({ value: null, error }) + ); + definitionWait = await isWaiting('SELECT * FROM backtests WHERE id = $1 FOR UPDATE'); + } finally { + await blocker.query('COMMIT'); + blocker.release(); + } + const winner = await selected; + if (!changed) { + throw new Error('Concurrent edit was not started'); + } + const loser = await changed; + expect(catalogWait).toBe(true); + expect(definitionWait).toBe(true); + expect(winner.error).toBeNull(); + expect(loser.error).toBeInstanceOf(Error); + expect(loser.error!.message).toContain('does not match'); + const retained = await f.api.getBacktest(saved.id); + expect(retained!.endDate.toISOString()).toBe(manifest().endDate); + expect(retained!.config.datasetHash).toBe(hash); + expect((await f.api.createRun({ backtestId: saved.id })).dataset.requestedHash).toBe(hash); + }); + + test('selected run snapshots commit atomically and same-key retry returns its original receipt before mutable definition validation', async () => { + const f = await fixture(); + await f.insert(hash, { manifest: manifest(), bars: [{}] }); + const saved = await f.api.createBacktest(request(), { autoStart: false }); + await f.pool.query( + `CREATE FUNCTION reject_dataset_outbox() RETURNS trigger LANGUAGE plpgsql AS $$ BEGIN RAISE EXCEPTION 'injected outbox failure'; END $$; CREATE TRIGGER reject_dataset_outbox BEFORE INSERT ON backtest_dispatch FOR EACH ROW EXECUTE FUNCTION reject_dataset_outbox()` + ); + await expect(f.api.createRun({ backtestId: saved.id })).rejects.toThrow( + 'injected outbox failure' + ); + expect((await f.pool.query('SELECT count(*)::int AS n FROM runs')).rows[0].n).toBe(0); + await f.pool.query('DROP TRIGGER reject_dataset_outbox ON backtest_dispatch'); + const submission = { principal: 'operator' as const, key: 'dataset-retry' }; + const first = await f.api.createRun({ backtestId: saved.id }, submission); + expect(first.dataset).toEqual({ + requestedHash: hash, + pinnedHash: null, + source: 'auto', + state: 'requested', + }); + await f.pool.query( + 'UPDATE backtests SET symbols=\'["OTHER.TEST"]\',config=\'{"datasetHash":"bad"}\' WHERE id=$1', + [saved.id] + ); + await f.pool.query('DELETE FROM backtest_datasets'); + const retried = await f.api.createRun({ backtestId: saved.id }, submission); + expect(retried.id).toBe(first.id); + expect(retried.dataset).toEqual(first.dataset); + expect((await f.pool.query('SELECT count(*)::int AS n FROM backtest_dispatch')).rows[0].n).toBe( + 1 + ); + await expect( + f.api.createRun({ backtestId: saved.id }, { ...submission, key: 'different' }) + ).rejects.toThrow(); + }); + + test('source_request_freeze_status exposes immutable request and binding independently of run success or later template edits', async () => { + const f = await fixture(); + await f.insert(hash, { manifest: manifest(), bars: [{}] }); + const saved = await f.api.createBacktest( + { ...request(), config: { dataSource: 'eod' } }, + { autoStart: false } + ); + const run = await f.api.createRun({ backtestId: saved.id }); + expect(run.dataset).toEqual({ + requestedHash: null, + pinnedHash: null, + source: 'eod', + state: 'requested', + }); + await f.pool.query("UPDATE runs SET status='running' WHERE id=$1", [run.id]); + expect((await f.api.getRun(run.id))!.dataset.state).toBe('preparing'); + await f.pool.query("UPDATE runs SET status='failed' WHERE id=$1", [run.id]); + expect((await f.api.getRun(run.id))!.dataset.state).toBe('unavailable'); + await f.pool.query('UPDATE runs SET dataset_hash=$2 WHERE id=$1', [run.id, hash]); + await f.pool.query('UPDATE backtests SET config=\'{"dataSource":"questdb"}\' WHERE id=$1', [ + saved.id, + ]); + expect(await f.api.getRun(run.id)).toMatchObject({ + status: 'failed', + dataset: { requestedHash: null, pinnedHash: hash, source: 'eod', state: 'pinned' }, + }); + await f.pool.query('UPDATE runs SET request_snapshot=NULL WHERE id=$1', [run.id]); + expect((await f.api.getRun(run.id))!.dataset).toEqual({ + requestedHash: null, + pinnedHash: hash, + source: null, + state: 'unknown', + }); + }); +});