190 lines
6.7 KiB
TypeScript
190 lines
6.7 KiB
TypeScript
/** Read-only promotion custody. This module cannot import or execute strategy code. */
|
|
import { createHash } from 'node:crypto';
|
|
import type { QueryResultRow } from 'pg';
|
|
import {
|
|
paperDeploymentSchema,
|
|
type PaperDeployment,
|
|
type PaperPromotionPreview,
|
|
} from '@stock-bot/stock-config/paper-deployments';
|
|
import { canonicalStrategyJson } from '@stock-bot/stock-config/strategy';
|
|
import { verifyRetainedProgramPackage } from './retained-package';
|
|
|
|
export interface PaperDeploymentDatabase {
|
|
query(text: string, values?: unknown[]): Promise<{ rows: QueryResultRow[] }>;
|
|
}
|
|
export class PaperDeploymentError extends Error {
|
|
constructor(
|
|
readonly status: 400 | 403 | 404 | 409 | 422 | 503,
|
|
message: string
|
|
) {
|
|
super(message);
|
|
}
|
|
}
|
|
export const paperHash = (value: unknown) =>
|
|
createHash('sha256').update(canonicalStrategyJson(value)).digest('hex');
|
|
export function paperPreviewHash(
|
|
preview: Omit<PaperPromotionPreview, 'previewHash'> | PaperPromotionPreview
|
|
) {
|
|
const { previewHash: _ignored, ...body } = preview as PaperPromotionPreview;
|
|
return paperHash(body);
|
|
}
|
|
export function retainedPaperDeployment(raw: unknown): PaperDeployment {
|
|
const value = paperDeploymentSchema.parse(raw);
|
|
const { promotionHash, ...body } = value;
|
|
if (
|
|
paperHash(body) !== promotionHash ||
|
|
paperPreviewHash(value.preview) !== value.preview.previewHash
|
|
) {
|
|
throw new Error('Retained paper promotion identity mismatch');
|
|
}
|
|
return value;
|
|
}
|
|
export async function readPaperDeployment(
|
|
database: PaperDeploymentDatabase,
|
|
id: string
|
|
): Promise<PaperDeployment> {
|
|
const row = (await database.query('SELECT * FROM paper_deployments WHERE id=$1', [id])).rows[0];
|
|
if (!row) {
|
|
throw new PaperDeploymentError(404, 'Paper deployment not found');
|
|
}
|
|
const value = retainedPaperDeployment(row.document);
|
|
if (
|
|
value.id !== row.id ||
|
|
value.preview.configuration.matching.risk.ledger.accountId !== row.account_id ||
|
|
value.preview.strategy.versionId !== row.strategy_version_id ||
|
|
value.promotionHash !== row.promotion_hash
|
|
) {
|
|
throw new Error('Retained paper deployment row identity mismatch');
|
|
}
|
|
return value;
|
|
}
|
|
/** Admission and activation require a current operator approval. Historical GET stays available. */
|
|
export async function authorizedPaperPackage(
|
|
database: PaperDeploymentDatabase,
|
|
deployment: PaperDeployment | Pick<PaperPromotionPreview, 'strategy'>,
|
|
lock = false
|
|
) {
|
|
const preview = 'preview' in deployment ? deployment.preview : deployment;
|
|
const version = (
|
|
await database.query(
|
|
`SELECT v.envelope,v.origin,s.archived_at FROM strategy_versions v JOIN strategies s ON s.id=v.strategy_id WHERE v.id=$1 AND s.id=$2${lock ? ' FOR UPDATE OF s' : ''}`,
|
|
[preview.strategy.versionId, preview.strategy.familyId]
|
|
)
|
|
).rows[0];
|
|
const review = (
|
|
await database.query(
|
|
'SELECT id,decision FROM strategy_review_events WHERE version_id=$1 ORDER BY ordinal DESC LIMIT 1',
|
|
[preview.strategy.versionId]
|
|
)
|
|
).rows[0];
|
|
if (!version || version.archived_at !== null || review?.decision !== 'approve') {
|
|
throw new PaperDeploymentError(
|
|
409,
|
|
'Paper deployment requires an active family and current operator approval'
|
|
);
|
|
}
|
|
const pkg = verifyRetainedProgramPackage(version.envelope);
|
|
if (
|
|
version.origin !== preview.strategy.origin ||
|
|
pkg.artifact.sha256 !== preview.strategy.artifactSha256 ||
|
|
pkg.dependencyLock.sha256 !== preview.strategy.dependencyLockSha256
|
|
) {
|
|
throw new Error('Paper promotion artifact no longer matches retained bytes');
|
|
}
|
|
return { pkg, reviewId: String(review.id) };
|
|
}
|
|
|
|
/** Host-side retained identity check, independent of the web API's full financial source reader. */
|
|
export async function verifyPaperEvidenceCustody(
|
|
database: PaperDeploymentDatabase,
|
|
deployment: PaperDeployment
|
|
) {
|
|
const { input, evidence } = deployment.preview,
|
|
source = input.outOfSample;
|
|
let report: Record<string, unknown> | undefined;
|
|
if (source.kind === 'chronological-report/v1') {
|
|
const row = (
|
|
await database.query('SELECT validation_report FROM research_experiments WHERE id=$1', [
|
|
source.validationId,
|
|
])
|
|
).rows[0];
|
|
report = row?.validation_report;
|
|
if ((report?.test as { runId?: string } | undefined)?.runId !== input.testRunId) {
|
|
throw new Error('Paper test membership changed');
|
|
}
|
|
} else if (source.kind === 'walk-forward-report/v1') {
|
|
const row = (
|
|
await database.query('SELECT report FROM research_walk_forwards WHERE id=$1', [
|
|
source.walkForwardId,
|
|
])
|
|
).rows[0];
|
|
report = row?.report;
|
|
if (
|
|
!(report?.segments as Array<{ test: { runId: string } }> | undefined)?.some(
|
|
segment => segment.test.runId === input.testRunId
|
|
)
|
|
) {
|
|
throw new Error('Paper walk-forward test membership changed');
|
|
}
|
|
} else {
|
|
throw new Error('Paper promotion requires sealed out-of-sample evidence');
|
|
}
|
|
if (!report) {
|
|
throw new Error('Paper source report is missing');
|
|
}
|
|
const { _receipt, reportHash, ...body } = report;
|
|
if (
|
|
!_receipt ||
|
|
paperHash(body) !== reportHash ||
|
|
reportHash !== source.reportHash ||
|
|
report.id !== source.reportId ||
|
|
report.previewHash !== source.previewHash
|
|
) {
|
|
throw new Error('Paper source report changed');
|
|
}
|
|
const cost = (
|
|
await database.query(
|
|
'SELECT preview,preview_hash,validation_phase FROM research_experiments WHERE id=$1',
|
|
[input.costExperimentId]
|
|
)
|
|
).rows[0];
|
|
if (
|
|
!cost ||
|
|
cost.validation_phase !== null ||
|
|
cost.preview?.version !== 'cost-sensitivity-preview/v1' ||
|
|
cost.preview_hash !== input.costPreviewHash ||
|
|
cost.preview?.previewHash !== input.costPreviewHash ||
|
|
cost.preview.candidates.length !== evidence.costs.length
|
|
) {
|
|
throw new Error('Paper cost source changed');
|
|
}
|
|
const rows = (
|
|
await database.query('SELECT id FROM runs WHERE experiment_id=$1 ORDER BY trial_index', [
|
|
input.costExperimentId,
|
|
])
|
|
).rows;
|
|
if (
|
|
canonicalStrategyJson(rows.map(row => row.id)) !==
|
|
canonicalStrategyJson(evidence.costs.map(item => item.runId))
|
|
) {
|
|
throw new Error('Paper cost membership changed');
|
|
}
|
|
for (const item of [evidence.test, ...evidence.costs]) {
|
|
const row = (
|
|
await database.query(
|
|
'SELECT r.status,r.request_snapshot,r.dataset_hash,br.canonical_result FROM runs r JOIN backtest_results br ON br.run_id=r.id WHERE r.id=$1',
|
|
[item.runId]
|
|
)
|
|
).rows[0];
|
|
if (
|
|
!row ||
|
|
row.status !== 'completed' ||
|
|
row.dataset_hash !== item.datasetHash ||
|
|
paperHash(row.canonical_result) !== item.resultHash ||
|
|
canonicalStrategyJson(row.canonical_result.request) !==
|
|
canonicalStrategyJson(row.request_snapshot)
|
|
) {
|
|
throw new Error('Paper retained result identity changed');
|
|
}
|
|
}
|
|
}
|