fix(web): preserve historical backtests with null configuration (CL25)

This commit is contained in:
Boki 2026-10-28 15:50:32 -04:00
parent 731acc41db
commit ed7429cfbc
10 changed files with 41 additions and 23 deletions

View file

@ -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(),

View file

@ -24,7 +24,7 @@ export interface BacktestJob {
startDate: Date;
endDate: Date;
initialCapital: number;
config: Record<string, unknown>;
config: Record<string, unknown> | null;
createdAt: Date;
updatedAt: Date;
error?: string;

View file

@ -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<string, unknown>;
config?: Record<string, unknown> | null;
}
const invalid = (message: string): never => {
throw new HistoricalDataRequestError(message);

View file

@ -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 = () => (
<div className="max-w-4xl mx-auto space-y-4">
{catalog && backtest && (showCanonicalSetup || backtest.config.canonical) ? (
{catalog && backtest && (showCanonicalSetup || backtest.config?.canonical) ? (
<CanonicalSetup
key={backtest.id}
backtest={backtest}
disabled={archived || isLoading}
onSave={request => updateBacktest(backtest.id, request)}
onClose={!backtest.config.canonical ? () => setShowCanonicalSetup(false) : undefined}
onClose={!backtest.config?.canonical ? () => setShowCanonicalSetup(false) : undefined}
/>
) : (
<>

View file

@ -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<CatalogSelection>({
@ -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);

View file

@ -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.

View file

@ -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."
}
}

View file

@ -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.

View file

@ -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');

View file

@ -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(