From cd1aa6148119ea364de52bcfb4cfa1bac8259ca9 Mon Sep 17 00:00:00 2001 From: Boki Date: Wed, 28 Oct 2026 13:48:41 -0400 Subject: [PATCH] fix(api): reject retired backtest creation before writes (CL23) --- .../web-api/src/routes/backtest.routes.ts | 9 +- .../web-api/src/routes/backtests-v2.routes.ts | 2 +- .../src/services/backtest-v2.service.ts | 2 +- .../web-api/src/services/backtest.service.ts | 23 +- .../src/services/backtests/templates.ts | 32 +-- .../architecture-cleanup-execution.md | 2 + docs/development/backlog/README.md | 2 +- docs/development/backlog/manifest.json | 12 +- docs/development/backlog/tasks/CL23.md | 4 + test/integration/retired-backtest-api.test.ts | 257 ++++++++++++++++++ 10 files changed, 297 insertions(+), 48 deletions(-) create mode 100644 test/integration/retired-backtest-api.test.ts diff --git a/apps/stock/web-api/src/routes/backtest.routes.ts b/apps/stock/web-api/src/routes/backtest.routes.ts index 97dcaedb..58058fe8 100644 --- a/apps/stock/web-api/src/routes/backtest.routes.ts +++ b/apps/stock/web-api/src/routes/backtest.routes.ts @@ -2,7 +2,7 @@ import { Hono } from 'hono'; import type { IServiceContainer } from '@stock-bot/handlers'; import { getLogger } from '@stock-bot/logger'; import { isBacktestRequestError } from '@stock-bot/stock-config/backtest'; -import { BacktestService } from '../services/backtest.service'; +import { BacktestService, LegacyBacktestCreationRetiredError } from '../services/backtest.service'; const logger = getLogger('backtest-routes'); @@ -10,7 +10,7 @@ export function createBacktestRoutes(container: IServiceContainer) { const backtestRoutes = new Hono(); const backtestService = new BacktestService(container); - // Create a new backtest + // Retired creation remains an explicit diagnostic for old clients. backtestRoutes.post('/api/backtests', async c => { try { const body = await c.req.json(); @@ -32,10 +32,13 @@ export function createBacktestRoutes(container: IServiceContainer) { return c.json(backtest, 201); } catch (error) { - logger.error('Failed to create backtest', { error }); + if (error instanceof LegacyBacktestCreationRetiredError) { + return c.json({ code: error.code, error: error.message }, 410); + } if (isBacktestRequestError(error)) { return c.json({ error: error.message }, 400); } + logger.error('Failed to create backtest', { error }); return c.json({ error: 'Failed to create backtest' }, 500); } }); diff --git a/apps/stock/web-api/src/routes/backtests-v2.routes.ts b/apps/stock/web-api/src/routes/backtests-v2.routes.ts index 47f85395..3e195090 100644 --- a/apps/stock/web-api/src/routes/backtests-v2.routes.ts +++ b/apps/stock/web-api/src/routes/backtests-v2.routes.ts @@ -66,7 +66,7 @@ export function createBacktestV2Routes(container: IServiceContainer) { if (body.autoStart !== undefined && typeof body.autoStart !== 'boolean') { return c.json({ error: 'autoStart must be a boolean' }, 400); } - // Omitted autoStart preserves legacy clients. New web clients explicitly save only. + // Saving requires explicit autoStart:false; run submission is a separate operation. const { autoStart, ...definition } = body; const backtest = await backtestService.createBacktest(definition, { autoStart }); return c.json(backtest, 201); 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 2c69f1c9..99d7de89 100644 --- a/apps/stock/web-api/src/services/backtest-v2.service.ts +++ b/apps/stock/web-api/src/services/backtest-v2.service.ts @@ -34,7 +34,7 @@ export class BacktestServiceV2 { ) { const services = requireServices(container, 'postgres'); this.runs = new BacktestRuns(services, request); - this.templates = new BacktestTemplates(services, input => this.runs.createRun(input)); + this.templates = new BacktestTemplates(services); this.results = new BacktestResults(services); this.reproduction = new BacktestReproduction(services, this.results); } diff --git a/apps/stock/web-api/src/services/backtest.service.ts b/apps/stock/web-api/src/services/backtest.service.ts index 702db0bf..eeeef9fd 100644 --- a/apps/stock/web-api/src/services/backtest.service.ts +++ b/apps/stock/web-api/src/services/backtest.service.ts @@ -30,7 +30,16 @@ export interface BacktestJob { error?: string; } -/** Compatibility facade: V1 uses the same definitions, runs, and result reader as V2. */ +export class LegacyBacktestCreationRetiredError extends Error { + readonly code = 'legacy_backtest_creation_retired'; + constructor() { + super( + 'Legacy backtest creation is retired. Create a catalog template with POST /api/v2/backtests, then submit a run through its /runs endpoint.' + ); + } +} + +/** Historical V1 reads and cancellation use the same saved records as V2. */ export class BacktestService { private readonly service: BacktestServiceV2; constructor(container: IServiceContainer, request?: BacktestTransport) { @@ -39,15 +48,9 @@ export class BacktestService { async createBacktest(request: BacktestRequest): Promise { rejectCatalogVersionReferences(request); - const backtest = await this.service.createBacktest( - { - ...request, - name: typeof request.config?.name === 'string' ? request.config.name : 'Backtest', - }, - { autoStart: false } - ); - const run = await this.service.createRun({ backtestId: backtest.id, speedMultiplier: null }); - return this.toJob(backtest, run); + // Reject before saving a template: no legacy definition can execute, and a + // failure after its commit would leave an orphan on every client retry. + throw new LegacyBacktestCreationRetiredError(); } async getBacktest(id: string): Promise { const backtest = await this.service.getBacktest(id); diff --git a/apps/stock/web-api/src/services/backtests/templates.ts b/apps/stock/web-api/src/services/backtests/templates.ts index f25acde3..53394a79 100644 --- a/apps/stock/web-api/src/services/backtests/templates.ts +++ b/apps/stock/web-api/src/services/backtests/templates.ts @@ -1,7 +1,6 @@ import { randomUUID as uuidv4 } from 'node:crypto'; import type { PoolClient } from 'pg'; import { at } from '@stock-bot/invariants'; -import { getLogger } from '@stock-bot/logger'; import { backtestRequestFromDefinition, backtestSettingsFromDefinition, @@ -23,19 +22,12 @@ import { type Backtest, type BacktestContainer, type BacktestRequest, - type Run, - type RunRequest, } from './contracts'; import { mapBacktest } from './mapping'; -const logger = getLogger('backtest-v2-service'); - /** Focused templates operations; transaction order is preserved. */ export class BacktestTemplates { - constructor( - private readonly container: BacktestContainer, - private readonly startRun: (request: RunRequest) => Promise - ) {} + constructor(private readonly container: BacktestContainer) {} async createBacktest( request: BacktestRequest, options: { autoStart?: boolean } = {} @@ -46,6 +38,9 @@ export class BacktestTemplates { } if (!catalog) { rejectCatalogVersionReferences(request); + if (options.autoStart !== false) { + throw new HistoricalDataRequestError('Backtest drafts require explicit autoStart:false'); + } } const backtestId = uuidv4(); const result = await this.container.postgres.transaction(async client => { @@ -76,24 +71,7 @@ export class BacktestTemplates { ); }); - const backtest = mapBacktest(at(result.rows, 0)); - - // Automatically create and start a run for the new backtest - if (options.autoStart !== false) { - try { - await this.startRun({ - backtestId: backtest.id, - speedMultiplier: null, // Max speed (instant) - }); - } catch (error) { - logger.error('Failed to auto-create run for new backtest', { - backtestId: backtest.id, - error, - }); - // Don't fail the backtest creation if run creation fails - } - } - return backtest; + return mapBacktest(at(result.rows, 0)); } async getBacktest(id: string): Promise { diff --git a/docs/development/architecture-cleanup-execution.md b/docs/development/architecture-cleanup-execution.md index 318ec7f2..9d4db7f6 100644 --- a/docs/development/architecture-cleanup-execution.md +++ b/docs/development/architecture-cleanup-execution.md @@ -11,3 +11,5 @@ Agents use root-reserved disjoint files in the integration worktree. Root alone - **CL24:** Root reviewed route compatibility, removed demo-only consumers and real App rendering. Focused home/navigation tests passed; scoped lint/format passed. Final browser gate pending combined source. - **CL22:** Queue library tsc build passed; independent root queue-lifecycle and cache-ownership suites passed (see /tmp/stock-bot-cl22-root.log). Scoped lint/format passed. Pending payload ownership, drain behavior, and connection cleanup covered without service mutation. + +- **CL23:** Independent root retired-backtest-api, catalog-backtest-contract and backtest-result-mapping suites: 16 passed, 125 assertions. Scoped lint/format passed. Regression verifies no writes on retired V1/implicit autostart, explicit save-only behavior and preserved historical read/cancellation. diff --git a/docs/development/backlog/README.md b/docs/development/backlog/README.md index 39f55230..870ae2f4 100644 --- a/docs/development/backlog/README.md +++ b/docs/development/backlog/README.md @@ -1,6 +1,6 @@ # Canonical development backlog -**Active: E13 architecture cleanup, CL22–CL35 (2/14 complete).** Owner authorized all October 28 audit recommendations and a commit per validated task. Earlier completion counts below are historical. [Execution record](../architecture-cleanup-execution.md). +**Active: E13 architecture cleanup, CL22–CL35 (3/14 complete).** Owner authorized all October 28 audit recommendations and a commit per validated task. Earlier completion counts below are historical. [Execution record](../architecture-cleanup-execution.md). **Current scheduled backlog: 99/99 complete.** The owner resumed performance and authorized review of all seven conditions. P08 and O02 are implemented; five optional extensions remain deliberately deferred, and four merged IDs are redirects. This is not a claim that all 108 retained IDs were implemented. [Decisions, measurements and validation](../conditional-review.md). diff --git a/docs/development/backlog/manifest.json b/docs/development/backlog/manifest.json index d69de824..9034cbf6 100644 --- a/docs/development/backlog/manifest.json +++ b/docs/development/backlog/manifest.json @@ -3757,7 +3757,7 @@ "complexity": "M", "assignment": null, "write_locks": ["CL22"], - "completed_commit": null, + "completed_commit": "3fc0a272d8356fa1de98f703d4df763f4938547c", "blocker": null, "release_gates": [], "completion_evidence": "architecture-cleanup-execution.md", @@ -3770,7 +3770,7 @@ "epic": "E13", "priority": "P1", "severity": "High", - "status": "in_progress", + "status": "done", "dependencies": [], "decision_dependencies": [], "task_file": "backlog/tasks/CL23.md", @@ -3780,7 +3780,9 @@ "completed_commit": null, "blocker": null, "release_gates": [], - "completion_evidence": "architecture-cleanup-execution.md" + "completion_evidence": "architecture-cleanup-execution.md", + "integration_state": "accepted", + "validation": "Independent root retired-backtest-api, catalog-backtest-contract and backtest-result-mapping suites: 16 passed, 125 assertions. Scoped lint/format passed. Regression verifies no writes on retired V1/implicit autostart, explicit save-only behavior and preserved historical read/cancellation." }, { "id": "CL24", @@ -10385,7 +10387,7 @@ ], "work_policy": "Root integrates/commits reviewed tasks; agents own disjoint explicit files in the root integration worktree. Only root builds shared outputs and runs combined gates. No isolated native agent build claim.", "first_wave": ["CL22", "CL23", "CL24"], - "completed": 2, - "last_verification": "Queue library tsc build passed; independent root queue-lifecycle and cache-ownership suites passed (see /tmp/stock-bot-cl22-root.log). Scoped lint/format passed. Pending payload ownership, drain behavior, and connection cleanup covered without service mutation." + "completed": 3, + "last_verification": "Independent root retired-backtest-api, catalog-backtest-contract and backtest-result-mapping suites: 16 passed, 125 assertions. Scoped lint/format passed. Regression verifies no writes on retired V1/implicit autostart, explicit save-only behavior and preserved historical read/cancellation." } } diff --git a/docs/development/backlog/tasks/CL23.md b/docs/development/backlog/tasks/CL23.md index 61675ba8..dc0035c2 100644 --- a/docs/development/backlog/tasks/CL23.md +++ b/docs/development/backlog/tasks/CL23.md @@ -18,3 +18,7 @@ Retired API/catalog regressions; v2 save/submit and retained readers. Focused re No new service/framework, financial simulator, real trading activation, external research execution, push/PR or .env changes. D04/P03/P05/P06/CL21 remain deferred. Root owns shared outputs, task state and commits; agents own disjoint files in the integration worktree. + +## Accepted verification + +Independent root retired-backtest-api, catalog-backtest-contract and backtest-result-mapping suites: 16 passed, 125 assertions. Scoped lint/format passed. Regression verifies no writes on retired V1/implicit autostart, explicit save-only behavior and preserved historical read/cancellation. diff --git a/test/integration/retired-backtest-api.test.ts b/test/integration/retired-backtest-api.test.ts new file mode 100644 index 00000000..1293bfe6 --- /dev/null +++ b/test/integration/retired-backtest-api.test.ts @@ -0,0 +1,257 @@ +import { expect, mock, test } from 'bun:test'; +import { Hono } from 'hono'; +import type { PoolClient } from 'pg'; +import { getLogger } from '@stock-bot/logger'; +import type { IServiceContainer } from '@stock-bot/services'; +import { createBacktestRoutes } from '../../apps/stock/web-api/src/routes/backtest.routes'; +import { createBacktestV2Routes } from '../../apps/stock/web-api/src/routes/backtests-v2.routes'; +import { BacktestServiceV2 } from '../../apps/stock/web-api/src/services/backtest-v2.service'; +import { BacktestService } from '../../apps/stock/web-api/src/services/backtest.service'; + +const input = { + strategy: 'sma-crossover', + symbols: ['AAPL.US'], + startDate: '2024-01-01T00:00:00.000Z', + endDate: '2024-02-01T00:00:00.000Z', + initialCapital: 10000, +}; +const logger = getLogger('retired-backtest-api-test'); +const retired = { + code: 'legacy_backtest_creation_retired', + error: + 'Legacy backtest creation is retired. Create a catalog template with POST /api/v2/backtests, then submit a run through its /runs endpoint.', +}; + +function forbiddenWork() { + const query = mock(async () => { + throw new Error('Unexpected database query'); + }); + const transaction = mock(async () => { + throw new Error('Unexpected database transaction'); + }); + const send = mock(async () => { + throw new Error('Unexpected queue dispatch'); + }); + const transport = mock(async () => { + throw new Error('Unexpected execution request'); + }); + const container = { + logger, + postgres: { query, transaction }, + queueManager: { send }, + } as unknown as IServiceContainer; + const expectUntouched = () => { + for (const operation of [query, transaction, send, transport]) { + expect(operation).not.toHaveBeenCalled(); + } + }; + return { container, transport, expectUntouched }; +} + +test('retired v1 creation returns 410 before any persistence or execution, including retries', async () => { + const fixture = forbiddenWork(); + const app = createBacktestRoutes(fixture.container); + for (let attempt = 0; attempt < 2; attempt++) { + const response = await app.request('/api/backtests', { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify(input), + }); + expect(response.status).toBe(410); + expect(await response.json()).toEqual(retired); + fixture.expectUntouched(); + } +}); + +test('direct legacy callers cannot save a template before execution rejection; catalog markers retain early validation', async () => { + const fixture = forbiddenWork(); + const service = new BacktestService(fixture.container, fixture.transport); + await expect(service.createBacktest(input)).rejects.toMatchObject({ + code: retired.code, + message: retired.error, + }); + for (const marker of [ + { strategy: 'catalog' }, + { strategyVersionId: null }, + { config: { strategyVersionId: null } }, + ]) { + const request = { ...input, ...marker }; + await expect(service.createBacktest(request)).rejects.toThrow('Retained strategy versions'); + const response = await createBacktestRoutes(fixture.container).request('/api/backtests', { + method: 'POST', + body: JSON.stringify(request), + }); + expect(response.status).toBe(400); + } + fixture.expectUntouched(); +}); + +test('v2 templates reject implicit and requested autostart before any writes', async () => { + const fixture = forbiddenWork(); + const service = new BacktestServiceV2(fixture.container, fixture.transport); + const app = createBacktestV2Routes(fixture.container); + for (const autoStart of [undefined, true]) { + for (const strategy of ['sma-crossover', 'catalog']) { + const request = { ...input, strategy }; + const message = + strategy === 'catalog' + ? 'Catalog drafts require explicit autoStart:false' + : 'Backtest drafts require explicit autoStart:false'; + await expect(service.createBacktest(request, { autoStart })).rejects.toThrow(message); + const response = await app.request('/api/v2/backtests', { + method: 'POST', + body: JSON.stringify({ ...request, autoStart }), + }); + expect(response.status).toBe(400); + expect(await response.json()).toEqual({ error: message }); + } + } + // A disguised catalog reference still gets its original diagnostic first. + await expect(service.createBacktest({ ...input, strategyVersionId: null })).rejects.toThrow( + 'Retained strategy versions' + ); + fixture.expectUntouched(); +}); + +test('explicit v2 save-only retains historical template creation without creating or dispatching a run', async () => { + const fixture = forbiddenWork(); + const query = mock(async (text: string, values: unknown[]) => { + if (!text.startsWith('INSERT INTO backtests')) { + throw new Error(`Unexpected template save query: ${text}`); + } + return { + rows: [ + { + id: values[0], + name: values[1], + strategy: values[2], + symbols: JSON.parse(values[3] as string), + start_date: values[4], + end_date: values[5], + initial_capital: values[6], + config: JSON.parse(values[7] as string), + strategy_version_id: values[8], + strategy_parameters: values[9], + }, + ], + }; + }); + const transaction = mock(async (work: (client: PoolClient) => Promise) => + work({ query } as unknown as PoolClient) + ); + const container = { + ...fixture.container, + postgres: { ...fixture.container.postgres, transaction }, + } as unknown as IServiceContainer; + const response = await createBacktestV2Routes(container).request('/api/v2/backtests', { + method: 'POST', + body: JSON.stringify({ ...input, name: 'Retained template', autoStart: false }), + }); + expect(response.status).toBe(201); + expect(await response.json()).toMatchObject({ + ...input, + name: 'Retained template', + strategyVersionId: null, + }); + expect(transaction).toHaveBeenCalledTimes(1); + expect(query).toHaveBeenCalledTimes(1); + fixture.expectUntouched(); +}); + +test('legacy history, results and cancellation continue using the v2 readers and durable cancellation', async () => { + const backtestId = '8a6bf849-20b0-4b4a-becf-e6933fc97532'; + const runId = '6fb259ac-5f35-4512-bbbf-d4f85d562465'; + const created = new Date(input.startDate); + const completed = new Date(input.endDate); + const template = { + id: backtestId, + name: 'Retained history', + strategy: input.strategy, + symbols: input.symbols, + start_date: created, + end_date: completed, + initial_capital: '10000', + config: {}, + created_at: created, + updated_at: created, + archived_at: null, + }; + const run = { + id: runId, + backtest_id: backtestId, + run_number: 1, + status: 'completed', + speed_multiplier: null, + progress: '100', + created_at: created, + updated_at: completed, + completed_at: completed, + }; + const stored = { + ...template, + run_id: runId, + backtest_id: backtestId, + completed_at: completed, + metrics: { totalReturn: 5, winRate: 50, totalTrades: 0 }, + analytics: null, + trades: [], + equity_curve: [{ date: input.endDate, value: 10500 }], + ohlc_data: {}, + positions: [], + execution_time: 12, + }; + const writes: { text: string; values?: unknown[] }[] = []; + const postgres = { + async query(text: string, values?: unknown[]) { + if (text.includes('FROM backtest_results')) { + return { rows: [stored] }; + } + if (text.startsWith('SELECT * FROM backtests')) { + return { rows: [template] }; + } + if (text.startsWith('SELECT * FROM runs')) { + return { rows: [run] }; + } + if (text.startsWith('UPDATE runs SET cancel_requested')) { + writes.push({ text, values }); + return { rows: [{ status: 'cancelled' }] }; + } + throw new Error(`Unexpected query: ${text}`); + }, + async transaction() { + throw new Error('History must not create a transaction'); + }, + }; + const container = { logger, postgres } as unknown as IServiceContainer; + const app = new Hono() + .route('/', createBacktestRoutes(container)) + .route('/', createBacktestV2Routes(container)); + const detail = await app.request(`/api/backtests/${backtestId}`); + expect(detail.status).toBe(200); + const job = await detail.json(); + expect(job).toMatchObject({ id: backtestId, runId, status: 'completed', initialCapital: 10000 }); + const listing = await app.request('/api/backtests'); + expect(listing.status).toBe(200); + expect(await listing.json()).toEqual([job]); + const result = await app.request(`/api/backtests/${backtestId}/results`); + const currentResult = await app.request(`/api/v2/runs/${runId}/results`); + expect(result.status).toBe(200); + expect(currentResult.status).toBe(200); + const legacyResult = await result.json(); + expect(legacyResult).toEqual(await currentResult.json()); + expect(legacyResult).toMatchObject({ + legacy: true, + runId, + metrics: { totalReturn: 0.05, winRate: 0.5 }, + provenance: { configurationSource: 'legacy-definition-fallback', engineVersion: null }, + }); + expect(writes).toEqual([]); + + // Cancellation remains available for an existing pending run; it only records intent in SQL. + run.status = 'pending'; + const cancelled = await app.request(`/api/backtests/${backtestId}/cancel`, { method: 'POST' }); + expect(cancelled.status).toBe(200); + expect(await cancelled.json()).toEqual({ message: 'Backtest cancelled' }); + expect(writes).toHaveLength(1); + expect(writes[0]?.values).toEqual([runId]); +});