361 lines
14 KiB
TypeScript
361 lines
14 KiB
TypeScript
import { randomUUID } from 'node:crypto';
|
|
import { requireServices, type IServiceContainer } from '@stock-bot/services';
|
|
import type {
|
|
CanonicalRunRequest,
|
|
CanonicalRunResult,
|
|
} from '@stock-bot/stock-config/canonical-research';
|
|
import {
|
|
paperPromotionInputSchema,
|
|
paperPromotionPreviewSchema,
|
|
paperPromotionSubmissionSchema,
|
|
type PaperDeployment,
|
|
type PaperPromotionInput,
|
|
type PaperPromotionPreview,
|
|
} from '@stock-bot/stock-config/paper-deployments';
|
|
import { assertStrategyJsonText, canonicalStrategyJson } from '@stock-bot/stock-config/strategy';
|
|
import { validatePaperConfiguration } from '@stock-bot/trading-runtime/paper-configuration';
|
|
import {
|
|
authorizedPaperPackage,
|
|
PaperDeploymentError,
|
|
paperHash,
|
|
paperPreviewHash,
|
|
readPaperDeployment,
|
|
retainedPaperDeployment,
|
|
} from '@stock-bot/trading-runtime/paper-deployment-custody';
|
|
import { readPaperHostIdentity } from '@stock-bot/trading-runtime/paper-host-identity';
|
|
import type { ResearchEvidenceReference } from '@stock-bot/types';
|
|
import type { BacktestResultQuery } from './backtests/contracts';
|
|
import type { BacktestResults } from './backtests/results';
|
|
import { retainedCostSensitivityPreview } from './cost-sensitivity-input';
|
|
import { canonicalReproductionHash } from './reproduction-comparison';
|
|
import { verifyResearchSource } from './research-source-evidence';
|
|
|
|
const equal = (a: unknown, b: unknown) => canonicalStrategyJson(a) === canonicalStrategyJson(b);
|
|
const reference = (runId: string): ResearchEvidenceReference => ({
|
|
runId,
|
|
metricsVersion: 'canonical-analytics/v1',
|
|
metricPath: 'analytics.metrics.totalReturn',
|
|
});
|
|
const inputError = (message: string): never => {
|
|
throw new PaperDeploymentError(422, message);
|
|
};
|
|
/** Explicit economic comparison: only run identity, dates, and the two studied cost rates may vary. */
|
|
export function paperEconomicProfile(request: CanonicalRunRequest) {
|
|
const { ledger, feeRate: _fee, ...risk } = request.policy.matching.risk;
|
|
const { sessionId: _session, accountId: _account, riskSession: _clock, ...capital } = ledger;
|
|
const { risk: _risk, slippageRate: _slippage, ...execution } = request.policy.matching;
|
|
const { matching: _matching, risk_boundaries: _boundaries, ...policy } = request.policy;
|
|
const { reviewId: _review, ...strategy } = request.strategy;
|
|
return {
|
|
strategy,
|
|
capital,
|
|
risk,
|
|
execution,
|
|
policy,
|
|
analyticsPolicy: request.analyticsPolicy,
|
|
build: request.build,
|
|
modelArtifacts: request.modelArtifacts,
|
|
};
|
|
}
|
|
function evidence(result: CanonicalRunResult) {
|
|
return {
|
|
runId: result.runId,
|
|
datasetHash: result.request.datasetHash,
|
|
economicHash: canonicalReproductionHash(result),
|
|
resultHash: paperHash(result),
|
|
metrics: { ...result.analytics.metrics },
|
|
fillCount: result.analytics.fillCount,
|
|
limitations: [...result.financial.limitations, ...result.financial.modelLimitations],
|
|
};
|
|
}
|
|
|
|
export class PaperDeploymentsService {
|
|
private readonly database;
|
|
constructor(
|
|
private readonly container: IServiceContainer,
|
|
private readonly results: Pick<BacktestResults, 'getRunResults'>,
|
|
private readonly identity = readPaperHostIdentity
|
|
) {
|
|
this.database = requireServices(container, 'postgres').postgres;
|
|
}
|
|
private async prepare(
|
|
input: PaperPromotionInput,
|
|
db: BacktestResultQuery,
|
|
lock = false
|
|
): Promise<PaperPromotionPreview> {
|
|
const selected = paperPromotionInputSchema.parse(input),
|
|
source = selected.outOfSample;
|
|
const results = await verifyResearchSource(
|
|
source,
|
|
[reference(selected.testRunId)],
|
|
db,
|
|
(id, tx) => this.results.getRunResults(id, tx)
|
|
);
|
|
const test = results.get(selected.testRunId);
|
|
if (!test) {
|
|
return inputError('Selected test evidence is unavailable');
|
|
}
|
|
let sourceHash: string | undefined;
|
|
if (source.kind === 'chronological-report/v1') {
|
|
const row = (
|
|
await db.query(
|
|
'SELECT validation_report,validation_manifest FROM research_experiments WHERE id=$1',
|
|
[source.validationId]
|
|
)
|
|
).rows[0];
|
|
if (row?.validation_report?.test?.runId !== test.runId) {
|
|
return inputError('Select the sealed test run, not training or validation');
|
|
}
|
|
sourceHash = row.validation_manifest?.source?.request?.datasetHash;
|
|
} else {
|
|
const row = (
|
|
await db.query('SELECT report,preview FROM research_walk_forwards WHERE id=$1', [
|
|
source.walkForwardId,
|
|
])
|
|
).rows[0];
|
|
if (
|
|
!row?.report?.segments?.some(
|
|
(segment: { test?: { runId: string } }) => segment.test?.runId === test.runId
|
|
)
|
|
) {
|
|
return inputError('Select a sealed walk-forward test run');
|
|
}
|
|
sourceHash = row.preview?.source?.request?.datasetHash;
|
|
}
|
|
const costRow = (
|
|
await db.query('SELECT * FROM research_experiments WHERE id=$1', [selected.costExperimentId])
|
|
).rows[0];
|
|
if (
|
|
!costRow ||
|
|
costRow.validation_phase !== null ||
|
|
costRow.preview?.version !== 'cost-sensitivity-preview/v1'
|
|
) {
|
|
return inputError('Select a standalone cost-sensitivity study');
|
|
}
|
|
const costs = retainedCostSensitivityPreview(costRow.preview);
|
|
if (
|
|
costs.previewHash !== selected.costPreviewHash ||
|
|
costRow.preview_hash !== costs.previewHash ||
|
|
costs.source.request.datasetHash !== sourceHash
|
|
) {
|
|
return inputError('Cost evidence must use the exact common source dataset and preview');
|
|
}
|
|
const rows = (
|
|
await db.query(
|
|
'SELECT id,status,trial_index FROM runs WHERE experiment_id=$1 ORDER BY trial_index',
|
|
[selected.costExperimentId]
|
|
)
|
|
).rows;
|
|
if (
|
|
rows.length !== costs.candidates.length ||
|
|
rows.some((r, i) => r.status !== 'completed' || r.trial_index !== i)
|
|
) {
|
|
return inputError('Every cost scenario must have a completed retained result');
|
|
}
|
|
const costResults = await verifyResearchSource(
|
|
{ kind: 'experiment/v1', experimentId: costRow.id, previewHash: costs.previewHash },
|
|
rows.map(r => reference(r.id)),
|
|
db,
|
|
(id, tx) => this.results.getRunResults(id, tx)
|
|
);
|
|
const cost = costResults.get(selected.costRunId);
|
|
if (!cost) {
|
|
return inputError('Selected cost scenario is not a completed member');
|
|
}
|
|
for (const item of costResults.values()) {
|
|
if (!equal(paperEconomicProfile(test.request), paperEconomicProfile(item.request))) {
|
|
return inputError(
|
|
'Test and cost evidence must share the exact version, parameters, seed, capital, risk, execution and research build'
|
|
);
|
|
}
|
|
}
|
|
const selection = structuredClone(cost.request.strategy.selection),
|
|
matching = structuredClone(cost.request.policy.matching);
|
|
const { transport } = selected;
|
|
matching.risk.ledger.accountId = transport.accountId;
|
|
matching.risk.ledger.sessionId = transport.sessionId;
|
|
matching.risk.ledger.riskSession = transport.riskSession;
|
|
const configuration = validatePaperConfiguration({
|
|
version: 2,
|
|
matching: {
|
|
...matching,
|
|
series: [
|
|
{
|
|
instrumentId: selection.instrumentId,
|
|
seriesId: transport.quoteSeriesId,
|
|
mode: 'Quote',
|
|
},
|
|
],
|
|
},
|
|
strategies: [selection],
|
|
policy: transport.policy,
|
|
});
|
|
if (configuration.version !== 2) {
|
|
throw new Error('Promotion requires deployment configuration');
|
|
}
|
|
const interval = costs.dataset.series.find(s => s.id === selection.seriesId)?.interval;
|
|
if (interval === '1d') {
|
|
return inputError(
|
|
'Paper promotion currently requires an explicit intraday observation interval'
|
|
);
|
|
}
|
|
const retainedInterval = interval
|
|
? { '1m': 60000, '5m': 300000, '15m': 900000, '1h': 3600000, '1d': 86400000 }[interval]
|
|
: undefined;
|
|
if (
|
|
configuration.policy.observations.length !== 1 ||
|
|
configuration.policy.observations[0]?.intervalMs !== retainedInterval
|
|
) {
|
|
return inputError('Paper observation interval must equal the retained research series');
|
|
}
|
|
const strategy = {
|
|
familyId: test.request.strategy.familyId,
|
|
versionId: test.request.strategy.versionId,
|
|
origin: test.request.strategy.origin,
|
|
reviewId: test.request.strategy.reviewId as string,
|
|
artifactSha256: test.request.strategy.package.artifact.sha256,
|
|
dependencyLockSha256: test.request.strategy.package.dependencyLock.sha256,
|
|
};
|
|
const host = await this.identity();
|
|
const sharedBuildFields = [
|
|
'engineWrapperSha256',
|
|
'engineBinarySha256',
|
|
'dependencyLockSha256',
|
|
'runtime',
|
|
'runtimeVersion',
|
|
'platform',
|
|
'arch',
|
|
] as const;
|
|
if (sharedBuildFields.some(field => host[field] !== test.request.build[field])) {
|
|
throw new PaperDeploymentError(
|
|
409,
|
|
'Paper and research require the same native, dependency and runtime build; rerun evidence on the installed build'
|
|
);
|
|
}
|
|
const draft = {
|
|
version: 'paper-promotion-preview/v1' as const,
|
|
input: selected,
|
|
strategy,
|
|
configuration,
|
|
host,
|
|
evidence: {
|
|
test: evidence(test),
|
|
costs: rows.map(r => {
|
|
const result = costResults.get(r.id);
|
|
if (!result) {
|
|
throw new Error('Missing verified cost result');
|
|
}
|
|
return evidence(result);
|
|
}),
|
|
},
|
|
limitations: [
|
|
'Human promotion authorizes these exact strategy bytes to execute as trusted paper-host code; research isolation does not carry over.',
|
|
'Paper uses explicit quotes and displayed sizes instead of historical Open prices and volume participation; fills may differ.',
|
|
'Future feed timing, sessions, corporate-action handling and liquidity are operator-supplied. No live broker is connected.',
|
|
'Paper starts with the factory initial strategy state and empty positions; historical strategy checkpoints are not copied.',
|
|
'Sealed reset-account holdouts and cost studies are evidence, not a guarantee of future performance.',
|
|
],
|
|
};
|
|
const authorization = await authorizedPaperPackage(db, draft, lock);
|
|
draft.strategy.reviewId = authorization.reviewId;
|
|
return paperPromotionPreviewSchema.parse({ ...draft, previewHash: paperPreviewHash(draft) });
|
|
}
|
|
async preview(raw: unknown) {
|
|
assertStrategyJsonText(raw);
|
|
const input = paperPromotionInputSchema.parse(raw);
|
|
return this.database.transaction(async tx => {
|
|
await tx.query('SET TRANSACTION ISOLATION LEVEL REPEATABLE READ READ ONLY');
|
|
return this.prepare(input, tx);
|
|
});
|
|
}
|
|
async create(raw: unknown, key: string): Promise<PaperDeployment> {
|
|
if (!/^[!-~]{1,200}$/.test(key)) {
|
|
throw new PaperDeploymentError(400, 'A printable Idempotency-Key is required');
|
|
}
|
|
assertStrategyJsonText(raw);
|
|
const input = paperPromotionSubmissionSchema.parse(raw),
|
|
requestHash = paperHash(input);
|
|
return this.database.transaction(async tx => {
|
|
await tx.query("SELECT pg_advisory_xact_lock(hashtextextended('paper-promotion:'||$1,0))", [
|
|
key,
|
|
]);
|
|
const old = (
|
|
await tx.query(
|
|
'SELECT document,request_hash FROM paper_deployments WHERE idempotency_key=$1',
|
|
[key]
|
|
)
|
|
).rows[0];
|
|
if (old) {
|
|
if (old.request_hash !== requestHash) {
|
|
throw new PaperDeploymentError(409, 'Paper promotion key already names another request');
|
|
}
|
|
return retainedPaperDeployment(old.document);
|
|
}
|
|
const { previewHash, ...rawInput } = input;
|
|
const preview = await this.prepare(rawInput, tx, true);
|
|
if (preview.previewHash !== previewHash) {
|
|
throw new PaperDeploymentError(
|
|
409,
|
|
'Paper preview changed; review the evidence and host identity again'
|
|
);
|
|
}
|
|
const body = {
|
|
id: randomUUID(),
|
|
version: 'paper-deployment/v1' as const,
|
|
principal: 'operator' as const,
|
|
createdAt: new Date().toISOString(),
|
|
preview,
|
|
};
|
|
const document = { ...body, promotionHash: paperHash(body) };
|
|
try {
|
|
await tx.query(
|
|
'INSERT INTO paper_deployments(id,account_id,strategy_version_id,promotion_hash,idempotency_key,request_hash,document) VALUES($1,$2,$3,$4,$5,$6,$7::jsonb)',
|
|
[
|
|
document.id,
|
|
preview.configuration.matching.risk.ledger.accountId,
|
|
preview.strategy.versionId,
|
|
document.promotionHash,
|
|
key,
|
|
requestHash,
|
|
JSON.stringify(document),
|
|
]
|
|
);
|
|
} catch (error) {
|
|
if ((error as { code?: string }).code === '23505') {
|
|
throw new PaperDeploymentError(409, 'Paper account already has an immutable deployment');
|
|
}
|
|
throw error;
|
|
}
|
|
return document;
|
|
});
|
|
}
|
|
async list(): Promise<PaperDeployment[]> {
|
|
return (
|
|
await this.database.query(
|
|
'SELECT document FROM paper_deployments ORDER BY created_at DESC,id'
|
|
)
|
|
).rows.map(r => retainedPaperDeployment(r.document));
|
|
}
|
|
async get(id: string) {
|
|
return readPaperDeployment(this.database, id);
|
|
}
|
|
/** Recheck full retained financial evidence before forwarding a human bind or activation. */
|
|
async authorizeCommand(id: string) {
|
|
return this.database.transaction(async tx => {
|
|
await tx.query('SET TRANSACTION ISOLATION LEVEL REPEATABLE READ READ ONLY');
|
|
const saved = await readPaperDeployment(tx, id);
|
|
const current = await this.prepare(saved.preview.input, tx);
|
|
const oldBody = {
|
|
...saved.preview,
|
|
strategy: { ...saved.preview.strategy, reviewId: current.strategy.reviewId },
|
|
};
|
|
if (paperPreviewHash(oldBody) !== current.previewHash) {
|
|
throw new PaperDeploymentError(
|
|
409,
|
|
'Retained deployment evidence or installed paper host changed'
|
|
);
|
|
}
|
|
return saved;
|
|
});
|
|
}
|
|
}
|