feat(research): reproduce retained canonical runs with economic comparison
This commit is contained in:
parent
e3bd708838
commit
30accfcf43
31 changed files with 2969 additions and 28 deletions
|
|
@ -60,7 +60,8 @@ export async function runMigrations(container: IServiceContainer): Promise<void>
|
|||
f === '17-research-retention.sql' ||
|
||||
f === '18-backtest-strategy-versions.sql' ||
|
||||
f === '19-canonical-research.sql' ||
|
||||
f === '20-research-workspace.sql')
|
||||
f === '20-research-workspace.sql' ||
|
||||
f === '21-run-reproduction.sql')
|
||||
) // Explicit additive migration allowlist; never replay destructive init migrations
|
||||
.sort();
|
||||
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
import { Hono } from 'hono';
|
||||
import { z } from 'zod';
|
||||
import { getVerifiedHttpPrincipal } from '@stock-bot/di';
|
||||
import { getCredentialHttpPrincipal, getVerifiedHttpPrincipal } from '@stock-bot/di';
|
||||
import type { IServiceContainer } from '@stock-bot/handlers';
|
||||
import { getLogger } from '@stock-bot/logger';
|
||||
import {
|
||||
|
|
@ -13,6 +13,7 @@ import {
|
|||
CatalogExecutionUnavailableError,
|
||||
RunSubmissionConflictError,
|
||||
} from '../services/backtest-v2.service';
|
||||
import { RunReproductionError } from '../services/run-reproduction';
|
||||
import { StrategyCatalogError } from '../services/strategy-catalog.service';
|
||||
|
||||
const logger = getLogger('backtests-v2-routes');
|
||||
|
|
@ -184,6 +185,79 @@ export function createBacktestV2Routes(container: IServiceContainer) {
|
|||
}
|
||||
});
|
||||
|
||||
app.get('/api/v2/runs/:id/reproduction', async c => {
|
||||
c.header('Cache-Control', 'no-store');
|
||||
const id = z.string().uuid().safeParse(c.req.param('id'));
|
||||
if (!id.success) {
|
||||
return c.json({ error: 'Invalid original run ID' }, 400);
|
||||
}
|
||||
try {
|
||||
return c.json(await backtestService.getReproductionPreview(id.data));
|
||||
} catch (error) {
|
||||
if (error instanceof RunReproductionError) {
|
||||
return c.json({ error: error.message, code: error.code }, error.status);
|
||||
}
|
||||
logger.error('Failed to preview reproduction', error);
|
||||
return c.json({ error: 'Could not inspect original run reproduction' }, 500);
|
||||
}
|
||||
});
|
||||
|
||||
app.post('/api/v2/runs/:id/reproduce', async c => {
|
||||
c.header('Cache-Control', 'no-store');
|
||||
const principal = getCredentialHttpPrincipal(c.req.raw);
|
||||
if (!principal) {
|
||||
return c.json({ error: 'Verified credential principal required' }, 401);
|
||||
}
|
||||
let originalRunId: string;
|
||||
let key: string;
|
||||
try {
|
||||
originalRunId = z.string().uuid().parse(c.req.param('id'));
|
||||
key = z
|
||||
.string()
|
||||
.regex(/^[\x21-\x7e]{1,200}$/)
|
||||
.parse(c.req.header('Idempotency-Key'));
|
||||
z.object({})
|
||||
.strict()
|
||||
.parse(await c.req.json());
|
||||
} catch {
|
||||
return c.json(
|
||||
{ error: 'Use a valid run ID, an empty object and a 1–200 visible ASCII Idempotency-Key' },
|
||||
400
|
||||
);
|
||||
}
|
||||
try {
|
||||
const run = await backtestService.reproduceRun(originalRunId, { principal, key });
|
||||
c.header('Location', `/api/v2/runs/${run.id}`);
|
||||
return c.json(run, 202);
|
||||
} catch (error) {
|
||||
if (error instanceof RunReproductionError) {
|
||||
return c.json({ error: error.message, code: error.code }, error.status);
|
||||
}
|
||||
if (error instanceof BacktestRetentionError || error instanceof RunSubmissionConflictError) {
|
||||
return c.json({ error: error.message }, 409);
|
||||
}
|
||||
logger.error('Failed to reproduce original run', error);
|
||||
return c.json({ error: 'Could not reproduce original run' }, 500);
|
||||
}
|
||||
});
|
||||
|
||||
app.get('/api/v2/runs/:id/reproduction-comparison', async c => {
|
||||
c.header('Cache-Control', 'no-store');
|
||||
const id = z.string().uuid().safeParse(c.req.param('id'));
|
||||
if (!id.success) {
|
||||
return c.json({ error: 'Invalid run ID' }, 400);
|
||||
}
|
||||
try {
|
||||
return c.json(await backtestService.getReproductionComparison(id.data));
|
||||
} catch (error) {
|
||||
if (error instanceof RunReproductionError) {
|
||||
return c.json({ error: error.message, code: error.code }, error.status);
|
||||
}
|
||||
logger.error('Failed to compare reproduction', error);
|
||||
return c.json({ error: 'Could not compare retained reproduction results' }, 500);
|
||||
}
|
||||
});
|
||||
|
||||
app.get('/api/v2/runs/:id', async c => {
|
||||
try {
|
||||
const run = await backtestService.getRun(c.req.param('id'));
|
||||
|
|
|
|||
|
|
@ -16,6 +16,8 @@ import {
|
|||
import {
|
||||
canonicalRunRequestSchema,
|
||||
parseCanonicalFinancialResult,
|
||||
type CanonicalReproductionComparison,
|
||||
type CanonicalReproductionPreview,
|
||||
type CanonicalRunCapability,
|
||||
type CanonicalRunResult,
|
||||
type ResearchRunResult,
|
||||
|
|
@ -33,6 +35,8 @@ import type { WebSocketHandler } from '../websocket/run-updates';
|
|||
import { mapStoredBacktestResult, type StoredBacktestResult } from './backtest-result';
|
||||
import { admitCanonicalRequest, validateCanonicalSetup } from './canonical-research.service';
|
||||
import { assertSelectedDatasetMatchesRequest } from './dataset-catalog.service';
|
||||
import { canonicalReproductionHash } from './reproduction-comparison';
|
||||
import { RunReproductionError, verifyReproductionInputs } from './run-reproduction';
|
||||
import { StrategyCatalogError, StrategyCatalogService } from './strategy-catalog.service';
|
||||
|
||||
const logger = getLogger('backtest-v2-service');
|
||||
|
|
@ -78,6 +82,7 @@ export interface Backtest {
|
|||
}
|
||||
|
||||
export interface Run {
|
||||
originalRunId: string | null;
|
||||
dataset: BacktestRunDatasetSelection;
|
||||
id: string;
|
||||
backtestId: string;
|
||||
|
|
@ -504,6 +509,224 @@ export class BacktestServiceV2 {
|
|||
return this.mapRun(row);
|
||||
}
|
||||
|
||||
/** Preview validates retained inputs without admitting work or consulting current settings. */
|
||||
async getReproductionPreview(originalRunId: string): Promise<CanonicalReproductionPreview> {
|
||||
return this.container.postgres.transaction(async client => {
|
||||
const source = (await client.query('SELECT * FROM runs WHERE id=$1', [originalRunId]))
|
||||
.rows[0];
|
||||
if (!source) {
|
||||
throw new RunReproductionError(404, 'Original run not found');
|
||||
}
|
||||
const preview: CanonicalReproductionPreview = {
|
||||
originalRunId,
|
||||
backtestId: source.backtest_id,
|
||||
available: false,
|
||||
reason: null,
|
||||
request: null,
|
||||
currentReviewId: null,
|
||||
};
|
||||
try {
|
||||
const request = await this.originalCanonicalRequest(client, source);
|
||||
preview.request = request;
|
||||
const parent = (
|
||||
await client.query('SELECT archived_at FROM backtests WHERE id=$1 FOR UPDATE', [
|
||||
source.backtest_id,
|
||||
])
|
||||
).rows[0];
|
||||
if (!parent || parent.archived_at !== null) {
|
||||
throw new RunReproductionError(
|
||||
409,
|
||||
'Backtest is archived; restore it before reproducing a run'
|
||||
);
|
||||
}
|
||||
preview.currentReviewId = await verifyReproductionInputs(client, this.container, request);
|
||||
preview.available = true;
|
||||
} catch (cause) {
|
||||
if (!(cause instanceof RunReproductionError)) {
|
||||
throw cause;
|
||||
}
|
||||
preview.reason = cause.message;
|
||||
}
|
||||
return preview;
|
||||
});
|
||||
}
|
||||
|
||||
async reproduceRun(originalRunId: string, submission: RunSubmission): Promise<Run> {
|
||||
if (
|
||||
!submission ||
|
||||
!['operator', 'service'].includes(submission.principal) ||
|
||||
!/^[\x21-\x7e]{1,200}$/.test(submission.key)
|
||||
) {
|
||||
throw new HistoricalDataRequestError('Reproduction requires a verified submission receipt');
|
||||
}
|
||||
const submissionHash = createHash('sha256')
|
||||
.update(
|
||||
JSON.stringify({
|
||||
version: 1,
|
||||
operation: 'reproduce-original',
|
||||
originalRunId,
|
||||
})
|
||||
)
|
||||
.digest('hex');
|
||||
const row = await this.container.postgres.transaction(async client => {
|
||||
const replay = async () => {
|
||||
const saved = (
|
||||
await client.query(
|
||||
'SELECT * FROM runs WHERE submission_principal=$1 AND submission_key=$2',
|
||||
[submission.principal, submission.key]
|
||||
)
|
||||
).rows[0];
|
||||
if (saved && saved.submission_hash !== submissionHash) {
|
||||
throw new RunSubmissionConflictError();
|
||||
}
|
||||
return saved;
|
||||
};
|
||||
const previous = await replay();
|
||||
if (previous) {
|
||||
return previous;
|
||||
}
|
||||
const source = (await client.query('SELECT * FROM runs WHERE id=$1', [originalRunId]))
|
||||
.rows[0];
|
||||
if (!source) {
|
||||
throw new RunReproductionError(404, 'Original run not found');
|
||||
}
|
||||
const parent = (
|
||||
await client.query('SELECT archived_at FROM backtests WHERE id=$1 FOR UPDATE', [
|
||||
source.backtest_id,
|
||||
])
|
||||
).rows[0];
|
||||
const concurrent = await replay();
|
||||
if (concurrent) {
|
||||
return concurrent;
|
||||
}
|
||||
if (!parent || parent.archived_at !== null) {
|
||||
throw new BacktestRetentionError('backtest_archived');
|
||||
}
|
||||
const original = await this.originalCanonicalRequest(client, source);
|
||||
const reviewId = await verifyReproductionInputs(client, this.container, original);
|
||||
const runId = uuidv4();
|
||||
const snapshot = structuredClone(original);
|
||||
snapshot.runId = runId;
|
||||
snapshot.policy.matching.risk.ledger.sessionId = runId;
|
||||
snapshot.policy.matching.risk.ledger.accountId = `research:${runId}`;
|
||||
snapshot.strategy.reviewId = reviewId;
|
||||
canonicalRunRequestSchema.parse(snapshot);
|
||||
const inserted = await client.query(
|
||||
`INSERT INTO runs
|
||||
(id,backtest_id,run_number,status,speed_multiplier,request_snapshot,dataset_hash,
|
||||
submission_principal,submission_key,submission_hash,original_run_id)
|
||||
SELECT $1,$2,COALESCE(MAX(run_number),0)+1,'pending'::run_status,NULL,$3::jsonb,$4,$5,$6,$7,$8
|
||||
FROM runs WHERE backtest_id=$2
|
||||
ON CONFLICT (submission_principal,submission_key) DO NOTHING RETURNING *`,
|
||||
[
|
||||
runId,
|
||||
source.backtest_id,
|
||||
JSON.stringify(snapshot),
|
||||
snapshot.datasetHash,
|
||||
submission.principal,
|
||||
submission.key,
|
||||
submissionHash,
|
||||
originalRunId,
|
||||
]
|
||||
);
|
||||
if (!inserted.rows[0]) {
|
||||
const winner = await replay();
|
||||
if (!winner) {
|
||||
throw new Error('Concurrent reproduction disappeared; retry with the same key');
|
||||
}
|
||||
return winner;
|
||||
}
|
||||
await client.query('INSERT INTO backtest_dispatch (run_id) VALUES ($1)', [runId]);
|
||||
return inserted.rows[0];
|
||||
});
|
||||
return this.mapRun(row);
|
||||
}
|
||||
|
||||
async getReproductionComparison(runId: string): Promise<CanonicalReproductionComparison> {
|
||||
const current = (await this.container.postgres.query('SELECT * FROM runs WHERE id=$1', [runId]))
|
||||
.rows[0];
|
||||
if (!current) {
|
||||
throw new RunReproductionError(404, 'Run not found');
|
||||
}
|
||||
const comparison: CanonicalReproductionComparison = {
|
||||
version: 'canonical-reproduction/v1',
|
||||
runId,
|
||||
backtestId: current.backtest_id,
|
||||
originalRunId: current.original_run_id ?? null,
|
||||
status: 'not-reproduction',
|
||||
reason: null,
|
||||
originalHash: null,
|
||||
reproducedHash: null,
|
||||
};
|
||||
if (!comparison.originalRunId) {
|
||||
return comparison;
|
||||
}
|
||||
if (['pending', 'running', 'paused'].includes(current.status)) {
|
||||
return { ...comparison, status: 'pending', reason: 'The reproduction has not completed' };
|
||||
}
|
||||
if (current.status !== 'completed') {
|
||||
return {
|
||||
...comparison,
|
||||
status: 'unavailable',
|
||||
reason: 'The reproduction did not complete successfully',
|
||||
};
|
||||
}
|
||||
const source = (
|
||||
await this.container.postgres.query('SELECT * FROM runs WHERE id=$1', [
|
||||
comparison.originalRunId,
|
||||
])
|
||||
).rows[0];
|
||||
if (!source || source.status !== 'completed' || source.backtest_id !== current.backtest_id) {
|
||||
return {
|
||||
...comparison,
|
||||
status: 'unavailable',
|
||||
reason: 'The original completed run is unavailable',
|
||||
};
|
||||
}
|
||||
const original = await this.getRunResults(source.id);
|
||||
const reproduced = await this.getRunResults(runId);
|
||||
if (!original || !reproduced || !('kind' in original) || !('kind' in reproduced)) {
|
||||
return {
|
||||
...comparison,
|
||||
status: 'unavailable',
|
||||
reason: 'Complete canonical results are unavailable',
|
||||
};
|
||||
}
|
||||
const originalHash = canonicalReproductionHash(original);
|
||||
const reproducedHash = canonicalReproductionHash(reproduced);
|
||||
return {
|
||||
...comparison,
|
||||
originalHash,
|
||||
reproducedHash,
|
||||
status: originalHash === reproducedHash ? 'match' : 'mismatch',
|
||||
};
|
||||
}
|
||||
|
||||
private async originalCanonicalRequest(client: PoolClient, source: QueryResultRow) {
|
||||
if (source.status !== 'completed') {
|
||||
throw new RunReproductionError(409, 'Only completed original runs can be reproduced');
|
||||
}
|
||||
if (source.request_snapshot?.kind !== 'canonical-research/v1') {
|
||||
throw new RunReproductionError(
|
||||
409,
|
||||
'The original run lacks compatible frozen canonical inputs'
|
||||
);
|
||||
}
|
||||
const request = canonicalRunRequestSchema.parse(source.request_snapshot);
|
||||
if (
|
||||
request.runId !== source.id ||
|
||||
request.backtestId !== source.backtest_id ||
|
||||
request.datasetHash !== source.dataset_hash
|
||||
) {
|
||||
throw new Error('The retained canonical source identity is inconsistent');
|
||||
}
|
||||
const result = await this.getRunResults(source.id, client);
|
||||
if (!result || !('kind' in result) || result.kind !== 'canonical-result/v1') {
|
||||
throw new RunReproductionError(409, 'The original canonical result is unavailable');
|
||||
}
|
||||
return request;
|
||||
}
|
||||
|
||||
async getRun(id: string): Promise<Run | null> {
|
||||
const result = await this.container.postgres.query('SELECT * FROM runs WHERE id = $1', [id]);
|
||||
|
||||
|
|
@ -755,6 +978,7 @@ export class BacktestServiceV2 {
|
|||
|
||||
private mapRun(row: QueryResultRow): Run {
|
||||
return {
|
||||
originalRunId: row.original_run_id ?? null,
|
||||
dataset: datasetSelectionForRun(row),
|
||||
id: row.id,
|
||||
backtestId: row.backtest_id,
|
||||
|
|
|
|||
49
apps/stock/web-api/src/services/reproduction-comparison.ts
Normal file
49
apps/stock/web-api/src/services/reproduction-comparison.ts
Normal file
|
|
@ -0,0 +1,49 @@
|
|||
import { createHash } from 'node:crypto';
|
||||
import {
|
||||
canonicalRunRequestSchema,
|
||||
parseCanonicalFinancialResult,
|
||||
type CanonicalRunResult,
|
||||
} from '@stock-bot/stock-config/canonical-research';
|
||||
import { canonicalStrategyJson } from '@stock-bot/stock-config/strategy';
|
||||
|
||||
/** Call with a retained result validated by getRunResults. This copies facts;
|
||||
* it never recalculates financial values or statistically approximates equality.
|
||||
* Only new admission identities are normalized. Market sessions, owner/decision/
|
||||
* order/fill IDs and every ordered financial/reporting fact remain significant. */
|
||||
export function canonicalReproductionHash(result: CanonicalRunResult): string {
|
||||
const request = canonicalRunRequestSchema.parse(result.request);
|
||||
if (
|
||||
result.kind !== 'canonical-result/v1' ||
|
||||
result.status !== 'completed' ||
|
||||
result.financialEngine !== 'rust' ||
|
||||
result.strategyExecution !== 'typescript-retained-builtin/v1' ||
|
||||
result.runId !== request.runId ||
|
||||
result.backtestId !== request.backtestId
|
||||
) {
|
||||
throw new Error('Reproduction comparison requires matching canonical result identity');
|
||||
}
|
||||
const financial = parseCanonicalFinancialResult(result.financial, request);
|
||||
// Parsed objects are detached. Do not recursively erase similarly named fields:
|
||||
// riskSession.sessionId, for example, is a real economic clock input.
|
||||
request.runId = 'run';
|
||||
request.strategy.reviewId = 'admission-review';
|
||||
request.policy.matching.risk.ledger.sessionId = 'run';
|
||||
request.policy.matching.risk.ledger.accountId = 'account';
|
||||
financial.identity.sessionId = 'run';
|
||||
financial.policy.matching.risk.ledger.sessionId = 'run';
|
||||
financial.policy.matching.risk.ledger.accountId = 'account';
|
||||
financial.view.portfolio.sessionId = 'run';
|
||||
financial.view.portfolio.accountId = 'account';
|
||||
return createHash('sha256')
|
||||
.update(
|
||||
canonicalStrategyJson({
|
||||
version: 'canonical-reproduction/v1',
|
||||
financialEngine: result.financialEngine,
|
||||
strategyExecution: result.strategyExecution,
|
||||
request,
|
||||
financial,
|
||||
analytics: result.analytics,
|
||||
})
|
||||
)
|
||||
.digest('hex');
|
||||
}
|
||||
104
apps/stock/web-api/src/services/run-reproduction.ts
Normal file
104
apps/stock/web-api/src/services/run-reproduction.ts
Normal file
|
|
@ -0,0 +1,104 @@
|
|||
import type { PoolClient } from 'pg';
|
||||
import type { IServiceContainer } from '@stock-bot/services';
|
||||
import type { CanonicalRunRequest } from '@stock-bot/stock-config/canonical-research';
|
||||
import { canonicalStrategyJson } from '@stock-bot/stock-config/strategy';
|
||||
import { HistoricalDataRequestError } from '@stock-bot/types';
|
||||
import { readCanonicalBuildIdentity } from '../../../orchestrator/src/backtest/canonical-build';
|
||||
import { readCanonicalDataset } from './canonical-research.service';
|
||||
import { StrategyCatalogError, StrategyCatalogService } from './strategy-catalog.service';
|
||||
|
||||
export class RunReproductionError extends Error {
|
||||
readonly code = 'run_reproduction_unavailable';
|
||||
constructor(
|
||||
public readonly status: 404 | 409,
|
||||
message: string
|
||||
) {
|
||||
super(message);
|
||||
}
|
||||
}
|
||||
|
||||
/** Under the parent lock, validate the ORIGINAL version, never current template settings. */
|
||||
export async function verifyReproductionInputs(
|
||||
client: PoolClient,
|
||||
container: IServiceContainer,
|
||||
request: CanonicalRunRequest
|
||||
): Promise<string> {
|
||||
const selected = (
|
||||
await client.query(
|
||||
`SELECT v.strategy_id,v.origin,s.archived_at FROM strategy_versions v
|
||||
JOIN strategies s ON s.id=v.strategy_id WHERE v.id=$1 FOR UPDATE OF s`,
|
||||
[request.strategy.versionId]
|
||||
)
|
||||
).rows[0];
|
||||
if (
|
||||
!selected ||
|
||||
selected.strategy_id !== request.strategy.familyId ||
|
||||
selected.origin !== 'builtin'
|
||||
) {
|
||||
throw new RunReproductionError(409, 'The original retained built-in version is unavailable');
|
||||
}
|
||||
if (selected.archived_at !== null) {
|
||||
throw new RunReproductionError(409, 'The original strategy family is archived');
|
||||
}
|
||||
const review = (
|
||||
await client.query(
|
||||
'SELECT id,decision FROM strategy_review_events WHERE version_id=$1 ORDER BY ordinal DESC LIMIT 1',
|
||||
[request.strategy.versionId]
|
||||
)
|
||||
).rows[0];
|
||||
if (review?.decision !== 'approve') {
|
||||
throw new RunReproductionError(
|
||||
409,
|
||||
'The original strategy version requires current operator approval'
|
||||
);
|
||||
}
|
||||
try {
|
||||
const pkg = await new StrategyCatalogService(container).getVersionArtifact(
|
||||
request.strategy.versionId,
|
||||
client
|
||||
);
|
||||
if (canonicalStrategyJson(pkg) !== canonicalStrategyJson(request.strategy.package)) {
|
||||
throw new RunReproductionError(
|
||||
409,
|
||||
'The retained strategy artifact differs from the original request'
|
||||
);
|
||||
}
|
||||
const dataset = await readCanonicalDataset(client, request.datasetHash);
|
||||
const execution = dataset.manifest.executionSeries[0];
|
||||
if (
|
||||
execution?.instrumentId !== request.strategy.selection.instrumentId ||
|
||||
execution.seriesId !== request.strategy.selection.seriesId
|
||||
) {
|
||||
throw new RunReproductionError(
|
||||
409,
|
||||
'The retained dataset does not match the original execution series'
|
||||
);
|
||||
}
|
||||
} catch (cause) {
|
||||
if (cause instanceof StrategyCatalogError || cause instanceof HistoricalDataRequestError) {
|
||||
throw new RunReproductionError(409, cause.message);
|
||||
}
|
||||
throw cause;
|
||||
}
|
||||
let build;
|
||||
try {
|
||||
build = await readCanonicalBuildIdentity();
|
||||
} catch (cause) {
|
||||
if (
|
||||
cause &&
|
||||
typeof cause === 'object' &&
|
||||
'code' in cause &&
|
||||
['ENOENT', 'ENOTDIR', 'EACCES'].includes(String(cause.code))
|
||||
) {
|
||||
throw new RunReproductionError(409, 'The original canonical build is not installed');
|
||||
}
|
||||
throw cause;
|
||||
}
|
||||
if (canonicalStrategyJson(build) !== canonicalStrategyJson(request.build)) {
|
||||
throw new RunReproductionError(
|
||||
409,
|
||||
'The original worker/native/runtime build is not installed; historical build execution is unavailable'
|
||||
);
|
||||
}
|
||||
return review.id;
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue