diff --git a/README.md b/README.md index c766aaf6..30ae5f07 100644 --- a/README.md +++ b/README.md @@ -97,6 +97,12 @@ then evaluates holdouts and costs, retaining failed trials and exact evidence ci Findings remain explicitly AI-authored and unvalidated narratives. Use [ResearchClient](scripts/research-client.ts) for individual APIs, including walk-forward. +Use `ResearchClient.canonicalRunResult(runId)` to inspect a completed canonical run's +full retained request, native fills, positions, final risk state, analytics and provenance. +The client and API share result validation; financial decimal strings and unavailable +metrics are preserved. Missing results remain read errors so callers can inspect the +saved trial status and diagnostics. + To save a comparison across studies, call `ResearchClient.saveFinding` with `source: null` or omit `source`. Include a nonempty list of canonical metric references with each run's exact strategy-version ID. The API resolves their values from retained completed runs; diff --git a/apps/stock/web-api/src/services/backtests/results.ts b/apps/stock/web-api/src/services/backtests/results.ts index 2b9dc3d3..541a0649 100644 --- a/apps/stock/web-api/src/services/backtests/results.ts +++ b/apps/stock/web-api/src/services/backtests/results.ts @@ -1,9 +1,7 @@ import { at } from '@stock-bot/invariants'; -import { buildCanonicalBacktestReport } from '@stock-bot/research/results'; +import { parseCanonicalRunResult } from '@stock-bot/research/results'; import { canonicalRunRequestSchema, - canonicalStrategyExecution, - parseCanonicalFinancialResult, type CanonicalRunResult, type ResearchRunResult, } from '@stock-bot/stock-config/canonical-research'; @@ -48,24 +46,11 @@ export class BacktestResults { const row = at(result.rows, 0); if (row.canonical_result !== null && row.canonical_result !== undefined) { - const saved = row.canonical_result; const request = canonicalRunRequestSchema.parse(row.request_snapshot); - const financial = parseCanonicalFinancialResult(saved.financial, request); + const saved = parseCanonicalRunResult(row.canonical_result, runId); if ( - saved.kind !== 'canonical-result/v1' || - saved.runId !== runId || saved.backtestId !== row.backtest_id || - saved.status !== 'completed' || - saved.financialEngine !== 'rust' || - saved.strategyExecution !== canonicalStrategyExecution(request) || - !Number.isFinite(Date.parse(saved.completedAt)) || - !Number.isFinite(saved.executionTime) || - saved.executionTime < 0 || - canonicalStrategyJson(saved.request) !== canonicalStrategyJson(request) || - canonicalStrategyJson(saved.analytics) !== - canonicalStrategyJson( - buildCanonicalBacktestReport(financial, request.analyticsPolicy).analytics - ) + canonicalStrategyJson(saved.request) !== canonicalStrategyJson(request) ) { throw new Error('Saved canonical result does not match its admitted request'); } diff --git a/libs/research/src/results.ts b/libs/research/src/results.ts index 8f4839a8..f80166f1 100644 --- a/libs/research/src/results.ts +++ b/libs/research/src/results.ts @@ -8,6 +8,13 @@ import { } from '@stock-bot/calculations/analytics'; import { cagr, simpleReturn } from '@stock-bot/calculations/returns'; import type { ReplayReportResult } from '@stock-bot/stock-config/canonical-replay'; +import { + canonicalRunRequestSchema, + canonicalStrategyExecution, + parseCanonicalFinancialResult, + type CanonicalRunResult, +} from '@stock-bot/stock-config/canonical-research'; +import { canonicalStrategyJson } from '@stock-bot/stock-config/strategy'; import type { CanonicalBacktestAnalytics, CanonicalMetrics, @@ -25,6 +32,44 @@ const metricsInput = z }) .strict(); +const canonicalResultEnvelope = z.object({ + kind: z.literal('canonical-result/v1'), + runId: z.string().uuid(), + backtestId: z.string().uuid(), + status: z.literal('completed'), + completedAt: z.string().refine(value => Number.isFinite(Date.parse(value))), + executionTime: z.number().finite().nonnegative(), + financialEngine: z.literal('rust'), + strategyExecution: z.enum(['typescript-retained-builtin/v1', 'typescript-isolated-candidate/v1']), + request: z.unknown(), + financial: z.unknown(), + analytics: z.unknown(), +}); + +/** Verify one completed result without converting its financial facts or raw payload. + * Storage readers must additionally bind the embedded request to their trusted snapshot. */ +export function parseCanonicalRunResult(input: unknown, runId: string): CanonicalRunResult { + const saved = canonicalResultEnvelope.parse(input); + const request = canonicalRunRequestSchema.parse(saved.request); + const financial = parseCanonicalFinancialResult(saved.financial, request); + if ( + saved.runId !== runId || + request.runId !== saved.runId || + request.backtestId !== saved.backtestId || + saved.strategyExecution !== canonicalStrategyExecution(request) || + canonicalStrategyJson(saved.request) !== canonicalStrategyJson(request) || + canonicalStrategyJson(saved.analytics) !== + canonicalStrategyJson( + buildCanonicalBacktestReport(financial, request.analyticsPolicy).analytics + ) + ) { + throw new Error('Saved canonical result does not match its admitted request'); + } + // Validation above is intentionally separate from projection: decimal strings, + // nulls and the complete retained payload remain exactly as received. + return input as CanonicalRunResult; +} + export interface CanonicalBacktestReport { /** Exact validated Rust facts; never converted through the legacy DTO. */ financial: ReplayReportResult; diff --git a/scripts/research-client.ts b/scripts/research-client.ts index 1368d4b1..a3bc7864 100644 --- a/scripts/research-client.ts +++ b/scripts/research-client.ts @@ -1,5 +1,6 @@ /** Authorized research API client. No strategy import, financial simulation, or trading controls. */ import { z } from 'zod'; +import { parseCanonicalRunResult } from '@stock-bot/research/results'; import { chronologicalValidationInputSchema, chronologicalValidationSubmissionSchema, @@ -762,6 +763,18 @@ export class ResearchClient { key ); } + canonicalRunResult(runId: string, signal?: AbortSignal) { + runId = uuid.parse(runId); + return this.#request( + `runs/${id(runId)}/results`, + 'GET', + 200, + value => parseCanonicalRunResult(value, runId), + undefined, + undefined, + signal + ); + } artifact(artifactId: string, signal?: AbortSignal) { artifactId = uuid.parse(artifactId); return this.#request( diff --git a/scripts/test/research-client.test.ts b/scripts/test/research-client.test.ts index 371188d5..629d0e87 100644 --- a/scripts/test/research-client.test.ts +++ b/scripts/test/research-client.test.ts @@ -1,6 +1,7 @@ import { createHash } from 'node:crypto'; import { describe, expect, test } from 'bun:test'; import type { ExperimentDetail } from '@stock-bot/stock-config/experiments'; +import { canonicalResultFixture } from '../../test/fixtures/canonical-result'; import { comparisonFixture, tableFixture } from '../benchmark-experiment-tables'; import { pollResearch, @@ -35,6 +36,70 @@ function client(handler: (call: Call, index: number) => Response | Promise tableFixture(1) as ExperimentDetail; + +describe('canonical run inspection', () => { + test('reads complete native finances and retained inputs through authenticated GET', async () => { + const result = canonicalResultFixture(); + const before = structuredClone(result); + const { value, calls } = client(() => Response.json(result)); + const saved = await value.canonicalRunResult(result.runId.toUpperCase()); + expect(saved).toEqual(before); + expect(result).toEqual(before); + expect(saved.financial.projection.valuation.equity).toBe('9969.30000000'); + expect(saved.financial.projection.valuation.fees).toBe('0.70000000'); + expect(saved.financial.projection.fills).toHaveLength(2); + expect(saved.analytics.metrics.roundTripCount).toBeNull(); + expect(calls).toHaveLength(1); + expect(calls[0]!.url.pathname).toBe(`/api/v2/runs/${result.runId}/results`); + expect(calls[0]!.init.method).toBe('GET'); + expect(calls[0]!.body).toBeUndefined(); + expect(new Headers(calls[0]!.init.headers).get('authorization')).toBe(`Bearer ${token}`); + expect(new Headers(calls[0]!.init.headers).has('idempotency-key')).toBe(false); + }); + + test('invalid or legacy result responses fail read-only without retrying', async () => { + const result = canonicalResultFixture(); + const changed = structuredClone(result); + changed.analytics.metrics.totalReturn = 99; + for (const response of [ + null, + {}, + { runId: result.runId, engine: 'native', status: 'completed' }, + { ...result, runId: projectId }, + changed, + ]) { + const { value, calls } = client(() => Response.json(response)); + await expect(value.canonicalRunResult(result.runId)).rejects.toMatchObject({ + uncertain: false, + status: null, + }); + expect(calls).toHaveLength(1); + expect(calls[0]!.init.method).toBe('GET'); + } + }); + + test('unavailable results, aborts and invalid IDs never create replacement work', async () => { + for (const status of [401, 404, 500]) { + const { value, calls } = client(() => + Response.json({ error: 'Result unavailable' }, { status }) + ); + await expect(value.canonicalRunResult(projectId)).rejects.toMatchObject({ + status, + uncertain: false, + }); + expect(calls).toHaveLength(1); + } + const controller = new AbortController(); + const stalled = client(() => new Promise(() => {})); + expect(() => stalled.value.canonicalRunResult('../orders')).toThrow(); + expect(stalled.calls).toHaveLength(0); + const pending = stalled.value.canonicalRunResult(projectId, controller.signal); + controller.abort(); + await expect(pending).rejects.toMatchObject({ uncertain: false }); + expect(stalled.calls).toHaveLength(1); + }); +}); + function crossStudyFinding() { const detail = ordinary(); const input = { diff --git a/test/fixtures/canonical-result.ts b/test/fixtures/canonical-result.ts new file mode 100644 index 00000000..6c59319e --- /dev/null +++ b/test/fixtures/canonical-result.ts @@ -0,0 +1,29 @@ +import { buildCanonicalBacktestReport } from '@stock-bot/research/results'; +import type { CanonicalRunResult } from '@stock-bot/stock-config/canonical-research'; +import { prepareReplayLoad } from '../../apps/stock/orchestrator/src/backtest/native-replay'; +import { runStrategyReplay } from '../../apps/stock/orchestrator/src/backtest/strategy-runtime'; +import { smaStrategySelectionSchema } from '../../apps/stock/orchestrator/src/contracts/builtin-strategy'; +import { createSmaStrategy } from '../../apps/stock/orchestrator/src/strategies/canonical-sma'; +import { canonicalRunnerFixture } from './canonical-runner'; + +/** Actual Rust finances and existing SMA logic; fixture-only metadata is not an admission proof. */ +export function canonicalResultFixture(): CanonicalRunResult { + const { request, dataset } = canonicalRunnerFixture(); + const { result: financial } = runStrategyReplay( + prepareReplayLoad(dataset, request.policy), + [createSmaStrategy(smaStrategySelectionSchema.parse(request.strategy.selection))], + { resultFormat: 'report' } + ); + return { + kind: 'canonical-result/v1', + runId: request.runId, + backtestId: request.backtestId, + status: 'completed', + completedAt: '2026-10-27T12:00:00.000Z', + executionTime: 1, + financialEngine: 'rust', + strategyExecution: 'typescript-retained-builtin/v1', + request, + ...buildCanonicalBacktestReport(financial, request.analyticsPolicy), + }; +} diff --git a/test/integration/canonical-result-contract.test.ts b/test/integration/canonical-result-contract.test.ts new file mode 100644 index 00000000..65b5c677 --- /dev/null +++ b/test/integration/canonical-result-contract.test.ts @@ -0,0 +1,80 @@ +import { describe, expect, test } from 'bun:test'; +import { parseCanonicalRunResult } from '@stock-bot/research/results'; +import { parseFinancialDecimal } from '@stock-bot/types'; +import { canonicalResultFixture } from '../fixtures/canonical-result'; + +describe('shared complete canonical result contract', () => { + test('preserves the original native payload, exact money and unavailable analytics', () => { + const value = canonicalResultFixture(); + const before = JSON.stringify(value); + const parsed = parseCanonicalRunResult(value, value.runId); + expect(parsed).toBe(value); + expect(JSON.stringify(value)).toBe(before); + expect(parsed.financial.projection.valuation.equity).toBe('9969.30000000'); + expect(parsed.financial.projection.valuation.fees).toBe('0.70000000'); + expect(parsed.financial.projection.fills).toHaveLength(2); + expect(parsed.analytics.metrics.roundTripCount).toBeNull(); + expect(parsed.analytics.unavailable.roundTripCount).toBe('unsupported-round-trips'); + }); + + test('rejects foreign identities, native policies and inconsistent statistical evidence', () => { + const value = canonicalResultFixture(); + const other = '11111111-1111-4111-8111-111111111111'; + const mutations: ((copy: typeof value) => void)[] = [ + copy => { + copy.runId = other; + }, + copy => { + copy.backtestId = other; + }, + copy => { + copy.request.runId = other; + }, + copy => { + copy.request.backtestId = other; + }, + copy => { + copy.strategyExecution = 'typescript-isolated-candidate/v1'; + }, + copy => { + copy.completedAt = 'not-a-date'; + }, + copy => { + copy.executionTime = -1; + }, + copy => { + copy.financial.identity.sessionId = other; + }, + copy => { + copy.financial.identity.datasetHash = 'f'.repeat(64); + }, + copy => { + copy.financial.policy.matching.risk.feeRate = parseFinancialDecimal('0.02'); + }, + copy => { + copy.analytics.metrics.totalReturn = 99; + }, + copy => { + copy.analytics.fillCount++; + }, + copy => { + copy.analytics.unavailable.roundTripCount = 'insufficient-periods'; + }, + ]; + for (const mutate of mutations) { + const copy = structuredClone(value); + mutate(copy); + expect(() => parseCanonicalRunResult(copy, value.runId)).toThrow(); + } + expect(() => parseCanonicalRunResult(value, other)).toThrow(); + for (const input of [ + null, + {}, + { ...value, kind: 'legacy' }, + { ...value, financialEngine: 'native' }, + { ...value, status: 'failed' }, + ]) { + expect(() => parseCanonicalRunResult(input, value.runId)).toThrow(); + } + }); +}); diff --git a/test/postgres/ai-research-workflow.test.ts b/test/postgres/ai-research-workflow.test.ts index a3938194..52a61407 100644 --- a/test/postgres/ai-research-workflow.test.ts +++ b/test/postgres/ai-research-workflow.test.ts @@ -11,6 +11,7 @@ import type { StrategyVersionPackage } from '@stock-bot/types'; import { BacktestRunner } from '../../apps/stock/orchestrator/src/backtest/BacktestRunner'; import { PostgresBacktestRunRepository } from '../../apps/stock/orchestrator/src/backtest/PostgresBacktestRunRepository'; import { RustBacktestAdapter } from '../../apps/stock/orchestrator/src/backtest/RustBacktestAdapter'; +import { createBacktestV2Routes } from '../../apps/stock/web-api/src/routes/backtests-v2.routes'; import { createExperimentRoutes } from '../../apps/stock/web-api/src/routes/experiments.routes'; import { createResearchAgentRoutes } from '../../apps/stock/web-api/src/routes/research-agents.routes'; import { createResearchRoutes } from '../../apps/stock/web-api/src/routes/research.routes'; @@ -116,6 +117,7 @@ async function fixture() { app.route('/', createStrategyRoutes(container)); app.route('/', createResearchRoutes(container)); app.route('/', createExperimentRoutes(container)); + app.route('/', createBacktestV2Routes(container)); const engine = new RustBacktestAdapter({ logger, }); @@ -406,11 +408,16 @@ describe.skipIf(!url)('AI research workflow through authenticated APIs and Rust' reopenedFinding.latestRevision, ]); for (const evidence of finding.latestRevision.evidence) { - const saved = await f.api.getRunResults(evidence.runId); + const saved = await f.client.canonicalRunResult(evidence.runId); if (!saved || !('kind' in saved) || saved.kind !== 'canonical-result/v1') { throw new Error('Missing native result'); } expect(saved.strategyExecution).toBe('typescript-isolated-candidate/v1'); + const retained = await f.api.getRunResults(evidence.runId); + if (!retained || !('kind' in retained) || retained.kind !== 'canonical-result/v1') { + throw new Error('Missing retained canonical result'); + } + expect(saved).toEqual(retained); expect(saved.request.strategy.versionId).toBe(outcome.versionId); expect(saved.request.strategy.package.artifact.sha256).toHaveLength(64); expect(evidence.datasetHash).toBe(saved.request.datasetHash); @@ -436,6 +443,13 @@ describe.skipIf(!url)('AI research workflow through authenticated APIs and Rust' ).toBeTrue(); expect(broken.findings).toEqual([]); expect(broken.stoppedReason).toContain('failed'); + await expect( + f.client.canonicalRunResult(broken.screening!.trials[0]!.runId!) + ).rejects.toMatchObject({ status: 404, uncertain: false }); + await expect(f.client.canonicalRunResult(randomUUID())).rejects.toMatchObject({ + status: 404, + uncertain: false, + }); expect(result.comparison?.rows).toHaveLength(4); expect(result.comparison?.selection.leftId).toBe(result.outcomes[0]!.costs!.id); expect(result.comparison?.selection.rightId).toBe(result.outcomes[1]!.costs!.id); @@ -504,7 +518,7 @@ describe.skipIf(!url)('AI research workflow through authenticated APIs and Rust' expect(Object.hasOwn(savedInput, 'source')).toBe(source === null); expect(savedInput.evidence).toEqual(comparisonInput.evidence); for (const reference of finding.latestRevision.evidence) { - const native = await f.api.getRunResults(reference.runId); + const native = await f.client.canonicalRunResult(reference.runId); if (!native || !('kind' in native) || native.kind !== 'canonical-result/v1') { throw new Error('Missing native comparison evidence'); } @@ -601,6 +615,10 @@ describe.skipIf(!url)('AI research workflow through authenticated APIs and Rust' status: 401, uncertain: false, }); + await expect(f.client.canonicalRunResult(reference.runId)).rejects.toMatchObject({ + status: 401, + uncertain: false, + }); await expect(f.client.artifactRevisions(note.id)).rejects.toMatchObject({ status: 401, uncertain: false, diff --git a/test/postgres/run-reproduction.test.ts b/test/postgres/run-reproduction.test.ts index 27694a14..f46ab67c 100644 --- a/test/postgres/run-reproduction.test.ts +++ b/test/postgres/run-reproduction.test.ts @@ -552,6 +552,14 @@ describe.skipIf(!url)('retained original-run reproduction', () => { const f = await fixture(); const { run, result } = await completed(f); await f.pool.query('ALTER TABLE runs DISABLE TRIGGER USER'); + // A valid but different SQL snapshot must not be replaced by the embedded request. + await f.pool.query('UPDATE runs SET request_snapshot=$1 WHERE id=$2', [ + { ...result.request, name: 'Different trusted snapshot' }, + run.id, + ]); + await expect(f.api.getRunResults(run.id)).rejects.toThrow('does not match'); + await f.pool.query('UPDATE runs SET request_snapshot=NULL WHERE id=$1', [run.id]); + await expect(f.api.getRunResults(run.id)).rejects.toThrow(); await f.pool.query('UPDATE runs SET request_snapshot=$1 WHERE id=$2', [ { ...result.request, policy: {} }, run.id,