feat(research): select and reuse frozen datasets in workbench
This commit is contained in:
parent
6a67ae8683
commit
b106c1ca85
29 changed files with 2295 additions and 426 deletions
|
|
@ -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;
|
||||
}
|
||||
|
|
|
|||
43
apps/stock/web-api/src/routes/datasets.routes.ts
Normal file
43
apps/stock/web-api/src/routes/datasets.routes.ts
Normal file
|
|
@ -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;
|
||||
}
|
||||
|
|
@ -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<Backtest> {
|
||||
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<BacktestRequest>): Promise<Backtest | null> {
|
||||
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<Backtest[]> {
|
||||
|
|
@ -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',
|
||||
};
|
||||
}
|
||||
|
|
|
|||
130
apps/stock/web-api/src/services/dataset-catalog.service.ts
Normal file
130
apps/stock/web-api/src/services/dataset-catalog.service.ts
Normal file
|
|
@ -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<HistoricalDatasetCatalogEntry[]> {
|
||||
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<HistoricalDatasetCatalogEntry | null> {
|
||||
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<void> {
|
||||
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);
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue