stock-bot/apps/stock/web-api/src/services/run-reproduction.ts

121 lines
4.2 KiB
TypeScript

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 { verifyCandidateExecution } from '../../../orchestrator/src/backtest/candidate-sandbox';
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 | null> {
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 !== request.strategy.origin
) {
throw new RunReproductionError(409, 'The original retained strategy 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 (
request.strategy.origin === 'builtin'
? review?.decision !== 'approve'
: review?.decision === 'revoke'
) {
throw new RunReproductionError(
409,
request.strategy.origin === 'builtin'
? 'The original strategy version requires current operator approval'
: 'The original candidate version is explicitly revoked'
);
}
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'
);
}
if (request.strategy.origin === 'candidate') {
try {
await verifyCandidateExecution(request.strategy.execution);
} catch {
throw new RunReproductionError(
409,
'The retained isolated candidate runtime is not installed'
);
}
}
return review?.id ?? null;
}