352 lines
13 KiB
TypeScript
352 lines
13 KiB
TypeScript
/**
|
|
* Converts editable workbench choices into a fully bound canonical request.
|
|
* Admission validates retained data/code and freezes financial policies/build
|
|
* identity; it neither runs a strategy nor writes the run/dispatch rows.
|
|
* Submission services own persistence; previews can discard the returned request.
|
|
* The worker verifies inputs again before execution.
|
|
*/
|
|
import { randomUUID } from 'node:crypto';
|
|
import type { PoolClient } from 'pg';
|
|
import { datasetUnavailableReason } from '@stock-bot/research/dataset-contracts';
|
|
import { validateDatasetV2 } from '@stock-bot/research/datasets';
|
|
import type { IServiceContainer } from '@stock-bot/services';
|
|
import {
|
|
retainedProgramSelectionSchema,
|
|
type CandidateExecution,
|
|
} from '@stock-bot/stock-config/candidate-execution';
|
|
import {
|
|
canonicalResearchSettingsSchema,
|
|
canonicalRunRequestSchema,
|
|
type CanonicalDatasetCatalogEntry,
|
|
type CanonicalRunRequest,
|
|
} from '@stock-bot/stock-config/canonical-research';
|
|
import {
|
|
builtinStrategySelectionSchema,
|
|
validateStrategyParameters,
|
|
} from '@stock-bot/stock-config/strategy';
|
|
import { readCandidateExecution } from '@stock-bot/trading-runtime/candidate-environment';
|
|
import { readCanonicalBuildIdentity } from '@stock-bot/trading-runtime/canonical-build';
|
|
import {
|
|
HistoricalDataRequestError,
|
|
parseFinancialDecimal,
|
|
type HistoricalDatasetV2,
|
|
type StrategyParameterValue,
|
|
} from '@stock-bot/types';
|
|
import { canonicalRiskSessionClock } from './canonical-risk-clock';
|
|
import type { DatasetCatalogQuery } from './dataset-catalog.service';
|
|
import { StrategyCatalogService } from './strategy-catalog.service';
|
|
|
|
export interface CanonicalTemplate {
|
|
name: string;
|
|
strategyVersionId?: string | null;
|
|
strategyParameters?: Record<string, StrategyParameterValue> | null;
|
|
symbols: string[];
|
|
startDate: string | Date;
|
|
endDate: string | Date;
|
|
initialCapital: number;
|
|
config?: Record<string, unknown> | null;
|
|
}
|
|
const invalid = (message: string): never => {
|
|
throw new HistoricalDataRequestError(message);
|
|
};
|
|
|
|
/** Read rejection statuses for exports; existing callers may still catch the base request error. */
|
|
export class CanonicalDatasetReadError extends HistoricalDataRequestError {
|
|
constructor(
|
|
readonly status: 400 | 404 | 409 | 422,
|
|
message: string
|
|
) {
|
|
super(message);
|
|
}
|
|
}
|
|
|
|
/** The existing workbench gate, shared by retained selection and source preview. */
|
|
export function canonicalDatasetUnavailableReason(dataset: HistoricalDatasetV2): string | null {
|
|
return datasetUnavailableReason(dataset.manifest);
|
|
}
|
|
|
|
/**
|
|
* Revalidate the stored payload and hash before trusting a catalog selection.
|
|
* A syntactically valid hash or manifest alone is not execution eligibility.
|
|
*/
|
|
export async function readCanonicalDataset(
|
|
database: DatasetCatalogQuery,
|
|
hash: unknown,
|
|
signal?: AbortSignal
|
|
): Promise<HistoricalDatasetV2> {
|
|
signal?.throwIfAborted();
|
|
if (typeof hash !== 'string' || !/^[a-f0-9]{64}$/.test(hash)) {
|
|
throw new CanonicalDatasetReadError(400, 'Choose an explicitly retained v2 dataset');
|
|
}
|
|
const row = (await database.query('SELECT payload FROM backtest_datasets WHERE hash=$1', [hash]))
|
|
.rows[0];
|
|
signal?.throwIfAborted();
|
|
if (!row) {
|
|
throw new CanonicalDatasetReadError(404, 'Selected canonical dataset was not found');
|
|
}
|
|
let dataset;
|
|
try {
|
|
dataset = validateDatasetV2(row.payload);
|
|
} catch {
|
|
throw new CanonicalDatasetReadError(409, 'Retained v2 dataset failed content validation');
|
|
}
|
|
if (dataset.manifest.hash !== hash) {
|
|
throw new CanonicalDatasetReadError(409, 'Retained dataset identity mismatch');
|
|
}
|
|
const unavailable = canonicalDatasetUnavailableReason(dataset);
|
|
if (unavailable) {
|
|
throw new CanonicalDatasetReadError(422, unavailable);
|
|
}
|
|
return dataset;
|
|
}
|
|
|
|
export async function canonicalDatasetEntry(
|
|
database: DatasetCatalogQuery,
|
|
row: { hash: string; created_at: Date }
|
|
): Promise<CanonicalDatasetCatalogEntry> {
|
|
try {
|
|
const dataset = await readCanonicalDataset(database, row.hash);
|
|
return {
|
|
hash: row.hash,
|
|
createdAt: new Date(row.created_at).toISOString(),
|
|
manifest: dataset.manifest,
|
|
available: true,
|
|
reason: null,
|
|
};
|
|
} catch (error) {
|
|
if (!(error instanceof HistoricalDataRequestError)) {
|
|
throw error;
|
|
}
|
|
return {
|
|
hash: row.hash,
|
|
createdAt: new Date(row.created_at).toISOString(),
|
|
manifest: null,
|
|
available: false,
|
|
reason: error.message,
|
|
};
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Require template symbols, interval and trading bounds to match retained input
|
|
* exactly. Warmup remains part of that dataset rather than an implicit new fetch.
|
|
* This v2 boundary avoids rounding session timestamps through the v1 daily parser.
|
|
*/
|
|
export async function validateCanonicalSetup(
|
|
database: DatasetCatalogQuery,
|
|
template: CanonicalTemplate
|
|
) {
|
|
const config = template.config ?? {};
|
|
if (
|
|
Object.keys(config).some(key => !['datasetHash', 'dataFrequency', 'canonical'].includes(key))
|
|
) {
|
|
return invalid('Canonical settings cannot include legacy fees, risk controls or fill models');
|
|
}
|
|
const settings = canonicalResearchSettingsSchema.parse(config.canonical);
|
|
const dataset = await readCanonicalDataset(database, config.datasetHash);
|
|
const execution = dataset.manifest.executionSeries[0];
|
|
const series = dataset.manifest.series.find(item => item.id === execution?.seriesId);
|
|
if (!execution || !series) {
|
|
return invalid('Retained dataset is missing its execution series');
|
|
}
|
|
if (
|
|
template.symbols.length !== 1 ||
|
|
template.symbols[0] !== execution.instrumentId ||
|
|
config.dataFrequency !== series.interval ||
|
|
new Date(template.startDate).getTime() !== dataset.manifest.bounds.tradeStart ||
|
|
new Date(template.endDate).getTime() !== dataset.manifest.bounds.tradeEnd
|
|
) {
|
|
return invalid(
|
|
'Canonical symbols, interval and exact trade bounds must match the retained dataset'
|
|
);
|
|
}
|
|
let initial;
|
|
try {
|
|
initial = parseFinancialDecimal(String(template.initialCapital));
|
|
} catch {
|
|
return invalid('Initial capital must be an exact supported financial decimal');
|
|
}
|
|
const units = BigInt(initial.replace('.', ''));
|
|
if (units <= 0n || units % 1000000n !== 0n) {
|
|
return invalid('Saved initial capital must be positive USD with at most two decimal places');
|
|
}
|
|
if (BigInt(settings.ownerBudget.replace('.', '')) > units) {
|
|
return invalid('Strategy owner budget cannot exceed initial capital');
|
|
}
|
|
return { settings, dataset, execution, series, initial };
|
|
}
|
|
|
|
/**
|
|
* Build the immutable request while the caller holds the backtest row lock.
|
|
* Family locks also serialize admission with review/archive changes. Candidate
|
|
* overrides validate both the granted baseline and the replacement; catalog
|
|
* approval never turns candidate code into trusted research callbacks.
|
|
*
|
|
* The returned request pins a retained package, dataset hash, execution profile,
|
|
* Rust/worker build and policies. Account identity derives from runId; preview
|
|
* callers may use a placeholder and discard the request. Execution callers must
|
|
* persist the request and dispatch intent together, using a new research run ID.
|
|
*/
|
|
export async function admitCanonicalRequest(
|
|
client: PoolClient,
|
|
container: IServiceContainer,
|
|
template: CanonicalTemplate,
|
|
backtestId: string,
|
|
runId = randomUUID(),
|
|
override?: { versionId: string; parameters: Record<string, StrategyParameterValue> },
|
|
baselineVersionId = template.strategyVersionId
|
|
): Promise<CanonicalRunRequest> {
|
|
if (override) {
|
|
await client.query(
|
|
'SELECT s.id FROM strategies s WHERE s.id IN (SELECT strategy_id FROM strategy_versions WHERE id=ANY($1::uuid[])) ORDER BY s.id FOR UPDATE',
|
|
[[template.strategyVersionId, override.versionId].filter(Boolean)]
|
|
);
|
|
await admitCanonicalRequest(client, container, template, backtestId, runId);
|
|
const candidate = await admitCanonicalRequest(
|
|
client,
|
|
container,
|
|
{
|
|
...template,
|
|
strategyVersionId: override.versionId,
|
|
strategyParameters: override.parameters,
|
|
},
|
|
backtestId,
|
|
runId,
|
|
undefined,
|
|
template.strategyVersionId
|
|
);
|
|
if (candidate.strategy.origin !== 'candidate') {
|
|
return invalid('Candidate override requires an immutable candidate version');
|
|
}
|
|
return candidate;
|
|
}
|
|
if (!template.strategyVersionId || !template.strategyParameters) {
|
|
return invalid('Select an immutable strategy version and validated parameters');
|
|
}
|
|
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`,
|
|
[template.strategyVersionId]
|
|
)
|
|
).rows[0];
|
|
if (
|
|
!selected ||
|
|
selected.archived_at !== null ||
|
|
!['builtin', 'candidate'].includes(selected.origin)
|
|
) {
|
|
return invalid('Select an active retained strategy version');
|
|
}
|
|
const review = (
|
|
await client.query(
|
|
'SELECT id,decision FROM strategy_review_events WHERE version_id=$1 ORDER BY ordinal DESC LIMIT 1',
|
|
[template.strategyVersionId]
|
|
)
|
|
).rows[0];
|
|
if (
|
|
selected.origin === 'builtin' ? review?.decision !== 'approve' : review?.decision === 'revoke'
|
|
) {
|
|
return invalid(
|
|
selected.origin === 'builtin'
|
|
? 'An operator must approve this built-in version before execution'
|
|
: 'The candidate version is revoked'
|
|
);
|
|
}
|
|
const pkg = await new StrategyCatalogService(container).getVersionArtifact(
|
|
template.strategyVersionId,
|
|
client
|
|
);
|
|
let candidateExecution: CandidateExecution | undefined;
|
|
if (selected.origin === 'candidate') {
|
|
if (
|
|
pkg.execution?.kind !== 'isolated-candidate/v1' ||
|
|
pkg.program.apiVersion !== 'canonical-ts/v1'
|
|
) {
|
|
return invalid(
|
|
'Candidate requires a retained isolated execution declaration and supported API'
|
|
);
|
|
}
|
|
try {
|
|
candidateExecution = await readCandidateExecution();
|
|
} catch (error) {
|
|
return invalid(error instanceof Error ? error.message : 'Candidate isolation unavailable');
|
|
}
|
|
} else if (pkg.execution !== undefined) {
|
|
return invalid('Built-in origin cannot select a candidate execution profile');
|
|
}
|
|
const { settings, dataset, execution, initial } = await validateCanonicalSetup(client, template);
|
|
const clock = canonicalRiskSessionClock(dataset);
|
|
const ownerId = `strategy:${template.strategyVersionId}`;
|
|
const selection = (
|
|
selected.origin === 'candidate'
|
|
? retainedProgramSelectionSchema
|
|
: builtinStrategySelectionSchema
|
|
).parse({
|
|
strategyId: pkg.program.strategyId,
|
|
strategyVersion: pkg.program.strategyVersion,
|
|
ownerId,
|
|
seed: settings.seed,
|
|
instrumentId: execution.instrumentId,
|
|
seriesId: execution.seriesId,
|
|
ownerBudget: settings.ownerBudget,
|
|
parameters: validateStrategyParameters(pkg, template.strategyParameters),
|
|
// API/checkpoint identities are retained in the package, not selection fields.
|
|
});
|
|
return canonicalRunRequestSchema.parse({
|
|
kind: 'canonical-research/v1',
|
|
runId,
|
|
backtestId,
|
|
name: template.name,
|
|
strategy: {
|
|
familyId: selected.strategy_id,
|
|
versionId: template.strategyVersionId,
|
|
origin: selected.origin,
|
|
reviewId: review?.id ?? null,
|
|
...(candidateExecution ? { execution: candidateExecution, baselineVersionId } : {}),
|
|
package: pkg,
|
|
selection,
|
|
},
|
|
datasetHash: dataset.manifest.hash,
|
|
policy: {
|
|
matching: {
|
|
risk: {
|
|
ledger: {
|
|
version: 1,
|
|
sessionId: runId,
|
|
accountId: `research:${runId}`,
|
|
baseCurrency: 'USD',
|
|
reserveOwnerId: 'reserve',
|
|
ownerIds: [ownerId],
|
|
initialCapital: initial,
|
|
riskSession: clock.riskSession,
|
|
},
|
|
feeRate: settings.feeRate,
|
|
maxOrderQuantity: settings.maxOrderQuantity,
|
|
maxPositionQuantity: settings.maxPositionQuantity,
|
|
maxSymbolExposure: settings.maxSymbolExposure,
|
|
maxGrossExposure: settings.maxGrossExposure,
|
|
maxDailyLoss: settings.maxDailyLoss,
|
|
maxDrawdownAmount: settings.maxDrawdownAmount,
|
|
maxMarkAgeMs: settings.maxMarkAgeMs,
|
|
},
|
|
owners: [{ ownerId, mode: 'Target' }],
|
|
series: [{ ...execution, mode: 'Open' }],
|
|
halfSpreadRate: settings.halfSpreadRate,
|
|
slippageRate: settings.slippageRate,
|
|
latencyMs: settings.latencyMs,
|
|
},
|
|
participation_rate: settings.participationRate,
|
|
cadence: [{ owner_id: ownerId, series_ids: [execution.seriesId] }],
|
|
allow_exploratory: false,
|
|
risk_boundaries: clock.riskBoundaries,
|
|
},
|
|
analyticsPolicy: {
|
|
version: 1,
|
|
periodsPerYear: settings.periodsPerYear,
|
|
annualRiskFreeRate: settings.annualRiskFreeRate,
|
|
benchmark: null,
|
|
},
|
|
build: await readCanonicalBuildIdentity(),
|
|
modelArtifacts: [],
|
|
});
|
|
}
|