From ed7429cfbc0d792249c13d92328f6fd1ae0a6ac2 Mon Sep 17 00:00:00 2001 From: Boki Date: Wed, 28 Oct 2026 15:50:32 -0400 Subject: [PATCH] fix(web): preserve historical backtests with null configuration (CL25) --- .../contracts/product-responses/backtests.ts | 2 +- .../web-api/src/services/backtest.service.ts | 2 +- .../services/canonical-research.service.ts | 6 +++--- .../backtest/BacktestDetailPageV2.tsx | 6 +++--- .../backtest/components/CanonicalSetup.tsx | 19 ++++++++++--------- .../architecture-cleanup-execution.md | 2 ++ docs/development/backlog/manifest.json | 6 +++--- docs/development/backlog/tasks/CL25.md | 4 ++++ test/e2e/workbench.test.ts | 7 +++++-- .../product-response-contracts.test.ts | 10 +++++++++- 10 files changed, 41 insertions(+), 23 deletions(-) diff --git a/apps/stock/config/src/contracts/product-responses/backtests.ts b/apps/stock/config/src/contracts/product-responses/backtests.ts index 115305c1..1d592e59 100644 --- a/apps/stock/config/src/contracts/product-responses/backtests.ts +++ b/apps/stock/config/src/contracts/product-responses/backtests.ts @@ -17,7 +17,7 @@ export const backtestResponseSchema = z.object({ startDate: date, endDate: date, initialCapital: z.number().finite(), - config: z.record(z.unknown()), + config: z.record(z.unknown()).nullable(), createdAt: date, updatedAt: date, archivedAt: date.nullable(), diff --git a/apps/stock/web-api/src/services/backtest.service.ts b/apps/stock/web-api/src/services/backtest.service.ts index 8120def0..d4cbc972 100644 --- a/apps/stock/web-api/src/services/backtest.service.ts +++ b/apps/stock/web-api/src/services/backtest.service.ts @@ -24,7 +24,7 @@ export interface BacktestJob { startDate: Date; endDate: Date; initialCapital: number; - config: Record; + config: Record | null; createdAt: Date; updatedAt: Date; error?: string; diff --git a/apps/stock/web-api/src/services/canonical-research.service.ts b/apps/stock/web-api/src/services/canonical-research.service.ts index 1d128a32..8bace79b 100644 --- a/apps/stock/web-api/src/services/canonical-research.service.ts +++ b/apps/stock/web-api/src/services/canonical-research.service.ts @@ -24,14 +24,14 @@ import { builtinStrategySelectionSchema, validateStrategyParameters, } from '@stock-bot/stock-config/strategy'; +import { readCandidateExecution } from '@stock-bot/trading-runtime/candidate-environment'; +import { readCanonicalBuildIdentity } from '@stock-bot/trading-runtime/canonical-build'; import { HistoricalDataRequestError, parseFinancialDecimal, type HistoricalDatasetV2, type StrategyParameterValue, } from '@stock-bot/types'; -import { readCandidateExecution } from '@stock-bot/trading-runtime/candidate-environment'; -import { readCanonicalBuildIdentity } from '@stock-bot/trading-runtime/canonical-build'; import { canonicalRiskSessionClock } from './canonical-risk-clock'; import type { DatasetCatalogQuery } from './dataset-catalog.service'; import { StrategyCatalogService } from './strategy-catalog.service'; @@ -44,7 +44,7 @@ export interface CanonicalTemplate { startDate: string | Date; endDate: string | Date; initialCapital: number; - config?: Record; + config?: Record | null; } const invalid = (message: string): never => { throw new HistoricalDataRequestError(message); diff --git a/apps/stock/web-app/src/features/backtest/BacktestDetailPageV2.tsx b/apps/stock/web-app/src/features/backtest/BacktestDetailPageV2.tsx index 56ef87b1..461298db 100644 --- a/apps/stock/web-app/src/features/backtest/BacktestDetailPageV2.tsx +++ b/apps/stock/web-app/src/features/backtest/BacktestDetailPageV2.tsx @@ -208,7 +208,7 @@ export function BacktestDetailPageV2() { dataSource: (backtest.config?.dataSource ?? 'auto') as BacktestConfig['dataSource'], datasetHash: typeof backtest.config?.datasetHash === 'string' - ? backtest.config.datasetHash + ? backtest.config?.datasetHash : undefined, commission: Number(backtest.config?.commission ?? 0.001), slippage: Number(backtest.config?.slippage ?? 0.0001), @@ -226,13 +226,13 @@ export function BacktestDetailPageV2() { const renderSettings = () => (
- {catalog && backtest && (showCanonicalSetup || backtest.config.canonical) ? ( + {catalog && backtest && (showCanonicalSetup || backtest.config?.canonical) ? ( updateBacktest(backtest.id, request)} - onClose={!backtest.config.canonical ? () => setShowCanonicalSetup(false) : undefined} + onClose={!backtest.config?.canonical ? () => setShowCanonicalSetup(false) : undefined} /> ) : ( <> diff --git a/apps/stock/web-app/src/features/backtest/components/CanonicalSetup.tsx b/apps/stock/web-app/src/features/backtest/components/CanonicalSetup.tsx index f9bfc316..937d675b 100644 --- a/apps/stock/web-app/src/features/backtest/components/CanonicalSetup.tsx +++ b/apps/stock/web-app/src/features/backtest/components/CanonicalSetup.tsx @@ -166,7 +166,7 @@ function defaults(capital: number): CanonicalResearchSettings { }; } function initialPolicy(backtest: Backtest): RawPolicy { - const input = backtest.config.canonical; + const input = backtest.config?.canonical; const source = input && typeof input === 'object' ? input : defaults(backtest.initialCapital); return Object.fromEntries( policyFields.map(({ key }) => { @@ -259,8 +259,9 @@ export function CanonicalSetup({ const [capital, setCapital] = useState(String(backtest.initialCapital)); const [raw, setRaw] = useState(() => initialPolicy(backtest)); const [hash, setHash] = useState( - typeof backtest.config.canonical === 'object' && typeof backtest.config.datasetHash === 'string' - ? backtest.config.datasetHash + typeof backtest.config?.canonical === 'object' && + typeof backtest.config?.datasetHash === 'string' + ? backtest.config?.datasetHash : '' ); const [selection, setSelection] = useState({ @@ -322,15 +323,15 @@ export function CanonicalSetup({ setCapital(String(backtest.initialCapital)); setRaw(initialPolicy(backtest)); setHash( - typeof backtest.config.canonical === 'object' && - typeof backtest.config.datasetHash === 'string' - ? backtest.config.datasetHash + typeof backtest.config?.canonical === 'object' && + typeof backtest.config?.datasetHash === 'string' + ? backtest.config?.datasetHash : '' ); selectedHash.current = - typeof backtest.config.canonical === 'object' && - typeof backtest.config.datasetHash === 'string' - ? backtest.config.datasetHash + typeof backtest.config?.canonical === 'object' && + typeof backtest.config?.datasetHash === 'string' + ? backtest.config?.datasetHash : ''; setKnownHash(''); setKnownHashError(null); diff --git a/docs/development/architecture-cleanup-execution.md b/docs/development/architecture-cleanup-execution.md index 328151eb..9509276b 100644 --- a/docs/development/architecture-cleanup-execution.md +++ b/docs/development/architecture-cleanup-execution.md @@ -37,3 +37,5 @@ Agents use root-reserved disjoint files in the integration worktree. Root alone - **CL22:** Independent review reproduced premature worker drain at2s. Follow-up removes false-success2s/5s queue deadlines; actual Queue.close is idempotent and retains workers/transports until completion. Deferred-worker regression crosses both old deadlines; real Redis DB15 smoke preserves queued payloads through observer/producer shutdown and subsequent consumption. Root queue build and focused tests passed; service-level exit deadline remains authoritative. - **CL29:** Shared insertion helper preserves exact run/outbox SQL payload and order under caller-owned transaction; UUIDs, numbering, locks, quotas, receipts and holdout choice stay with callers. Focused26 tests351 assertions passed; independent SQL review no blockers. Complete repository check passed; full disposable PostgreSQL/Redis287 tests2949 assertions passed, including duplicate keys, second-dispatch rollback and heldout admission. + +- **CL25:** Chromium caught a valid historical SQL-null configuration rejected by the new schema. Read contracts now preserve null and canonical setup/detail access is guarded; no stored records rewritten. Source typecheck and108 focused tests835 assertions passed; final Chromium27 workflows971 assertions passed, including historical unavailable-results and run-error recovery. Error assertions follow real server/transport responses. diff --git a/docs/development/backlog/manifest.json b/docs/development/backlog/manifest.json index ef8b1957..07548d4a 100644 --- a/docs/development/backlog/manifest.json +++ b/docs/development/backlog/manifest.json @@ -3822,7 +3822,7 @@ "release_gates": [], "completion_evidence": "architecture-cleanup-execution.md", "integration_state": "accepted", - "validation": "Shared response wire schemas and server type aliases; root mapping/date/invalid-response/run-control tests 59 passed (388 assertions), agent complete focused UI/transport/reproduction set 358 passed. Scoped lint/format passed. Preserves historical optional records and submission receipt/idempotency guards." + "validation": "Chromium caught a valid historical SQL-null configuration rejected by the new schema. Read contracts now preserve null and canonical setup/detail access is guarded; no stored records rewritten. Source typecheck and108 focused tests835 assertions passed; final Chromium27 workflows971 assertions passed, including historical unavailable-results and run-error recovery. Error assertions follow real server/transport responses." }, { "id": "CL26", @@ -3897,7 +3897,7 @@ "complexity": "M", "assignment": null, "write_locks": ["CL29"], - "completed_commit": null, + "completed_commit": "731acc41db221887e3e527fe0cc139f739273975", "blocker": null, "release_gates": [], "completion_evidence": "architecture-cleanup-execution.md", @@ -10410,6 +10410,6 @@ "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": 14, - "last_verification": "Shared insertion helper preserves exact run/outbox SQL payload and order under caller-owned transaction; UUIDs, numbering, locks, quotas, receipts and holdout choice stay with callers. Focused26 tests351 assertions passed; independent SQL review no blockers. Complete repository check passed; full disposable PostgreSQL/Redis287 tests2949 assertions passed, including duplicate keys, second-dispatch rollback and heldout admission." + "last_verification": "Chromium caught a valid historical SQL-null configuration rejected by the new schema. Read contracts now preserve null and canonical setup/detail access is guarded; no stored records rewritten. Source typecheck and108 focused tests835 assertions passed; final Chromium27 workflows971 assertions passed, including historical unavailable-results and run-error recovery. Error assertions follow real server/transport responses." } } diff --git a/docs/development/backlog/tasks/CL25.md b/docs/development/backlog/tasks/CL25.md index 40570590..91842e1f 100644 --- a/docs/development/backlog/tasks/CL25.md +++ b/docs/development/backlog/tasks/CL25.md @@ -22,3 +22,7 @@ No new service/framework, financial simulator, real trading activation, external ## Accepted verification Shared response wire schemas and server type aliases; root mapping/date/invalid-response/run-control tests 59 passed (388 assertions), agent complete focused UI/transport/reproduction set 358 passed. Scoped lint/format passed. Preserves historical optional records and submission receipt/idempotency guards. + +## Accepted verification + +Chromium caught a valid historical SQL-null configuration rejected by the new schema. Read contracts now preserve null and canonical setup/detail access is guarded; no stored records rewritten. Source typecheck and108 focused tests835 assertions passed; final Chromium27 workflows971 assertions passed, including historical unavailable-results and run-error recovery. Error assertions follow real server/transport responses. diff --git a/test/e2e/workbench.test.ts b/test/e2e/workbench.test.ts index b962919c..60a0f57b 100644 --- a/test/e2e/workbench.test.ts +++ b/test/e2e/workbench.test.ts @@ -2082,12 +2082,15 @@ test('browser_reopen_and_switch', async () => { ).toEqual(beforeHistorySelection); // A real missing row, not an invented empty result. await f.page.goto(`${f.origin}/backtests/${definitionId}/run/${randomUUID()}`); - await visible(f.page, 'Failed to get run: Not Found'); + await visible(f.page, 'Run not found'); await visible(f.page, 'Retry run'); // Transport failure has a visible retry; restoring the real endpoint recovers. await f.page.route(`**/api/v2/runs/${secondId}`, route => route.abort('failed')); await f.page.goto(secondUrl); - await visible(f.page, /Failed to fetch|Load failed/); + await visible( + f.page, + 'The backtest response was lost. Check saved runs before submitting again.' + ); await f.page.unroute(`**/api/v2/runs/${secondId}`); await f.page.getByRole('button', { name: 'Retry run', exact: true }).click(); await visible(f.page, 'Completed'); diff --git a/test/integration/product-response-contracts.test.ts b/test/integration/product-response-contracts.test.ts index 6c498072..17eeec70 100644 --- a/test/integration/product-response-contracts.test.ts +++ b/test/integration/product-response-contracts.test.ts @@ -90,6 +90,14 @@ function respond(body: unknown, status = 200) { return fetch; } +test('historical templates with SQL-null configuration remain readable without rewriting them', async () => { + const mapped = mapBacktest({ ...row, config: null }); + const wire = JSON.parse(JSON.stringify(mapped)); + expect(backtestResponseSchema.parse(wire).config).toBeNull(); + respond(mapped); + expect((await backtest.backtestApiV2.getBacktest(backtestId)).config).toBeNull(); +}); + test('real server backtest/run mappings survive JSON serialization and display the server clock field', async () => { const mapped = mapBacktest(row); respond(mapped); @@ -133,7 +141,7 @@ test('existing optional fields remain optional without accepting malformed rende for (const bad of [ { ...serialized, symbols: 'AAPL' }, { ...serialized, initialCapital: '10000' }, - { ...serialized, config: null }, + { ...serialized, config: [] }, ]) { respond(bad); await expect(backtest.backtestApiV2.getBacktest(backtestId)).rejects.toThrow(