feat(research): isolate candidates and add reviewed paper promotion
This commit is contained in:
parent
26b97265c6
commit
25b5cbf481
128 changed files with 13038 additions and 1388 deletions
|
|
@ -68,7 +68,10 @@ export async function runMigrations(container: IServiceContainer): Promise<void>
|
|||
f === '25-walk-forward.sql' ||
|
||||
f === '26-cost-sensitivity.sql' ||
|
||||
f === '27-research-evidence-sources.sql' ||
|
||||
f === '28-research-agents.sql')
|
||||
f === '28-research-agents.sql' ||
|
||||
f === '29-isolated-candidates.sql' ||
|
||||
f === '30-paper-deployments.sql' ||
|
||||
f === '31-research-agent-project-links.sql')
|
||||
) // Explicit additive migration allowlist; never replay destructive init migrations
|
||||
.sort();
|
||||
|
||||
|
|
|
|||
|
|
@ -15,6 +15,7 @@ import { createExchangeRoutes } from './exchange.routes';
|
|||
import { createExperimentRoutes } from './experiments.routes';
|
||||
import { createHealthRoutes } from './health.routes';
|
||||
import { createMonitoringRoutes } from './monitoring.routes';
|
||||
import { createPaperDeploymentRoutes } from './paper-deployments.routes';
|
||||
import { createPipelineRoutes } from './pipeline.routes';
|
||||
import { createResearchAgentRoutes } from './research-agents.routes';
|
||||
import { createResearchRoutes } from './research.routes';
|
||||
|
|
@ -24,7 +25,11 @@ import { createStrategyRoutes } from './strategies.routes';
|
|||
// the old 1 MiB restriction; normalizers still validate every submitted record.
|
||||
export const WEB_API_MAX_REQUEST_BODY_SIZE = Number.MAX_SAFE_INTEGER;
|
||||
|
||||
export function createRoutes(container: IServiceContainer, suppliedSecurity?: HttpSecurity): Hono {
|
||||
export function createRoutes(
|
||||
container: IServiceContainer,
|
||||
suppliedSecurity?: HttpSecurity,
|
||||
integrations?: { paperOrchestratorOrigin?: string }
|
||||
): Hono {
|
||||
const agents = new ResearchAgentsService(container);
|
||||
const security =
|
||||
suppliedSecurity ??
|
||||
|
|
@ -67,6 +72,13 @@ export function createRoutes(container: IServiceContainer, suppliedSecurity?: Ht
|
|||
app.route('/', createResearchRoutes(container));
|
||||
app.route('/', createResearchAgentRoutes(container, security.researchEnabled));
|
||||
app.route('/', createExperimentRoutes(container));
|
||||
app.route(
|
||||
'/',
|
||||
createPaperDeploymentRoutes(container, {
|
||||
origin: integrations ? integrations.paperOrchestratorOrigin : process.env.ORCHESTRATOR_URL,
|
||||
origins: security.allowedOrigins,
|
||||
})
|
||||
);
|
||||
|
||||
return app;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -75,7 +75,10 @@ export function createExperimentRoutes(container: IServiceContainer) {
|
|||
};
|
||||
app.post('/api/v2/experiments/cost-sensitivity/preview', async c =>
|
||||
c.json({
|
||||
preview: await service.previewCosts(parseCostSensitivityInput(await body(c.req.raw))),
|
||||
preview: await service.previewCosts(
|
||||
parseCostSensitivityInput(await body(c.req.raw)),
|
||||
getResearchHttpPrincipal(c.req.raw) ?? ''
|
||||
),
|
||||
})
|
||||
);
|
||||
app.post('/api/v2/experiments/cost-sensitivity', async c => {
|
||||
|
|
@ -91,7 +94,12 @@ export function createExperimentRoutes(container: IServiceContainer) {
|
|||
return c.json({ experiment }, 202);
|
||||
});
|
||||
app.post('/api/v2/experiments/walk-forward/preview', async c =>
|
||||
c.json({ preview: await walkForwards.preview(parseWalkForwardInput(await body(c.req.raw))) })
|
||||
c.json({
|
||||
preview: await walkForwards.preview(
|
||||
parseWalkForwardInput(await body(c.req.raw)),
|
||||
getResearchHttpPrincipal(c.req.raw) ?? ''
|
||||
),
|
||||
})
|
||||
);
|
||||
app.post('/api/v2/experiments/walk-forward', async c => {
|
||||
const input = parseWalkForwardSubmission(await body(c.req.raw));
|
||||
|
|
@ -140,7 +148,9 @@ export function createExperimentRoutes(container: IServiceContainer) {
|
|||
});
|
||||
app.post('/api/v2/experiments/validation/preview', async c => {
|
||||
const input = parseChronologicalValidation(await body(c.req.raw));
|
||||
return c.json({ preview: await service.previewValidation(input) });
|
||||
return c.json({
|
||||
preview: await service.previewValidation(input, getResearchHttpPrincipal(c.req.raw) ?? ''),
|
||||
});
|
||||
});
|
||||
app.post('/api/v2/experiments/validation', async c => {
|
||||
const input = parseValidationSubmission(await body(c.req.raw));
|
||||
|
|
@ -204,7 +214,9 @@ export function createExperimentRoutes(container: IServiceContainer) {
|
|||
});
|
||||
app.post('/api/v2/experiments/preview', async c => {
|
||||
const input = parseExperimentInput(await body(c.req.raw));
|
||||
return c.json({ preview: await service.preview(input) });
|
||||
return c.json({
|
||||
preview: await service.preview(input, getResearchHttpPrincipal(c.req.raw) ?? ''),
|
||||
});
|
||||
});
|
||||
app.post('/api/v2/experiments', async c => {
|
||||
const input = parseExperimentSubmission(await body(c.req.raw));
|
||||
|
|
|
|||
178
apps/stock/web-api/src/routes/paper-deployments.routes.ts
Normal file
178
apps/stock/web-api/src/routes/paper-deployments.routes.ts
Normal file
|
|
@ -0,0 +1,178 @@
|
|||
import { Hono } from 'hono';
|
||||
import { z } from 'zod';
|
||||
import type { IServiceContainer } from '@stock-bot/services';
|
||||
import { paperDeploymentStatusSchema } from '@stock-bot/stock-config/paper-deployments';
|
||||
import {
|
||||
paperActivationSchema,
|
||||
paperHaltSchema,
|
||||
PaperRuntimeError,
|
||||
} from '../../../orchestrator/src/contracts/paper-runtime';
|
||||
import { PaperDeploymentError } from '../../../orchestrator/src/paper/paper-deployment-custody';
|
||||
import {
|
||||
paperAllowedOrigins,
|
||||
requirePaperOperator,
|
||||
} from '../../../orchestrator/src/paper/paper-operator';
|
||||
import { PaperDeploymentsService } from '../services/paper-deployments.service';
|
||||
import { ResearchError } from '../services/research-errors';
|
||||
|
||||
/** Forwards the original human credential; never substitutes a service token. */
|
||||
export async function forwardPaperCommand(
|
||||
request: Request,
|
||||
id: string,
|
||||
operation: 'bind' | 'activate' | 'halt' | 'readiness',
|
||||
body: unknown,
|
||||
options: {
|
||||
origin?: string;
|
||||
request?: (url: string | URL | Request, init?: RequestInit) => Promise<Response>;
|
||||
}
|
||||
) {
|
||||
if (!options.origin) {
|
||||
throw new PaperDeploymentError(503, 'Paper orchestrator origin is not configured');
|
||||
}
|
||||
let base: URL;
|
||||
try {
|
||||
base = new URL(options.origin);
|
||||
} catch {
|
||||
throw new PaperDeploymentError(503, 'Paper orchestrator origin is invalid');
|
||||
}
|
||||
if (
|
||||
!['http:', 'https:'].includes(base.protocol) ||
|
||||
base.username ||
|
||||
base.password ||
|
||||
base.pathname !== '/' ||
|
||||
base.search ||
|
||||
base.hash
|
||||
) {
|
||||
throw new PaperDeploymentError(503, 'Paper orchestrator requires a fixed HTTP origin');
|
||||
}
|
||||
const headers = new Headers({ 'Content-Type': 'application/json' });
|
||||
for (const name of ['authorization', 'cookie', 'origin']) {
|
||||
const value = request.headers.get(name);
|
||||
if (value) {
|
||||
headers.set(name, value);
|
||||
}
|
||||
}
|
||||
let response: Response;
|
||||
try {
|
||||
response = await (options.request ?? fetch)(
|
||||
new URL(`/api/paper/deployments/${id}/${operation}`, base),
|
||||
{
|
||||
method: operation === 'readiness' ? 'GET' : 'POST',
|
||||
headers,
|
||||
...(operation === 'readiness' ? {} : { body: JSON.stringify(body) }),
|
||||
redirect: 'error',
|
||||
signal: AbortSignal.timeout(15000),
|
||||
}
|
||||
);
|
||||
} catch {
|
||||
throw new PaperDeploymentError(
|
||||
503,
|
||||
'Paper orchestrator could not confirm the command; check readiness before retrying'
|
||||
);
|
||||
}
|
||||
const value: unknown = await response.json().catch(() => null);
|
||||
if (!response.ok) {
|
||||
const status = [400, 403, 404, 409, 422, 503].includes(response.status) ? response.status : 503;
|
||||
const message =
|
||||
value && typeof value === 'object' && 'error' in value && typeof value.error === 'string'
|
||||
? value.error
|
||||
: 'Paper orchestrator rejected the request';
|
||||
throw new PaperDeploymentError(status as 400 | 403 | 404 | 409 | 422 | 503, message);
|
||||
}
|
||||
const status = paperDeploymentStatusSchema.parse(value);
|
||||
if (status.deploymentId !== id) {
|
||||
throw new Error('Paper orchestrator returned another deployment');
|
||||
}
|
||||
return status;
|
||||
}
|
||||
export function createPaperDeploymentRoutes(
|
||||
container: IServiceContainer,
|
||||
options: {
|
||||
origin?: string;
|
||||
origins?: readonly string[];
|
||||
request?: (url: string | URL | Request, init?: RequestInit) => Promise<Response>;
|
||||
service?: PaperDeploymentsService;
|
||||
} = {}
|
||||
) {
|
||||
const app = new Hono(),
|
||||
service = options.service ?? new PaperDeploymentsService(container),
|
||||
origins = options.origins ?? paperAllowedOrigins();
|
||||
app.use('*', async (c, next) => {
|
||||
c.header('Cache-Control', 'no-store');
|
||||
if (c.req.method !== 'GET' || c.req.path.endsWith('/readiness')) {
|
||||
requirePaperOperator(c.req.raw, origins);
|
||||
}
|
||||
await next();
|
||||
});
|
||||
app.onError((error, c) => {
|
||||
if (error instanceof PaperDeploymentError || error instanceof ResearchError) {
|
||||
return c.json({ error: error.message }, error.status);
|
||||
}
|
||||
if (
|
||||
error instanceof z.ZodError ||
|
||||
error instanceof SyntaxError ||
|
||||
error instanceof PaperRuntimeError
|
||||
) {
|
||||
return c.json(
|
||||
{
|
||||
error:
|
||||
error instanceof PaperRuntimeError ? error.message : 'Invalid paper promotion request',
|
||||
},
|
||||
400
|
||||
);
|
||||
}
|
||||
container.logger.error('Paper deployment operation failed', { error });
|
||||
return c.json({ error: 'Paper deployment evidence or storage unavailable' }, 500);
|
||||
});
|
||||
app.get('/api/v2/paper-deployments', async c => c.json({ deployments: await service.list() }));
|
||||
app.post('/api/v2/paper-deployments/preview', async c =>
|
||||
c.json(await service.preview(await c.req.json()))
|
||||
);
|
||||
app.post('/api/v2/paper-deployments', async c =>
|
||||
c.json(await service.create(await c.req.json(), c.req.header('Idempotency-Key') ?? ''), 201)
|
||||
);
|
||||
app.get('/api/v2/paper-deployments/:id', async c =>
|
||||
c.json(
|
||||
await service.get(
|
||||
z
|
||||
.string()
|
||||
.uuid()
|
||||
.transform(value => value.toLowerCase())
|
||||
.parse(c.req.param('id'))
|
||||
)
|
||||
)
|
||||
);
|
||||
for (const operation of ['bind', 'activate', 'halt', 'readiness'] as const) {
|
||||
const path = `/api/v2/paper-deployments/:id/${operation}`;
|
||||
app.on(operation === 'readiness' ? 'GET' : 'POST', path, async c => {
|
||||
const id = z
|
||||
.string()
|
||||
.uuid()
|
||||
.transform(value => value.toLowerCase())
|
||||
.parse(c.req.param('id'));
|
||||
const body =
|
||||
operation === 'readiness'
|
||||
? undefined
|
||||
: operation === 'activate'
|
||||
? paperActivationSchema.parse(await c.req.json())
|
||||
: operation === 'halt'
|
||||
? paperHaltSchema.parse(await c.req.json())
|
||||
: z
|
||||
.object({})
|
||||
.strict()
|
||||
.parse(await c.req.json());
|
||||
if (operation === 'bind' || operation === 'activate') {
|
||||
await service.authorizeCommand(id);
|
||||
} else {
|
||||
await service.get(id);
|
||||
}
|
||||
return c.json(
|
||||
await forwardPaperCommand(c.req.raw, id, operation, body, {
|
||||
origin: options.origin ?? process.env.ORCHESTRATOR_URL,
|
||||
request: options.request,
|
||||
})
|
||||
);
|
||||
});
|
||||
}
|
||||
return app;
|
||||
}
|
||||
|
|
@ -15,6 +15,7 @@ import {
|
|||
} from '@stock-bot/stock-config/backtest';
|
||||
import {
|
||||
canonicalRunRequestSchema,
|
||||
canonicalStrategyExecution,
|
||||
parseCanonicalFinancialResult,
|
||||
type CanonicalReproductionComparison,
|
||||
type CanonicalReproductionPreview,
|
||||
|
|
@ -862,7 +863,7 @@ export class BacktestServiceV2 {
|
|||
saved.backtestId !== row.backtest_id ||
|
||||
saved.status !== 'completed' ||
|
||||
saved.financialEngine !== 'rust' ||
|
||||
saved.strategyExecution !== 'typescript-retained-builtin/v1' ||
|
||||
saved.strategyExecution !== canonicalStrategyExecution(request) ||
|
||||
!Number.isFinite(Date.parse(saved.completedAt)) ||
|
||||
!Number.isFinite(saved.executionTime) ||
|
||||
saved.executionTime < 0 ||
|
||||
|
|
@ -884,15 +885,21 @@ export class BacktestServiceV2 {
|
|||
|
||||
async canonicalCapability(id: string): Promise<CanonicalRunCapability> {
|
||||
try {
|
||||
await this.container.postgres.transaction(async client => {
|
||||
const execution = await this.container.postgres.transaction(async client => {
|
||||
const row = (await client.query('SELECT * FROM backtests WHERE id=$1 FOR UPDATE', [id]))
|
||||
.rows[0];
|
||||
if (!row || row.archived_at !== null) {
|
||||
throw new Error('Backtest is missing or archived');
|
||||
}
|
||||
await admitCanonicalRequest(client, this.container, this.mapBacktest(row), id);
|
||||
const request = await admitCanonicalRequest(
|
||||
client,
|
||||
this.container,
|
||||
this.mapBacktest(row),
|
||||
id
|
||||
);
|
||||
return request.strategy.origin === 'candidate' ? request.strategy.execution : undefined;
|
||||
});
|
||||
return { available: true, reason: null };
|
||||
return { available: true, reason: null, ...(execution ? { execution } : {}) };
|
||||
} catch (error) {
|
||||
return {
|
||||
available: false,
|
||||
|
|
|
|||
|
|
@ -1,19 +1,27 @@
|
|||
import { randomUUID } from 'node:crypto';
|
||||
import type { PoolClient } from 'pg';
|
||||
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 } from '@stock-bot/stock-config/strategy';
|
||||
import {
|
||||
builtinStrategySelectionSchema,
|
||||
validateStrategyParameters,
|
||||
} from '@stock-bot/stock-config/strategy';
|
||||
import {
|
||||
HistoricalDataRequestError,
|
||||
parseFinancialDecimal,
|
||||
type HistoricalDatasetV2,
|
||||
type StrategyParameterValue,
|
||||
} from '@stock-bot/types';
|
||||
import { readCandidateExecution } from '../../../orchestrator/src/backtest/candidate-sandbox';
|
||||
import { readCanonicalBuildIdentity } from '../../../orchestrator/src/backtest/canonical-build';
|
||||
import { validateDatasetV2 } from '../../../orchestrator/src/data/historical-dataset-v2';
|
||||
import { canonicalRiskSessionClock } from './canonical-risk-clock';
|
||||
|
|
@ -155,8 +163,34 @@ export async function admitCanonicalRequest(
|
|||
container: IServiceContainer,
|
||||
template: CanonicalTemplate,
|
||||
backtestId: string,
|
||||
runId = randomUUID()
|
||||
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');
|
||||
}
|
||||
|
|
@ -167,10 +201,12 @@ export async function admitCanonicalRequest(
|
|||
[template.strategyVersionId]
|
||||
)
|
||||
).rows[0];
|
||||
if (!selected || selected.archived_at !== null || selected.origin !== 'builtin') {
|
||||
return invalid(
|
||||
'Only active, server-seeded built-in versions can execute; candidates require isolation'
|
||||
);
|
||||
if (
|
||||
!selected ||
|
||||
selected.archived_at !== null ||
|
||||
!['builtin', 'candidate'].includes(selected.origin)
|
||||
) {
|
||||
return invalid('Select an active retained strategy version');
|
||||
}
|
||||
const review = (
|
||||
await client.query(
|
||||
|
|
@ -178,17 +214,45 @@ export async function admitCanonicalRequest(
|
|||
[template.strategyVersionId]
|
||||
)
|
||||
).rows[0];
|
||||
if (review?.decision !== 'approve') {
|
||||
return invalid('An operator must approve this built-in version before execution');
|
||||
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 = builtinStrategySelectionSchema.parse({
|
||||
const selection = (
|
||||
selected.origin === 'candidate'
|
||||
? retainedProgramSelectionSchema
|
||||
: builtinStrategySelectionSchema
|
||||
).parse({
|
||||
strategyId: pkg.program.strategyId,
|
||||
strategyVersion: pkg.program.strategyVersion,
|
||||
ownerId,
|
||||
|
|
@ -196,7 +260,7 @@ export async function admitCanonicalRequest(
|
|||
instrumentId: execution.instrumentId,
|
||||
seriesId: execution.seriesId,
|
||||
ownerBudget: settings.ownerBudget,
|
||||
parameters: template.strategyParameters,
|
||||
parameters: validateStrategyParameters(pkg, template.strategyParameters),
|
||||
// API/checkpoint identities are retained in the package, not selection fields.
|
||||
});
|
||||
return canonicalRunRequestSchema.parse({
|
||||
|
|
@ -207,8 +271,9 @@ export async function admitCanonicalRequest(
|
|||
strategy: {
|
||||
familyId: selected.strategy_id,
|
||||
versionId: template.strategyVersionId,
|
||||
origin: 'builtin',
|
||||
reviewId: review.id,
|
||||
origin: selected.origin,
|
||||
reviewId: review?.id ?? null,
|
||||
...(candidateExecution ? { execution: candidateExecution, baselineVersionId } : {}),
|
||||
package: pkg,
|
||||
selection,
|
||||
},
|
||||
|
|
|
|||
|
|
@ -120,7 +120,7 @@ export class ChronologicalValidationService {
|
|||
return concurrent;
|
||||
}
|
||||
const { recipe: _recipe, ...sourceInput } = input;
|
||||
const source = await this.experiments.lockedPreview(client, sourceInput);
|
||||
const source = await this.experiments.lockedPreview(client, sourceInput, identity.principal);
|
||||
const sourceDataset = await readCanonicalDataset(client, source.request.datasetHash);
|
||||
const prepared = prepareChronologicalValidation(input, source, sourceDataset);
|
||||
if (prepared.preview.previewHash !== previewHash) {
|
||||
|
|
|
|||
|
|
@ -40,7 +40,12 @@ export function buildCostSensitivityPreview(
|
|||
const input = parseCostSensitivityInput(raw),
|
||||
source = retainedExperimentPreview(baseline);
|
||||
if (
|
||||
!equal(source.input, { backtestId: input.backtestId, name: input.name, grid: {} }) ||
|
||||
!equal(source.input, {
|
||||
backtestId: input.backtestId,
|
||||
name: input.name,
|
||||
grid: {},
|
||||
...(input.candidate ? { candidate: input.candidate } : {}),
|
||||
}) ||
|
||||
source.candidates.length !== 1
|
||||
) {
|
||||
throw new Error('Cost sensitivity requires the unchanged empty-grid source');
|
||||
|
|
|
|||
|
|
@ -1,5 +1,6 @@
|
|||
import { createHash } from 'node:crypto';
|
||||
import { z } from 'zod';
|
||||
import { retainedProgramSelectionSchema } from '@stock-bot/stock-config/candidate-execution';
|
||||
import {
|
||||
canonicalRunRequestSchema,
|
||||
type CanonicalRunRequest,
|
||||
|
|
@ -108,7 +109,11 @@ export function experimentCandidates(
|
|||
return combinations.map((parameters, index) => {
|
||||
try {
|
||||
const validated = validateStrategyParameters(request.strategy.package, parameters);
|
||||
const selection = builtinStrategySelectionSchema.parse({
|
||||
const selection = (
|
||||
request.strategy.origin === 'candidate'
|
||||
? retainedProgramSelectionSchema
|
||||
: builtinStrategySelectionSchema
|
||||
).parse({
|
||||
...request.strategy.selection,
|
||||
parameters: validated,
|
||||
});
|
||||
|
|
|
|||
|
|
@ -2,6 +2,7 @@ import { randomUUID } from 'node:crypto';
|
|||
import type { PoolClient, QueryResultRow } from 'pg';
|
||||
import { z } from 'zod';
|
||||
import { requireServices, type IServiceContainer } from '@stock-bot/services';
|
||||
import { canonicalStrategyExecution } from '@stock-bot/stock-config/canonical-research';
|
||||
import type {
|
||||
CostSensitivityInput,
|
||||
WorkbenchExperimentDetail,
|
||||
|
|
@ -39,7 +40,11 @@ import {
|
|||
PREVIEW_RUN_ID,
|
||||
} from './experiment-input';
|
||||
import { mapExperimentRetry, parseExperimentRetry, retryColumns } from './experiment-retry';
|
||||
import { lockExperimentResearchAgent, lockResearchAgent } from './research-agent-budget';
|
||||
import {
|
||||
lockExperimentResearchAgent,
|
||||
lockResearchAgent,
|
||||
verifyCandidateGrant,
|
||||
} from './research-agent-budget';
|
||||
import { RunReproductionError, verifyReproductionInputs } from './run-reproduction';
|
||||
import { StrategyCatalogError } from './strategy-catalog.service';
|
||||
import { parseChronologicalValidation, prepareChronologicalValidation } from './validation-preview';
|
||||
|
|
@ -118,32 +123,52 @@ export class ExperimentsService {
|
|||
constructor(private readonly container: IServiceContainer) {
|
||||
this.database = requireServices(container, 'postgres').postgres;
|
||||
}
|
||||
async preview(raw: unknown): Promise<ExperimentPreview> {
|
||||
async preview(raw: unknown, principal = 'operator'): Promise<ExperimentPreview> {
|
||||
const input = parseExperimentInput(raw);
|
||||
return this.database.transaction(client => this.lockedPreview(client, input));
|
||||
}
|
||||
async previewCosts(raw: unknown) {
|
||||
const input = parseCostSensitivityInput(raw);
|
||||
return this.database.transaction(client => this.lockedCostPreview(client, input));
|
||||
}
|
||||
private async lockedCostPreview(client: PoolClient, input: CostSensitivityInput) {
|
||||
const source = await this.lockedPreview(client, {
|
||||
backtestId: input.backtestId,
|
||||
name: input.name,
|
||||
grid: {},
|
||||
return this.database.transaction(async client => {
|
||||
await lockResearchAgent(client, principal);
|
||||
return this.lockedPreview(client, input, principal);
|
||||
});
|
||||
}
|
||||
async previewCosts(raw: unknown, principal = 'operator') {
|
||||
const input = parseCostSensitivityInput(raw);
|
||||
return this.database.transaction(async client => {
|
||||
await lockResearchAgent(client, principal);
|
||||
return this.lockedCostPreview(client, input, principal);
|
||||
});
|
||||
}
|
||||
private async lockedCostPreview(
|
||||
client: PoolClient,
|
||||
input: CostSensitivityInput,
|
||||
principal = 'operator'
|
||||
) {
|
||||
const source = await this.lockedPreview(
|
||||
client,
|
||||
{
|
||||
backtestId: input.backtestId,
|
||||
name: input.name,
|
||||
grid: {},
|
||||
...(input.candidate ? { candidate: input.candidate } : {}),
|
||||
},
|
||||
principal
|
||||
);
|
||||
return buildCostSensitivityPreview(input, source);
|
||||
}
|
||||
async previewValidation(raw: unknown) {
|
||||
async previewValidation(raw: unknown, principal = 'operator') {
|
||||
const input = parseChronologicalValidation(raw);
|
||||
const { recipe: _recipe, ...sourceInput } = input;
|
||||
return this.database.transaction(async client => {
|
||||
const source = await this.lockedPreview(client, sourceInput);
|
||||
await lockResearchAgent(client, principal);
|
||||
const source = await this.lockedPreview(client, sourceInput, principal);
|
||||
const dataset = await readCanonicalDataset(client, source.request.datasetHash);
|
||||
return prepareChronologicalValidation(input, source, dataset).preview;
|
||||
});
|
||||
}
|
||||
async lockedPreview(client: PoolClient, input: ExperimentInput): Promise<ExperimentPreview> {
|
||||
async lockedPreview(
|
||||
client: PoolClient,
|
||||
input: ExperimentInput,
|
||||
principal = 'operator'
|
||||
): Promise<ExperimentPreview> {
|
||||
const parent = (
|
||||
await client.query('SELECT * FROM backtests WHERE id=$1 FOR UPDATE', [input.backtestId])
|
||||
).rows[0];
|
||||
|
|
@ -172,7 +197,8 @@ export class ExperimentsService {
|
|||
config: parent.config,
|
||||
},
|
||||
input.backtestId,
|
||||
PREVIEW_RUN_ID
|
||||
PREVIEW_RUN_ID,
|
||||
input.candidate
|
||||
);
|
||||
} catch (cause) {
|
||||
if (
|
||||
|
|
@ -192,6 +218,7 @@ export class ExperimentsService {
|
|||
}
|
||||
throw cause;
|
||||
}
|
||||
await verifyCandidateGrant(client, request, principal);
|
||||
return buildExperimentPreview(
|
||||
input,
|
||||
request,
|
||||
|
|
@ -251,8 +278,8 @@ export class ExperimentsService {
|
|||
}
|
||||
const preview: WorkbenchExperimentPreview =
|
||||
'scenarios' in input
|
||||
? await this.lockedCostPreview(client, input)
|
||||
: await this.lockedPreview(client, input);
|
||||
? await this.lockedCostPreview(client, input, receipt.principal)
|
||||
: await this.lockedPreview(client, input, receipt.principal);
|
||||
if (preview.previewHash !== previewHash) {
|
||||
throw new ExperimentError(
|
||||
409,
|
||||
|
|
@ -648,7 +675,7 @@ export class ExperimentsService {
|
|||
run.result_run_id !== run.id ||
|
||||
run.result_backtest_id !== expected.backtestId ||
|
||||
run.financial_engine !== 'rust' ||
|
||||
run.strategy_execution !== 'typescript-retained-builtin/v1' ||
|
||||
run.strategy_execution !== canonicalStrategyExecution(expected) ||
|
||||
!equal(run.result_request, expected) ||
|
||||
run.analytics_version !== 1 ||
|
||||
!equal(run.analytics_policy, expectedPolicy) ||
|
||||
|
|
|
|||
361
apps/stock/web-api/src/services/paper-deployments.service.ts
Normal file
361
apps/stock/web-api/src/services/paper-deployments.service.ts
Normal file
|
|
@ -0,0 +1,361 @@
|
|||
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 type { ResearchEvidenceReference } from '@stock-bot/types';
|
||||
import { validatePaperConfiguration } from '../../../orchestrator/src/paper/feed';
|
||||
import {
|
||||
authorizedPaperPackage,
|
||||
PaperDeploymentError,
|
||||
paperHash,
|
||||
paperPreviewHash,
|
||||
readPaperDeployment,
|
||||
retainedPaperDeployment,
|
||||
} from '../../../orchestrator/src/paper/paper-deployment-custody';
|
||||
import { readPaperHostIdentity } from '../../../orchestrator/src/paper/paper-host-identity';
|
||||
import { BacktestServiceV2, type BacktestResultQuery } from './backtest-v2.service';
|
||||
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;
|
||||
private readonly results;
|
||||
constructor(
|
||||
private readonly container: IServiceContainer,
|
||||
private readonly identity = readPaperHostIdentity
|
||||
) {
|
||||
this.database = requireServices(container, 'postgres').postgres;
|
||||
this.results = new BacktestServiceV2(container);
|
||||
}
|
||||
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;
|
||||
});
|
||||
}
|
||||
}
|
||||
|
|
@ -1,6 +1,7 @@
|
|||
import { createHash } from 'node:crypto';
|
||||
import {
|
||||
canonicalRunRequestSchema,
|
||||
canonicalStrategyExecution,
|
||||
parseCanonicalFinancialResult,
|
||||
type CanonicalRunResult,
|
||||
} from '@stock-bot/stock-config/canonical-research';
|
||||
|
|
@ -16,7 +17,7 @@ export function canonicalReproductionHash(result: CanonicalRunResult): string {
|
|||
result.kind !== 'canonical-result/v1' ||
|
||||
result.status !== 'completed' ||
|
||||
result.financialEngine !== 'rust' ||
|
||||
result.strategyExecution !== 'typescript-retained-builtin/v1' ||
|
||||
result.strategyExecution !== canonicalStrategyExecution(request) ||
|
||||
result.runId !== request.runId ||
|
||||
result.backtestId !== request.backtestId
|
||||
) {
|
||||
|
|
|
|||
|
|
@ -20,9 +20,18 @@ export function researchGrantPolicy(request: CanonicalRunRequest) {
|
|||
const policy = structuredClone(request.policy);
|
||||
policy.matching.risk.ledger.sessionId = 'agent-grant-run';
|
||||
policy.matching.risk.ledger.accountId = 'agent-grant-account';
|
||||
if (request.strategy.origin === 'candidate') {
|
||||
const ownerId = `strategy:${request.strategy.baselineVersionId}`;
|
||||
policy.matching.risk.ledger.ownerIds = [ownerId];
|
||||
policy.matching.owners = [{ ownerId, mode: 'Target' }];
|
||||
policy.cadence = [{ owner_id: ownerId, series_ids: [request.strategy.selection.seriesId] }];
|
||||
}
|
||||
return {
|
||||
datasetHash: request.datasetHash,
|
||||
versionId: request.strategy.versionId,
|
||||
versionId:
|
||||
request.strategy.origin === 'candidate'
|
||||
? request.strategy.baselineVersionId
|
||||
: request.strategy.versionId,
|
||||
ownerBudget: request.strategy.selection.ownerBudget,
|
||||
seed: request.strategy.selection.seed,
|
||||
policy,
|
||||
|
|
@ -92,3 +101,18 @@ export async function lockExperimentResearchAgent(
|
|||
await lockResearchAgent(database, owner);
|
||||
}
|
||||
}
|
||||
|
||||
/** SQL remains authoritative; this preflight never executes candidate code or changes grants. */
|
||||
export async function verifyCandidateGrant(
|
||||
database: AgentQuery,
|
||||
request: CanonicalRunRequest,
|
||||
principal: string
|
||||
): Promise<void> {
|
||||
if (!isResearchAgent(principal) || request.strategy.origin !== 'candidate') {
|
||||
return;
|
||||
}
|
||||
await database.query(
|
||||
'SELECT assert_research_agent_grant(a,$2,$3::jsonb) FROM research_agents a WHERE id=$1',
|
||||
[principal, request.backtestId, request]
|
||||
);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -27,10 +27,13 @@ function record(row: QueryResultRow): ResearchAgentRecord {
|
|||
enabled: row.enabled,
|
||||
revision: row.revision,
|
||||
allowedProjectIds: row.policy.allowedProjectIds,
|
||||
grants: row.policy.grants.map((grant: { backtestId: string; policyHash: string }) => ({
|
||||
backtestId: grant.backtestId,
|
||||
policyHash: grant.policyHash,
|
||||
})),
|
||||
grants: row.policy.grants.map(
|
||||
(grant: { backtestId: string; policyHash: string; allowOwnCandidates?: boolean }) => ({
|
||||
backtestId: grant.backtestId,
|
||||
policyHash: grant.policyHash,
|
||||
...(grant.allowOwnCandidates ? { allowOwnCandidates: true } : {}),
|
||||
})
|
||||
),
|
||||
limits: row.policy.limits,
|
||||
createdAt: new Date(row.created_at).toISOString(),
|
||||
updatedAt: new Date(row.updated_at).toISOString(),
|
||||
|
|
@ -78,9 +81,13 @@ export class ResearchAgentsService {
|
|||
input: {
|
||||
allowedProjectIds: string[];
|
||||
allowedBacktestIds: string[];
|
||||
allowOwnCandidateBacktestIds?: string[];
|
||||
limits: ResearchAgentRecord['limits'];
|
||||
}
|
||||
) {
|
||||
if (input.allowOwnCandidateBacktestIds?.some(id => !input.allowedBacktestIds.includes(id))) {
|
||||
throw new ResearchAgentError(400, 'Candidate opt-ins must be a subset of granted backtests');
|
||||
}
|
||||
for (const id of input.allowedProjectIds) {
|
||||
if (
|
||||
!(
|
||||
|
|
@ -148,7 +155,12 @@ export class ResearchAgentsService {
|
|||
);
|
||||
}
|
||||
const policy = researchGrantPolicy(request);
|
||||
grants.push({ backtestId: id, policyHash: researchGrantHash(policy), policy });
|
||||
grants.push({
|
||||
backtestId: id,
|
||||
policyHash: researchGrantHash(policy),
|
||||
policy,
|
||||
...(input.allowOwnCandidateBacktestIds?.includes(id) ? { allowOwnCandidates: true } : {}),
|
||||
});
|
||||
}
|
||||
return { version: 1, allowedProjectIds: input.allowedProjectIds, grants, limits: input.limits };
|
||||
}
|
||||
|
|
@ -200,8 +212,33 @@ export class ResearchAgentsService {
|
|||
: await this.policy(client, {
|
||||
allowedProjectIds: input.allowedProjectIds ?? old.policy.allowedProjectIds,
|
||||
allowedBacktestIds: input.allowedBacktestIds,
|
||||
allowOwnCandidateBacktestIds: input.allowOwnCandidateBacktestIds ?? [],
|
||||
limits: input.limits ?? old.policy.limits,
|
||||
});
|
||||
if (
|
||||
input.allowedBacktestIds === undefined &&
|
||||
input.allowOwnCandidateBacktestIds !== undefined
|
||||
) {
|
||||
const allowed = new Set(
|
||||
policy.grants.map((grant: { backtestId: string }) => grant.backtestId)
|
||||
);
|
||||
if (input.allowOwnCandidateBacktestIds.some(id => !allowed.has(id))) {
|
||||
throw new ResearchAgentError(
|
||||
400,
|
||||
'Candidate opt-ins must be a subset of granted backtests'
|
||||
);
|
||||
}
|
||||
const candidateOptIns = input.allowOwnCandidateBacktestIds;
|
||||
policy.grants = policy.grants.map(
|
||||
(grant: { backtestId: string; allowOwnCandidates?: boolean }) => {
|
||||
const { allowOwnCandidates: _old, ...frozen } = grant;
|
||||
return {
|
||||
...frozen,
|
||||
...(candidateOptIns.includes(grant.backtestId) ? { allowOwnCandidates: true } : {}),
|
||||
};
|
||||
}
|
||||
);
|
||||
}
|
||||
if (input.allowedProjectIds) {
|
||||
for (const projectId of input.allowedProjectIds) {
|
||||
if (
|
||||
|
|
|
|||
|
|
@ -3,6 +3,7 @@ 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';
|
||||
|
|
@ -22,7 +23,7 @@ export async function verifyReproductionInputs(
|
|||
client: PoolClient,
|
||||
container: IServiceContainer,
|
||||
request: CanonicalRunRequest
|
||||
): Promise<string> {
|
||||
): Promise<string | null> {
|
||||
const selected = (
|
||||
await client.query(
|
||||
`SELECT v.strategy_id,v.origin,s.archived_at FROM strategy_versions v
|
||||
|
|
@ -33,9 +34,9 @@ export async function verifyReproductionInputs(
|
|||
if (
|
||||
!selected ||
|
||||
selected.strategy_id !== request.strategy.familyId ||
|
||||
selected.origin !== 'builtin'
|
||||
selected.origin !== request.strategy.origin
|
||||
) {
|
||||
throw new RunReproductionError(409, 'The original retained built-in version is unavailable');
|
||||
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');
|
||||
|
|
@ -46,10 +47,16 @@ export async function verifyReproductionInputs(
|
|||
[request.strategy.versionId]
|
||||
)
|
||||
).rows[0];
|
||||
if (review?.decision !== 'approve') {
|
||||
if (
|
||||
request.strategy.origin === 'builtin'
|
||||
? review?.decision !== 'approve'
|
||||
: review?.decision === 'revoke'
|
||||
) {
|
||||
throw new RunReproductionError(
|
||||
409,
|
||||
'The original strategy version requires current operator approval'
|
||||
request.strategy.origin === 'builtin'
|
||||
? 'The original strategy version requires current operator approval'
|
||||
: 'The original candidate version is explicitly revoked'
|
||||
);
|
||||
}
|
||||
try {
|
||||
|
|
@ -100,5 +107,15 @@ export async function verifyReproductionInputs(
|
|||
'The original worker/native/runtime build is not installed; historical build execution is unavailable'
|
||||
);
|
||||
}
|
||||
return review.id;
|
||||
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;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -111,7 +111,11 @@ const version = (row: QueryResultRow): StrategyVersionSummary => ({
|
|||
? row.review_status === 'approved'
|
||||
? 'Configure a supported canonical dataset and explicit financial policy before execution.'
|
||||
: 'An operator must approve this built-in version before configuring execution.'
|
||||
: 'Candidate execution requires isolation (A02); publication and approval do not execute code.',
|
||||
: row.review_status === 'revoked'
|
||||
? 'Candidate is revoked; new research admissions are unavailable.'
|
||||
: row.package.execution?.kind === 'isolated-candidate/v1'
|
||||
? 'Candidate runs only in the isolated research host. Configure retained data and financial policy; approval never selects trusted execution.'
|
||||
: 'Publish a new immutable version with an isolated execution declaration and author-declared warmup before execution.',
|
||||
});
|
||||
class ReceiptRace extends Error {}
|
||||
|
||||
|
|
|
|||
|
|
@ -76,7 +76,7 @@ export function validationPhasePreview(
|
|||
preview: ChronologicalValidationPreview,
|
||||
phase: ValidationPhase,
|
||||
winner?: ExperimentCandidate,
|
||||
reviewId?: string
|
||||
reviewId?: string | null
|
||||
) {
|
||||
const partition = preview.partitions.find(p => p.phase === phase);
|
||||
if (!partition) {
|
||||
|
|
@ -84,7 +84,11 @@ export function validationPhasePreview(
|
|||
}
|
||||
const request = structuredClone(partition.request);
|
||||
if (phase !== 'train') {
|
||||
if (!winner || !reviewId) {
|
||||
if (
|
||||
!winner ||
|
||||
reviewId === undefined ||
|
||||
(request.strategy.origin === 'builtin' && reviewId === null)
|
||||
) {
|
||||
throw new Error('Holdout admission requires a frozen winner and current approval');
|
||||
}
|
||||
request.strategy.selection.parameters = structuredClone(
|
||||
|
|
@ -97,6 +101,14 @@ export function validationPhasePreview(
|
|||
backtestId: preview.input.backtestId,
|
||||
name: `${preview.input.name} · ${phase}`,
|
||||
grid: phase === 'train' ? preview.input.grid : {},
|
||||
...(preview.input.candidate
|
||||
? {
|
||||
candidate: {
|
||||
...preview.input.candidate,
|
||||
parameters: structuredClone(request.strategy.selection.parameters),
|
||||
},
|
||||
}
|
||||
: {}),
|
||||
},
|
||||
canonicalRunRequestSchema.parse(request),
|
||||
partition.dataset
|
||||
|
|
|
|||
|
|
@ -1,7 +1,7 @@
|
|||
import { canonicalRunRequestSchema } from '@stock-bot/stock-config/canonical-research';
|
||||
import {
|
||||
chronologicalPolicyForOrigin,
|
||||
chronologicalValidationInputSchema,
|
||||
chronologicalValidationPolicy,
|
||||
type ChronologicalValidationInput,
|
||||
type ChronologicalValidationPreview,
|
||||
type ValidationPartitionPreview,
|
||||
|
|
@ -33,6 +33,13 @@ export function parseChronologicalValidation(input: unknown): ChronologicalValid
|
|||
}
|
||||
}
|
||||
function requiredHistory(source: ExperimentPreview): number {
|
||||
if (source.request.strategy.origin === 'candidate') {
|
||||
const execution = source.request.strategy.package.execution;
|
||||
if (!execution) {
|
||||
throw new ExperimentError(409, 'Candidate is missing its author-declared warmup');
|
||||
}
|
||||
return execution.warmupBars;
|
||||
}
|
||||
return Math.max(
|
||||
...source.candidates.map(candidate => {
|
||||
const selection = builtinStrategySelectionSchema.parse({
|
||||
|
|
@ -136,6 +143,11 @@ export function prepareChronologicalValidation(
|
|||
);
|
||||
}
|
||||
const warnings: string[] = [];
|
||||
if (source.request.strategy.origin === 'candidate') {
|
||||
warnings.push(
|
||||
'Candidate warmup is author-declared; input checks do not establish absence of leakage, model fitting validity, or reproducible strategy decisions'
|
||||
);
|
||||
}
|
||||
if (counts.unavailableAtEnd) {
|
||||
warnings.push(
|
||||
`${counts.unavailableAtEnd} completed-bar observations arrive after the evaluation end and cannot inform decisions or terminal marks`
|
||||
|
|
@ -170,7 +182,7 @@ export function prepareChronologicalValidation(
|
|||
execution: 'preview-only' as const,
|
||||
input,
|
||||
source,
|
||||
policy: chronologicalValidationPolicy,
|
||||
policy: chronologicalPolicyForOrigin(source.request.strategy.origin),
|
||||
partitions,
|
||||
};
|
||||
return { preview: { ...manifest, previewHash: experimentHash(manifest) }, datasets };
|
||||
|
|
|
|||
|
|
@ -78,13 +78,20 @@ export class WalkForwardService {
|
|||
this.experiments = new ExperimentsService(container);
|
||||
this.validations = new ChronologicalValidationService(container);
|
||||
}
|
||||
async preview(raw: unknown) {
|
||||
async preview(raw: unknown, principal = 'operator') {
|
||||
const input = parseWalkForwardInput(raw);
|
||||
return this.database.transaction(async client => (await this.prepare(client, input)).preview);
|
||||
return this.database.transaction(async client => {
|
||||
await lockResearchAgent(client, principal);
|
||||
return (await this.prepare(client, input, principal)).preview;
|
||||
});
|
||||
}
|
||||
private async prepare(client: PoolClient, input: ReturnType<typeof parseWalkForwardInput>) {
|
||||
private async prepare(
|
||||
client: PoolClient,
|
||||
input: ReturnType<typeof parseWalkForwardInput>,
|
||||
principal = 'operator'
|
||||
) {
|
||||
const { windows: _windows, ...sourceInput } = input;
|
||||
const source = await this.experiments.lockedPreview(client, sourceInput);
|
||||
const source = await this.experiments.lockedPreview(client, sourceInput, principal);
|
||||
const dataset = await readCanonicalDataset(client, source.request.datasetHash);
|
||||
return prepareWalkForward(input, source, dataset);
|
||||
}
|
||||
|
|
@ -122,7 +129,7 @@ export class WalkForwardService {
|
|||
if (concurrent) {
|
||||
return concurrent;
|
||||
}
|
||||
const prepared = await this.prepare(client, input);
|
||||
const prepared = await this.prepare(client, input, identity.principal);
|
||||
if (prepared.preview.previewHash !== previewHash) {
|
||||
throw new ExperimentError(
|
||||
409,
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue