feat(research): add retained-input parameter sweep workbench
This commit is contained in:
parent
30accfcf43
commit
6f64ef62ba
41 changed files with 4469 additions and 34 deletions
|
|
@ -28,6 +28,10 @@
|
|||
"./research": {
|
||||
"types": "./dist/contracts/research.d.ts",
|
||||
"default": "./dist/contracts/research.js"
|
||||
},
|
||||
"./experiments": {
|
||||
"types": "./dist/contracts/experiments.d.ts",
|
||||
"default": "./dist/contracts/experiments.js"
|
||||
}
|
||||
},
|
||||
"scripts": {
|
||||
|
|
|
|||
97
apps/stock/config/src/contracts/experiments.ts
Normal file
97
apps/stock/config/src/contracts/experiments.ts
Normal file
|
|
@ -0,0 +1,97 @@
|
|||
/** Bounded retained-input experiments use the existing canonical runner and results. */
|
||||
import { z } from 'zod';
|
||||
import type {
|
||||
CanonicalBacktestAnalytics,
|
||||
HistoricalDatasetManifestV2,
|
||||
StrategyParameterValue,
|
||||
} from '@stock-bot/types';
|
||||
import type { CanonicalRunRequest } from './canonical-research';
|
||||
|
||||
/** Admission bound for atomic expansion, not a promise of concurrent execution. */
|
||||
export const MAX_EXPERIMENT_TRIALS = 100;
|
||||
const value = z.union([z.string(), z.number().finite(), z.boolean()]);
|
||||
// Zod's record parser drops __proto__; reject raw keys before parsing so an
|
||||
// invalid sweep cannot silently become the empty-grid baseline trial.
|
||||
const grid = z.preprocess(
|
||||
(input, context) => {
|
||||
if (
|
||||
input &&
|
||||
typeof input === 'object' &&
|
||||
Object.keys(input).some(key => ['__proto__', 'prototype', 'constructor'].includes(key))
|
||||
) {
|
||||
context.addIssue({
|
||||
code: z.ZodIssueCode.custom,
|
||||
message: 'Invalid parameter name',
|
||||
fatal: true,
|
||||
});
|
||||
return z.NEVER;
|
||||
}
|
||||
return input;
|
||||
},
|
||||
z.record(z.array(value).min(1).max(MAX_EXPERIMENT_TRIALS))
|
||||
);
|
||||
export const experimentInputSchema = z
|
||||
.object({
|
||||
backtestId: z.string().uuid(),
|
||||
name: z.string().trim().min(1),
|
||||
grid,
|
||||
})
|
||||
.strict();
|
||||
export const experimentSubmissionSchema = experimentInputSchema.extend({
|
||||
previewHash: z.string().regex(/^[a-f0-9]{64}$/),
|
||||
});
|
||||
export type ExperimentInput = z.infer<typeof experimentInputSchema>;
|
||||
export type ExperimentSubmission = z.infer<typeof experimentSubmissionSchema>;
|
||||
export interface ExperimentCandidate {
|
||||
/** Zero-based deterministic position in the frozen grid. */
|
||||
index: number;
|
||||
trialKey: string;
|
||||
parameters: Record<string, StrategyParameterValue>;
|
||||
}
|
||||
export interface ExperimentPreview {
|
||||
version: 'research-experiment-preview/v1';
|
||||
previewHash: string;
|
||||
input: ExperimentInput;
|
||||
/** Template snapshot with a fixed preview run identity; never executed as-is. */
|
||||
request: CanonicalRunRequest;
|
||||
dataset: HistoricalDatasetManifestV2;
|
||||
candidates: ExperimentCandidate[];
|
||||
}
|
||||
export type ExperimentRunStatus =
|
||||
| 'pending'
|
||||
| 'running'
|
||||
| 'paused'
|
||||
| 'completed'
|
||||
| 'failed'
|
||||
| 'cancelled';
|
||||
export type ExperimentCounts = Record<ExperimentRunStatus, number>;
|
||||
export interface ExperimentSummary {
|
||||
id: string;
|
||||
name: string;
|
||||
backtestId: string;
|
||||
createdAt: string;
|
||||
cancelRequested: boolean;
|
||||
/** Frozen candidate count, not merely the number of successfully joined rows. */
|
||||
trialCount: number;
|
||||
counts: ExperimentCounts;
|
||||
datasetHash: string;
|
||||
strategyVersionId: string;
|
||||
previewHash: string;
|
||||
}
|
||||
export interface ExperimentTrial extends ExperimentCandidate {
|
||||
runId: string | null;
|
||||
status: ExperimentRunStatus | 'missing';
|
||||
progress: number;
|
||||
cancelRequested: boolean;
|
||||
error: string | null;
|
||||
/** False prevents ranking a result whose retained inputs disagree with its experiment. */
|
||||
comparable: boolean;
|
||||
diagnostic: string | null;
|
||||
metrics: CanonicalBacktestAnalytics['metrics'] | null;
|
||||
unavailable: CanonicalBacktestAnalytics['unavailable'] | null;
|
||||
limitations: string[];
|
||||
}
|
||||
export interface ExperimentDetail extends ExperimentSummary {
|
||||
preview: ExperimentPreview;
|
||||
trials: ExperimentTrial[];
|
||||
}
|
||||
|
|
@ -61,7 +61,8 @@ export async function runMigrations(container: IServiceContainer): Promise<void>
|
|||
f === '18-backtest-strategy-versions.sql' ||
|
||||
f === '19-canonical-research.sql' ||
|
||||
f === '20-research-workspace.sql' ||
|
||||
f === '21-run-reproduction.sql')
|
||||
f === '21-run-reproduction.sql' ||
|
||||
f === '22-experiments.sql')
|
||||
) // Explicit additive migration allowlist; never replay destructive init migrations
|
||||
.sort();
|
||||
|
||||
|
|
|
|||
|
|
@ -11,6 +11,7 @@ import { createBacktestRoutes } from './backtest.routes';
|
|||
import { createBacktestV2Routes } from './backtests-v2.routes';
|
||||
import { createDatasetRoutes } from './datasets.routes';
|
||||
import { createExchangeRoutes } from './exchange.routes';
|
||||
import { createExperimentRoutes } from './experiments.routes';
|
||||
import { createHealthRoutes } from './health.routes';
|
||||
import { createMonitoringRoutes } from './monitoring.routes';
|
||||
import { createPipelineRoutes } from './pipeline.routes';
|
||||
|
|
@ -53,6 +54,7 @@ export function createRoutes(
|
|||
app.route('/', createDatasetRoutes(container));
|
||||
app.route('/', createStrategyRoutes(container));
|
||||
app.route('/', createResearchRoutes(container));
|
||||
app.route('/', createExperimentRoutes(container));
|
||||
|
||||
return app;
|
||||
}
|
||||
|
|
|
|||
81
apps/stock/web-api/src/routes/experiments.routes.ts
Normal file
81
apps/stock/web-api/src/routes/experiments.routes.ts
Normal file
|
|
@ -0,0 +1,81 @@
|
|||
import { Hono, type MiddlewareHandler } from 'hono';
|
||||
import { z } from 'zod';
|
||||
import { getCredentialHttpPrincipal } from '@stock-bot/di';
|
||||
import { getLogger } from '@stock-bot/logger';
|
||||
import type { IServiceContainer } from '@stock-bot/services';
|
||||
import {
|
||||
ExperimentError,
|
||||
experimentId,
|
||||
experimentReceipt,
|
||||
parseExperimentInput,
|
||||
parseExperimentSubmission,
|
||||
} from '../services/experiment-input';
|
||||
import { ExperimentsService } from '../services/experiments.service';
|
||||
|
||||
/** Mounted HTTP security owns read authorization; every mutation additionally requires credential proof. */
|
||||
export function createExperimentRoutes(container: IServiceContainer) {
|
||||
const app = new Hono();
|
||||
const service = new ExperimentsService(container);
|
||||
const logger = getLogger('experiments-api');
|
||||
const credentials: MiddlewareHandler = async (c, next) => {
|
||||
c.header('Cache-Control', 'no-store');
|
||||
if (!['GET', 'HEAD'].includes(c.req.method) && !getCredentialHttpPrincipal(c.req.raw)) {
|
||||
return c.json({ error: 'Verified credential principal required' }, 401);
|
||||
}
|
||||
await next();
|
||||
return undefined;
|
||||
};
|
||||
app.use('/api/v2/experiments', credentials);
|
||||
app.use('/api/v2/experiments/*', credentials);
|
||||
app.onError((error, c) => {
|
||||
if (error instanceof ExperimentError) {
|
||||
return c.json({ error: error.message }, error.status);
|
||||
}
|
||||
logger.error('Experiment operation failed', error);
|
||||
return c.json({ error: 'Experiment operation unavailable' }, 500);
|
||||
});
|
||||
const body = async (request: Request): Promise<unknown> => {
|
||||
try {
|
||||
return await request.json();
|
||||
} catch {
|
||||
throw new ExperimentError(400, 'Invalid JSON request');
|
||||
}
|
||||
};
|
||||
app.post('/api/v2/experiments/preview', async c => {
|
||||
const input = parseExperimentInput(await body(c.req.raw));
|
||||
return c.json({ preview: await service.preview(input) });
|
||||
});
|
||||
app.post('/api/v2/experiments', async c => {
|
||||
const input = parseExperimentSubmission(await body(c.req.raw));
|
||||
const receipt = experimentReceipt({
|
||||
principal: getCredentialHttpPrincipal(c.req.raw) ?? '',
|
||||
key: c.req.header('Idempotency-Key') ?? '',
|
||||
});
|
||||
const experiment = await service.submit(input, receipt);
|
||||
c.header('Location', `/api/v2/experiments/${experiment.id}`);
|
||||
return c.json({ experiment }, 202);
|
||||
});
|
||||
app.get('/api/v2/experiments', async c => {
|
||||
const filter = c.req.query('backtestId');
|
||||
if (filter !== undefined) {
|
||||
experimentId(filter);
|
||||
}
|
||||
return c.json({ experiments: await service.list(filter) });
|
||||
});
|
||||
app.get('/api/v2/experiments/:id', async c =>
|
||||
c.json({ experiment: await service.get(experimentId(c.req.param('id'))) })
|
||||
);
|
||||
app.post('/api/v2/experiments/:id/cancel', async c => {
|
||||
const id = experimentId(c.req.param('id'));
|
||||
if (
|
||||
!z
|
||||
.object({})
|
||||
.strict()
|
||||
.safeParse(await body(c.req.raw)).success
|
||||
) {
|
||||
throw new ExperimentError(400, 'Cancellation accepts an empty object only');
|
||||
}
|
||||
return c.json({ experiment: await service.cancel(id) });
|
||||
});
|
||||
return app;
|
||||
}
|
||||
180
apps/stock/web-api/src/services/experiment-input.ts
Normal file
180
apps/stock/web-api/src/services/experiment-input.ts
Normal file
|
|
@ -0,0 +1,180 @@
|
|||
import { createHash } from 'node:crypto';
|
||||
import { z } from 'zod';
|
||||
import {
|
||||
canonicalRunRequestSchema,
|
||||
type CanonicalRunRequest,
|
||||
} from '@stock-bot/stock-config/canonical-research';
|
||||
import {
|
||||
experimentInputSchema,
|
||||
experimentSubmissionSchema,
|
||||
MAX_EXPERIMENT_TRIALS,
|
||||
type ExperimentCandidate,
|
||||
type ExperimentInput,
|
||||
type ExperimentPreview,
|
||||
type ExperimentSubmission,
|
||||
} from '@stock-bot/stock-config/experiments';
|
||||
import {
|
||||
assertStrategyJsonText,
|
||||
builtinStrategySelectionSchema,
|
||||
canonicalStrategyJson,
|
||||
validateStrategyParameters,
|
||||
} from '@stock-bot/stock-config/strategy';
|
||||
import type { HistoricalDatasetManifestV2 } from '@stock-bot/types';
|
||||
|
||||
export class ExperimentError extends Error {
|
||||
constructor(
|
||||
public readonly status: 400 | 404 | 409,
|
||||
message: string
|
||||
) {
|
||||
super(message);
|
||||
}
|
||||
}
|
||||
export const PREVIEW_RUN_ID = '00000000-0000-4000-8000-000000000001';
|
||||
export const experimentHash = (value: unknown) =>
|
||||
createHash('sha256').update(canonicalStrategyJson(value)).digest('hex');
|
||||
export function parseExperimentInput(input: unknown): ExperimentInput {
|
||||
try {
|
||||
assertStrategyJsonText(input);
|
||||
return experimentInputSchema.parse(input);
|
||||
} catch {
|
||||
throw new ExperimentError(400, 'Invalid experiment input');
|
||||
}
|
||||
}
|
||||
export function parseExperimentSubmission(input: unknown): ExperimentSubmission {
|
||||
try {
|
||||
assertStrategyJsonText(input);
|
||||
return experimentSubmissionSchema.parse(input);
|
||||
} catch {
|
||||
throw new ExperimentError(400, 'Invalid experiment submission');
|
||||
}
|
||||
}
|
||||
export function experimentId(input: unknown): string {
|
||||
const parsed = z.string().uuid().safeParse(input);
|
||||
if (!parsed.success) {
|
||||
throw new ExperimentError(400, 'Invalid experiment or backtest ID');
|
||||
}
|
||||
return parsed.data;
|
||||
}
|
||||
export function experimentReceipt(input: { principal: string; key: string }) {
|
||||
const parsed = z
|
||||
.object({
|
||||
principal: z.enum(['operator', 'service']),
|
||||
key: z.string().regex(/^[\x21-\x7e]{1,200}$/),
|
||||
})
|
||||
.strict()
|
||||
.safeParse(input);
|
||||
if (!parsed.success) {
|
||||
throw new ExperimentError(
|
||||
400,
|
||||
'A verified principal and visible ASCII Idempotency-Key of 1–200 characters are required'
|
||||
);
|
||||
}
|
||||
return parsed.data;
|
||||
}
|
||||
/** Parameter grids never change data, accounting, execution or analysis policy. */
|
||||
export function experimentCandidates(
|
||||
input: ExperimentInput,
|
||||
request: CanonicalRunRequest
|
||||
): ExperimentCandidate[] {
|
||||
const axes = Object.keys(input.grid).sort();
|
||||
let count = 1;
|
||||
for (const name of axes) {
|
||||
if (
|
||||
!Object.hasOwn(request.strategy.package.parameterSchema.properties, name) ||
|
||||
['__proto__', 'constructor', 'prototype'].includes(name)
|
||||
) {
|
||||
throw new ExperimentError(400, `Unknown or reserved parameter: ${name}`);
|
||||
}
|
||||
const values = input.grid[name] ?? [];
|
||||
if (new Set(values.map(canonicalStrategyJson)).size !== values.length) {
|
||||
throw new ExperimentError(400, `Duplicate values for parameter: ${name}`);
|
||||
}
|
||||
count *= values.length;
|
||||
if (count > MAX_EXPERIMENT_TRIALS) {
|
||||
throw new ExperimentError(
|
||||
400,
|
||||
`An experiment may contain at most ${MAX_EXPERIMENT_TRIALS} trials`
|
||||
);
|
||||
}
|
||||
}
|
||||
let combinations = [{ ...request.strategy.selection.parameters }];
|
||||
for (const name of axes) {
|
||||
combinations = combinations.flatMap(parameters =>
|
||||
(input.grid[name] ?? []).map(value => ({ ...parameters, [name]: value }))
|
||||
);
|
||||
}
|
||||
const keys = new Set<string>();
|
||||
return combinations.map((parameters, index) => {
|
||||
try {
|
||||
const validated = validateStrategyParameters(request.strategy.package, parameters);
|
||||
const selection = builtinStrategySelectionSchema.parse({
|
||||
...request.strategy.selection,
|
||||
parameters: validated,
|
||||
});
|
||||
const trialKey = experimentHash({ version: 1, parameters: selection.parameters });
|
||||
if (keys.has(trialKey)) {
|
||||
throw new Error('Duplicate normalized parameter combination');
|
||||
}
|
||||
keys.add(trialKey);
|
||||
return { index, parameters: selection.parameters, trialKey };
|
||||
} catch (cause) {
|
||||
throw new ExperimentError(
|
||||
400,
|
||||
`Invalid parameter combination ${index + 1}: ${cause instanceof Error ? cause.message : 'validation failed'}`
|
||||
);
|
||||
}
|
||||
});
|
||||
}
|
||||
export function buildExperimentPreview(
|
||||
input: ExperimentInput,
|
||||
request: CanonicalRunRequest,
|
||||
dataset: HistoricalDatasetManifestV2
|
||||
): ExperimentPreview {
|
||||
const manifest = {
|
||||
version: 'research-experiment-preview/v1' as const,
|
||||
input,
|
||||
request,
|
||||
dataset,
|
||||
candidates: experimentCandidates(input, request),
|
||||
};
|
||||
return { ...manifest, previewHash: experimentHash(manifest) };
|
||||
}
|
||||
export function experimentTrialRequest(
|
||||
preview: ExperimentPreview,
|
||||
candidate: ExperimentCandidate,
|
||||
runId: string
|
||||
): CanonicalRunRequest {
|
||||
const request = structuredClone(preview.request);
|
||||
request.runId = runId;
|
||||
request.policy.matching.risk.ledger.sessionId = runId;
|
||||
request.policy.matching.risk.ledger.accountId = `research:${runId}`;
|
||||
return canonicalRunRequestSchema.parse({
|
||||
...request,
|
||||
strategy: {
|
||||
...request.strategy,
|
||||
selection: { ...request.strategy.selection, parameters: candidate.parameters },
|
||||
},
|
||||
});
|
||||
}
|
||||
/** Fail closed for corrupt saved manifests; do not relabel storage failures as user errors. */
|
||||
export function retainedExperimentPreview(value: unknown): ExperimentPreview {
|
||||
const preview = value as ExperimentPreview;
|
||||
const input = experimentInputSchema.parse(preview.input);
|
||||
const request = canonicalRunRequestSchema.parse(preview.request);
|
||||
if (request.runId !== PREVIEW_RUN_ID || request.backtestId !== input.backtestId) {
|
||||
throw new Error('Retained experiment request identity mismatch');
|
||||
}
|
||||
if (!preview.dataset || preview.dataset.hash !== request.datasetHash) {
|
||||
throw new Error('Retained experiment dataset identity mismatch');
|
||||
}
|
||||
let expected;
|
||||
try {
|
||||
expected = buildExperimentPreview(input, request, preview.dataset);
|
||||
} catch {
|
||||
throw new Error('Retained experiment candidates failed integrity validation');
|
||||
}
|
||||
if (canonicalStrategyJson(preview) !== canonicalStrategyJson(expected)) {
|
||||
throw new Error('Retained experiment preview integrity failure');
|
||||
}
|
||||
return expected;
|
||||
}
|
||||
420
apps/stock/web-api/src/services/experiments.service.ts
Normal file
420
apps/stock/web-api/src/services/experiments.service.ts
Normal file
|
|
@ -0,0 +1,420 @@
|
|||
import { randomUUID } from 'node:crypto';
|
||||
import type { PoolClient, QueryResultRow } from 'pg';
|
||||
import { z } from 'zod';
|
||||
import { requireServices, type IServiceContainer } from '@stock-bot/services';
|
||||
import type {
|
||||
ExperimentCounts,
|
||||
ExperimentDetail,
|
||||
ExperimentInput,
|
||||
ExperimentPreview,
|
||||
ExperimentSummary,
|
||||
ExperimentTrial,
|
||||
} from '@stock-bot/stock-config/experiments';
|
||||
import { canonicalStrategyJson } from '@stock-bot/stock-config/strategy';
|
||||
import { HistoricalDataRequestError, type CanonicalBacktestAnalytics } from '@stock-bot/types';
|
||||
import { admitCanonicalRequest, readCanonicalDataset } from './canonical-research.service';
|
||||
import {
|
||||
buildExperimentPreview,
|
||||
ExperimentError,
|
||||
experimentHash,
|
||||
experimentId,
|
||||
experimentReceipt,
|
||||
experimentTrialRequest,
|
||||
parseExperimentInput,
|
||||
parseExperimentSubmission,
|
||||
PREVIEW_RUN_ID,
|
||||
retainedExperimentPreview,
|
||||
} from './experiment-input';
|
||||
import { StrategyCatalogError } from './strategy-catalog.service';
|
||||
|
||||
interface Query {
|
||||
query(text: string, values?: unknown[]): Promise<{ rows: QueryResultRow[] }>;
|
||||
}
|
||||
const equal = (left: unknown, right: unknown) =>
|
||||
left !== undefined &&
|
||||
right !== undefined &&
|
||||
canonicalStrategyJson(left) === canonicalStrategyJson(right);
|
||||
const metricsSchema = z
|
||||
.object({
|
||||
totalReturn: z.number().finite().nullable(),
|
||||
cagr: z.number().finite().nullable(),
|
||||
maxDrawdown: z.number().finite().nullable(),
|
||||
exposureTime: z.number().finite().nullable(),
|
||||
volatility: z.number().finite().nullable(),
|
||||
downsideDeviation: z.number().finite().nullable(),
|
||||
sharpeRatio: z.number().finite().nullable(),
|
||||
sortinoRatio: z.number().finite().nullable(),
|
||||
var95: z.number().finite().nullable(),
|
||||
cvar95: z.number().finite().nullable(),
|
||||
var99: z.number().finite().nullable(),
|
||||
alpha: z.null(),
|
||||
beta: z.null(),
|
||||
informationRatio: z.null(),
|
||||
roundTripCount: z.null(),
|
||||
winRate: z.null(),
|
||||
profitFactor: z.null(),
|
||||
avgWin: z.null(),
|
||||
avgLoss: z.null(),
|
||||
})
|
||||
.strict();
|
||||
const reasons = z.enum([
|
||||
'nonpositive-baseline',
|
||||
'negative-terminal-equity',
|
||||
'zero-duration',
|
||||
'nonfinite-result',
|
||||
'undefined-period-return',
|
||||
'insufficient-periods',
|
||||
'missing-risk-free',
|
||||
'missing-benchmark',
|
||||
'zero-variance',
|
||||
'zero-downside-deviation',
|
||||
'unsupported-round-trips',
|
||||
]);
|
||||
const unavailableSchema = z.record(metricsSchema.keyof(), reasons);
|
||||
const summaryColumns = `e.id,e.name,e.backtest_id,e.created_at,e.cancel_requested,e.preview_hash,
|
||||
jsonb_array_length(e.preview->'candidates') AS trial_count,
|
||||
e.preview#>>'{request,datasetHash}' AS dataset_hash,
|
||||
e.preview#>>'{request,strategy,versionId}' AS strategy_version_id,
|
||||
(SELECT jsonb_object_agg(status, n) FROM (SELECT status,count(*) AS n FROM runs WHERE experiment_id=e.id GROUP BY status) counts) AS counts`;
|
||||
const summary = (row: QueryResultRow): ExperimentSummary => ({
|
||||
id: row.id,
|
||||
name: row.name,
|
||||
backtestId: row.backtest_id,
|
||||
createdAt: new Date(row.created_at).toISOString(),
|
||||
cancelRequested: row.cancel_requested,
|
||||
trialCount: Number(row.trial_count),
|
||||
datasetHash: row.dataset_hash,
|
||||
strategyVersionId: row.strategy_version_id,
|
||||
previewHash: row.preview_hash,
|
||||
counts: Object.fromEntries(
|
||||
['pending', 'running', 'paused', 'completed', 'failed', 'cancelled'].map(status => [
|
||||
status,
|
||||
Number(row.counts?.[status] ?? 0),
|
||||
])
|
||||
) as ExperimentCounts,
|
||||
});
|
||||
|
||||
/** The manifest receipt and all durable children commit together; the existing worker owns execution. */
|
||||
export class ExperimentsService {
|
||||
private readonly database;
|
||||
constructor(private readonly container: IServiceContainer) {
|
||||
this.database = requireServices(container, 'postgres').postgres;
|
||||
}
|
||||
async preview(raw: unknown): Promise<ExperimentPreview> {
|
||||
const input = parseExperimentInput(raw);
|
||||
return this.database.transaction(client => this.lockedPreview(client, input));
|
||||
}
|
||||
private async lockedPreview(
|
||||
client: PoolClient,
|
||||
input: ExperimentInput
|
||||
): Promise<ExperimentPreview> {
|
||||
const parent = (
|
||||
await client.query('SELECT * FROM backtests WHERE id=$1 FOR UPDATE', [input.backtestId])
|
||||
).rows[0];
|
||||
if (!parent) {
|
||||
throw new ExperimentError(404, 'Backtest not found');
|
||||
}
|
||||
if (parent.archived_at !== null) {
|
||||
throw new ExperimentError(409, 'Restore the archived backtest before creating an experiment');
|
||||
}
|
||||
if (!parent.strategy_version_id) {
|
||||
throw new ExperimentError(409, 'Experiments require a retained canonical built-in template');
|
||||
}
|
||||
let request;
|
||||
try {
|
||||
request = await admitCanonicalRequest(
|
||||
client,
|
||||
this.container,
|
||||
{
|
||||
name: parent.name,
|
||||
strategyVersionId: parent.strategy_version_id,
|
||||
strategyParameters: parent.strategy_parameters,
|
||||
symbols: parent.symbols,
|
||||
startDate: parent.start_date,
|
||||
endDate: parent.end_date,
|
||||
initialCapital: Number(parent.initial_capital),
|
||||
config: parent.config,
|
||||
},
|
||||
input.backtestId,
|
||||
PREVIEW_RUN_ID
|
||||
);
|
||||
} catch (cause) {
|
||||
if (
|
||||
cause instanceof HistoricalDataRequestError ||
|
||||
cause instanceof StrategyCatalogError ||
|
||||
cause instanceof z.ZodError
|
||||
) {
|
||||
throw new ExperimentError(409, `Canonical experiment unavailable: ${cause.message}`);
|
||||
}
|
||||
if (
|
||||
cause &&
|
||||
typeof cause === 'object' &&
|
||||
'code' in cause &&
|
||||
['ENOENT', 'ENOTDIR', 'EACCES'].includes(String(cause.code))
|
||||
) {
|
||||
throw new ExperimentError(409, 'The canonical build is not installed');
|
||||
}
|
||||
throw cause;
|
||||
}
|
||||
return buildExperimentPreview(
|
||||
input,
|
||||
request,
|
||||
(await readCanonicalDataset(client, request.datasetHash)).manifest
|
||||
);
|
||||
}
|
||||
async submit(raw: unknown, actor: { principal: string; key: string }): Promise<ExperimentDetail> {
|
||||
const submission = parseExperimentSubmission(raw);
|
||||
const receipt = experimentReceipt(actor);
|
||||
const { previewHash, ...input } = submission;
|
||||
const hash = experimentHash({ version: 1, operation: 'create-experiment', submission });
|
||||
return this.database.transaction(async client => {
|
||||
const replay = async () => {
|
||||
const row = (
|
||||
await client.query(
|
||||
'SELECT id,submission_hash FROM research_experiments WHERE submission_principal=$1 AND submission_key=$2',
|
||||
[receipt.principal, receipt.key]
|
||||
)
|
||||
).rows[0];
|
||||
if (row && row.submission_hash !== hash) {
|
||||
throw new ExperimentError(
|
||||
409,
|
||||
'Idempotency-Key already belongs to a different experiment intent'
|
||||
);
|
||||
}
|
||||
return row ? this.readDetail(client, row.id) : null;
|
||||
};
|
||||
const previous = await replay();
|
||||
if (previous) {
|
||||
return previous;
|
||||
}
|
||||
// Serialize same-parent admissions, then recheck accepted receipts before current eligibility.
|
||||
await client.query('SELECT id FROM backtests WHERE id=$1 FOR UPDATE', [input.backtestId]);
|
||||
const concurrent = await replay();
|
||||
if (concurrent) {
|
||||
return concurrent;
|
||||
}
|
||||
const preview = await this.lockedPreview(client, input);
|
||||
if (preview.previewHash !== previewHash) {
|
||||
throw new ExperimentError(
|
||||
409,
|
||||
'Experiment preview is stale; preview the current inputs again'
|
||||
);
|
||||
}
|
||||
const experimentId = randomUUID();
|
||||
const inserted = await client.query(
|
||||
`INSERT INTO research_experiments (id,backtest_id,name,preview,preview_hash,submission_principal,submission_key,submission_hash)
|
||||
VALUES ($1,$2,$3,$4,$5,$6,$7,$8) ON CONFLICT (submission_principal,submission_key) DO NOTHING RETURNING id`,
|
||||
[
|
||||
experimentId,
|
||||
input.backtestId,
|
||||
input.name,
|
||||
preview,
|
||||
previewHash,
|
||||
receipt.principal,
|
||||
receipt.key,
|
||||
hash,
|
||||
]
|
||||
);
|
||||
if (!inserted.rows.length) {
|
||||
const winner = await replay();
|
||||
if (!winner) {
|
||||
throw new Error('Concurrent experiment receipt disappeared');
|
||||
}
|
||||
return winner;
|
||||
}
|
||||
let runNumber = Number(
|
||||
(
|
||||
await client.query(
|
||||
'SELECT COALESCE(MAX(run_number),0) AS n FROM runs WHERE backtest_id=$1',
|
||||
[input.backtestId]
|
||||
)
|
||||
).rows[0].n
|
||||
);
|
||||
for (const candidate of preview.candidates) {
|
||||
const runId = randomUUID();
|
||||
const request = experimentTrialRequest(preview, candidate, runId);
|
||||
await client.query(
|
||||
`INSERT INTO runs (id,backtest_id,run_number,status,speed_multiplier,request_snapshot,dataset_hash,experiment_id,trial_key,trial_index)
|
||||
VALUES ($1,$2,$3,'pending',NULL,$4,$5,$6,$7,$8)`,
|
||||
[
|
||||
runId,
|
||||
input.backtestId,
|
||||
++runNumber,
|
||||
request,
|
||||
request.datasetHash,
|
||||
experimentId,
|
||||
candidate.trialKey,
|
||||
candidate.index,
|
||||
]
|
||||
);
|
||||
await client.query('INSERT INTO backtest_dispatch (run_id) VALUES ($1)', [runId]);
|
||||
}
|
||||
return this.readDetail(client, experimentId);
|
||||
});
|
||||
}
|
||||
async list(backtestId?: string): Promise<ExperimentSummary[]> {
|
||||
if (backtestId !== undefined) {
|
||||
experimentId(backtestId);
|
||||
}
|
||||
const rows = await this.database.query(
|
||||
`SELECT ${summaryColumns} FROM research_experiments e
|
||||
${backtestId === undefined ? '' : 'WHERE e.backtest_id=$1'} ORDER BY e.created_at DESC,e.id DESC`,
|
||||
backtestId === undefined ? [] : [backtestId]
|
||||
);
|
||||
return rows.rows.map(summary);
|
||||
}
|
||||
async get(id: string): Promise<ExperimentDetail> {
|
||||
experimentId(id);
|
||||
return this.readDetail(this.database, id);
|
||||
}
|
||||
async cancel(id: string): Promise<ExperimentDetail> {
|
||||
experimentId(id);
|
||||
return this.database.transaction(async client => {
|
||||
const row = (
|
||||
await client.query(
|
||||
'UPDATE research_experiments SET cancel_requested=TRUE WHERE id=$1 RETURNING id',
|
||||
[id]
|
||||
)
|
||||
).rows[0];
|
||||
if (!row) {
|
||||
throw new ExperimentError(404, 'Experiment not found');
|
||||
}
|
||||
await client.query(
|
||||
`UPDATE runs SET cancel_requested=TRUE,
|
||||
status=CASE WHEN status='pending' THEN 'cancelled'::run_status ELSE status END,
|
||||
completed_at=CASE WHEN status='pending' THEN NOW() ELSE completed_at END,updated_at=NOW()
|
||||
WHERE experiment_id=$1 AND status IN ('pending','running','paused')`,
|
||||
[id]
|
||||
);
|
||||
return this.readDetail(client, id);
|
||||
});
|
||||
}
|
||||
private async readDetail(database: Query, id: string): Promise<ExperimentDetail> {
|
||||
const row = (
|
||||
await database.query(
|
||||
`SELECT ${summaryColumns},e.preview FROM research_experiments e WHERE e.id=$1`,
|
||||
[id]
|
||||
)
|
||||
).rows[0];
|
||||
if (!row) {
|
||||
throw new ExperimentError(404, 'Experiment not found');
|
||||
}
|
||||
const preview = retainedExperimentPreview(row.preview);
|
||||
// Deliberately project only compact result metadata; never load financial, trades, OHLC or return arrays.
|
||||
const runs = (
|
||||
await database.query(
|
||||
`SELECT r.id,r.backtest_id,r.trial_index,r.trial_key,r.status,r.progress,r.cancel_requested,r.error,r.dataset_hash,r.request_snapshot,
|
||||
br.canonical_result->>'kind' AS result_kind,br.canonical_result->>'status' AS result_status,
|
||||
br.canonical_result->>'runId' AS result_run_id,br.canonical_result->>'backtestId' AS result_backtest_id,
|
||||
br.canonical_result->>'financialEngine' AS financial_engine,br.canonical_result->>'strategyExecution' AS strategy_execution,
|
||||
br.canonical_result->'request' AS result_request,br.canonical_result#>'{analytics,policy}' AS analytics_policy,
|
||||
br.canonical_result#>'{analytics,version}' AS analytics_version,
|
||||
br.canonical_result#>'{financial,identity}' AS financial_identity,br.canonical_result#>'{financial,policy}' AS financial_policy,
|
||||
br.canonical_result#>'{analytics,metrics}' AS metrics,br.canonical_result#>'{analytics,unavailable}' AS unavailable,
|
||||
br.canonical_result#>'{financial,limitations}' AS limitations,br.canonical_result#>'{financial,modelLimitations}' AS model_limitations
|
||||
FROM runs r LEFT JOIN backtest_results br ON br.run_id=r.id WHERE r.experiment_id=$1 ORDER BY r.trial_index`,
|
||||
[id]
|
||||
)
|
||||
).rows;
|
||||
const trials = preview.candidates.map(candidate => {
|
||||
const run = runs.find(item => item.trial_index === candidate.index);
|
||||
const trial: ExperimentTrial = {
|
||||
...candidate,
|
||||
runId: run?.id ?? null,
|
||||
status: run?.status ?? 'missing',
|
||||
progress: Number(run?.progress ?? 0),
|
||||
cancelRequested: run?.cancel_requested ?? false,
|
||||
error: run?.error ?? null,
|
||||
comparable: false,
|
||||
diagnostic: null,
|
||||
metrics: null,
|
||||
unavailable: null,
|
||||
limitations: [],
|
||||
};
|
||||
if (!run) {
|
||||
trial.diagnostic = 'Expected trial run is missing';
|
||||
return trial;
|
||||
}
|
||||
const expected = experimentTrialRequest(preview, candidate, run.id);
|
||||
if (
|
||||
run.trial_key !== candidate.trialKey ||
|
||||
run.backtest_id !== preview.input.backtestId ||
|
||||
run.dataset_hash !== expected.datasetHash ||
|
||||
!equal(run.request_snapshot, expected)
|
||||
) {
|
||||
trial.diagnostic = 'Retained run inputs do not match the frozen experiment';
|
||||
return trial;
|
||||
}
|
||||
if (run.status !== 'completed') {
|
||||
trial.diagnostic = run.error ?? `Trial is ${run.status}`;
|
||||
return trial;
|
||||
}
|
||||
const expectedPolicy: CanonicalBacktestAnalytics['policy'] = {
|
||||
...expected.analyticsPolicy,
|
||||
calendarId: expected.policy.matching.risk.ledger.riskSession.calendarId,
|
||||
calendarRevision: expected.policy.matching.risk.ledger.riskSession.calendarRevision,
|
||||
sampling: 'account-boundary-after-observations-v1',
|
||||
marks: 'last-available-no-per-session-freshness-certification',
|
||||
returnUnit: 'fraction',
|
||||
variance: 'sample-n-minus-one',
|
||||
riskFreeConversion: 'annual-rate-divided-by-periods-per-year',
|
||||
downside: 'full-series-rms-relative-to-risk-free',
|
||||
partialPeriods: 'visible-excluded-from-periodic-statistics',
|
||||
drawdown: 'session-end-and-terminal-sampled',
|
||||
exposureBasis: 'elapsed-calendar-time',
|
||||
cagrBasis: 'elapsed-calendar-days-365',
|
||||
zeroTerminalCagr: 'negative-one-for-positive-elapsed-time',
|
||||
};
|
||||
const metrics = metricsSchema.safeParse(run.metrics);
|
||||
const unavailable = unavailableSchema.safeParse(run.unavailable);
|
||||
if (
|
||||
run.result_kind !== 'canonical-result/v1' ||
|
||||
run.result_status !== 'completed' ||
|
||||
run.result_run_id !== run.id ||
|
||||
run.result_backtest_id !== expected.backtestId ||
|
||||
run.financial_engine !== 'rust' ||
|
||||
run.strategy_execution !== 'typescript-retained-builtin/v1' ||
|
||||
!equal(run.result_request, expected) ||
|
||||
run.analytics_version !== 1 ||
|
||||
!equal(run.analytics_policy, expectedPolicy) ||
|
||||
!equal(run.financial_identity, {
|
||||
version: 1,
|
||||
sessionId: run.id,
|
||||
datasetHash: expected.datasetHash,
|
||||
}) ||
|
||||
!equal(run.financial_policy, expected.policy) ||
|
||||
!metrics.success ||
|
||||
!unavailable.success ||
|
||||
!Array.isArray(run.model_limitations) ||
|
||||
run.model_limitations.some((item: unknown) => typeof item !== 'string') ||
|
||||
!Array.isArray(run.limitations) ||
|
||||
run.limitations.some((item: unknown) => typeof item !== 'string')
|
||||
) {
|
||||
trial.diagnostic = 'Completed result provenance or metrics are unavailable or inconsistent';
|
||||
return trial;
|
||||
}
|
||||
if (
|
||||
Object.entries(metrics.data).some(([key, value]) =>
|
||||
value === null
|
||||
? !Object.hasOwn(unavailable.data, key)
|
||||
: Object.hasOwn(unavailable.data, key)
|
||||
)
|
||||
) {
|
||||
trial.diagnostic = 'Completed result metric availability is inconsistent';
|
||||
return trial;
|
||||
}
|
||||
trial.comparable = true;
|
||||
trial.metrics = metrics.data;
|
||||
trial.unavailable = unavailable.data;
|
||||
trial.limitations = [...run.limitations, ...run.model_limitations];
|
||||
return trial;
|
||||
});
|
||||
const counts = summary({ ...row, counts: {} }).counts;
|
||||
for (const run of runs) {
|
||||
if (Object.hasOwn(counts, run.status)) {
|
||||
counts[run.status as keyof ExperimentCounts]++;
|
||||
}
|
||||
}
|
||||
return { ...summary(row), counts, preview, trials };
|
||||
}
|
||||
}
|
||||
|
|
@ -3,6 +3,7 @@ import { Layout } from '@/components/layout';
|
|||
import { BacktestDetailPageV2, BacktestListPageV2 } from '@/features/backtest';
|
||||
import { DashboardPage } from '@/features/dashboard';
|
||||
import { ExchangesPage } from '@/features/exchanges';
|
||||
import { ExperimentDetailPage, ExperimentListPage } from '@/features/experiments';
|
||||
import { MonitoringPage } from '@/features/monitoring';
|
||||
import { PipelinePage } from '@/features/pipeline';
|
||||
import { ResearchListPage, ResearchProjectPage } from '@/features/research';
|
||||
|
|
@ -48,6 +49,10 @@ export function App() {
|
|||
<Route index element={<ResearchListPage />} />
|
||||
<Route path=":projectId" element={<ResearchProjectPage />} />
|
||||
</Route>
|
||||
<Route path="experiments">
|
||||
<Route index element={<ExperimentListPage />} />
|
||||
<Route path=":experimentId" element={<ExperimentDetailPage />} />
|
||||
</Route>
|
||||
<Route
|
||||
path="settings"
|
||||
element={<div className="p-4">Settings Page - Coming Soon</div>}
|
||||
|
|
|
|||
|
|
@ -13,6 +13,9 @@ export function Layout() {
|
|||
if (path === 'research' || path.startsWith('research/')) {
|
||||
return 'Research';
|
||||
}
|
||||
if (path === 'experiments' || path.startsWith('experiments/')) {
|
||||
return 'Experiments';
|
||||
}
|
||||
if (!path || path === 'dashboard') {
|
||||
return 'Dashboard';
|
||||
}
|
||||
|
|
|
|||
|
|
@ -509,6 +509,14 @@ export function BacktestDetailPageV2() {
|
|||
{archived ? 'Restore backtest' : 'Archive backtest'}
|
||||
</button>
|
||||
)}
|
||||
{backtest && catalog && !archived && (
|
||||
<Link
|
||||
to={`/experiments?backtestId=${encodeURIComponent(backtest.id)}`}
|
||||
className="px-3 py-2 text-sm text-primary-500 border border-border rounded-md"
|
||||
>
|
||||
Create experiment
|
||||
</Link>
|
||||
)}
|
||||
{currentRun && (
|
||||
<div className="px-4">
|
||||
<p className="text-xs text-text-secondary">Run current settings</p>
|
||||
|
|
|
|||
|
|
@ -0,0 +1,237 @@
|
|||
import { useEffect, useRef, useState } from 'react';
|
||||
import { Link, useParams } from 'react-router-dom';
|
||||
import type { ExperimentTrial } from '@stock-bot/stock-config/experiments';
|
||||
import { Button } from '@/components/ui/Button';
|
||||
import { ExperimentCounts } from './components/ExperimentCounts';
|
||||
import { ExperimentInputs } from './components/ExperimentInputs';
|
||||
import { experimentApi, type ExperimentDetailView as Detail } from './services/experimentApi';
|
||||
|
||||
export function ExperimentDetailPage() {
|
||||
const { experimentId = '' } = useParams<{ experimentId: string }>();
|
||||
return <ExperimentDetailView key={experimentId} experimentId={experimentId} />;
|
||||
}
|
||||
function metricText(trial: ExperimentTrial, key: keyof NonNullable<ExperimentTrial['metrics']>) {
|
||||
const value = trial.metrics?.[key];
|
||||
return value === null || value === undefined
|
||||
? `Unavailable${trial.unavailable?.[key] ? `: ${trial.unavailable[key]}` : ''}`
|
||||
: String(value);
|
||||
}
|
||||
function ExperimentDetailView({ experimentId }: { experimentId: string }) {
|
||||
const alive = useRef(false);
|
||||
const pending = useRef(false);
|
||||
const [experiment, setExperiment] = useState<Detail | null>(null);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [error, setError] = useState('');
|
||||
const [reload, setReload] = useState(0);
|
||||
const [cancelling, setCancelling] = useState(false);
|
||||
useEffect(() => {
|
||||
alive.current = true;
|
||||
return () => {
|
||||
alive.current = false;
|
||||
};
|
||||
}, []);
|
||||
useEffect(() => {
|
||||
let current = true;
|
||||
const controller = new AbortController();
|
||||
setLoading(true);
|
||||
setError('');
|
||||
setExperiment(null);
|
||||
void experimentApi
|
||||
.get(experimentId, controller.signal)
|
||||
.then(value => {
|
||||
if (current) {
|
||||
setExperiment(value);
|
||||
}
|
||||
})
|
||||
.catch(cause => {
|
||||
if (current) {
|
||||
setError(cause instanceof Error ? cause.message : 'Could not load experiment');
|
||||
}
|
||||
})
|
||||
.finally(() => {
|
||||
if (current) {
|
||||
setLoading(false);
|
||||
}
|
||||
});
|
||||
return () => {
|
||||
current = false;
|
||||
controller.abort();
|
||||
};
|
||||
}, [experimentId, reload]);
|
||||
const cancel = async () => {
|
||||
if (pending.current || !experiment || loading) {
|
||||
return;
|
||||
}
|
||||
pending.current = true;
|
||||
setCancelling(true);
|
||||
setError('');
|
||||
try {
|
||||
const value = await experimentApi.cancel(experimentId);
|
||||
if (alive.current) {
|
||||
setExperiment(value);
|
||||
}
|
||||
} catch (cause) {
|
||||
if (alive.current) {
|
||||
setError(
|
||||
`${cause instanceof Error ? cause.message : 'Could not request cancellation'}. Refresh to verify the saved state, or retry cancellation.`
|
||||
);
|
||||
}
|
||||
} finally {
|
||||
pending.current = false;
|
||||
if (alive.current) {
|
||||
setCancelling(false);
|
||||
}
|
||||
}
|
||||
};
|
||||
const active =
|
||||
experiment &&
|
||||
experiment.counts.pending + experiment.counts.running + experiment.counts.paused > 0;
|
||||
return (
|
||||
<div className="h-full overflow-auto space-y-5 p-1">
|
||||
<Link className="text-primary-500 text-sm" to="/experiments">
|
||||
All experiments
|
||||
</Link>
|
||||
<div className="flex flex-wrap items-center justify-between gap-3">
|
||||
<h1 className="text-lg font-bold">{experiment?.name ?? 'Experiment'}</h1>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
disabled={loading || cancelling}
|
||||
onClick={() => setReload(value => value + 1)}
|
||||
>
|
||||
Refresh experiment
|
||||
</Button>
|
||||
</div>
|
||||
{loading && <p role="status">Loading experiment...</p>}
|
||||
{error && (
|
||||
<p role="alert" className="text-error">
|
||||
{error}
|
||||
</p>
|
||||
)}
|
||||
{experiment && (
|
||||
<>
|
||||
<ExperimentCounts experiment={experiment} />
|
||||
<div className="flex flex-wrap items-center gap-4">
|
||||
<Link
|
||||
className="text-primary-500 text-sm"
|
||||
to={`/backtests/${encodeURIComponent(experiment.backtestId)}`}
|
||||
>
|
||||
Open saved backtest
|
||||
</Link>
|
||||
{active && !experiment.cancelRequested && (
|
||||
<Button
|
||||
variant="danger"
|
||||
size="sm"
|
||||
disabled={cancelling}
|
||||
onClick={() => void cancel()}
|
||||
>
|
||||
{cancelling ? 'Requesting cancellation...' : 'Cancel remaining trials'}
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
<ExperimentInputs preview={experiment.preview} />
|
||||
<section aria-label="Experiment trial outcomes" className="space-y-2">
|
||||
<h2 className="font-semibold">Every trial outcome</h2>
|
||||
<p className="text-sm text-text-secondary">
|
||||
Rows retain grid order. Metrics come from saved results; unavailable, failed and
|
||||
incomparable outcomes remain visible. Returns and drawdowns are fractions. No
|
||||
cross-experiment ranking is applied.
|
||||
</p>
|
||||
<div className="overflow-x-auto">
|
||||
<table className="w-full text-sm text-left">
|
||||
<thead>
|
||||
<tr>
|
||||
{[
|
||||
'Trial / parameters',
|
||||
'Status',
|
||||
'Comparability',
|
||||
'Total return',
|
||||
'Max drawdown',
|
||||
'Sharpe ratio',
|
||||
'Diagnostics / run',
|
||||
].map(label => (
|
||||
<th key={label} className="p-2 border-b border-border whitespace-nowrap">
|
||||
{label}
|
||||
</th>
|
||||
))}
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{experiment.trials.map(trial => (
|
||||
<tr key={trial.trialKey} className="align-top">
|
||||
<td className="p-2 border-b border-border">
|
||||
<span>Trial {trial.index + 1}</span>
|
||||
<pre className="whitespace-pre-wrap text-xs">
|
||||
{JSON.stringify(trial.parameters, null, 2)}
|
||||
</pre>
|
||||
</td>
|
||||
<td className="p-2 border-b border-border">
|
||||
{trial.status}
|
||||
<p className="text-xs">
|
||||
{trial.status === 'missing'
|
||||
? 'Child run missing'
|
||||
: `${trial.progress}% complete`}
|
||||
</p>
|
||||
{trial.cancelRequested && <p className="text-xs">Cancellation requested</p>}
|
||||
</td>
|
||||
<td className="p-2 border-b border-border">
|
||||
{trial.comparable
|
||||
? 'Comparable'
|
||||
: trial.status === 'completed'
|
||||
? 'Incomparable'
|
||||
: 'Not evaluated'}
|
||||
</td>
|
||||
<td className="p-2 border-b border-border">
|
||||
{metricText(trial, 'totalReturn')}
|
||||
</td>
|
||||
<td className="p-2 border-b border-border">
|
||||
{metricText(trial, 'maxDrawdown')}
|
||||
</td>
|
||||
<td className="p-2 border-b border-border">
|
||||
{metricText(trial, 'sharpeRatio')}
|
||||
</td>
|
||||
<td className="p-2 border-b border-border min-w-56 space-y-2">
|
||||
{trial.error && <p className="text-error">{trial.error}</p>}
|
||||
{trial.diagnostic && <p>{trial.diagnostic}</p>}
|
||||
{trial.limitations.map((limitation, index) => (
|
||||
<p key={index}>{limitation}</p>
|
||||
))}
|
||||
{!trial.metrics && <p>Metrics unavailable</p>}
|
||||
{trial.metrics && (
|
||||
<details>
|
||||
<summary className="cursor-pointer">All reported metrics</summary>
|
||||
<dl>
|
||||
{Object.keys(trial.metrics).map(key => (
|
||||
<div key={key}>
|
||||
<dt>{key}</dt>
|
||||
<dd>
|
||||
{metricText(
|
||||
trial,
|
||||
key as keyof NonNullable<ExperimentTrial['metrics']>
|
||||
)}
|
||||
</dd>
|
||||
</div>
|
||||
))}
|
||||
</dl>
|
||||
</details>
|
||||
)}
|
||||
{trial.runId && (
|
||||
<Link
|
||||
className="text-primary-500"
|
||||
to={`/backtests/${encodeURIComponent(experiment.backtestId)}/run/${encodeURIComponent(trial.runId)}`}
|
||||
>
|
||||
Open trial {trial.index + 1} run
|
||||
</Link>
|
||||
)}
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</section>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
|
@ -0,0 +1,116 @@
|
|||
import { useEffect, useState } from 'react';
|
||||
import { Link, useSearchParams } from 'react-router-dom';
|
||||
import type { ExperimentSummary } from '@stock-bot/stock-config/experiments';
|
||||
import { Button } from '@/components/ui/Button';
|
||||
import { ExperimentCounts } from './components/ExperimentCounts';
|
||||
import { ExperimentEditor } from './components/ExperimentEditor';
|
||||
import { experimentApi } from './services/experimentApi';
|
||||
|
||||
export function ExperimentListPage() {
|
||||
const [params] = useSearchParams();
|
||||
const backtestId = params.get('backtestId') || '';
|
||||
return <ExperimentList key={backtestId} backtestId={backtestId} />;
|
||||
}
|
||||
function ExperimentList({ backtestId }: { backtestId: string }) {
|
||||
const [rows, setRows] = useState<ExperimentSummary[]>([]);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [error, setError] = useState('');
|
||||
const [reload, setReload] = useState(0);
|
||||
const [dirty, setDirty] = useState(false);
|
||||
useEffect(() => {
|
||||
let current = true;
|
||||
const controller = new AbortController();
|
||||
setLoading(true);
|
||||
setError('');
|
||||
setRows([]);
|
||||
void experimentApi
|
||||
.list(backtestId || undefined, controller.signal)
|
||||
.then(value => {
|
||||
if (current) {
|
||||
setRows(value);
|
||||
}
|
||||
})
|
||||
.catch(cause => {
|
||||
if (current) {
|
||||
setError(cause instanceof Error ? cause.message : 'Could not load experiments');
|
||||
}
|
||||
})
|
||||
.finally(() => {
|
||||
if (current) {
|
||||
setLoading(false);
|
||||
}
|
||||
});
|
||||
return () => {
|
||||
current = false;
|
||||
controller.abort();
|
||||
};
|
||||
}, [backtestId, reload]);
|
||||
return (
|
||||
<div
|
||||
className="h-full overflow-auto space-y-6 p-1"
|
||||
onClickCapture={event => {
|
||||
if (
|
||||
(event.target as HTMLElement).closest('a') &&
|
||||
dirty &&
|
||||
!event.ctrlKey &&
|
||||
!event.metaKey &&
|
||||
!event.shiftKey &&
|
||||
!window.confirm(
|
||||
'Leave this experiment draft or unconfirmed submission? Its retry inputs and key will be discarded. You can inspect saved experiments in another tab.'
|
||||
)
|
||||
) {
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
}
|
||||
}}
|
||||
>
|
||||
<div>
|
||||
<h1 className="text-lg font-bold text-text-primary">Experiments</h1>
|
||||
<p className="text-sm text-text-secondary">
|
||||
Retained-input parameter sweeps and every trial outcome.
|
||||
</p>
|
||||
</div>
|
||||
<ExperimentEditor initialBacktestId={backtestId} onDirty={setDirty} />
|
||||
<section aria-label="Saved experiments" className="space-y-3">
|
||||
<div className="flex items-center justify-between gap-3">
|
||||
<h2 className="font-semibold">Saved experiments</h2>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
disabled={loading}
|
||||
onClick={() => setReload(value => value + 1)}
|
||||
>
|
||||
Refresh experiments
|
||||
</Button>
|
||||
</div>
|
||||
{backtestId && (
|
||||
<p className="text-sm">
|
||||
Showing experiments for the selected backtest.{' '}
|
||||
<Link className="text-primary-500" to="/experiments">
|
||||
Show all experiments
|
||||
</Link>
|
||||
</p>
|
||||
)}
|
||||
{loading && <p role="status">Loading experiments...</p>}
|
||||
{error && (
|
||||
<p role="alert" className="text-error">
|
||||
{error}
|
||||
</p>
|
||||
)}
|
||||
{!loading && !error && rows.length === 0 && <p>No experiments yet.</p>}
|
||||
{rows.map(item => (
|
||||
<article key={item.id} className="rounded-lg border border-border p-3 space-y-2">
|
||||
<Link
|
||||
className="font-medium text-primary-500"
|
||||
to={`/experiments/${encodeURIComponent(item.id)}`}
|
||||
>
|
||||
{item.name}
|
||||
</Link>
|
||||
<p className="text-xs text-text-secondary">Created {item.createdAt}</p>
|
||||
<ExperimentCounts experiment={item} />
|
||||
</article>
|
||||
))}
|
||||
</section>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
|
@ -0,0 +1,22 @@
|
|||
import type { ExperimentSummary } from '@stock-bot/stock-config/experiments';
|
||||
|
||||
export function ExperimentCounts({ experiment }: { experiment: ExperimentSummary }) {
|
||||
const missing =
|
||||
experiment.trialCount - Object.values(experiment.counts).reduce((sum, count) => sum + count, 0);
|
||||
return (
|
||||
<div className="text-sm text-text-secondary space-y-1">
|
||||
<p>
|
||||
{experiment.trialCount} trials ·{' '}
|
||||
{Object.entries(experiment.counts)
|
||||
.map(([status, count]) => `${status}: ${count}`)
|
||||
.join(' · ')}{' '}
|
||||
· missing: {missing}
|
||||
</p>
|
||||
{experiment.cancelRequested && (
|
||||
<p>
|
||||
Cancellation requested. Running trials may still finish before acknowledging cancellation.
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
|
@ -0,0 +1,333 @@
|
|||
import { useEffect, useRef, useState } from 'react';
|
||||
import { Link, useNavigate } from 'react-router-dom';
|
||||
import { z } from 'zod';
|
||||
import {
|
||||
experimentInputSchema,
|
||||
MAX_EXPERIMENT_TRIALS,
|
||||
type ExperimentSubmission,
|
||||
} from '@stock-bot/stock-config/experiments';
|
||||
import { Button } from '@/components/ui/Button';
|
||||
import { backtestApiV2, type Backtest } from '@/features/backtest/services/backtestApiV2';
|
||||
import { useUnsavedWarning } from '@/features/strategies/components/useUnsavedWarning';
|
||||
import {
|
||||
experimentApi,
|
||||
ExperimentApiError,
|
||||
type ExperimentPreviewView,
|
||||
} from '../services/experimentApi';
|
||||
import { ExperimentInputs } from './ExperimentInputs';
|
||||
|
||||
const fieldClass =
|
||||
'mt-1 w-full rounded-md border border-border bg-background px-3 py-2 text-text-primary disabled:opacity-60';
|
||||
const message = (cause: unknown) =>
|
||||
cause instanceof z.ZodError
|
||||
? cause.issues.map(issue => `${issue.path.join('.') || 'Input'}: ${issue.message}`).join('; ')
|
||||
: cause instanceof Error
|
||||
? cause.message
|
||||
: 'Could not prepare the experiment';
|
||||
const canonical = (value: Backtest) =>
|
||||
value &&
|
||||
typeof value.id === 'string' &&
|
||||
typeof value.name === 'string' &&
|
||||
!value.archivedAt &&
|
||||
value.strategyVersionId &&
|
||||
value.config &&
|
||||
typeof value.config.canonical === 'object' &&
|
||||
value.config.canonical !== null &&
|
||||
typeof value.config.datasetHash === 'string';
|
||||
|
||||
export function ExperimentEditor({
|
||||
initialBacktestId,
|
||||
onDirty,
|
||||
}: {
|
||||
initialBacktestId: string;
|
||||
onDirty: (dirty: boolean) => void;
|
||||
}) {
|
||||
const navigate = useNavigate();
|
||||
const alive = useRef(false);
|
||||
const generation = useRef(0);
|
||||
const previewRequest = useRef<AbortController | null>(null);
|
||||
const pending = useRef(false);
|
||||
const intent = useRef<{ body: ExperimentSubmission; key: string } | null>(null);
|
||||
const [hasIntent, setHasIntent] = useState(false);
|
||||
const [backtestId, setBacktestId] = useState(initialBacktestId);
|
||||
const [name, setName] = useState('');
|
||||
const [grid, setGrid] = useState('{}');
|
||||
const [backtests, setBacktests] = useState<Backtest[]>([]);
|
||||
const [templateLoading, setTemplateLoading] = useState(true);
|
||||
const [templateError, setTemplateError] = useState('');
|
||||
const [templateReload, setTemplateReload] = useState(0);
|
||||
const [limit, setLimit] = useState(50);
|
||||
const [moreTemplates, setMoreTemplates] = useState(false);
|
||||
const [preview, setPreview] = useState<ExperimentPreviewView | null>(null);
|
||||
const [previewLoading, setPreviewLoading] = useState(false);
|
||||
const [error, setError] = useState('');
|
||||
const [submitting, setSubmitting] = useState(false);
|
||||
const [ambiguous, setAmbiguous] = useState(false);
|
||||
const dirty = hasIntent || Boolean(name || grid !== '{}' || backtestId !== initialBacktestId);
|
||||
useUnsavedWarning(dirty);
|
||||
useEffect(() => {
|
||||
onDirty(dirty);
|
||||
}, [dirty, onDirty]);
|
||||
useEffect(() => {
|
||||
alive.current = true;
|
||||
return () => {
|
||||
alive.current = false;
|
||||
generation.current++;
|
||||
previewRequest.current?.abort();
|
||||
};
|
||||
}, []);
|
||||
useEffect(() => {
|
||||
let current = true;
|
||||
const controller = new AbortController();
|
||||
setTemplateLoading(true);
|
||||
setTemplateError('');
|
||||
void (async () => {
|
||||
const rows = await backtestApiV2.listBacktests(limit, 0, false, controller.signal);
|
||||
if (!Array.isArray(rows)) {
|
||||
throw new Error('The saved backtest list could not be read');
|
||||
}
|
||||
const selected =
|
||||
initialBacktestId && !rows.some(item => item?.id === initialBacktestId)
|
||||
? await backtestApiV2.getBacktest(initialBacktestId)
|
||||
: null;
|
||||
if (current) {
|
||||
setMoreTemplates(rows.length === limit);
|
||||
setBacktests((selected ? [...rows, selected] : rows).filter(canonical));
|
||||
}
|
||||
})()
|
||||
.catch(cause => {
|
||||
if (current) {
|
||||
setTemplateError(message(cause));
|
||||
}
|
||||
})
|
||||
.finally(() => {
|
||||
if (current) {
|
||||
setTemplateLoading(false);
|
||||
}
|
||||
});
|
||||
return () => {
|
||||
current = false;
|
||||
controller.abort();
|
||||
};
|
||||
}, [initialBacktestId, templateReload, limit]);
|
||||
|
||||
const invalidate = (change: () => void) => {
|
||||
if (intent.current) {
|
||||
return;
|
||||
}
|
||||
generation.current++;
|
||||
previewRequest.current?.abort();
|
||||
setPreview(null);
|
||||
setPreviewLoading(false);
|
||||
setError('');
|
||||
change();
|
||||
};
|
||||
const prepare = async () => {
|
||||
if (intent.current || previewLoading) {
|
||||
return;
|
||||
}
|
||||
const current = ++generation.current;
|
||||
previewRequest.current?.abort();
|
||||
const controller = new AbortController();
|
||||
previewRequest.current = controller;
|
||||
setPreview(null);
|
||||
setError('');
|
||||
setPreviewLoading(true);
|
||||
try {
|
||||
const input = experimentInputSchema.parse({ backtestId, name, grid: JSON.parse(grid) });
|
||||
const value = await experimentApi.preview(input, controller.signal);
|
||||
if (alive.current && current === generation.current) {
|
||||
setPreview(value);
|
||||
}
|
||||
} catch (cause) {
|
||||
if (alive.current && current === generation.current) {
|
||||
setError(message(cause));
|
||||
}
|
||||
} finally {
|
||||
if (alive.current && current === generation.current) {
|
||||
setPreviewLoading(false);
|
||||
}
|
||||
}
|
||||
};
|
||||
const submit = async () => {
|
||||
if (pending.current || (!intent.current && !preview)) {
|
||||
return;
|
||||
}
|
||||
if (!intent.current) {
|
||||
if (!preview) {
|
||||
return;
|
||||
}
|
||||
intent.current = {
|
||||
key: crypto.randomUUID(),
|
||||
body: { ...preview.input, previewHash: preview.previewHash },
|
||||
};
|
||||
}
|
||||
const captured = intent.current;
|
||||
pending.current = true;
|
||||
setHasIntent(true);
|
||||
setSubmitting(true);
|
||||
setError('');
|
||||
try {
|
||||
const accepted = await experimentApi.create(captured.body, captured.key);
|
||||
if (alive.current) {
|
||||
intent.current = null;
|
||||
setHasIntent(false);
|
||||
navigate(`/experiments/${encodeURIComponent(accepted.id)}`);
|
||||
}
|
||||
} catch (cause) {
|
||||
if (alive.current) {
|
||||
setError(message(cause));
|
||||
setAmbiguous(!(cause instanceof ExperimentApiError) || cause.ambiguous);
|
||||
}
|
||||
} finally {
|
||||
pending.current = false;
|
||||
if (alive.current) {
|
||||
setSubmitting(false);
|
||||
}
|
||||
}
|
||||
};
|
||||
const newIntent = () => {
|
||||
if (
|
||||
pending.current ||
|
||||
!window.confirm(
|
||||
'Release this submission? If its response was lost, it may already exist. Check the experiment list before creating another.'
|
||||
)
|
||||
) {
|
||||
return;
|
||||
}
|
||||
intent.current = null;
|
||||
setHasIntent(false);
|
||||
setAmbiguous(false);
|
||||
setPreview(null);
|
||||
setError('');
|
||||
};
|
||||
return (
|
||||
<section
|
||||
aria-label="Create experiment"
|
||||
className="rounded-lg border border-border bg-surface p-4 space-y-4"
|
||||
>
|
||||
<h2 className="font-semibold text-text-primary">New parameter sweep</h2>
|
||||
<p className="text-sm text-text-secondary">
|
||||
Choose a saved canonical backtest and vary its strategy parameters. Preview validates every
|
||||
combination before any trials are submitted.
|
||||
</p>
|
||||
{templateLoading && <p role="status">Loading saved backtests...</p>}
|
||||
{templateError && (
|
||||
<div role="alert">
|
||||
{templateError}{' '}
|
||||
<Button variant="outline" size="sm" onClick={() => setTemplateReload(value => value + 1)}>
|
||||
Retry saved backtests
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
{!templateLoading && !templateError && backtests.length === 0 && (
|
||||
<p>
|
||||
No saved canonical backtests are available.{' '}
|
||||
<Link className="text-primary-500" to="/backtests">
|
||||
Configure a backtest
|
||||
</Link>{' '}
|
||||
with a retained dataset and strategy version.
|
||||
</p>
|
||||
)}
|
||||
<div className="grid gap-4 sm:grid-cols-2 text-sm">
|
||||
<label>
|
||||
Saved backtest
|
||||
<select
|
||||
className={fieldClass}
|
||||
value={backtestId}
|
||||
disabled={hasIntent || templateLoading}
|
||||
onChange={event => invalidate(() => setBacktestId(event.target.value))}
|
||||
>
|
||||
<option value="">Select a saved canonical backtest</option>
|
||||
{initialBacktestId && !backtests.some(item => item.id === initialBacktestId) && (
|
||||
<option value={initialBacktestId}>Selected backtest is unavailable</option>
|
||||
)}
|
||||
{backtests.map(item => (
|
||||
<option key={item.id} value={item.id}>
|
||||
{item.name}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</label>
|
||||
<label>
|
||||
Experiment name
|
||||
<input
|
||||
className={fieldClass}
|
||||
value={name}
|
||||
disabled={hasIntent}
|
||||
onChange={event => invalidate(() => setName(event.target.value))}
|
||||
/>
|
||||
</label>
|
||||
</div>
|
||||
{moreTemplates && (
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
disabled={templateLoading || hasIntent}
|
||||
onClick={() => setLimit(value => value + 50)}
|
||||
>
|
||||
Load more backtests
|
||||
</Button>
|
||||
)}
|
||||
<label className="block text-sm">
|
||||
Parameter grid (JSON)
|
||||
<textarea
|
||||
className={`${fieldClass} font-mono`}
|
||||
rows={4}
|
||||
value={grid}
|
||||
disabled={hasIntent}
|
||||
onChange={event => invalidate(() => setGrid(event.target.value))}
|
||||
aria-describedby="experiment-grid-help"
|
||||
/>
|
||||
</label>
|
||||
<p id="experiment-grid-help" className="text-xs text-text-secondary">
|
||||
Use parameter names from the selected strategy with arrays of values, e.g.{' '}
|
||||
{'{"fastPeriod":[5,10],"slowPeriod":[20,30]}'}. All combinations must be valid. {'{}'} runs
|
||||
the unchanged parameters once. Maximum {MAX_EXPERIMENT_TRIALS} trials per experiment; this
|
||||
does not promise concurrent execution.
|
||||
</p>
|
||||
<Button
|
||||
variant="outline"
|
||||
disabled={
|
||||
hasIntent ||
|
||||
previewLoading ||
|
||||
!backtests.some(item => item.id === backtestId) ||
|
||||
!name.trim()
|
||||
}
|
||||
onClick={() => void prepare()}
|
||||
>
|
||||
Preview experiment
|
||||
</Button>
|
||||
{previewLoading && <p role="status">Validating experiment inputs...</p>}
|
||||
{preview && <ExperimentInputs preview={preview} />}
|
||||
{error && (
|
||||
<p role="alert" className="text-error">
|
||||
{error}
|
||||
</p>
|
||||
)}
|
||||
{hasIntent && (
|
||||
<p role="status" className="text-sm text-text-secondary">
|
||||
{ambiguous ? 'Acceptance is unconfirmed. ' : ''}This submission keeps its exact inputs and
|
||||
key. Retry to recover the same experiment; check saved experiments before starting
|
||||
another.
|
||||
</p>
|
||||
)}
|
||||
{(preview || hasIntent) && (
|
||||
<div className="flex flex-wrap gap-2">
|
||||
<Button disabled={submitting} onClick={() => void submit()}>
|
||||
{submitting
|
||||
? 'Submitting experiment...'
|
||||
: hasIntent
|
||||
? 'Retry experiment submission'
|
||||
: 'Confirm experiment'}
|
||||
</Button>
|
||||
{hasIntent && (
|
||||
<Button variant="outline" disabled={submitting} onClick={newIntent}>
|
||||
Start new experiment
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
|
@ -0,0 +1,86 @@
|
|||
import type { ExperimentPreviewView } from '../services/experimentApi';
|
||||
|
||||
export function ExperimentInputs({ preview }: { preview: ExperimentPreviewView }) {
|
||||
const { request, dataset } = preview;
|
||||
const series = dataset.series.find(item => item.id === request.strategy.selection.seriesId);
|
||||
return (
|
||||
<section
|
||||
aria-label="Frozen experiment inputs"
|
||||
className="space-y-2 text-sm text-text-secondary"
|
||||
>
|
||||
<p className="font-medium text-text-primary">
|
||||
{preview.candidates.length} trials · {request.name}
|
||||
</p>
|
||||
<dl className="grid gap-2 sm:grid-cols-2 break-all">
|
||||
<div>
|
||||
<dt>Strategy version</dt>
|
||||
<dd>{request.strategy.versionId}</dd>
|
||||
</div>
|
||||
<div>
|
||||
<dt>Dataset</dt>
|
||||
<dd>{request.datasetHash}</dd>
|
||||
</div>
|
||||
<div>
|
||||
<dt>Asset / timeframe</dt>
|
||||
<dd>
|
||||
{request.strategy.selection.instrumentId} / {series?.interval}
|
||||
</dd>
|
||||
</div>
|
||||
<div>
|
||||
<dt>Trading window (UTC, end exclusive)</dt>
|
||||
<dd>
|
||||
{new Date(dataset.bounds.tradeStart).toISOString()} —{' '}
|
||||
{new Date(dataset.bounds.tradeEnd).toISOString()}
|
||||
</dd>
|
||||
</div>
|
||||
<div>
|
||||
<dt>Warmup starts (UTC)</dt>
|
||||
<dd>{new Date(dataset.bounds.warmupStart).toISOString()}</dd>
|
||||
</div>
|
||||
<div>
|
||||
<dt>Initial capital / owner budget (USD)</dt>
|
||||
<dd>
|
||||
{request.policy.matching.risk.ledger.initialCapital} /{' '}
|
||||
{request.strategy.selection.ownerBudget}
|
||||
</dd>
|
||||
</div>
|
||||
<div>
|
||||
<dt>Seed</dt>
|
||||
<dd>{request.strategy.selection.seed}</dd>
|
||||
</div>
|
||||
</dl>
|
||||
<p>
|
||||
Only strategy parameters vary. Every trial retains this dataset, strategy version, capital,
|
||||
costs and risk policy.
|
||||
</p>
|
||||
<details>
|
||||
<summary className="cursor-pointer text-primary-500">
|
||||
Exact parameters, policies and provenance
|
||||
</summary>
|
||||
<pre className="mt-2 max-h-80 overflow-auto whitespace-pre-wrap text-xs">
|
||||
{JSON.stringify(
|
||||
{
|
||||
previewHash: preview.previewHash,
|
||||
input: preview.input,
|
||||
candidates: preview.candidates,
|
||||
strategy: {
|
||||
versionId: request.strategy.versionId,
|
||||
reviewId: request.strategy.reviewId,
|
||||
selection: request.strategy.selection,
|
||||
artifactHash: request.strategy.package.artifact.sha256,
|
||||
dependencyLockHash: request.strategy.package.dependencyLock.sha256,
|
||||
},
|
||||
dataset,
|
||||
policy: request.policy,
|
||||
analyticsPolicy: request.analyticsPolicy,
|
||||
build: request.build,
|
||||
modelArtifacts: request.modelArtifacts,
|
||||
},
|
||||
null,
|
||||
2
|
||||
)}
|
||||
</pre>
|
||||
</details>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
2
apps/stock/web-app/src/features/experiments/index.ts
Normal file
2
apps/stock/web-app/src/features/experiments/index.ts
Normal file
|
|
@ -0,0 +1,2 @@
|
|||
export { ExperimentListPage } from './ExperimentListPage';
|
||||
export { ExperimentDetailPage } from './ExperimentDetailPage';
|
||||
|
|
@ -0,0 +1,298 @@
|
|||
import { z } from 'zod';
|
||||
import { canonicalRunRequestSchema } from '@stock-bot/stock-config/canonical-research';
|
||||
import {
|
||||
experimentInputSchema,
|
||||
MAX_EXPERIMENT_TRIALS,
|
||||
type ExperimentDetail,
|
||||
type ExperimentInput,
|
||||
type ExperimentPreview,
|
||||
type ExperimentSubmission,
|
||||
type ExperimentSummary,
|
||||
} from '@stock-bot/stock-config/experiments';
|
||||
import { canonicalStrategyJson } from '@stock-bot/stock-config/strategy';
|
||||
import { API_BASE_URL, apiFetch } from '@/lib/api';
|
||||
|
||||
export class ExperimentApiError extends Error {
|
||||
constructor(
|
||||
message: string,
|
||||
public readonly status: number | null
|
||||
) {
|
||||
super(message);
|
||||
}
|
||||
get ambiguous() {
|
||||
return this.status === null || this.status >= 500;
|
||||
}
|
||||
}
|
||||
const hash = z.string().regex(/^[a-f0-9]{64}$/);
|
||||
const count = z.number().int().nonnegative().max(MAX_EXPERIMENT_TRIALS);
|
||||
const scalar = z.union([z.string(), z.number().finite(), z.boolean()]);
|
||||
const candidate = z.object({
|
||||
index: count,
|
||||
trialKey: hash,
|
||||
parameters: z.record(scalar),
|
||||
});
|
||||
const statuses = ['pending', 'running', 'paused', 'completed', 'failed', 'cancelled'] as const;
|
||||
const counts = z.object({
|
||||
pending: count,
|
||||
running: count,
|
||||
paused: count,
|
||||
completed: count,
|
||||
failed: count,
|
||||
cancelled: count,
|
||||
});
|
||||
const summary = z.object({
|
||||
id: z.string().uuid(),
|
||||
name: z.string().min(1),
|
||||
backtestId: z.string().uuid(),
|
||||
createdAt: z.string().min(1),
|
||||
cancelRequested: z.boolean(),
|
||||
trialCount: count.min(1),
|
||||
counts,
|
||||
datasetHash: hash,
|
||||
strategyVersionId: z.string().uuid(),
|
||||
previewHash: hash,
|
||||
});
|
||||
const timestamp = z.number().int().min(-8640000000000000).max(8640000000000000);
|
||||
const dataset = z
|
||||
.object({
|
||||
version: z.literal(2),
|
||||
hash,
|
||||
bounds: z.object({
|
||||
warmupStart: timestamp,
|
||||
tradeStart: timestamp,
|
||||
tradeEnd: timestamp,
|
||||
}),
|
||||
series: z.array(
|
||||
z.object({ id: z.string(), instrumentId: z.string(), interval: z.string() }).passthrough()
|
||||
),
|
||||
})
|
||||
.passthrough();
|
||||
/** Only the manifest fields consumed by this UI are structurally decoded here. */
|
||||
export type ExperimentPreviewView = Omit<ExperimentPreview, 'dataset'> & {
|
||||
dataset: z.infer<typeof dataset>;
|
||||
};
|
||||
export type ExperimentDetailView = Omit<ExperimentDetail, 'preview'> & {
|
||||
preview: ExperimentPreviewView;
|
||||
};
|
||||
const preview = z.object({
|
||||
version: z.literal('research-experiment-preview/v1'),
|
||||
previewHash: hash,
|
||||
input: experimentInputSchema,
|
||||
request: canonicalRunRequestSchema,
|
||||
dataset,
|
||||
candidates: z.array(candidate).min(1).max(MAX_EXPERIMENT_TRIALS),
|
||||
});
|
||||
const metric = z.number().finite().nullable();
|
||||
const metrics = z.object({
|
||||
totalReturn: metric,
|
||||
cagr: metric,
|
||||
maxDrawdown: metric,
|
||||
exposureTime: metric,
|
||||
volatility: metric,
|
||||
downsideDeviation: metric,
|
||||
sharpeRatio: metric,
|
||||
sortinoRatio: metric,
|
||||
var95: metric,
|
||||
cvar95: metric,
|
||||
var99: metric,
|
||||
alpha: z.null(),
|
||||
beta: z.null(),
|
||||
informationRatio: z.null(),
|
||||
roundTripCount: z.null(),
|
||||
winRate: z.null(),
|
||||
profitFactor: z.null(),
|
||||
avgWin: z.null(),
|
||||
avgLoss: z.null(),
|
||||
});
|
||||
const trial = candidate.extend({
|
||||
runId: z.string().uuid().nullable(),
|
||||
status: z.enum([...statuses, 'missing']),
|
||||
progress: z.number().finite().min(0).max(100),
|
||||
cancelRequested: z.boolean(),
|
||||
error: z.string().nullable(),
|
||||
comparable: z.boolean(),
|
||||
diagnostic: z.string().nullable(),
|
||||
metrics: metrics.nullable(),
|
||||
unavailable: z.record(z.string()).nullable(),
|
||||
limitations: z.array(z.string()),
|
||||
});
|
||||
const detail = summary.extend({ preview, trials: z.array(trial).max(MAX_EXPERIMENT_TRIALS) });
|
||||
const same = (left: unknown, right: unknown) =>
|
||||
canonicalStrategyJson(left) === canonicalStrategyJson(right);
|
||||
const invalid = () =>
|
||||
new ExperimentApiError(
|
||||
'The experiment response could not be verified. Refresh or retry the same submission.',
|
||||
null
|
||||
);
|
||||
|
||||
function parseSummary(value: unknown): ExperimentSummary {
|
||||
const parsed = summary.parse(value);
|
||||
if (Object.values(parsed.counts).reduce((sum, value) => sum + value, 0) > parsed.trialCount) {
|
||||
throw invalid();
|
||||
}
|
||||
return parsed;
|
||||
}
|
||||
function parsePreview(value: unknown): ExperimentPreviewView {
|
||||
const parsed = preview.parse(value);
|
||||
if (
|
||||
parsed.input.backtestId !== parsed.request.backtestId ||
|
||||
parsed.dataset.hash !== parsed.request.datasetHash ||
|
||||
parsed.dataset.bounds.warmupStart > parsed.dataset.bounds.tradeStart ||
|
||||
parsed.dataset.bounds.tradeStart >= parsed.dataset.bounds.tradeEnd ||
|
||||
!parsed.dataset.series.some(
|
||||
series =>
|
||||
series.id === parsed.request.strategy.selection.seriesId &&
|
||||
series.instrumentId === parsed.request.strategy.selection.instrumentId
|
||||
) ||
|
||||
parsed.candidates.some((item, index) => item.index !== index) ||
|
||||
new Set(parsed.candidates.map(item => item.trialKey)).size !== parsed.candidates.length
|
||||
) {
|
||||
throw invalid();
|
||||
}
|
||||
// The server retains and verifies the complete manifest; the browser only renders its identity/window.
|
||||
return parsed;
|
||||
}
|
||||
function parseDetail(value: unknown): ExperimentDetailView {
|
||||
const parsed = detail.parse(value);
|
||||
parseSummary(parsed);
|
||||
const retained = parsePreview(parsed.preview);
|
||||
if (
|
||||
parsed.backtestId !== retained.input.backtestId ||
|
||||
parsed.name !== retained.input.name ||
|
||||
parsed.previewHash !== retained.previewHash ||
|
||||
parsed.datasetHash !== retained.request.datasetHash ||
|
||||
parsed.strategyVersionId !== retained.request.strategy.versionId ||
|
||||
parsed.trialCount !== retained.candidates.length ||
|
||||
parsed.trials.length !== parsed.trialCount
|
||||
) {
|
||||
throw invalid();
|
||||
}
|
||||
const runIds = new Set<string>();
|
||||
for (const [index, item] of parsed.trials.entries()) {
|
||||
const expected = retained.candidates[index];
|
||||
if (
|
||||
!expected ||
|
||||
item.index !== expected.index ||
|
||||
item.trialKey !== expected.trialKey ||
|
||||
!same(item.parameters, expected.parameters) ||
|
||||
(item.status === 'missing') !== (item.runId === null) ||
|
||||
(item.comparable && (item.status !== 'completed' || !item.metrics || !item.unavailable)) ||
|
||||
(item.runId !== null && runIds.has(item.runId))
|
||||
) {
|
||||
throw invalid();
|
||||
}
|
||||
if (item.runId) {
|
||||
runIds.add(item.runId);
|
||||
}
|
||||
}
|
||||
if (
|
||||
statuses.some(
|
||||
status =>
|
||||
parsed.counts[status] !== parsed.trials.filter(item => item.status === status).length
|
||||
)
|
||||
) {
|
||||
throw invalid();
|
||||
}
|
||||
return { ...parsed, preview: retained } as ExperimentDetailView;
|
||||
}
|
||||
async function request<T>(
|
||||
path: string,
|
||||
init: RequestInit,
|
||||
expectedStatus: number,
|
||||
parse: (body: unknown) => T
|
||||
): Promise<T> {
|
||||
let response: Response;
|
||||
try {
|
||||
response = await apiFetch(`${API_BASE_URL}/api/v2/experiments${path}`, init);
|
||||
} catch (cause) {
|
||||
if (init.signal?.aborted) {
|
||||
throw cause;
|
||||
}
|
||||
throw new ExperimentApiError(
|
||||
'The experiment response was lost. Retry the same submission to check whether it was accepted.',
|
||||
null
|
||||
);
|
||||
}
|
||||
const body: unknown = await response.json().catch(() => null);
|
||||
if (!response.ok) {
|
||||
const parsed = z.object({ error: z.string() }).safeParse(body);
|
||||
throw new ExperimentApiError(
|
||||
parsed.success ? parsed.data.error : `Experiment request failed (${response.status})`,
|
||||
response.status
|
||||
);
|
||||
}
|
||||
try {
|
||||
if (response.status !== expectedStatus) {
|
||||
throw invalid();
|
||||
}
|
||||
return parse(body);
|
||||
} catch {
|
||||
throw invalid();
|
||||
}
|
||||
}
|
||||
const envelope = (body: unknown, field: string): unknown =>
|
||||
z.record(z.unknown()).parse(body)[field];
|
||||
const json = (body: unknown): RequestInit => ({
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(body),
|
||||
});
|
||||
export const experimentApi = {
|
||||
list: (backtestId?: string, signal?: AbortSignal) =>
|
||||
request(
|
||||
backtestId ? `?backtestId=${encodeURIComponent(backtestId)}` : '',
|
||||
{ signal },
|
||||
200,
|
||||
body => {
|
||||
const rows = z.array(z.unknown()).parse(envelope(body, 'experiments')).map(parseSummary);
|
||||
if (
|
||||
new Set(rows.map(row => row.id)).size !== rows.length ||
|
||||
(backtestId && rows.some(row => row.backtestId !== backtestId))
|
||||
) {
|
||||
throw invalid();
|
||||
}
|
||||
return rows;
|
||||
}
|
||||
),
|
||||
preview: (input: ExperimentInput, signal?: AbortSignal) =>
|
||||
request('/preview', { ...json(input), signal }, 200, body => {
|
||||
const value = parsePreview(envelope(body, 'preview'));
|
||||
if (!same(value.input, input)) {
|
||||
throw invalid();
|
||||
}
|
||||
return value;
|
||||
}),
|
||||
create: (input: ExperimentSubmission, key: string) =>
|
||||
request(
|
||||
'',
|
||||
{
|
||||
...json(input),
|
||||
headers: { 'Content-Type': 'application/json', 'Idempotency-Key': key },
|
||||
},
|
||||
202,
|
||||
body => {
|
||||
const value = parseDetail(envelope(body, 'experiment'));
|
||||
const { previewHash, ...original } = input;
|
||||
if (value.previewHash !== previewHash || !same(value.preview.input, original)) {
|
||||
throw invalid();
|
||||
}
|
||||
return value;
|
||||
}
|
||||
),
|
||||
get: (id: string, signal?: AbortSignal) =>
|
||||
request(`/${encodeURIComponent(id)}`, { signal }, 200, body => {
|
||||
const value = parseDetail(envelope(body, 'experiment'));
|
||||
if (value.id !== id) {
|
||||
throw invalid();
|
||||
}
|
||||
return value;
|
||||
}),
|
||||
cancel: (id: string) =>
|
||||
request(`/${encodeURIComponent(id)}/cancel`, json({}), 200, body => {
|
||||
const value = parseDetail(envelope(body, 'experiment'));
|
||||
if (value.id !== id || !value.cancelRequested) {
|
||||
throw invalid();
|
||||
}
|
||||
return value;
|
||||
}),
|
||||
};
|
||||
|
|
@ -34,6 +34,7 @@ export const navigation: NavigationItem[] = [
|
|||
{ name: 'Analytics', href: '/analytics', icon: PresentationChartLineIcon },
|
||||
{ name: 'Backtests', href: '/backtests', icon: BeakerIcon },
|
||||
{ name: 'Research', href: '/research', icon: BeakerIcon },
|
||||
{ name: 'Experiments', href: '/experiments', icon: BeakerIcon },
|
||||
{
|
||||
name: 'System',
|
||||
icon: ServerStackIcon,
|
||||
|
|
|
|||
326
database/postgres/init/22-experiments.sql
Normal file
326
database/postgres/init/22-experiments.sql
Normal file
|
|
@ -0,0 +1,326 @@
|
|||
-- Bounded experiments reuse canonical runs and the existing durable dispatch outbox.
|
||||
CREATE TABLE IF NOT EXISTS research_experiments (
|
||||
id UUID PRIMARY KEY,
|
||||
backtest_id UUID NOT NULL REFERENCES backtests(id) ON DELETE RESTRICT,
|
||||
name TEXT NOT NULL CHECK (length(btrim(name))>0),
|
||||
preview JSONB NOT NULL,
|
||||
preview_hash TEXT NOT NULL CHECK (preview_hash ~ '^[a-f0-9]{64}$'),
|
||||
submission_principal TEXT NOT NULL CHECK (submission_principal IN ('operator','service')),
|
||||
submission_key TEXT NOT NULL CHECK (submission_key ~ '^[!-~]{1,200}$'),
|
||||
submission_hash TEXT NOT NULL CHECK (submission_hash ~ '^[a-f0-9]{64}$'),
|
||||
cancel_requested BOOLEAN NOT NULL DEFAULT FALSE,
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||
UNIQUE(submission_principal,submission_key)
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS research_experiments_parent ON research_experiments(backtest_id,created_at DESC);
|
||||
ALTER TABLE runs ADD COLUMN IF NOT EXISTS experiment_id UUID;
|
||||
ALTER TABLE runs ADD COLUMN IF NOT EXISTS trial_key TEXT;
|
||||
ALTER TABLE runs ADD COLUMN IF NOT EXISTS trial_index INTEGER;
|
||||
DO $$ BEGIN
|
||||
IF NOT EXISTS (SELECT 1 FROM pg_constraint WHERE conname='runs_experiment_fkey' AND conrelid='runs'::regclass) THEN
|
||||
ALTER TABLE runs ADD CONSTRAINT runs_experiment_fkey FOREIGN KEY(experiment_id) REFERENCES research_experiments(id) ON DELETE RESTRICT;
|
||||
END IF;
|
||||
IF NOT EXISTS (SELECT 1 FROM pg_constraint WHERE conname='runs_experiment_identity' AND conrelid='runs'::regclass) THEN
|
||||
ALTER TABLE runs ADD CONSTRAINT runs_experiment_identity CHECK (
|
||||
(experiment_id IS NULL AND trial_key IS NULL AND trial_index IS NULL)
|
||||
OR (experiment_id IS NOT NULL AND trial_key ~ '^[a-f0-9]{64}$' AND trial_index>=0
|
||||
AND trial_key IS NOT NULL AND trial_index IS NOT NULL
|
||||
AND original_run_id IS NULL AND submission_principal IS NULL AND submission_key IS NULL AND submission_hash IS NULL)
|
||||
);
|
||||
END IF;
|
||||
END $$;
|
||||
CREATE UNIQUE INDEX IF NOT EXISTS runs_experiment_trial_key ON runs(experiment_id,trial_key);
|
||||
CREATE UNIQUE INDEX IF NOT EXISTS runs_experiment_trial_index ON runs(experiment_id,trial_index);
|
||||
|
||||
CREATE OR REPLACE FUNCTION protect_experiment_evidence() RETURNS trigger LANGUAGE plpgsql AS $$ BEGIN
|
||||
IF NEW.id IS DISTINCT FROM OLD.id OR NEW.backtest_id IS DISTINCT FROM OLD.backtest_id
|
||||
OR NEW.name IS DISTINCT FROM OLD.name OR NEW.preview IS DISTINCT FROM OLD.preview
|
||||
OR NEW.preview_hash IS DISTINCT FROM OLD.preview_hash OR NEW.created_at IS DISTINCT FROM OLD.created_at
|
||||
OR NEW.submission_principal IS DISTINCT FROM OLD.submission_principal
|
||||
OR NEW.submission_key IS DISTINCT FROM OLD.submission_key OR NEW.submission_hash IS DISTINCT FROM OLD.submission_hash
|
||||
OR (OLD.cancel_requested AND NOT NEW.cancel_requested) THEN
|
||||
RAISE EXCEPTION 'Experiment evidence is immutable and cancellation is permanent' USING ERRCODE='23514';
|
||||
END IF;
|
||||
RETURN NEW;
|
||||
END $$;
|
||||
DROP TRIGGER IF EXISTS experiment_evidence_identity ON research_experiments;
|
||||
CREATE TRIGGER experiment_evidence_identity BEFORE UPDATE ON research_experiments FOR EACH ROW EXECUTE FUNCTION protect_experiment_evidence();
|
||||
DROP TRIGGER IF EXISTS experiment_retained ON research_experiments;
|
||||
CREATE TRIGGER experiment_retained BEFORE DELETE ON research_experiments FOR EACH ROW EXECUTE FUNCTION reject_research_evidence_mutation();
|
||||
DROP TRIGGER IF EXISTS experiment_no_truncate ON research_experiments;
|
||||
CREATE TRIGGER experiment_no_truncate BEFORE TRUNCATE ON research_experiments FOR EACH STATEMENT EXECUTE FUNCTION reject_research_evidence_mutation();
|
||||
|
||||
CREATE OR REPLACE FUNCTION require_experiment_manifest() RETURNS trigger LANGUAGE plpgsql AS $$
|
||||
DECLARE parent RECORD; selected RECORD; approval RECORD; retained JSONB; request JSONB; candidate JSONB; candidate_index INTEGER := 0;
|
||||
BEGIN
|
||||
SELECT * INTO parent FROM backtests WHERE id=NEW.backtest_id FOR UPDATE;
|
||||
request := NEW.preview->'request';
|
||||
IF (parent.id IS NOT NULL AND parent.archived_at IS NULL AND NOT NEW.cancel_requested
|
||||
AND jsonb_typeof(NEW.preview)='object' AND NEW.preview->>'version'='research-experiment-preview/v1'
|
||||
AND NEW.preview->>'previewHash'=NEW.preview_hash AND NEW.preview#>>'{input,name}'=NEW.name
|
||||
AND NEW.preview#>>'{input,backtestId}'=NEW.backtest_id::text
|
||||
AND jsonb_typeof(NEW.preview#>'{input,grid}')='object'
|
||||
AND jsonb_typeof(NEW.preview->'candidates')='array'
|
||||
AND jsonb_array_length(NEW.preview->'candidates') BETWEEN 1 AND 100
|
||||
AND request->>'kind'='canonical-research/v1' AND request->>'backtestId'=NEW.backtest_id::text
|
||||
AND request->>'runId'='00000000-0000-4000-8000-000000000001'
|
||||
AND request->>'name'=parent.name
|
||||
AND request#>>'{strategy,versionId}'=parent.strategy_version_id::text
|
||||
AND request#>'{strategy,selection,parameters}'=parent.strategy_parameters
|
||||
AND request->>'datasetHash'=parent.config->>'datasetHash'
|
||||
AND request#>>'{policy,matching,risk,ledger,sessionId}'=request->>'runId'
|
||||
AND request#>>'{policy,matching,risk,ledger,accountId}'='research:'||(request->>'runId')
|
||||
AND request#>>'{policy,matching,risk,ledger,baseCurrency}'='USD'
|
||||
AND request#>>'{policy,matching,risk,ledger,reserveOwnerId}'='reserve'
|
||||
AND (request#>>'{policy,matching,risk,ledger,initialCapital}')::numeric=parent.initial_capital
|
||||
AND request#>>'{strategy,selection,ownerBudget}'=parent.config#>>'{canonical,ownerBudget}'
|
||||
AND request#>'{strategy,selection,seed}'=parent.config#>'{canonical,seed}'
|
||||
AND request#>>'{policy,allow_exploratory}'='false'
|
||||
AND jsonb_typeof(request->'build')='object'
|
||||
AND request#>>'{build,version}'='1' AND request#>>'{build,runtime}'='bun'
|
||||
AND request#>>'{build,workerSha256}' ~ '^[a-f0-9]{64}$'
|
||||
AND request#>>'{build,engineWrapperSha256}' ~ '^[a-f0-9]{64}$'
|
||||
AND request#>>'{build,engineBinarySha256}' ~ '^[a-f0-9]{64}$'
|
||||
AND request#>>'{build,dependencyLockSha256}' ~ '^[a-f0-9]{64}$'
|
||||
AND length(request#>>'{build,runtimeVersion}')>0 AND length(request#>>'{build,platform}')>0 AND length(request#>>'{build,arch}')>0
|
||||
AND request->'modelArtifacts'='[]'::jsonb) IS NOT TRUE THEN
|
||||
RAISE EXCEPTION 'Experiment manifest requires an active canonical template and complete frozen identity' USING ERRCODE='23514';
|
||||
END IF;
|
||||
IF EXISTS (SELECT 1 FROM jsonb_each(parent.config->'canonical') settings
|
||||
WHERE CASE settings.key
|
||||
WHEN 'version' THEN request#>'{analyticsPolicy,version}'
|
||||
WHEN 'ownerBudget' THEN request#>'{strategy,selection,ownerBudget}'
|
||||
WHEN 'seed' THEN request#>'{strategy,selection,seed}'
|
||||
WHEN 'halfSpreadRate' THEN request#>'{policy,matching,halfSpreadRate}'
|
||||
WHEN 'slippageRate' THEN request#>'{policy,matching,slippageRate}'
|
||||
WHEN 'latencyMs' THEN request#>'{policy,matching,latencyMs}'
|
||||
WHEN 'participationRate' THEN request#>'{policy,participation_rate}'
|
||||
WHEN 'periodsPerYear' THEN request#>'{analyticsPolicy,periodsPerYear}'
|
||||
WHEN 'annualRiskFreeRate' THEN request#>'{analyticsPolicy,annualRiskFreeRate}'
|
||||
ELSE request#>ARRAY['policy','matching','risk',settings.key] END IS DISTINCT FROM settings.value) THEN
|
||||
RAISE EXCEPTION 'Experiment financial and analysis settings must match its saved template' USING ERRCODE='23514';
|
||||
END IF;
|
||||
SELECT v.*,s.archived_at AS family_archived INTO selected FROM strategy_versions v JOIN strategies s ON s.id=v.strategy_id
|
||||
WHERE v.id=parent.strategy_version_id FOR UPDATE OF s;
|
||||
SELECT id,decision INTO approval FROM strategy_review_events WHERE version_id=selected.id ORDER BY ordinal DESC LIMIT 1;
|
||||
IF (selected.origin='builtin' AND selected.family_archived IS NULL AND approval.decision='approve'
|
||||
AND request#>>'{strategy,origin}'='builtin' AND request#>>'{strategy,familyId}'=selected.strategy_id::text
|
||||
AND request#>>'{strategy,reviewId}'=approval.id::text AND request#>'{strategy,package}'=selected.envelope
|
||||
AND request#>>'{strategy,selection,ownerId}'='strategy:'||selected.id::text
|
||||
AND request#>'{policy,matching,risk,ledger,ownerIds}'=jsonb_build_array('strategy:'||selected.id::text)
|
||||
AND request#>'{policy,matching,owners}'=jsonb_build_array(jsonb_build_object('ownerId','strategy:'||selected.id::text,'mode','Target'))
|
||||
AND request#>>'{strategy,selection,strategyId}'=selected.envelope#>>'{program,strategyId}'
|
||||
AND request#>>'{strategy,selection,strategyVersion}'=selected.envelope#>>'{program,strategyVersion}') IS NOT TRUE THEN
|
||||
RAISE EXCEPTION 'Experiment requires the exact current approved built-in version' USING ERRCODE='23514';
|
||||
END IF;
|
||||
SELECT payload INTO retained FROM backtest_datasets WHERE hash=request->>'datasetHash';
|
||||
IF (retained#>>'{manifest,version}'='2' AND retained#>>'{manifest,eligibility}'='eligible'
|
||||
AND retained->'manifest'=NEW.preview->'dataset' AND retained#>>'{manifest,hash}'=request->>'datasetHash'
|
||||
AND jsonb_array_length(retained#>'{manifest,executionSeries}')=1 AND jsonb_array_length(retained#>'{manifest,series}')=1
|
||||
AND jsonb_array_length(retained#>'{manifest,universe,instrumentIds}')=1
|
||||
AND request#>>'{strategy,selection,instrumentId}'=retained#>>'{manifest,executionSeries,0,instrumentId}'
|
||||
AND request#>>'{strategy,selection,seriesId}'=retained#>>'{manifest,executionSeries,0,seriesId}'
|
||||
AND request#>'{policy,matching,series}'=jsonb_build_array(jsonb_build_object('instrumentId',request#>>'{strategy,selection,instrumentId}','seriesId',request#>>'{strategy,selection,seriesId}','mode','Open'))
|
||||
AND request#>'{policy,cadence}'=jsonb_build_array(jsonb_build_object('owner_id','strategy:'||selected.id::text,'series_ids',jsonb_build_array(request#>>'{strategy,selection,seriesId}')))) IS NOT TRUE THEN
|
||||
RAISE EXCEPTION 'Experiment requires the exact eligible retained single-asset dataset' USING ERRCODE='23514';
|
||||
END IF;
|
||||
FOR candidate IN SELECT value FROM jsonb_array_elements(NEW.preview->'candidates') LOOP
|
||||
IF (jsonb_typeof(candidate)='object' AND candidate->>'index'=candidate_index::text
|
||||
AND candidate->>'trialKey' ~ '^[a-f0-9]{64}$' AND jsonb_typeof(candidate->'parameters')='object'
|
||||
AND candidate->'parameters' <> '{}'::jsonb
|
||||
AND NOT EXISTS (SELECT 1 FROM jsonb_object_keys(candidate->'parameters') p(key)
|
||||
WHERE p.key IN ('__proto__','constructor','prototype') OR NOT selected.envelope#>'{parameterSchema,properties}' ? p.key)
|
||||
AND NOT EXISTS (SELECT 1 FROM jsonb_array_elements_text(selected.envelope#>'{parameterSchema,required}') required(key)
|
||||
WHERE NOT candidate->'parameters' ? required.key)
|
||||
AND NOT EXISTS (SELECT 1 FROM jsonb_each(candidate->'parameters') p WHERE jsonb_typeof(p.value) NOT IN ('string','number','boolean'))) IS NOT TRUE THEN
|
||||
RAISE EXCEPTION 'Experiment candidates require contiguous indexes, keys and complete scalar parameters' USING ERRCODE='23514';
|
||||
END IF;
|
||||
candidate_index := candidate_index+1;
|
||||
END LOOP;
|
||||
IF (SELECT count(DISTINCT value->>'trialKey') FROM jsonb_array_elements(NEW.preview->'candidates'))<>candidate_index
|
||||
OR (SELECT count(DISTINCT value->'parameters') FROM jsonb_array_elements(NEW.preview->'candidates'))<>candidate_index THEN
|
||||
RAISE EXCEPTION 'Experiment candidates must be unique' USING ERRCODE='23514';
|
||||
END IF;
|
||||
RETURN NEW;
|
||||
END $$;
|
||||
DROP TRIGGER IF EXISTS experiment_manifest_admission ON research_experiments;
|
||||
CREATE TRIGGER experiment_manifest_admission BEFORE INSERT ON research_experiments FOR EACH ROW EXECUTE FUNCTION require_experiment_manifest();
|
||||
|
||||
CREATE OR REPLACE FUNCTION protect_run_evidence_identity() RETURNS trigger
|
||||
LANGUAGE plpgsql AS $$ BEGIN
|
||||
IF NEW.experiment_id IS DISTINCT FROM OLD.experiment_id
|
||||
OR NEW.trial_key IS DISTINCT FROM OLD.trial_key
|
||||
OR NEW.trial_index IS DISTINCT FROM OLD.trial_index
|
||||
OR NEW.original_run_id IS DISTINCT FROM OLD.original_run_id
|
||||
OR NEW.id IS DISTINCT FROM OLD.id
|
||||
OR NEW.backtest_id IS DISTINCT FROM OLD.backtest_id
|
||||
OR NEW.run_number IS DISTINCT FROM OLD.run_number
|
||||
OR NEW.created_at IS DISTINCT FROM OLD.created_at
|
||||
OR NEW.submission_principal IS DISTINCT FROM OLD.submission_principal
|
||||
OR NEW.submission_key IS DISTINCT FROM OLD.submission_key
|
||||
OR NEW.submission_hash IS DISTINCT FROM OLD.submission_hash
|
||||
OR (OLD.request_snapshot IS NOT NULL AND NEW.request_snapshot IS DISTINCT FROM OLD.request_snapshot)
|
||||
OR (OLD.request_snapshot IS NULL AND NEW.request_snapshot IS NOT NULL AND OLD.status <> 'pending')
|
||||
OR (OLD.dataset_hash IS NOT NULL AND NEW.dataset_hash IS DISTINCT FROM OLD.dataset_hash) THEN
|
||||
RAISE EXCEPTION 'Retained run identity, submission receipt, snapshot and bound dataset are immutable'
|
||||
USING ERRCODE = '23514';
|
||||
END IF;
|
||||
-- Legacy NULL snapshots may be populated once by migration10. Workers may bind
|
||||
-- a dataset once; lease, status, progress and control updates remain mutable.
|
||||
RETURN NEW;
|
||||
END $$;
|
||||
|
||||
CREATE OR REPLACE FUNCTION require_active_backtest_for_new_run() RETURNS trigger
|
||||
LANGUAGE plpgsql AS $$
|
||||
DECLARE parent RECORD; selected RECORD; approval RECORD; retained JSONB; snapshot JSONB; original RECORD; expected JSONB; experiment RECORD; candidate JSONB;
|
||||
BEGIN
|
||||
SELECT * INTO parent FROM backtests WHERE id=NEW.backtest_id FOR UPDATE;
|
||||
IF NOT FOUND THEN RETURN NEW; END IF;
|
||||
IF parent.archived_at IS NOT NULL THEN
|
||||
RAISE EXCEPTION 'Backtest is archived; restore it before submitting a new run' USING ERRCODE='23514';
|
||||
END IF;
|
||||
snapshot := NEW.request_snapshot;
|
||||
IF NEW.experiment_id IS NOT NULL THEN
|
||||
SELECT * INTO experiment FROM research_experiments WHERE id=NEW.experiment_id FOR UPDATE;
|
||||
candidate := experiment.preview->'candidates'->NEW.trial_index;
|
||||
IF (experiment.id IS NOT NULL AND experiment.backtest_id=NEW.backtest_id AND NOT experiment.cancel_requested
|
||||
AND NEW.trial_index>=0 AND candidate->>'index'=NEW.trial_index::text
|
||||
AND candidate->>'trialKey'=NEW.trial_key
|
||||
AND NEW.original_run_id IS NULL AND NEW.submission_principal IS NULL
|
||||
AND NEW.submission_key IS NULL AND NEW.submission_hash IS NULL
|
||||
AND NEW.status='pending' AND NEW.speed_multiplier IS NULL
|
||||
AND NEW.dataset_hash=experiment.preview#>>'{request,datasetHash}') IS NOT TRUE THEN
|
||||
RAISE EXCEPTION 'Experiment trial requires its uncancelled manifest, exact candidate and no individual receipt or lineage' USING ERRCODE='23514';
|
||||
END IF;
|
||||
SELECT v.*,s.archived_at AS family_archived INTO selected FROM strategy_versions v JOIN strategies s ON s.id=v.strategy_id
|
||||
WHERE v.id::text=experiment.preview#>>'{request,strategy,versionId}' FOR UPDATE OF s;
|
||||
SELECT id,decision INTO approval FROM strategy_review_events WHERE version_id=selected.id ORDER BY ordinal DESC LIMIT 1;
|
||||
IF (selected.origin='builtin' AND selected.family_archived IS NULL AND approval.decision='approve'
|
||||
AND experiment.preview#>>'{request,strategy,reviewId}'=approval.id::text
|
||||
AND experiment.preview#>>'{request,strategy,familyId}'=selected.strategy_id::text
|
||||
AND experiment.preview#>'{request,strategy,package}'=selected.envelope) IS NOT TRUE THEN
|
||||
RAISE EXCEPTION 'Experiment requires its current approved original retained built-in version' USING ERRCODE='23514';
|
||||
END IF;
|
||||
expected := jsonb_set(experiment.preview->'request','{runId}',to_jsonb(NEW.id::text));
|
||||
expected := jsonb_set(expected,'{policy,matching,risk,ledger,sessionId}',to_jsonb(NEW.id::text));
|
||||
expected := jsonb_set(expected,'{policy,matching,risk,ledger,accountId}',to_jsonb('research:'||NEW.id::text));
|
||||
expected := jsonb_set(expected,'{strategy,selection,parameters}',candidate->'parameters');
|
||||
IF snapshot IS DISTINCT FROM expected THEN
|
||||
RAISE EXCEPTION 'Experiment trial must preserve its exact frozen request and candidate parameters' USING ERRCODE='23514';
|
||||
END IF;
|
||||
SELECT payload INTO retained FROM backtest_datasets WHERE hash=NEW.dataset_hash;
|
||||
IF (retained#>>'{manifest,version}'='2' AND retained#>>'{manifest,eligibility}'='eligible'
|
||||
AND retained->'manifest'=experiment.preview->'dataset'
|
||||
AND jsonb_array_length(retained#>'{manifest,executionSeries}')=1
|
||||
AND jsonb_array_length(retained#>'{manifest,series}')=1
|
||||
AND snapshot#>>'{strategy,selection,instrumentId}'=retained#>>'{manifest,executionSeries,0,instrumentId}'
|
||||
AND snapshot#>>'{strategy,selection,seriesId}'=retained#>>'{manifest,executionSeries,0,seriesId}') IS NOT TRUE THEN
|
||||
RAISE EXCEPTION 'Experiment requires the same eligible retained single-asset dataset' USING ERRCODE='23514';
|
||||
END IF;
|
||||
RETURN NEW;
|
||||
END IF;
|
||||
IF NEW.original_run_id IS NOT NULL THEN
|
||||
SELECT r.*,br.canonical_result INTO original FROM runs r
|
||||
LEFT JOIN backtest_results br ON br.run_id=r.id WHERE r.id=NEW.original_run_id;
|
||||
IF (original.id IS NOT NULL AND original.id<>NEW.id
|
||||
AND original.backtest_id=NEW.backtest_id AND original.status='completed'
|
||||
AND original.request_snapshot->>'kind'='canonical-research/v1'
|
||||
AND original.request_snapshot->>'runId'=original.id::text
|
||||
AND original.request_snapshot->>'backtestId'=NEW.backtest_id::text
|
||||
AND original.request_snapshot->>'datasetHash'=original.dataset_hash
|
||||
AND original.canonical_result->>'kind'='canonical-result/v1'
|
||||
AND original.canonical_result->>'status'='completed'
|
||||
AND original.canonical_result->>'runId'=original.id::text
|
||||
AND original.canonical_result->>'backtestId'=NEW.backtest_id::text
|
||||
AND original.canonical_result->'request'=original.request_snapshot
|
||||
AND original.canonical_result->>'financialEngine'='rust'
|
||||
AND original.canonical_result->>'strategyExecution'='typescript-retained-builtin/v1'
|
||||
AND NEW.dataset_hash=original.dataset_hash
|
||||
AND NEW.status='pending' AND NEW.speed_multiplier IS NULL
|
||||
AND NEW.submission_principal IN ('operator','service')
|
||||
AND NEW.submission_key ~ '^[!-~]{1,200}$'
|
||||
AND NEW.submission_hash ~ '^[a-f0-9]{64}$') IS NOT TRUE THEN
|
||||
RAISE EXCEPTION 'Reproduction requires a completed canonical source in the same backtest and a submission receipt' USING ERRCODE='23514';
|
||||
END IF;
|
||||
SELECT v.*,s.archived_at AS family_archived INTO selected FROM strategy_versions v
|
||||
JOIN strategies s ON s.id=v.strategy_id
|
||||
WHERE v.id::text=original.request_snapshot#>>'{strategy,versionId}' FOR UPDATE OF s;
|
||||
SELECT id,decision INTO approval FROM strategy_review_events
|
||||
WHERE version_id=selected.id ORDER BY ordinal DESC LIMIT 1;
|
||||
IF (selected.origin='builtin' AND selected.family_archived IS NULL
|
||||
AND approval.decision='approve'
|
||||
AND original.request_snapshot#>>'{strategy,origin}'='builtin'
|
||||
AND original.request_snapshot#>>'{strategy,familyId}'=selected.strategy_id::text
|
||||
AND original.request_snapshot#>'{strategy,package}'=selected.envelope) IS NOT TRUE THEN
|
||||
RAISE EXCEPTION 'Reproduction requires the currently approved original retained built-in version' USING ERRCODE='23514';
|
||||
END IF;
|
||||
expected := jsonb_set(original.request_snapshot, '{runId}', to_jsonb(NEW.id::text));
|
||||
expected := jsonb_set(expected, '{policy,matching,risk,ledger,sessionId}', to_jsonb(NEW.id::text));
|
||||
expected := jsonb_set(expected, '{policy,matching,risk,ledger,accountId}', to_jsonb('research:'||NEW.id::text));
|
||||
expected := jsonb_set(expected, '{strategy,reviewId}', to_jsonb(approval.id::text));
|
||||
IF snapshot IS DISTINCT FROM expected THEN
|
||||
RAISE EXCEPTION 'Reproduction must preserve the original frozen request except run identities and current approval' USING ERRCODE='23514';
|
||||
END IF;
|
||||
SELECT payload INTO retained FROM backtest_datasets WHERE hash=NEW.dataset_hash;
|
||||
IF (retained#>>'{manifest,version}'='2'
|
||||
AND retained#>>'{manifest,eligibility}'='eligible'
|
||||
AND jsonb_array_length(retained#>'{manifest,executionSeries}')=1
|
||||
AND jsonb_array_length(retained#>'{manifest,series}')=1
|
||||
AND jsonb_array_length(snapshot#>'{policy,matching,series}')=1
|
||||
AND jsonb_array_length(snapshot#>'{policy,matching,owners}')=1
|
||||
AND jsonb_array_length(snapshot#>'{policy,matching,risk,ledger,ownerIds}')=1
|
||||
AND snapshot#>>'{policy,allow_exploratory}'='false'
|
||||
AND snapshot#>>'{strategy,selection,instrumentId}'=retained#>>'{manifest,executionSeries,0,instrumentId}'
|
||||
AND snapshot#>>'{strategy,selection,seriesId}'=retained#>>'{manifest,executionSeries,0,seriesId}') IS NOT TRUE THEN
|
||||
RAISE EXCEPTION 'Reproduction requires the original eligible retained single-asset dataset' USING ERRCODE='23514';
|
||||
END IF;
|
||||
RETURN NEW;
|
||||
END IF;
|
||||
IF parent.strategy_version_id IS NULL AND parent.strategy <> 'catalog' THEN
|
||||
IF snapshot->>'kind'='canonical-research/v1' THEN
|
||||
RAISE EXCEPTION 'Canonical research requires a catalog template' USING ERRCODE='23514';
|
||||
END IF;
|
||||
RETURN NEW;
|
||||
END IF;
|
||||
IF (snapshot->>'kind'='canonical-research/v1'
|
||||
AND snapshot->>'runId'=NEW.id::text
|
||||
AND snapshot->>'backtestId'=NEW.backtest_id::text
|
||||
AND snapshot#>>'{strategy,versionId}'=parent.strategy_version_id::text
|
||||
AND snapshot->>'datasetHash'=NEW.dataset_hash
|
||||
AND NEW.status='pending' AND NEW.speed_multiplier IS NULL) IS NOT TRUE THEN
|
||||
RAISE EXCEPTION 'Catalog strategy execution requires an admitted canonical request' USING ERRCODE='23514';
|
||||
END IF;
|
||||
-- This is the same family lock used by operator review and archive. Later
|
||||
-- review changes affect new admissions, never rewrite accepted snapshots.
|
||||
SELECT v.*,s.archived_at AS family_archived INTO selected FROM strategy_versions v
|
||||
JOIN strategies s ON s.id=v.strategy_id WHERE v.id=parent.strategy_version_id FOR UPDATE OF s;
|
||||
SELECT id,decision INTO approval FROM strategy_review_events
|
||||
WHERE version_id=parent.strategy_version_id ORDER BY ordinal DESC LIMIT 1;
|
||||
IF (selected.origin='builtin' AND selected.family_archived IS NULL
|
||||
AND approval.decision='approve'
|
||||
AND snapshot#>>'{strategy,origin}'='builtin'
|
||||
AND snapshot#>>'{strategy,familyId}'=selected.strategy_id::text
|
||||
AND snapshot#>>'{strategy,reviewId}'=approval.id::text
|
||||
AND snapshot#>'{strategy,package}'=selected.envelope
|
||||
AND snapshot#>'{strategy,selection,parameters}'=parent.strategy_parameters
|
||||
AND snapshot#>>'{strategy,selection,ownerId}'='strategy:'||selected.id::text) IS NOT TRUE THEN
|
||||
RAISE EXCEPTION 'Canonical research requires the exact approved retained built-in version' USING ERRCODE='23514';
|
||||
END IF;
|
||||
SELECT payload INTO retained FROM backtest_datasets WHERE hash=NEW.dataset_hash;
|
||||
IF (retained#>>'{manifest,version}'='2'
|
||||
AND retained#>>'{manifest,eligibility}'='eligible'
|
||||
AND jsonb_array_length(retained#>'{manifest,executionSeries}')=1
|
||||
AND jsonb_array_length(retained#>'{manifest,series}')=1
|
||||
AND jsonb_array_length(snapshot#>'{policy,matching,series}')=1
|
||||
AND jsonb_array_length(snapshot#>'{policy,matching,owners}')=1
|
||||
AND jsonb_array_length(snapshot#>'{policy,matching,risk,ledger,ownerIds}')=1
|
||||
AND snapshot#>>'{policy,allow_exploratory}'='false'
|
||||
AND snapshot#>>'{strategy,selection,instrumentId}'=retained#>>'{manifest,executionSeries,0,instrumentId}'
|
||||
AND snapshot#>>'{strategy,selection,seriesId}'=retained#>>'{manifest,executionSeries,0,seriesId}'
|
||||
AND snapshot#>>'{policy,matching,series,0,instrumentId}'=snapshot#>>'{strategy,selection,instrumentId}'
|
||||
AND snapshot#>>'{policy,matching,series,0,seriesId}'=snapshot#>>'{strategy,selection,seriesId}') IS NOT TRUE THEN
|
||||
RAISE EXCEPTION 'Canonical research requires one eligible retained v2 execution asset' USING ERRCODE='23514';
|
||||
END IF;
|
||||
RETURN NEW;
|
||||
END $$;
|
||||
|
||||
|
|
@ -1,8 +1,8 @@
|
|||
# Revised development roadmap
|
||||
|
||||
Baseline `b7aeca4` · execution 2026-10-24 · **R04 committed; R12 original reproduction validated and awaiting acceptance/commit**
|
||||
Baseline `b7aeca4` · execution 2026-10-24 · **R12 committed; retained-input R06/R07 experiment components validated and uncommitted**
|
||||
|
||||
Authorization update: the owner requested “how far are we in the backlog, also commit and continue”. R04 is committed as `e3bd708`; R12 is implemented under ADR-006 using the accepted retained-input R05 component. **33/45 scheduled tasks are committed; R12 is the next validated task.** Full R05 remains partial. Performance work remains paused. New R12 commits, pushes, PRs and trading/default-engine operations remain outside this continuation's scope.
|
||||
Authorization update: the owner requested “comit and continue”. R12 is committed as `30accfc`; **34/45 scheduled tasks are committed**. R06/R07 components use the accepted retained-input R05 runner with pinned preview, atomic admission and same-experiment UI contracts. Full R05 remains partial; this slice excludes failed-trial retry, cross-experiment comparisons and all performance work. New-wave commits, pushes, PRs and trading/default-engine operations remain outside this continuation's scope.
|
||||
|
||||
## Strategy and review outcome
|
||||
|
||||
|
|
@ -583,3 +583,19 @@ R04 is accepted and committed as `e3bd708`. R12 is independently reviewed and `v
|
|||
Scope is completed retained canonical single-asset trusted built-ins on the same installed build. Hash agreement proves matching retained economic outputs, not statistical validity or profitability. Historical executable provisioning, provider-to-v2 preparation, candidate isolation and multi-asset/default cutover are not included. R05 remains partial; R06/S06 remain blocked. No performance optimization, profiling, benchmark, new-wave commit, push, PR or trading operation occurred.
|
||||
|
||||
**Recommended next wave:** an R06 retained-input experiment component, then a focused R07 sweep UI against pinned APIs. One immutable strategy version, eligible single-asset dataset, installed build and fixed policies; deterministic bounded parameter grids expand into the existing durable runs/outbox. Independent review confirms provider preparation is not required for those retained inputs. Before execution, record component prerequisites without marking full R05/R06 complete or silently releasing R06/R07/S06. Experiment admission needs its own SQL guard against the immutable manifest; do not mutate templates per trial or misuse reproduction lineage. Failed retry must preserve diagnostics and fencing; if omitted initially, leave R06 partial. No parallel worker scheduler or performance work. Root owns contracts/browser integration; one backend owner and one frontend owner can work with an independent reviewer.
|
||||
|
||||
## Twenty-seventh-wave handoff — 2026-10-24
|
||||
|
||||
R12 is accepted and committed as `30accfc`. R06/R07 retained-input components are independently reviewed and `partial_validated_uncommitted`; both full tasks remain in progress. Thirty-five implementation/test files deliver the first bounded experiment workflow through the existing APIs, durable runs and authoritative Rust engine. Backend/frontend worktrees are under `/tmp/stock-bot-wave27.iR6JOC/`; root owned shared contracts, composition, existing fixtures and browser acceptance.
|
||||
|
||||
- **Usable research flow:** start from a saved canonical backtest or Experiments, enter a named parameter grid, preview the exact retained dataset/version/window/build/policies, submit and inspect every candidate. Detail shows scalar metrics, units/null reasons, failures, missing/incomparable outcomes and exact saved-run links. Explicit refresh, cancellation and reopening are supported.
|
||||
- **One execution path:** at most 100 trials are atomically admitted with the experiment receipt and existing dispatch outbox. Only validated strategy parameters and new run/account/session identities vary. All combinations must pass retained schema and built-in cross-field validation; normalized duplicates and reserved keys reject. No template rewrite loop, second scheduler, accounting logic or runner rewrite.
|
||||
- **Reproducible admission:** the submit body commits to its preview hash, including current review/build and retained manifest. Drift rejects before persistence. Accepted receipts replay before current eligibility checks. SQL22 protects immutable experiment/trial identity, exact request reconstruction, current approval and retained inputs; ordinary/reproduction admission behavior is preserved.
|
||||
- **Truthful outcomes:** cancellation latches and stops pending trials while existing workers acknowledge active cancellation. Terminal results remain unchanged. Detail counts come from the same loaded trial rows; comparison validates complete v1 statistical conventions and compact financial identity/policy. Summaries read selected JSON fields without financial/trade/OHLC/return arrays and do not recalculate economics.
|
||||
- **Validation:** full repository check passed **696 integration and 150 Rust tests** (4 manual Rust ignored), plus 93 tooling / 43 utility / 44 calculation tests and build/source/contracts/secrets/lint. Full disposable PostgreSQL/Redis: **179 tests / 1508 assertions**. Full Chromium: **10 workflows / 258 assertions**, including actual varied-parameter native trials, rendered returns, receipt replay, post-admission template changes, standalone reproduction of an experiment trial, cancellation and reopening. The initial new browser selector included nested option text; correcting the selector resolved the test without production changes. Scoped strict types, lint, formatting and diff checks passed.
|
||||
- **Independent review:** all 14 agent-owned hashes verified. Combined experiment contract/API/UI tests independently passed 34/230; isolated PostgreSQL/native 10/132 evidence reviewed. Review corrected pre-parser reserved-key loss, normalized duplicates, count/read consistency, full provenance comparisons, cancellation fencing, owned-link draft loss and retained timeframe rendering.
|
||||
- **Recorded identity:** the manifest holds all 35 source/test hashes and archive identity. Release addon SHA256 `ef00eed556f5c32332d36a9a00ef710682e90deb00b54552e4b5c8bfdfbe8103` matches the previous wave. Both exact disposable containers were stopped; development services were untouched.
|
||||
|
||||
Full R06 remains incomplete until failed-trial retry preserves prior diagnostics and passes stale-attempt fencing tests. R07 broader comparisons/table measurement remain outstanding; all performance work stays paused. R05 provider preparation and broader cutover remain partial; R08/A01/S06 are not silently released. No candidate/multi-asset/default/paper/live/AI execution, new-wave commit, push or PR occurred. Editor retry state lives in the current page; saved experiments and accepted receipts are durable. Hash/provenance agreement does not establish strategy merit.
|
||||
|
||||
**Next after acceptance/commit: complete R06 failed-trial retry** using the same immutable logical run and existing attempts/outbox. Append prior diagnostics before clearing active errors; reject retries with stored results or completed/cancelled state, retain old-attempt fencing and add a focused UI action only after the backend contract passes. Performance remains paused.
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
# Canonical development backlog
|
||||
|
||||
**First twenty-five waves committed; R12 is validated and uncommitted.** R04 is accepted as `e3bd708`. Original-run reproduction now preserves retained inputs independently of current settings, with lineage, repeat-safe submission and economic comparison. **33 of 45 scheduled tasks are committed (73% by count); R12 adds one validated task awaiting acceptance/commit.** Broader R05 remains in progress. Performance work remains paused. See [current handoff](../ROADMAP.md#twenty-sixth-wave-handoff--2026-10-24) and manifest execution scope.
|
||||
**First twenty-six waves committed; R06/R07 retained-input experiment components are validated and uncommitted.** R12 is accepted as `30accfc`. **34 of 45 scheduled tasks are committed (76% by count).** The web workbench now previews/submits bounded grids, compares every trial outcome and reopens evidence through existing durable canonical runs. Full R05 remains partial; failed-trial retry and broader comparisons are excluded from this component. Performance work remains paused.
|
||||
|
||||
## One source of truth
|
||||
|
||||
|
|
@ -77,13 +77,13 @@ Relative size: S narrow correction, M coherent boundary, L sensitive owner-contr
|
|||
| [R03 Add projects, hypotheses and evidence-linked findings APIs](tasks/R03.md) | P1 / done | R01, R10, ADR-006 | — | Full-stack research product / M |
|
||||
| [R04 Deliver research workspace and save-findings flow](tasks/R04.md) | P1 / done | R03, W02, ADR-006 | W04 | Full-stack research product / M |
|
||||
| [R05 Freeze complete provenance and cut over durable canonical runs](tasks/R05.md) | P0 / in_progress | F08, S02, R01, R10, D01, W03, C06, ADR-006 | Multi-asset default mark-policy disposition | Full-stack research product / M |
|
||||
| [R06 Create immutable experiments and bounded sweep expansion](tasks/R06.md) | P1 / blocked | R05, ADR-006 | — | Full-stack research product / M |
|
||||
| [R07 Deliver sweep configuration and comparable-result views](tasks/R07.md) | P1 / blocked | R06, ADR-006 | W04 | Full-stack research product / M |
|
||||
| [R06 Create immutable experiments and bounded sweep expansion](tasks/R06.md) | P1 / in_progress (component) | Accepted R05 retained-input component; R01/R10/F08/S02/D01/W03/C06/R12, ADR-006 | — | Full-stack research product / M |
|
||||
| [R07 Deliver sweep configuration and comparable-result views](tasks/R07.md) | P1 / in_progress (component) | R06 component API pinned; release after integration, ADR-006 | W04 | Full-stack research product / M |
|
||||
| [R08 Add bounded chronological and reset-segment validation](tasks/R08.md) | P1 / blocked | R06, ADR-006 | — | Quantitative research integrity / M |
|
||||
| [R09 Expose validation, cost and regime evidence in the workbench](tasks/R09.md) | P1 / blocked | R07, R08, ADR-006 | S05 when Regime comparison is enabled; R03 when Saving or linking a research finding is enabled | Full-stack research product / M |
|
||||
| [R10 Protect retained research evidence and artifact integrity](tasks/R10.md) | P1 / done | R01, ADR-006 | — | Full-stack research product / M |
|
||||
| [R11 Select and reuse frozen datasets in the workbench](tasks/R11.md) | P1 / done | D01, O01, ADR-003, ADR-006 | W04 | Full-stack market data/research / M |
|
||||
| [R12 Reproduce an original run separately from rerunning current settings](tasks/R12.md) | P1 / review | Accepted R05 retained-input component; W04/R01/R10/F08/S02/D01/W03/C06, ADR-006 | — | Full-stack reproducible research / S |
|
||||
| [R12 Reproduce an original run separately from rerunning current settings](tasks/R12.md) | P1 / done | Accepted R05 retained-input component; W04/R01/R10/F08/S02/D01/W03/C06, ADR-006 | — | Full-stack reproducible research / S |
|
||||
|
||||
### E7 — Measured research throughput
|
||||
|
||||
|
|
@ -118,4 +118,4 @@ Relative size: S narrow correction, M coherent boundary, L sensitive owner-contr
|
|||
|
||||
Before any wave: unique IDs; existing task/ADR references; acyclic implementation graph; no scheduled task dependent on merged/deferred work; approvals/readiness; actual file locks; isolated native build outputs/workspace dependencies and test databases. Release gates are checked separately at activation.
|
||||
|
||||
R04 is committed; R12 awaits acceptance/commit after independent review and full repository/PostgreSQL/browser checks. R12 uses the accepted retained-input R05 component, not full R05 completion. Recommended next: an R06 retained-dataset experiment component and focused R07 UI after the planning owner records narrower prerequisites. Provider preparation is independent of sweeps over already eligible retained data. R05 broader cutover remains incomplete; R06/S06 are not unblocked. Performance and multi-asset/default/paper activation remain excluded.
|
||||
R12 is committed. R06/R07 retained-input components passed independent review and full repository/PostgreSQL/browser gates; they await acceptance/commit. See the [current handoff](../ROADMAP.md#twenty-seventh-wave-handoff--2026-10-24). Next implement R06 failed-trial retry with preserved diagnostics and attempt fencing. Full R05 remains partial, R06 failed retry remains outstanding, and R08/A01/S06 dependencies are not released by this component. Provider preparation is independent of sweeps over already eligible retained data. Performance and multi-asset/default/paper activation remain excluded.
|
||||
|
|
|
|||
|
|
@ -142,7 +142,15 @@ flowchart TD
|
|||
W03 --> R05
|
||||
C06 --> R05
|
||||
ADR006 --> R05
|
||||
R05 --> R06
|
||||
%% R06 component consumes accepted R05 retained-input slice 618fb9e; full R05 stays partial.
|
||||
R01 --> R06
|
||||
R10 --> R06
|
||||
F08 --> R06
|
||||
S02 --> R06
|
||||
D01 --> R06
|
||||
W03 --> R06
|
||||
C06 --> R06
|
||||
R12 --> R06
|
||||
ADR006 --> R06
|
||||
R06 --> R07
|
||||
ADR006 --> R07
|
||||
|
|
|
|||
|
|
@ -1,14 +1,14 @@
|
|||
{
|
||||
"schema_version": 1,
|
||||
"plan_revision": "2026-10-24.56",
|
||||
"plan_revision": "2026-10-24.58",
|
||||
"repository_base": "b7aeca4",
|
||||
"plan_status": "twenty_sixth_wave_validated_uncommitted",
|
||||
"plan_status": "twenty_seventh_wave_validated_uncommitted",
|
||||
"execution_authorized": true,
|
||||
"execution_scope": {
|
||||
"authorized_by": "User: how far are we in the backlog, also commit and continue after R04 handoff naming original reproduction; R04 committed e3bd708838ce17a4da0bc2b4d6be701b72625dd8",
|
||||
"tasks": ["R12"],
|
||||
"authorized_by": "User: comit and continue after R12 handoff recommending bounded experiments and sweep UI",
|
||||
"tasks": ["R06", "R07"],
|
||||
"permissions": [
|
||||
"Scoped same-installed-build retained canonical single-asset reproduction; independent implementation/review, fixtures and validation"
|
||||
"Retained-input single-asset experiment and sweep UI components under pinned existing ADR-006; isolated implementation/review and full validation"
|
||||
],
|
||||
"excluded": [
|
||||
"performance_profiling_or_optimization",
|
||||
|
|
@ -21,9 +21,10 @@
|
|||
"candidate_execution",
|
||||
"provider_to_v2_inference",
|
||||
"multi_asset_activation",
|
||||
"other_backlog_tasks",
|
||||
"AI_execution_or_credentials",
|
||||
"historical_binary_provisioning"
|
||||
"historical_binary_provisioning",
|
||||
"failed_run_retry",
|
||||
"cross_experiment_ranking"
|
||||
],
|
||||
"pending_policy_decisions": [
|
||||
"ADR-007",
|
||||
|
|
@ -1334,8 +1335,8 @@
|
|||
"epic": "E6",
|
||||
"priority": "P1",
|
||||
"severity": "High",
|
||||
"status": "blocked",
|
||||
"dependencies": ["R05"],
|
||||
"status": "in_progress",
|
||||
"dependencies": ["R01", "R10", "F08", "S02", "D01", "W03", "C06", "R12"],
|
||||
"decision_dependencies": ["ADR-006"],
|
||||
"task_file": "backlog/tasks/R06.md",
|
||||
"findings": ["WEB-01", "WEB-04", "KEEP-02"],
|
||||
|
|
@ -1343,12 +1344,38 @@
|
|||
"specialization": "Full-stack research product",
|
||||
"write_locks": ["sql-migrations", "experiment-api"],
|
||||
"parallel_policy": "Allowed only with satisfied dependencies/approvals and disjoint write locks AND actual files; see agents/integration.md.",
|
||||
"assignment": null,
|
||||
"assignment": "/root",
|
||||
"branch": null,
|
||||
"pull_request": null,
|
||||
"completed_commit": null,
|
||||
"blocker": null,
|
||||
"release_gates": []
|
||||
"release_gates": [],
|
||||
"integration_state": "partial_validated_uncommitted",
|
||||
"integration_base": "30accfcf4370e96e58f771dff67639ea2a278188",
|
||||
"worktree": "/home/boki/repos/stock-bot",
|
||||
"execution_component": "Retained-input atomic bounded experiments",
|
||||
"component_exclusions": ["failed retry and broader R05 cutover"],
|
||||
"satisfied_component_dependencies": [
|
||||
{
|
||||
"task": "R05",
|
||||
"scope": "Accepted retained-input single-asset durable runner only; provider preparation/default cutover not required",
|
||||
"commit": "618fb9e33cebc1fde4869eb1f975a12c55bd9b94"
|
||||
}
|
||||
],
|
||||
"reviewed_by": "/root/r04_review",
|
||||
"verification_reference": "ROADMAP.md#twenty-seventh-wave-handoff--2026-10-24",
|
||||
"review_notes": "Retained-input component independently reviewed and fully integrated. Full task stays in progress for its recorded exclusions; no downstream task is silently released.",
|
||||
"implementation_slices": [
|
||||
{
|
||||
"owner": "/root/r12_backend",
|
||||
"worktree": "/tmp/stock-bot-wave27.iR6JOC/backend",
|
||||
"scope": "Atomic experiment service/routes, SQL22 admission/retention, compact summaries and API/PostgreSQL tests"
|
||||
},
|
||||
{
|
||||
"owner": "/root",
|
||||
"scope": "Shared DTO/export, API/web composition, old migration fixtures, actual native browser workflow and planning"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": "R07",
|
||||
|
|
@ -1356,7 +1383,7 @@
|
|||
"epic": "E6",
|
||||
"priority": "P1",
|
||||
"severity": "High",
|
||||
"status": "blocked",
|
||||
"status": "in_progress",
|
||||
"dependencies": ["R06"],
|
||||
"decision_dependencies": ["ADR-006"],
|
||||
"task_file": "backlog/tasks/R07.md",
|
||||
|
|
@ -1365,12 +1392,32 @@
|
|||
"specialization": "Full-stack research product",
|
||||
"write_locks": ["web-experiments"],
|
||||
"parallel_policy": "Allowed only with satisfied dependencies/approvals and disjoint write locks AND actual files; see agents/integration.md.",
|
||||
"assignment": null,
|
||||
"assignment": "/root",
|
||||
"branch": null,
|
||||
"pull_request": null,
|
||||
"completed_commit": null,
|
||||
"blocker": null,
|
||||
"release_gates": ["W04"]
|
||||
"release_gates": ["W04"],
|
||||
"integration_state": "partial_validated_uncommitted",
|
||||
"integration_base": "30accfcf4370e96e58f771dff67639ea2a278188",
|
||||
"worktree": "/home/boki/repos/stock-bot",
|
||||
"execution_component": "Same-experiment preview/progress/comparison UI",
|
||||
"component_exclusions": ["cross-experiment comparisons and table performance measurements"],
|
||||
"component_readiness": "May implement against root-pinned shared DTO; release requires accepted integration of R06 retained-input component. Full R06 is not claimed complete.",
|
||||
"reviewed_by": "/root/r04_review",
|
||||
"verification_reference": "ROADMAP.md#twenty-seventh-wave-handoff--2026-10-24",
|
||||
"review_notes": "Retained-input component independently reviewed and fully integrated. Full task stays in progress for its recorded exclusions; no downstream task is silently released.",
|
||||
"implementation_slices": [
|
||||
{
|
||||
"owner": "/root/r12_frontend",
|
||||
"worktree": "/tmp/stock-bot-wave27.iR6JOC/frontend",
|
||||
"scope": "Experiment editor/list/detail, browser client and focused interaction tests"
|
||||
},
|
||||
{
|
||||
"owner": "/root",
|
||||
"scope": "Shared DTO/export, API/web composition, old migration fixtures, actual native browser workflow and planning"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": "R08",
|
||||
|
|
@ -1514,7 +1561,7 @@
|
|||
"epic": "E6",
|
||||
"priority": "P1",
|
||||
"severity": "High",
|
||||
"status": "review",
|
||||
"status": "done",
|
||||
"dependencies": ["W04", "R01", "R10", "F08", "S02", "D01", "W03", "C06"],
|
||||
"decision_dependencies": ["ADR-006"],
|
||||
"task_file": "backlog/tasks/R12.md",
|
||||
|
|
@ -1526,10 +1573,10 @@
|
|||
"assignment": "/root",
|
||||
"branch": null,
|
||||
"pull_request": null,
|
||||
"completed_commit": null,
|
||||
"completed_commit": "30accfcf4370e96e58f771dff67639ea2a278188",
|
||||
"blocker": null,
|
||||
"release_gates": [],
|
||||
"integration_state": "validated_uncommitted",
|
||||
"integration_state": "validated_committed",
|
||||
"integration_base": "e3bd708838ce17a4da0bc2b4d6be701b72625dd8",
|
||||
"worktree": "/home/boki/repos/stock-bot",
|
||||
"satisfied_component_dependencies": [
|
||||
|
|
@ -5422,7 +5469,7 @@
|
|||
"log": "/tmp/stock-bot-wave17.JfETUx/root-tests-typecheck-final.log"
|
||||
},
|
||||
{
|
||||
"command": "Scoped ESLint --no-ignore --max-warnings0 over all new tests/fixtures; scoped Prettier --check over all20 source/test files; git diff --check",
|
||||
"command": "Scoped ESLint --no-ignore --max-warnings 0 over all new tests/fixtures; scoped Prettier --check over all20 source/test files; git diff --check",
|
||||
"result": "passed",
|
||||
"logs": [
|
||||
"/tmp/stock-bot-wave17.JfETUx/root-test-lint.log",
|
||||
|
|
@ -5563,7 +5610,7 @@
|
|||
"log": "/tmp/stock-bot-wave18.V1G17v/root-tests-typecheck-final.log"
|
||||
},
|
||||
{
|
||||
"command": "Scoped ESLint --no-ignore --max-warnings0, Prettier --check and git diff --check; final schema-matrix test separately formatted/linted",
|
||||
"command": "Scoped ESLint --no-ignore --max-warnings 0, Prettier --check and git diff --check; final schema-matrix test separately formatted/linted",
|
||||
"result": "passed",
|
||||
"logs": [
|
||||
"/tmp/stock-bot-wave18.V1G17v/integration-lint.log",
|
||||
|
|
@ -6442,7 +6489,7 @@
|
|||
"Reproduction preserves frozen economic inputs, current original-version approval and repeat-safe receipts. No current-template dependency or historical executable manager."
|
||||
],
|
||||
"twenty_sixth_wave_validation": {
|
||||
"state": "validated_uncommitted",
|
||||
"state": "validated_committed",
|
||||
"log_directory": "/tmp/stock-bot-wave26.38tu9A",
|
||||
"integration_base": "e3bd708838ce17a4da0bc2b4d6be701b72625dd8",
|
||||
"source_archive": "/tmp/stock-bot-wave26.38tu9A/r12-integrated-source.tar",
|
||||
|
|
@ -6524,6 +6571,108 @@
|
|||
"Chromium only; existing build bundle-size/Rust warnings remain. No new-wave commit, push or PR."
|
||||
],
|
||||
"cleanup": "Both exact --rm PostgreSQL/Redis fixture containers stopped successfully. All 26 source/test hashes frozen; source archive, worktrees and logs retained. Development/production services and data untouched.",
|
||||
"next": "Recommend an R06 retained-input experiment component using one immutable strategy version, eligible single-asset dataset, installed build and bounded parameter grid; a focused R07 UI component may follow pinned APIs. Before execution, explicitly record component prerequisites rather than treating full R05/R06 as complete. Reuse durable runs/outbox with guarded experiment admission; do not mutate templates per trial or misuse reproduction lineage. Keep provider preparation, candidate isolation, multi-asset/default cutover and performance work separately gated."
|
||||
"next": "Recommend an R06 retained-input experiment component using one immutable strategy version, eligible single-asset dataset, installed build and bounded parameter grid; a focused R07 UI component may follow pinned APIs. Before execution, explicitly record component prerequisites rather than treating full R05/R06 as complete. Reuse durable runs/outbox with guarded experiment admission; do not mutate templates per trial or misuse reproduction lineage. Keep provider preparation, candidate isolation, multi-asset/default cutover and performance work separately gated.",
|
||||
"completed_commit": "30accfcf4370e96e58f771dff67639ea2a278188"
|
||||
},
|
||||
"twenty_seventh_wave": ["R06", "R07"],
|
||||
"twenty_seventh_wave_base": "30accfcf4370e96e58f771dff67639ea2a278188",
|
||||
"twenty_seventh_wave_notes": [
|
||||
"Explicit component prerequisite review: bounded retained-data grids do not require provider-to-v2 preparation. Full R05 remains partial; R06/R07 will remain partial pending exclusions.",
|
||||
"One atomic expansion reuses existing durable runs/outbox; fixed input preview commitment prevents mutable-template drift. Financial and performance policies unchanged."
|
||||
],
|
||||
"twenty_seventh_wave_validation": {
|
||||
"state": "validated_uncommitted",
|
||||
"scope": "R06/R07 retained-input components; both full tasks remain in_progress",
|
||||
"integration_base": "30accfcf4370e96e58f771dff67639ea2a278188",
|
||||
"log_directory": "/tmp/stock-bot-wave27.iR6JOC",
|
||||
"source_archive": "/tmp/stock-bot-wave27.iR6JOC/experiments-integrated-source.tar",
|
||||
"source_archive_sha256": "928b1a8ee8f50af139eda98a59b18427d1dfc91c1cd5127b32a19caec2b7e518",
|
||||
"source_file_count": 35,
|
||||
"source_sha256": {
|
||||
"apps/stock/config/package.json": "2f3990236eba9e4a628cdc2d9fadbdde298814487a88f7fab53774cf2184172b",
|
||||
"apps/stock/config/src/contracts/experiments.ts": "aa313979685cd2a65cf90128ce81cfa4c712039a9919c00c2f33d5f3f5b2cd99",
|
||||
"apps/stock/web-api/src/migrations/migration-runner.ts": "3031324068bd2758256bafb0797c2c80ea4ecdfb50ed0ab76f517a2c1ee2774c",
|
||||
"apps/stock/web-api/src/routes/create-routes.ts": "2b5addd782d0f8c5ff5ec220d40c961c94ce785c97938a5224e8f748064bee50",
|
||||
"apps/stock/web-api/src/routes/experiments.routes.ts": "65a7f4e4c8c39924c29d7928d9863e03bb6ca72663e745a4d6e358f00d76b95d",
|
||||
"apps/stock/web-api/src/services/experiment-input.ts": "406fba42b7a3e34f82a70800763be51a36da18fe0a1b682cec69a8b7a775596a",
|
||||
"apps/stock/web-api/src/services/experiments.service.ts": "c705479b5627af9f5cbd3c99e6bd071a97d98f2a743bdd840e019bb815bb1e67",
|
||||
"apps/stock/web-app/src/app/App.tsx": "c61b008451e049b9927aed9a37bf448e2c2359d6b816c0f7a191c306d2c1ba2e",
|
||||
"apps/stock/web-app/src/components/layout/Layout.tsx": "6551bb4819a8b7a7b12b6e5a5d2613ca9ff9aeb1b5ee15507dae2e844217f4bd",
|
||||
"apps/stock/web-app/src/features/backtest/BacktestDetailPageV2.tsx": "6e9975b52b99a80753a195849d16edc3c5d1cbc9a0ffcadff28c10f35749763b",
|
||||
"apps/stock/web-app/src/features/experiments/ExperimentDetailPage.tsx": "b18f9056108886e7c06c57f306337982b652266142a9bcd9bb0b2f31c65bb16d",
|
||||
"apps/stock/web-app/src/features/experiments/ExperimentListPage.tsx": "1faa4fde018e3661b20a4ba9cb4e683dbe6915168197c4b7feb98b0c84ac64be",
|
||||
"apps/stock/web-app/src/features/experiments/components/ExperimentCounts.tsx": "19215678ccb56e3453ae6787b2412e6df55c1ebfd4278afb873ca422ab79a22d",
|
||||
"apps/stock/web-app/src/features/experiments/components/ExperimentEditor.tsx": "cd38441c7387fcf19903459d7d5b4cb689741c2acbab8284c3ea9a997c1cb1a2",
|
||||
"apps/stock/web-app/src/features/experiments/components/ExperimentInputs.tsx": "fb701f90d46b185952c6e87ffaf427ae3f064fe68ea277dcb18a9b69ccfb4ab4",
|
||||
"apps/stock/web-app/src/features/experiments/index.ts": "9aa6104fc4f3eed210417423e8e3f5284b212b5ef6dbbeb6039343d3f32b4053",
|
||||
"apps/stock/web-app/src/features/experiments/services/experimentApi.ts": "88f1ab5bc884058d1a973836bec32cc5a280cbcff5c31063f1b6f3bd22d14b9d",
|
||||
"apps/stock/web-app/src/lib/constants.ts": "630a37afdb28256144cdf30ea78b3a0b0ced4ca712df55f969764e3389201777",
|
||||
"database/postgres/init/22-experiments.sql": "046e6c5e5e85e76d401c7e98eedcf51e1f64a2d3510471e97b2359a710bfb85a",
|
||||
"test/e2e/fixture.ts": "a10f996326d95e91a6980e922b03628a8dbd47dda702afc9b0bde985c977432d",
|
||||
"test/e2e/workbench.test.ts": "3afa027430295d35918deab7e4d9920dea6756401c28f82478d176f938416797",
|
||||
"test/integration/experiments-api.test.ts": "ab4b0ccd22ad93fa4f533bc9c1be88834650e5cd21a1ef0c9fbc692f67682c28",
|
||||
"test/integration/experiments-contracts.test.ts": "eec66ba6590d588fca6cd4b36f0eb683ad5c19cdc647654c50941bea45cdb34f",
|
||||
"test/integration/experiments-ui.test.tsx": "32ea7114cdd52a71e2501272ef64912c91e8da5927d571434877011f80c258e6",
|
||||
"test/postgres/canonical-durable-backtest.test.ts": "d9d4446e509d84df8e6d63c3acd16584a0e29c06d17019c078d39a77b937dcca",
|
||||
"test/postgres/canonical-research.test.ts": "f7befa2f2a0dbe4b72bd7d0262c691687c58f04a748ab69287fd969d17415e1b",
|
||||
"test/postgres/catalog-backtest-drafts.test.ts": "7ec1db246013177d912907c07ebbf99ce1b610d579b59fabfb6230aa13fa3929",
|
||||
"test/postgres/dataset-catalog.test.ts": "4bc0cb8292bb4096165eb7a28738d027f9d484c4e0763762435cc67e313c576a",
|
||||
"test/postgres/durable-backtest.test.ts": "db1a54e718bd1767bf8ffc2ac8bb0c380349668804deec8986062583381a9f46",
|
||||
"test/postgres/experiments.test.ts": "94c095f002c5edffb0f870f082bb8177a6d3ba1fb6f8615528b5cdafa8229bfe",
|
||||
"test/postgres/migration-runner.test.ts": "755f56f6f0368c28d4344c89444d956807a9ae90d26106ede04e677aebb16980",
|
||||
"test/postgres/research-retention.test.ts": "4da75d980e6c0cff6af4da2c79fd248eda9acbabd80ee84f6638de176b96aa8a",
|
||||
"test/postgres/research-runtime-isolation.test.ts": "a074ba4a12c3b6c9efa9510aa5348ca0e7e784e45db4ac6901584317fc5de644",
|
||||
"test/postgres/research-workspace.test.ts": "76095e19b4b578bf6e69d1de18cbd972240633948c04daee329fea4f9975cbf4",
|
||||
"test/postgres/run-reproduction.test.ts": "f8677363d3619091ff3e94346190d8a5641dcc75666a4051d9f4324822e6dacf"
|
||||
},
|
||||
"checks": [
|
||||
{
|
||||
"command": "CARGO_BUILD_JOBS=2 bun run check",
|
||||
"log": "/tmp/stock-bot-wave27.iR6JOC/check.log",
|
||||
"outcome": "All repository checks passed: build/source/contracts/secrets/lint; 93 tooling, 43 utility, 44 calculation, 696 integration and 150 Rust tests (4 manual Rust ignored)."
|
||||
},
|
||||
{
|
||||
"command": "PIPELINE_TEST_DATABASE_URL=<disposable PG> BACKTEST_TEST_REDIS_URL=<dedicated Redis /15> bun run test:postgres",
|
||||
"log": "/tmp/stock-bot-wave27.iR6JOC/postgres.log",
|
||||
"outcome": "179 tests / 1508 assertions passed across 20 files. Focused isolated SQL/native gate separately passed 10/132, including native candidate execution, rollback, receipt/approval/archive races, cancellation fencing, compact provenance and first migration preservation."
|
||||
},
|
||||
{
|
||||
"command": "PIPELINE_TEST_DATABASE_URL=<disposable PG> BACKTEST_TEST_REDIS_URL=<dedicated Redis /15> bun run test:e2e",
|
||||
"log": "/tmp/stock-bot-wave27.iR6JOC/e2e-final.log",
|
||||
"outcome": "10 Chromium workflows /258 assertions passed. New flow previews/submits2 real native trials, mutates template after admission, replays receipt, verifies rendered comparable returns, reproduces a trial with separate lineage, reopens experiment and cancels a separate pending batch. Initial new-test failure was an exact label selector including nested option text; corrected selector, focused 1/43 and final full 10/258 passed. Existing 9 workflows remained green."
|
||||
},
|
||||
{
|
||||
"command": "bunx tsc --project /tmp/stock-bot-wave27.iR6JOC/tests-tsconfig.json --noEmit",
|
||||
"log": "/tmp/stock-bot-wave27.iR6JOC/integrated-types-final.log",
|
||||
"outcome": "Strict new/changed tests and dependent sources passed; root web TypeScript check also passed. Initial narrow typed assertion mismatch fixed without changing the compared values."
|
||||
},
|
||||
{
|
||||
"command": "bunx eslint <new contract/tests and changed browser test> --max-warnings 0; bunx prettier --check <all changed TS/TSX/JSON>; git diff --check",
|
||||
"log": "/tmp/stock-bot-wave27.iR6JOC/integrated-test-lint.log",
|
||||
"outcome": "Scoped test lint, final source formatting and diff checks passed. Last browser formatting is whitespace only after browser verification; agent-owned hashes unchanged."
|
||||
},
|
||||
{
|
||||
"command": "CARGO_BUILD_JOBS=2 bun run --cwd apps/stock/engine build:release",
|
||||
"log": "/tmp/stock-bot-wave27.iR6JOC/native-release.log",
|
||||
"outcome": "Release addon restored before PostgreSQL/browser tests. SHA256 ef00eed556f5c32332d36a9a00ef710682e90deb00b54552e4b5c8bfdfbe8103 matches previous wave and checkout release library; no financial engine or runner changes."
|
||||
}
|
||||
],
|
||||
"reviews": [
|
||||
{
|
||||
"reviewer": "/root/r04_review",
|
||||
"scope": "Both isolated implementations, shared contract, SQL admission and migration compatibility, actual native/browser integration",
|
||||
"outcome": "Accepted all 14 agent-owned source/test hashes and final root integration delta. Independently ran combined experiment contract/API/UI 34 tests / 230 assertions, including API7/96 and UI26/127. Reviewed focused PG 10/132 evidence; root ran full suites."
|
||||
}
|
||||
],
|
||||
"limitations": [
|
||||
"Supports one current approved retained built-in version, eligible single-asset dataset and exact installed build; fixed seed/cost/risk/reporting policies. Only strategy parameters vary. Maximum 100 trials bounds one atomic admission; existing worker scheduling is unchanged.",
|
||||
"R06 remains partial: failed-trial retry and preserving historical retry diagnostics are not implemented; there is no retry-failed endpoint or UI action. R07 remains partial for broader cross-experiment comparison and paused table performance measurements.",
|
||||
"R05 provider preparation/default cutover remains incomplete. R08/A01/S06 dependencies are not released. No candidate code, multi-asset/default/paper/live activation, AI execution, historical binary provisioning, new simulator or job framework.",
|
||||
"Summary comparisons validate retained identity and reporting conventions; they do not establish profitability or out-of-sample validity. Null, failed, missing and incomparable outcomes are explicit.",
|
||||
"Ambiguous submission body/key stays in the active editor and owned-link navigation is guarded. Saved experiments are durable; unsent editor/retry state is not persisted across a deliberate unload.",
|
||||
"Chromium only; existing bundle-size/Rust warnings remain. No performance profiling/optimization/benchmark runs, new-wave commit, push or PR."
|
||||
],
|
||||
"cleanup": "Both exact --rm disposable PostgreSQL/Redis containers stopped successfully. 35 authored source/test files archived and hashed. Worktrees/logs retained; development/production services and data untouched.",
|
||||
"next": "Finish R06 failed-trial retry as a narrow durable-state change: retain prior diagnostics, keep immutable logical trial inputs, create a new fenced attempt only for failed runs without results, and reject completed/cancelled retries. Reuse existing lease/outbox machinery and expose truthful retry controls after backend integration. Keep performance paused and other release gates intact."
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -31,7 +31,7 @@ Write locks: sql-migrations, experiment-api. One agent owns this change. Lock na
|
|||
|
||||
## Dependencies and blockers
|
||||
|
||||
Implementation requires [R05](R05.md) integrated.
|
||||
The retained-input component requires the accepted R05 durable-run/provenance slice plus R01/R10/F08/S02/D01/W03/C06/R12. The manifest records that narrower prerequisite; provider preparation and broader default cutover remain outside it. Full R06 still requires the failed-retry acceptance below.
|
||||
|
||||
Architecture decisions: ADR-006. Agents may not independently amend their policies.
|
||||
|
||||
|
|
@ -66,3 +66,19 @@ Keep migrations additive and previous results readable. Do not add a switch that
|
|||
## Handoff
|
||||
|
||||
Report scope changes (if any), fixture expectations, API/schema changes, measurements, remaining limitations and commit/PR references once authorized. Request independent review; only the integration/planning owner may mark the manifest done.
|
||||
|
||||
## Authorized component — 2026-10-24
|
||||
|
||||
Retained-input single-asset experiments depend on the accepted R05 runner/provenance component (`618fb9e`), not provider preparation or default cutover. One atomic bounded grid uses a current approved retained built-in, one eligible dataset and installed build, and fixed financial/reporting policy. Preview commits to exact inputs; submission receipts survive current eligibility changes. Existing runs/outbox/worker own execution. Failed retry is excluded from this component; full R06 remains incomplete until retry diagnostics/fencing acceptance is met.
|
||||
|
||||
### Pinned experiment contract
|
||||
|
||||
`@stock-bot/stock-config/experiments` owns shared request/result DTOs. POST `/api/v2/experiments/preview` validates a saved canonical template plus bounded parameter grid; POST `/api/v2/experiments` requires its exact preview hash and an idempotency key. GET collection/detail exposes every frozen candidate and scalar result evidence; POST `/:id/cancel` is idempotent. Existing authenticated reads and credential mutations apply. Preview includes retained dataset manifest, current approved built-in package, complete financial/reporting policies and installed build. A template/review/build change before submission invalidates the preview. An accepted receipt is replayed before rechecking eligibility.
|
||||
|
||||
All children and outbox rows commit with the immutable experiment in one transaction. The initial bound is 100 trials; it bounds atomic admission and does not introduce a parallel scheduler. Only parameters and new run/account/session identities vary. `experiment_id`/`trial_key`/`trial_index` are immutable and mutually exclusive with new-run reproduction lineage. Child submission receipts are null; the experiment owns the unique principal/key receipt. SQL reconstructs exact trial requests from the manifest and preserves ordinary/reproduction admission guards. No template cloning/edit loop or separate financial engine.
|
||||
|
||||
Cancellation latches once, cancels pending children and requests worker acknowledgement for active children, preserving terminal outcomes. Counts are derived from actual children; the frozen candidate count exposes missing rows. Compact summaries validate retained provenance and statistical conventions, preserve null reasons and list inconsistent results as incomparable. No detail-array loading or financial recalculation is needed. Failed-run retry remains absent until history/fencing tests are implemented.
|
||||
|
||||
### Validated component handoff
|
||||
|
||||
The retained-input component is implemented and independently reviewed. Full repository, PostgreSQL and Chromium gates passed; exact source hashes and logs are in `manifest.json` → `twenty_seventh_wave_validation`. See the twenty-seventh-wave roadmap handoff. This component is uncommitted and does not complete the full task or release its downstream dependencies.
|
||||
|
|
|
|||
|
|
@ -28,7 +28,7 @@ Write locks: web-experiments. One agent owns this change. Lock names do not over
|
|||
|
||||
## Dependencies and blockers
|
||||
|
||||
Implementation requires [R06](R06.md) integrated.
|
||||
Component implementation may proceed against root-pinned R06 DTOs; activation requires integrated retained-input R06 admission/results. Full R06 failed-retry work is independent of this component and no retry action is exposed.
|
||||
|
||||
Architecture decisions: ADR-006. Agents may not independently amend their policies.
|
||||
|
||||
|
|
@ -64,3 +64,17 @@ Keep migrations additive and previous results readable. Do not add a switch that
|
|||
## Handoff
|
||||
|
||||
Report scope changes (if any), fixture expectations, API/schema changes, measurements, remaining limitations and commit/PR references once authorized. Request independent review; only the integration/planning owner may mark the manifest done.
|
||||
|
||||
## Authorized component — 2026-10-24
|
||||
|
||||
Implement same-experiment preview, submission, progress, cancellation, scalar comparison and exact run reopening against the pinned R06 component API. Component coding may proceed in parallel; release requires integrated R06 component. Cross-experiment comparison and table performance measurements remain outstanding, with all performance work paused. Full R07 remains incomplete.
|
||||
|
||||
### Pinned web workflow
|
||||
|
||||
`/experiments` selects a saved canonical backtest, names a sweep and previews a small parameter grid before submission. `/experiments/:experimentId` shows the frozen inputs, all trial outcomes, comparable scalar metrics with units/null reasons, cancellation state and exact saved-run links. An optional backtest query parameter starts from its detail page. The API is shared with other authorized clients; the browser does not calculate economics or rank incompatible runs.
|
||||
|
||||
Ambiguous submission preserves its exact body/key, and only an explicit new intent may replace it. Form edits invalidate previews; route changes and late reads/mutations cannot replace another experiment. Loading, empty, failed, missing and incomparable outcomes remain distinct. Refresh/reopen must retain immutable evidence and cancelled/partial outcomes. The browser acceptance executes real retained native trials, mutates the template after admission, replays the submission receipt, opens results and cancels a separate pending batch.
|
||||
|
||||
### Validated component handoff
|
||||
|
||||
The retained-input component is implemented and independently reviewed. Full repository, PostgreSQL and Chromium gates passed; exact source hashes and logs are in `manifest.json` → `twenty_seventh_wave_validation`. See the twenty-seventh-wave roadmap handoff. This component is uncommitted and does not complete the full task or release its downstream dependencies.
|
||||
|
|
|
|||
|
|
@ -293,6 +293,7 @@ export async function fixture(browser: Browser, native = false) {
|
|||
'19-canonical-research.sql',
|
||||
'20-research-workspace.sql',
|
||||
'21-run-reproduction.sql',
|
||||
'22-experiments.sql',
|
||||
]) {
|
||||
await pool.query(
|
||||
readFileSync(new URL(`../../database/postgres/init/${name}`, import.meta.url), 'utf8')
|
||||
|
|
@ -416,6 +417,7 @@ export async function fixture(browser: Browser, native = false) {
|
|||
!pathname.startsWith('/api/v2/strategies') &&
|
||||
!pathname.startsWith('/api/v2/strategy-versions') &&
|
||||
!pathname.startsWith('/api/v2/research-projects') &&
|
||||
!pathname.startsWith('/api/v2/experiments') &&
|
||||
!pathname.startsWith('/api/v2/hypotheses/') &&
|
||||
!pathname.startsWith('/api/v2/analysis-artifacts/') &&
|
||||
pathname !== '/api/auth/session') ||
|
||||
|
|
|
|||
|
|
@ -5,6 +5,7 @@ import {
|
|||
canonicalResearchSettingsSchema,
|
||||
type CanonicalRunResult,
|
||||
} from '@stock-bot/stock-config/canonical-research';
|
||||
import type { ExperimentDetail, ExperimentPreview } from '@stock-bot/stock-config/experiments';
|
||||
import { retainResearchDataset } from '../../scripts/import-research-dataset';
|
||||
import { canonicalSettings } from '../fixtures/canonical-research';
|
||||
import { canonicalSmaFixture } from '../fixtures/canonical-sma';
|
||||
|
|
@ -30,6 +31,189 @@ afterAll(async () => {
|
|||
});
|
||||
const fixture = (native = false) => createFixture(browser, native);
|
||||
|
||||
test('retained_experiment_preview_submit_compare_cancel_and_reopen_browser', async () => {
|
||||
const f = await fixture(true);
|
||||
f.page.on('dialog', dialog => void dialog.accept());
|
||||
try {
|
||||
const { dataset } = canonicalSmaFixture();
|
||||
await retainResearchDataset(f.pool, dataset);
|
||||
const selected = (await f.seedCatalog()).find(
|
||||
item => item.package.program.strategyId === 'sma_crossover'
|
||||
)!;
|
||||
await f.request(`/api/v2/strategy-versions/${selected.id}/reviews`, 'POST', {
|
||||
decision: 'approve',
|
||||
reason: 'Reviewed canonical fixture for bounded experiments',
|
||||
});
|
||||
const definition = {
|
||||
name: 'Retained sweep template',
|
||||
strategy: 'catalog',
|
||||
strategyVersionId: selected.id,
|
||||
strategyParameters: { fastPeriod: 2, slowPeriod: 3 },
|
||||
symbols: dataset.manifest.executionSeries.map(series => series.instrumentId),
|
||||
startDate: new Date(dataset.manifest.bounds.tradeStart).toISOString(),
|
||||
endDate: new Date(dataset.manifest.bounds.tradeEnd).toISOString(),
|
||||
initialCapital: 10000,
|
||||
config: {
|
||||
datasetHash: dataset.manifest.hash,
|
||||
dataFrequency: dataset.manifest.series[0]!.interval,
|
||||
canonical: canonicalSettings,
|
||||
},
|
||||
};
|
||||
const backtest = await f.request('/api/v2/backtests', 'POST', {
|
||||
...definition,
|
||||
autoStart: false,
|
||||
});
|
||||
await f.login();
|
||||
await f.page.goto(`${f.origin}/backtests/${backtest.id}`);
|
||||
await f.page.getByRole('link', { name: 'Create experiment', exact: true }).click();
|
||||
await f.page.getByLabel('Saved backtest').selectOption(backtest.id);
|
||||
await f.page.getByLabel('Experiment name', { exact: true }).fill('Retained SMA sweep');
|
||||
await f.page.getByLabel('Parameter grid (JSON)').fill('{"fastPeriod":[1,2],"slowPeriod":[3]}');
|
||||
const previewing = f.page.waitForResponse(response =>
|
||||
response.url().endsWith('/api/v2/experiments/preview')
|
||||
);
|
||||
await f.page.getByRole('button', { name: 'Preview experiment', exact: true }).click();
|
||||
const previewResponse = await previewing;
|
||||
expect(previewResponse.status()).toBe(200);
|
||||
const { preview } = (await previewResponse.json()) as { preview: ExperimentPreview };
|
||||
expect(preview.candidates).toHaveLength(2);
|
||||
expect(preview.dataset.hash).toBe(dataset.manifest.hash);
|
||||
expect(preview.dataset.bounds).toEqual(dataset.manifest.bounds);
|
||||
expect((await f.pool.query('SELECT * FROM runs')).rowCount).toBe(0);
|
||||
const submitting = f.page.waitForResponse(
|
||||
response =>
|
||||
response.request().method() === 'POST' && response.url().endsWith('/api/v2/experiments')
|
||||
);
|
||||
await f.page.getByRole('button', { name: 'Confirm experiment', exact: true }).click();
|
||||
const accepted = await submitting;
|
||||
expect(accepted.status()).toBe(202);
|
||||
const { experiment } = (await accepted.json()) as { experiment: ExperimentDetail };
|
||||
expect(accepted.headers().location).toBe(`/api/v2/experiments/${experiment.id}`);
|
||||
expect(experiment.trialCount).toBe(2);
|
||||
expect(experiment.counts.pending).toBe(2);
|
||||
expect(experiment.trials.map(trial => trial.parameters)).toEqual(
|
||||
preview.candidates.map(candidate => candidate.parameters)
|
||||
);
|
||||
await f.page.waitForURL(`${f.origin}/experiments/${experiment.id}`);
|
||||
const replay = await f.page.evaluate(
|
||||
async ({ body, key }) => {
|
||||
const response = await fetch('/api/v2/experiments', {
|
||||
method: 'POST',
|
||||
credentials: 'include',
|
||||
headers: { 'Content-Type': 'application/json', 'Idempotency-Key': key },
|
||||
body: JSON.stringify(body),
|
||||
});
|
||||
return { status: response.status, body: await response.json() };
|
||||
},
|
||||
{
|
||||
body: accepted.request().postDataJSON(),
|
||||
key: accepted.request().headers()['idempotency-key']!,
|
||||
}
|
||||
);
|
||||
expect(replay.status).toBe(202);
|
||||
expect(replay.body.experiment.id).toBe(experiment.id);
|
||||
expect((await f.pool.query('SELECT * FROM runs')).rowCount).toBe(2);
|
||||
expect((await f.pool.query('SELECT * FROM backtest_dispatch')).rowCount).toBe(2);
|
||||
// Edits after atomic admission cannot change either candidate's economics.
|
||||
await f.request(`/api/v2/backtests/${backtest.id}`, 'PUT', {
|
||||
...definition,
|
||||
name: 'Changed after sweep admission',
|
||||
initialCapital: 20000,
|
||||
strategyParameters: { fastPeriod: 1, slowPeriod: 2 },
|
||||
});
|
||||
f.dispatcher.start();
|
||||
await until(
|
||||
async () =>
|
||||
(await f.pool.query("SELECT count(*) FROM runs WHERE status='completed'")).rows[0].count ===
|
||||
'2',
|
||||
'both retained canonical experiment trials complete'
|
||||
);
|
||||
await f.page.getByRole('button', { name: 'Refresh experiment', exact: true }).click();
|
||||
await visible(f.page, /completed: 2/);
|
||||
const outcomes = f.page.getByRole('region', { name: 'Experiment trial outcomes' });
|
||||
expect(await outcomes.getByRole('cell', { name: 'Comparable', exact: true }).count()).toBe(2);
|
||||
const completed = (await f.request(`/api/v2/experiments/${experiment.id}`))
|
||||
.experiment as ExperimentDetail;
|
||||
expect(completed.counts.completed).toBe(2);
|
||||
expect(completed.trials.every(trial => trial.comparable && trial.metrics !== null)).toBe(true);
|
||||
expect(JSON.stringify(completed.trials)).not.toMatch(/"financial"|"sessionReturns"|"fills"/);
|
||||
for (const [index, trial] of completed.trials.entries()) {
|
||||
const cell = outcomes.locator('tbody tr').nth(index).locator('td').nth(3);
|
||||
expect(await cell.textContent()).toBe(String(trial.metrics!.totalReturn));
|
||||
}
|
||||
for (const trial of completed.trials) {
|
||||
const result = (await f.request(`/api/v2/runs/${trial.runId}/results`)) as CanonicalRunResult;
|
||||
expect(trial.parameters).toEqual(result.request.strategy.selection.parameters);
|
||||
expect(result.request.datasetHash).toBe(dataset.manifest.hash);
|
||||
expect(result.request.build).toEqual(preview.request.build);
|
||||
expect(String(result.request.policy.matching.risk.ledger.initialCapital)).toBe(
|
||||
'10000.00000000'
|
||||
);
|
||||
expect(trial.metrics).toEqual(result.analytics.metrics);
|
||||
expect(trial.unavailable).toEqual(result.analytics.unavailable);
|
||||
}
|
||||
const firstRunId = completed.trials[0]!.runId!;
|
||||
await f.page.locator(`a[href="/backtests/${backtest.id}/run/${firstRunId}"]`).click();
|
||||
await visible(f.page, 'Canonical research result');
|
||||
// Experiment linkage belongs to the trial; a standalone reproduction has
|
||||
// only original-run lineage and retains that trial's frozen parameters.
|
||||
await f.page.getByRole('button', { name: 'Reproduce original', exact: true }).click();
|
||||
const reproducing = f.page.waitForResponse(response =>
|
||||
response.url().endsWith(`/runs/${firstRunId}/reproduce`)
|
||||
);
|
||||
await f.page.getByRole('button', { name: 'Confirm reproduction', exact: true }).click();
|
||||
const reproducedResponse = await reproducing;
|
||||
expect(reproducedResponse.status()).toBe(202);
|
||||
const reproduced = await reproducedResponse.json();
|
||||
await f.page.waitForURL(`${f.origin}/backtests/${backtest.id}/run/${reproduced.id}`);
|
||||
await visible(f.page, 'Economic results match the original.');
|
||||
expect(
|
||||
(
|
||||
await f.pool.query('SELECT experiment_id,original_run_id FROM runs WHERE id=$1', [
|
||||
reproduced.id,
|
||||
])
|
||||
).rows[0]
|
||||
).toEqual({ experiment_id: null, original_run_id: firstRunId });
|
||||
await f.page.getByRole('link', { name: 'Experiments', exact: true }).click();
|
||||
await f.page.getByRole('link', { name: 'Retained SMA sweep', exact: true }).click();
|
||||
await f.page.reload();
|
||||
await f.page.getByRole('heading', { name: 'Retained SMA sweep', exact: true }).waitFor();
|
||||
expect((await f.request(`/api/v2/experiments/${experiment.id}`)).experiment).toEqual(completed);
|
||||
|
||||
// A second pending batch can be cancelled without touching completed evidence.
|
||||
await f.dispatcher.shutdown();
|
||||
await f.page.goto(`${f.origin}/experiments?backtestId=${backtest.id}`);
|
||||
await f.page.getByLabel('Saved backtest').selectOption(backtest.id);
|
||||
await f.page.getByLabel('Experiment name', { exact: true }).fill('Cancelled sweep');
|
||||
await f.page.getByLabel('Parameter grid (JSON)').fill('{"slowPeriod":[2,3]}');
|
||||
await f.page.getByRole('button', { name: 'Preview experiment', exact: true }).click();
|
||||
const cancellingBatch = f.page.waitForResponse(
|
||||
response =>
|
||||
response.request().method() === 'POST' && response.url().endsWith('/api/v2/experiments')
|
||||
);
|
||||
await f.page.getByRole('button', { name: 'Confirm experiment', exact: true }).click();
|
||||
const cancellationBatch = (await (await cancellingBatch).json()).experiment as ExperimentDetail;
|
||||
await f.page.waitForURL(`${f.origin}/experiments/${cancellationBatch.id}`);
|
||||
const cancelling = f.page.waitForResponse(response =>
|
||||
response.url().endsWith(`/experiments/${cancellationBatch.id}/cancel`)
|
||||
);
|
||||
await f.page.getByRole('button', { name: 'Cancel remaining trials', exact: true }).click();
|
||||
expect((await cancelling).status()).toBe(200);
|
||||
await visible(f.page, /cancelled: 2/);
|
||||
const cancelled = (await f.request(`/api/v2/experiments/${cancellationBatch.id}`))
|
||||
.experiment as ExperimentDetail;
|
||||
expect(cancelled.cancelRequested).toBe(true);
|
||||
expect(cancelled.counts.cancelled).toBe(2);
|
||||
expect(cancelled.trials.every(trial => trial.metrics === null)).toBe(true);
|
||||
expect((await f.pool.query('SELECT * FROM backtest_results')).rowCount).toBe(3);
|
||||
expect((await f.request(`/api/v2/experiments/${experiment.id}`)).experiment).toEqual(completed);
|
||||
expect(f.historicalDataReads).toEqual([]);
|
||||
expect(f.unexpectedNetwork).toEqual([]);
|
||||
} finally {
|
||||
await f.close();
|
||||
}
|
||||
});
|
||||
|
||||
// Serial by design: the production WebSocket projection has a process-local handler.
|
||||
test('browser_saved_run_lifecycle', async () => {
|
||||
const f = await fixture();
|
||||
|
|
|
|||
347
test/integration/experiments-api.test.ts
Normal file
347
test/integration/experiments-api.test.ts
Normal file
|
|
@ -0,0 +1,347 @@
|
|||
import { randomUUID } from 'node:crypto';
|
||||
import { describe, expect, mock, test } from 'bun:test';
|
||||
import { Hono } from 'hono';
|
||||
import { z } from 'zod';
|
||||
import { createHttpSecurity } from '@stock-bot/di';
|
||||
import type { IServiceContainer } from '@stock-bot/services';
|
||||
import { canonicalRunRequestSchema } from '@stock-bot/stock-config/canonical-research';
|
||||
import { builtinCatalogDescriptors } from '@stock-bot/stock-config/strategy';
|
||||
import { parseFinancialDecimal } from '@stock-bot/types';
|
||||
import { createExperimentRoutes } from '../../apps/stock/web-api/src/routes/experiments.routes';
|
||||
import {
|
||||
buildExperimentPreview,
|
||||
experimentCandidates,
|
||||
experimentHash,
|
||||
experimentTrialRequest,
|
||||
PREVIEW_RUN_ID,
|
||||
} from '../../apps/stock/web-api/src/services/experiment-input';
|
||||
import { canonicalSmaFixture } from '../fixtures/canonical-sma';
|
||||
|
||||
const tokens = {
|
||||
operator: 'experiment-admin-fixture-not-a-real-secret-1234',
|
||||
service: 'experiment-service-fixture-not-a-real-secret-1234',
|
||||
read: 'experiment-read-fixture-not-a-real-secret-1234',
|
||||
};
|
||||
const backtestId = randomUUID(),
|
||||
experimentId = randomUUID();
|
||||
const input = { backtestId, name: 'Sweep', grid: { fastPeriod: [1, 2] } };
|
||||
type Query = (sql: string, values?: unknown[]) => Promise<{ rows: Record<string, unknown>[] }>;
|
||||
function fixture(
|
||||
mode: 'enabled' | 'disabled' | 'absent' = 'enabled',
|
||||
query: Query = async () => ({ rows: [] })
|
||||
) {
|
||||
const client = { query: mock(query) };
|
||||
const database = {
|
||||
...client,
|
||||
transaction: mock(async <T>(work: (client: { query: Query }) => Promise<T>) => work(client)),
|
||||
};
|
||||
const app = new Hono();
|
||||
if (mode !== 'absent') {
|
||||
createHttpSecurity({
|
||||
adminToken: tokens.operator,
|
||||
serviceToken: tokens.service,
|
||||
readToken: tokens.read,
|
||||
environment: 'test',
|
||||
hostname: '127.0.0.1',
|
||||
disabled: mode === 'disabled',
|
||||
}).mount(app);
|
||||
}
|
||||
app.route('/', createExperimentRoutes({ postgres: database } as unknown as IServiceContainer));
|
||||
return {
|
||||
database,
|
||||
request(path = '', method = 'GET', body?: string, role?: keyof typeof tokens, key?: string) {
|
||||
return app.request(`/api/v2/experiments${path}`, {
|
||||
method,
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
...(role ? { Authorization: `Bearer ${tokens[role]}` } : {}),
|
||||
...(key === undefined ? {} : { 'Idempotency-Key': key }),
|
||||
},
|
||||
...(body === undefined ? {} : { body }),
|
||||
});
|
||||
},
|
||||
};
|
||||
}
|
||||
function retainedPreview() {
|
||||
const version = randomUUID(),
|
||||
owner = `strategy:${version}`;
|
||||
const fixture = canonicalSmaFixture([owner]);
|
||||
const descriptor = builtinCatalogDescriptors[0]!;
|
||||
const policy = structuredClone(fixture.config);
|
||||
policy.matching.risk.ledger.sessionId = PREVIEW_RUN_ID;
|
||||
policy.matching.risk.ledger.accountId = `research:${PREVIEW_RUN_ID}`;
|
||||
const request = canonicalRunRequestSchema.parse({
|
||||
kind: 'canonical-research/v1',
|
||||
runId: PREVIEW_RUN_ID,
|
||||
backtestId,
|
||||
name: 'Template',
|
||||
strategy: {
|
||||
familyId: randomUUID(),
|
||||
versionId: version,
|
||||
origin: 'builtin',
|
||||
reviewId: randomUUID(),
|
||||
package: {
|
||||
version: 1,
|
||||
program: descriptor.program,
|
||||
parameterSchema: descriptor.parameterSchema,
|
||||
artifact: {
|
||||
format: 'esm-bundle/v1',
|
||||
entryExport: descriptor.entryExport,
|
||||
content: 'fixture',
|
||||
sha256: 'a'.repeat(64),
|
||||
},
|
||||
dependencyLock: { format: 'bun-lock/v1', content: 'fixture', sha256: 'b'.repeat(64) },
|
||||
source: { revision: 'c'.repeat(40), dirty: false },
|
||||
build: { tool: 'bun', version: 'fixture', target: 'browser' },
|
||||
},
|
||||
selection: fixture.selections[0],
|
||||
},
|
||||
datasetHash: fixture.dataset.manifest.hash,
|
||||
policy,
|
||||
analyticsPolicy: { version: 1, periodsPerYear: 252, annualRiskFreeRate: 0, benchmark: null },
|
||||
build: {
|
||||
version: 1,
|
||||
workerSha256: 'a'.repeat(64),
|
||||
engineWrapperSha256: 'b'.repeat(64),
|
||||
engineBinarySha256: 'c'.repeat(64),
|
||||
dependencyLockSha256: 'd'.repeat(64),
|
||||
runtime: 'bun',
|
||||
runtimeVersion: 'fixture',
|
||||
platform: 'linux',
|
||||
arch: 'x64',
|
||||
},
|
||||
modelArtifacts: [],
|
||||
});
|
||||
return buildExperimentPreview(input, request, fixture.dataset.manifest);
|
||||
}
|
||||
|
||||
describe('experiment HTTP contract', () => {
|
||||
test('mutations require authenticated credential proof including preview/cancel and development bypass', async () => {
|
||||
for (const mode of ['enabled', 'disabled', 'absent'] as const) {
|
||||
const f = fixture(mode);
|
||||
for (const [path, body] of [
|
||||
['/preview', JSON.stringify(input)],
|
||||
['', JSON.stringify({ ...input, previewHash: 'a'.repeat(64) })],
|
||||
[`/${experimentId}/cancel`, '{}'],
|
||||
]) {
|
||||
expect((await f.request(path, 'POST', body, undefined, 'key')).status).toBe(401);
|
||||
}
|
||||
expect(f.database.query.mock.calls).toHaveLength(0);
|
||||
expect(f.database.transaction.mock.calls).toHaveLength(0);
|
||||
}
|
||||
});
|
||||
test('read role lists and inspects but cannot mutate; anonymous reads reject', async () => {
|
||||
const f = fixture();
|
||||
expect((await f.request()).status).toBe(401);
|
||||
expect((await f.request('', 'GET', undefined, 'read')).status).toBe(200);
|
||||
expect((await f.request(`/${experimentId}`, 'GET', undefined, 'read')).status).toBe(404);
|
||||
for (const path of ['/preview', '', `/${experimentId}/cancel`]) {
|
||||
expect((await f.request(path, 'POST', '{}', 'read', 'key')).status).toBe(403);
|
||||
}
|
||||
});
|
||||
test('strict bodies, malformed IDs, raw reserved parameters and receipt keys reject before storage', async () => {
|
||||
const submission = { ...input, previewHash: 'a'.repeat(64) };
|
||||
for (const [path, body, key] of [
|
||||
['/preview', '{', 'key'],
|
||||
['/preview', '[]', 'key'],
|
||||
['/preview', JSON.stringify({ ...input, feeRate: '0' }), 'key'],
|
||||
['/preview', `{"backtestId":"${backtestId}","name":"bad","grid":{"__proto__":[1]}}`, 'key'],
|
||||
['', JSON.stringify(submission), undefined],
|
||||
['', JSON.stringify(submission), 'contains space'],
|
||||
['', JSON.stringify(submission), 'x'.repeat(201)],
|
||||
['', JSON.stringify({ ...submission, previewHash: 'bad' }), 'key'],
|
||||
[`/${experimentId}/cancel`, '{"restart":true}', 'key'],
|
||||
['/bad/cancel', '{}', 'key'],
|
||||
]) {
|
||||
const f = fixture();
|
||||
expect((await f.request(path, 'POST', body, 'operator', key)).status).toBe(400);
|
||||
expect(f.database.query.mock.calls).toHaveLength(0);
|
||||
expect(f.database.transaction.mock.calls).toHaveLength(0);
|
||||
}
|
||||
const f = fixture();
|
||||
expect((await f.request('/bad', 'GET', undefined, 'read')).status).toBe(400);
|
||||
expect((await f.request('?backtestId=bad', 'GET', undefined, 'read')).status).toBe(400);
|
||||
});
|
||||
test('accepted experiment receipts replay with202/Location and compact missing children before template eligibility', async () => {
|
||||
const preview = retainedPreview(),
|
||||
submission = { ...input, previewHash: preview.previewHash },
|
||||
key = 'accepted';
|
||||
const hash = experimentHash({ version: 1, operation: 'create-experiment', submission });
|
||||
for (const principal of ['operator', 'service'] as const) {
|
||||
const f = fixture('enabled', async (sql, values) => {
|
||||
if (sql.includes('submission_principal=$1')) {
|
||||
expect(values).toEqual([principal, key]);
|
||||
return { rows: [{ id: experimentId, submission_hash: hash }] };
|
||||
}
|
||||
if (sql.includes('SELECT r.id')) {
|
||||
return { rows: [] };
|
||||
}
|
||||
expect(sql).not.toContain('FROM backtests');
|
||||
return {
|
||||
rows: [
|
||||
{
|
||||
id: experimentId,
|
||||
backtest_id: backtestId,
|
||||
name: input.name,
|
||||
created_at: '2026-10-24T00:00:00Z',
|
||||
cancel_requested: true,
|
||||
trial_count: 2,
|
||||
dataset_hash: preview.request.datasetHash,
|
||||
strategy_version_id: preview.request.strategy.versionId,
|
||||
preview_hash: preview.previewHash,
|
||||
counts: { completed: 2 },
|
||||
preview,
|
||||
},
|
||||
],
|
||||
};
|
||||
});
|
||||
const response = await f.request('', 'POST', JSON.stringify(submission), principal, key);
|
||||
expect(response.status).toBe(202);
|
||||
expect(response.headers.get('Location')).toBe(`/api/v2/experiments/${experimentId}`);
|
||||
expect(response.headers.get('Cache-Control')).toBe('no-store');
|
||||
const value = await response.json();
|
||||
expect(value.experiment).toMatchObject({
|
||||
id: experimentId,
|
||||
cancelRequested: true,
|
||||
trialCount: 2,
|
||||
counts: { completed: 0 },
|
||||
});
|
||||
expect(value.experiment.trials.map((t: { status: string }) => t.status)).toEqual([
|
||||
'missing',
|
||||
'missing',
|
||||
]);
|
||||
}
|
||||
});
|
||||
test('receipt conflicts and unavailable templates are409, missing is404, unexpected storage/schema errors remain sanitized500', async () => {
|
||||
const conflict = fixture('enabled', async () => ({
|
||||
rows: [{ id: experimentId, submission_hash: 'other' }],
|
||||
}));
|
||||
expect(
|
||||
(
|
||||
await conflict.request(
|
||||
'',
|
||||
'POST',
|
||||
JSON.stringify({ ...input, previewHash: 'a'.repeat(64) }),
|
||||
'operator',
|
||||
'key'
|
||||
)
|
||||
).status
|
||||
).toBe(409);
|
||||
const archived = fixture('enabled', async () => ({
|
||||
rows: [{ id: backtestId, archived_at: '2026-10-24T00:00:00Z' }],
|
||||
}));
|
||||
expect(
|
||||
(await archived.request('/preview', 'POST', JSON.stringify(input), 'operator')).status
|
||||
).toBe(409);
|
||||
const missing = fixture();
|
||||
expect(
|
||||
(await missing.request('/preview', 'POST', JSON.stringify(input), 'operator')).status
|
||||
).toBe(404);
|
||||
expect(
|
||||
(await missing.request(`/${experimentId}/cancel`, 'POST', '{}', 'operator')).status
|
||||
).toBe(404);
|
||||
for (const error of [new Error('private database detail'), new z.ZodError([])]) {
|
||||
const f = fixture('enabled', async () => {
|
||||
throw error;
|
||||
});
|
||||
for (const [path, method, body, key] of [
|
||||
['', 'GET', undefined, undefined],
|
||||
[`/${experimentId}`, 'GET', undefined, undefined],
|
||||
['/preview', 'POST', JSON.stringify(input), undefined],
|
||||
['', 'POST', JSON.stringify({ ...input, previewHash: 'a'.repeat(64) }), 'key'],
|
||||
[`/${experimentId}/cancel`, 'POST', '{}', undefined],
|
||||
]) {
|
||||
const response = await f.request(path, method, body, 'operator', key);
|
||||
expect(response.status).toBe(500);
|
||||
expect(await response.text()).not.toContain('private');
|
||||
}
|
||||
}
|
||||
});
|
||||
test('detail counts use child rows when statuses change after the earlier metadata query', async () => {
|
||||
const preview = retainedPreview();
|
||||
const f = fixture('enabled', async sql => {
|
||||
if (sql.includes('SELECT r.id')) {
|
||||
return {
|
||||
rows: preview.candidates.map((candidate, index) => {
|
||||
const id = randomUUID();
|
||||
return {
|
||||
id,
|
||||
backtest_id: backtestId,
|
||||
trial_index: index,
|
||||
trial_key: candidate.trialKey,
|
||||
status: index === 0 ? 'completed' : 'failed',
|
||||
progress: index === 0 ? 100 : 50,
|
||||
cancel_requested: false,
|
||||
error: index === 1 ? 'failure' : null,
|
||||
dataset_hash: preview.request.datasetHash,
|
||||
request_snapshot: experimentTrialRequest(preview, candidate, id),
|
||||
};
|
||||
}),
|
||||
};
|
||||
}
|
||||
return {
|
||||
rows: [
|
||||
{
|
||||
id: experimentId,
|
||||
backtest_id: backtestId,
|
||||
name: input.name,
|
||||
created_at: '2026-10-24T00:00:00Z',
|
||||
cancel_requested: false,
|
||||
trial_count: 2,
|
||||
dataset_hash: preview.request.datasetHash,
|
||||
strategy_version_id: preview.request.strategy.versionId,
|
||||
preview_hash: preview.previewHash,
|
||||
counts: { pending: 2 },
|
||||
preview,
|
||||
},
|
||||
],
|
||||
};
|
||||
});
|
||||
const response = await f.request(`/${experimentId}`, 'GET', undefined, 'read');
|
||||
expect(response.status).toBe(200);
|
||||
const { experiment } = await response.json();
|
||||
expect(experiment.counts).toEqual({
|
||||
pending: 0,
|
||||
running: 0,
|
||||
paused: 0,
|
||||
completed: 1,
|
||||
failed: 1,
|
||||
cancelled: 0,
|
||||
});
|
||||
expect(experiment.trials.map((trial: { status: string }) => trial.status)).toEqual([
|
||||
'completed',
|
||||
'failed',
|
||||
]);
|
||||
expect(experiment.trials.every((trial: { comparable: boolean }) => !trial.comparable)).toBe(
|
||||
true
|
||||
);
|
||||
});
|
||||
test('normalized duplicate parameter sets cannot create duplicate trial identity', () => {
|
||||
const preview = retainedPreview();
|
||||
const descriptor = builtinCatalogDescriptors[1]!;
|
||||
const request = structuredClone(preview.request);
|
||||
request.strategy.package.program = descriptor.program;
|
||||
request.strategy.package.parameterSchema = descriptor.parameterSchema;
|
||||
request.strategy.selection = {
|
||||
...request.strategy.selection,
|
||||
strategyId: 'mean_reversion',
|
||||
strategyVersion: 'mean-reversion-regime-long-only/v1',
|
||||
parameters: {
|
||||
lookbackPeriod: 2,
|
||||
trendPeriod: 3,
|
||||
momentumPeriod: 1,
|
||||
volatilityPeriod: 2,
|
||||
entryZScore: 1,
|
||||
exitZScore: 0.1,
|
||||
minTrendReturn: -0.5,
|
||||
minMomentumReturn: -0.5,
|
||||
maxVolatility: 1,
|
||||
minNotionalVolume: parseFinancialDecimal('0'),
|
||||
regimeFilter: 'none',
|
||||
},
|
||||
};
|
||||
expect(() =>
|
||||
experimentCandidates({ ...input, grid: { minNotionalVolume: ['1', '1.0'] } }, request)
|
||||
).toThrow('Duplicate normalized');
|
||||
});
|
||||
});
|
||||
24
test/integration/experiments-contracts.test.ts
Normal file
24
test/integration/experiments-contracts.test.ts
Normal file
|
|
@ -0,0 +1,24 @@
|
|||
import { expect, test } from 'bun:test';
|
||||
import {
|
||||
experimentInputSchema,
|
||||
experimentSubmissionSchema,
|
||||
} from '@stock-bot/stock-config/experiments';
|
||||
|
||||
test('reserved raw grid keys cannot silently become a baseline experiment', () => {
|
||||
for (const key of ['__proto__', 'constructor', 'prototype']) {
|
||||
const input = JSON.parse(
|
||||
`{"backtestId":"00000000-0000-4000-8000-000000000001","name":"Sweep","grid":{"${key}":[1]}}`
|
||||
);
|
||||
expect(experimentInputSchema.safeParse(input).success).toBe(false);
|
||||
expect(
|
||||
experimentSubmissionSchema.safeParse({ ...input, previewHash: 'a'.repeat(64) }).success
|
||||
).toBe(false);
|
||||
}
|
||||
expect(
|
||||
experimentInputSchema.parse({
|
||||
backtestId: '00000000-0000-4000-8000-000000000001',
|
||||
name: 'Baseline',
|
||||
grid: {},
|
||||
}).grid
|
||||
).toEqual({});
|
||||
});
|
||||
732
test/integration/experiments-ui.test.tsx
Normal file
732
test/integration/experiments-ui.test.tsx
Normal file
|
|
@ -0,0 +1,732 @@
|
|||
import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, test } from 'bun:test';
|
||||
import { GlobalWindow } from 'happy-dom';
|
||||
import { act, createElement, type ReactElement } from 'react';
|
||||
import type { Root } from 'react-dom/client';
|
||||
import { canonicalRunRequestSchema } from '@stock-bot/stock-config/canonical-research';
|
||||
import type {
|
||||
ExperimentDetail,
|
||||
ExperimentPreview,
|
||||
ExperimentTrial,
|
||||
} from '@stock-bot/stock-config/experiments';
|
||||
import { builtinCatalogDescriptors } from '@stock-bot/stock-config/strategy';
|
||||
import type { Backtest } from '../../apps/stock/web-app/src/features/backtest/services/backtestApiV2';
|
||||
import { nativeReplayFixture } from '../fixtures/native-replay';
|
||||
|
||||
const browser = new GlobalWindow({ url: 'http://localhost:5173' });
|
||||
const keys = ['window', 'document', 'Event', 'ResizeObserver', 'IS_REACT_ACT_ENVIRONMENT'] as const;
|
||||
const originals = new Map(keys.map(key => [key, Object.getOwnPropertyDescriptor(globalThis, key)]));
|
||||
let createRoot: typeof import('react-dom/client').createRoot;
|
||||
let router: typeof import('react-router-dom');
|
||||
let ExperimentListPage: typeof import('../../apps/stock/web-app/src/features/experiments').ExperimentListPage;
|
||||
let ExperimentDetailPage: typeof import('../../apps/stock/web-app/src/features/experiments').ExperimentDetailPage;
|
||||
let root: Root | undefined;
|
||||
let host: HTMLDivElement;
|
||||
let navigate: ReturnType<typeof router.useNavigate>;
|
||||
let location = '';
|
||||
const backtestId = '11111111-1111-4111-8111-111111111111';
|
||||
const otherBacktestId = '22222222-2222-4222-8222-222222222222';
|
||||
const experimentId = '33333333-3333-4333-8333-333333333333';
|
||||
const otherExperimentId = '44444444-4444-4444-8444-444444444444';
|
||||
const versionId = '55555555-5555-4555-8555-555555555555';
|
||||
const runId = (index: number) => `77777777-7777-4777-8777-${String(index + 1).padStart(12, '0')}`;
|
||||
function deferred<T>() {
|
||||
let resolve!: (value: T) => void;
|
||||
let reject!: (cause: Error) => void;
|
||||
const promise = new Promise<T>((yes, no) => {
|
||||
resolve = yes;
|
||||
reject = no;
|
||||
});
|
||||
return { promise, resolve, reject };
|
||||
}
|
||||
type Pending = ReturnType<typeof deferred<Response>> & {
|
||||
path: string;
|
||||
method: string;
|
||||
body: unknown;
|
||||
rawBody: unknown;
|
||||
headers: Headers;
|
||||
settled: boolean;
|
||||
signal?: AbortSignal | null;
|
||||
credentials?: RequestCredentials;
|
||||
};
|
||||
const requests: Pending[] = [];
|
||||
function request(path: string, method = 'GET') {
|
||||
const found = requests.find(
|
||||
item => item.path === path && item.method === method && !item.settled
|
||||
);
|
||||
if (!found) {
|
||||
throw new Error(
|
||||
`Missing ${method} ${path}: ${requests.map(item => `${item.method} ${item.path} ${item.settled}`).join(', ')}`
|
||||
);
|
||||
}
|
||||
return found;
|
||||
}
|
||||
function reply(item: Pending, value: unknown, status = 200) {
|
||||
item.settled = true;
|
||||
item.resolve(Response.json(value, { status }));
|
||||
}
|
||||
async function flush(action: () => void = () => {}) {
|
||||
await act(async () => {
|
||||
action();
|
||||
await Promise.resolve();
|
||||
});
|
||||
}
|
||||
function button(label: string) {
|
||||
const found = [...host.querySelectorAll('button')].find(
|
||||
item => item.textContent?.trim() === label
|
||||
);
|
||||
if (!found) {
|
||||
throw new Error(`Missing button ${label}: ${host.textContent}`);
|
||||
}
|
||||
return found;
|
||||
}
|
||||
function field(label: string) {
|
||||
const found = [...host.querySelectorAll('label')]
|
||||
.find(item => item.firstChild?.textContent?.trim() === label)
|
||||
?.querySelector('input,select,textarea');
|
||||
if (!found) {
|
||||
throw new Error(`Missing field ${label}`);
|
||||
}
|
||||
return found as HTMLInputElement | HTMLSelectElement | HTMLTextAreaElement;
|
||||
}
|
||||
function change(label: string, value: string) {
|
||||
const input = field(label);
|
||||
const prototype =
|
||||
input.tagName === 'SELECT'
|
||||
? browser.HTMLSelectElement.prototype
|
||||
: input.tagName === 'TEXTAREA'
|
||||
? browser.HTMLTextAreaElement.prototype
|
||||
: browser.HTMLInputElement.prototype;
|
||||
Object.getOwnPropertyDescriptor(prototype, 'value')!.set!.call(input, value);
|
||||
input.dispatchEvent(
|
||||
new browser.Event(input.tagName === 'SELECT' ? 'change' : 'input', {
|
||||
bubbles: true,
|
||||
}) as unknown as Event
|
||||
);
|
||||
}
|
||||
function Probe() {
|
||||
navigate = router.useNavigate();
|
||||
location = router.useLocation().pathname + router.useLocation().search;
|
||||
return null;
|
||||
}
|
||||
async function render(element: ReactElement, path: string) {
|
||||
root ??= createRoot(host);
|
||||
await flush(() =>
|
||||
root!.render(
|
||||
createElement(router.MemoryRouter, { initialEntries: [path] }, element, createElement(Probe))
|
||||
)
|
||||
);
|
||||
}
|
||||
const template = (id = backtestId): Backtest => ({
|
||||
id,
|
||||
name: 'Saved canonical template',
|
||||
strategy: 'sma',
|
||||
strategyVersionId: versionId,
|
||||
symbols: ['X0.US'],
|
||||
startDate: '2024-01-01',
|
||||
endDate: '2024-01-02',
|
||||
initialCapital: 100,
|
||||
config: { canonical: {}, datasetHash: 'a'.repeat(64) },
|
||||
archivedAt: null,
|
||||
createdAt: '2026-10-24',
|
||||
updatedAt: '2026-10-24',
|
||||
});
|
||||
function preview(count = 2, parent = backtestId): ExperimentPreview {
|
||||
const owner = `strategy:${versionId}`;
|
||||
const { config, dataset } = nativeReplayFixture(3, 1, [owner]);
|
||||
const previewId = '00000000-0000-4000-8000-000000000001';
|
||||
config.matching.risk.ledger.sessionId = previewId;
|
||||
config.matching.risk.ledger.accountId = `research:${previewId}`;
|
||||
const builtin = builtinCatalogDescriptors[0]!;
|
||||
const candidates = Array.from({ length: count }, (_, index) => ({
|
||||
index,
|
||||
trialKey: String(index + 1).padStart(64, '0'),
|
||||
parameters: { fastPeriod: index + 2, slowPeriod: 20 },
|
||||
}));
|
||||
return {
|
||||
version: 'research-experiment-preview/v1',
|
||||
previewHash: 'e'.repeat(64),
|
||||
input: {
|
||||
backtestId: parent,
|
||||
name: 'Trend study',
|
||||
grid: { fastPeriod: candidates.map(item => item.parameters.fastPeriod) },
|
||||
},
|
||||
dataset: dataset.manifest,
|
||||
candidates,
|
||||
request: canonicalRunRequestSchema.parse({
|
||||
kind: 'canonical-research/v1',
|
||||
runId: previewId,
|
||||
backtestId: parent,
|
||||
name: 'Frozen template name',
|
||||
strategy: {
|
||||
familyId: '66666666-6666-4666-8666-666666666666',
|
||||
versionId,
|
||||
origin: 'builtin',
|
||||
reviewId: '88888888-8888-4888-8888-888888888888',
|
||||
package: {
|
||||
version: 1,
|
||||
program: builtin.program,
|
||||
parameterSchema: builtin.parameterSchema,
|
||||
artifact: {
|
||||
format: 'esm-bundle/v1',
|
||||
entryExport: builtin.entryExport,
|
||||
content: 'Never execute fixture code',
|
||||
sha256: 'a'.repeat(64),
|
||||
},
|
||||
dependencyLock: {
|
||||
format: 'bun-lock/v1',
|
||||
content: 'Retained lock',
|
||||
sha256: 'b'.repeat(64),
|
||||
},
|
||||
source: { revision: 'c'.repeat(40), dirty: false },
|
||||
build: { tool: 'bun', version: '1.2.17', target: 'browser' },
|
||||
},
|
||||
selection: {
|
||||
strategyId: builtin.program.strategyId,
|
||||
strategyVersion: builtin.program.strategyVersion,
|
||||
ownerId: owner,
|
||||
seed: 17,
|
||||
instrumentId: 'X0.US',
|
||||
seriesId: 'X0.US:1m',
|
||||
ownerBudget: '100',
|
||||
parameters: { fastPeriod: 2, slowPeriod: 20 },
|
||||
},
|
||||
},
|
||||
datasetHash: dataset.manifest.hash,
|
||||
policy: config,
|
||||
analyticsPolicy: { version: 1, periodsPerYear: 252, annualRiskFreeRate: 0, benchmark: null },
|
||||
build: {
|
||||
version: 1,
|
||||
workerSha256: 'a'.repeat(64),
|
||||
engineWrapperSha256: 'b'.repeat(64),
|
||||
engineBinarySha256: 'c'.repeat(64),
|
||||
dependencyLockSha256: 'd'.repeat(64),
|
||||
runtime: 'bun',
|
||||
runtimeVersion: '1.2.17',
|
||||
platform: 'linux',
|
||||
arch: 'x64',
|
||||
},
|
||||
modelArtifacts: [],
|
||||
}),
|
||||
};
|
||||
}
|
||||
function metrics(): NonNullable<ExperimentTrial['metrics']> {
|
||||
return {
|
||||
totalReturn: 0,
|
||||
cagr: null,
|
||||
maxDrawdown: 0,
|
||||
exposureTime: 0,
|
||||
volatility: null,
|
||||
downsideDeviation: null,
|
||||
sharpeRatio: null,
|
||||
sortinoRatio: null,
|
||||
var95: null,
|
||||
cvar95: null,
|
||||
var99: null,
|
||||
alpha: null,
|
||||
beta: null,
|
||||
informationRatio: null,
|
||||
roundTripCount: null,
|
||||
winRate: null,
|
||||
profitFactor: null,
|
||||
avgWin: null,
|
||||
avgLoss: null,
|
||||
};
|
||||
}
|
||||
function detail(
|
||||
source = preview(),
|
||||
statuses: ExperimentTrial['status'][] = source.candidates.map(() => 'pending')
|
||||
): ExperimentDetail {
|
||||
const trials: ExperimentTrial[] = source.candidates.map((item, index) => ({
|
||||
...item,
|
||||
runId: statuses[index] === 'missing' ? null : runId(index),
|
||||
status: statuses[index]!,
|
||||
progress: statuses[index] === 'completed' ? 100 : 0,
|
||||
cancelRequested: false,
|
||||
error: statuses[index] === 'failed' ? 'Strategy callback failed' : null,
|
||||
comparable: statuses[index] === 'completed',
|
||||
diagnostic: statuses[index] === 'missing' ? 'Expected child run is missing' : null,
|
||||
metrics: statuses[index] === 'completed' ? metrics() : null,
|
||||
unavailable: statuses[index] === 'completed' ? { sharpeRatio: 'insufficient-periods' } : null,
|
||||
limitations: [],
|
||||
}));
|
||||
return {
|
||||
id: experimentId,
|
||||
name: source.input.name,
|
||||
backtestId: source.input.backtestId,
|
||||
createdAt: '2026-10-24T14:00:00Z',
|
||||
cancelRequested: false,
|
||||
trialCount: trials.length,
|
||||
counts: {
|
||||
pending: 0,
|
||||
running: 0,
|
||||
paused: 0,
|
||||
completed: 0,
|
||||
failed: 0,
|
||||
cancelled: 0,
|
||||
...Object.fromEntries(
|
||||
['pending', 'running', 'paused', 'completed', 'failed', 'cancelled'].map(status => [
|
||||
status,
|
||||
trials.filter(item => item.status === status).length,
|
||||
])
|
||||
),
|
||||
},
|
||||
datasetHash: source.request.datasetHash,
|
||||
strategyVersionId: versionId,
|
||||
previewHash: source.previewHash,
|
||||
preview: source,
|
||||
trials,
|
||||
};
|
||||
}
|
||||
async function list(parent = backtestId) {
|
||||
await render(createElement(ExperimentListPage), `/experiments?backtestId=${parent}`);
|
||||
await flush(() => {
|
||||
reply(request('/api/v2/backtests?limit=50&offset=0'), [template(parent)]);
|
||||
reply(request(`/api/v2/experiments?backtestId=${parent}`), { experiments: [] });
|
||||
});
|
||||
}
|
||||
async function ready(value = preview()) {
|
||||
await list(value.input.backtestId);
|
||||
await flush(() => {
|
||||
change('Experiment name', value.input.name);
|
||||
change('Parameter grid (JSON)', JSON.stringify(value.input.grid));
|
||||
});
|
||||
await flush(() => button('Preview experiment').click());
|
||||
await flush(() => reply(request('/api/v2/experiments/preview', 'POST'), { preview: value }));
|
||||
return value;
|
||||
}
|
||||
async function showDetail(value?: ExperimentDetail) {
|
||||
const routes = createElement(
|
||||
router.Routes,
|
||||
null,
|
||||
createElement(router.Route, {
|
||||
path: '/experiments/:experimentId',
|
||||
element: createElement(ExperimentDetailPage),
|
||||
})
|
||||
);
|
||||
await render(routes, `/experiments/${value?.id ?? experimentId}`);
|
||||
if (value) {
|
||||
await flush(() => reply(request(`/api/v2/experiments/${value.id}`), { experiment: value }));
|
||||
}
|
||||
}
|
||||
beforeAll(async () => {
|
||||
for (const [key, value] of Object.entries({
|
||||
window: browser,
|
||||
document: browser.document,
|
||||
Event: browser.Event,
|
||||
ResizeObserver: browser.ResizeObserver,
|
||||
IS_REACT_ACT_ENVIRONMENT: true,
|
||||
})) {
|
||||
Object.defineProperty(globalThis, key, { configurable: true, writable: true, value });
|
||||
}
|
||||
({ createRoot } = await import('react-dom/client'));
|
||||
router = await import('react-router-dom');
|
||||
({ ExperimentListPage, ExperimentDetailPage } = await import(
|
||||
'../../apps/stock/web-app/src/features/experiments'
|
||||
));
|
||||
});
|
||||
beforeEach(() => {
|
||||
requests.length = 0;
|
||||
location = '';
|
||||
host = browser.document.createElement('div') as unknown as HTMLDivElement;
|
||||
browser.document.body.append(host as never);
|
||||
Object.defineProperty(browser, 'confirm', { configurable: true, value: () => true });
|
||||
Object.defineProperty(browser, 'fetch', {
|
||||
configurable: true,
|
||||
value: (input: unknown, init?: RequestInit) => {
|
||||
const url = new URL(String(input));
|
||||
const item: Pending = {
|
||||
...deferred<Response>(),
|
||||
path: url.pathname + url.search,
|
||||
method: init?.method ?? 'GET',
|
||||
rawBody: init?.body,
|
||||
body: typeof init?.body === 'string' ? JSON.parse(init.body) : undefined,
|
||||
headers: new Headers(init?.headers),
|
||||
signal: init?.signal,
|
||||
credentials: init?.credentials,
|
||||
settled: false,
|
||||
};
|
||||
requests.push(item);
|
||||
return item.promise; // Deliberately ignore abort: identity fences must still reject stale responses.
|
||||
},
|
||||
});
|
||||
});
|
||||
afterEach(async () => {
|
||||
if (root) {
|
||||
await flush(() => root!.unmount());
|
||||
}
|
||||
root = undefined;
|
||||
host.remove();
|
||||
});
|
||||
afterAll(async () => {
|
||||
await browser.happyDOM.close();
|
||||
for (const key of keys) {
|
||||
const old = originals.get(key);
|
||||
if (old) {
|
||||
Object.defineProperty(globalThis, key, old);
|
||||
} else {
|
||||
Reflect.deleteProperty(globalThis, key);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
describe('bounded experiment creation', () => {
|
||||
test('preview displays frozen count/window/policies before duplicate-safe admission and exact navigation', async () => {
|
||||
const value = await ready();
|
||||
expect(host.textContent).toContain('No experiments yet.');
|
||||
expect(host.textContent).toContain('2 trials · Frozen template name');
|
||||
expect(host.textContent).toContain(new Date(value.dataset.bounds.tradeStart).toISOString());
|
||||
expect(host.textContent).toContain(value.request.datasetHash);
|
||||
const asset = [...host.querySelectorAll('dt')].find(
|
||||
item => item.textContent === 'Asset / timeframe'
|
||||
);
|
||||
expect(asset?.nextElementSibling?.textContent).toBe('X0.US / 1m');
|
||||
expect(
|
||||
requests.filter(item => item.path === '/api/v2/experiments' && item.method === 'POST')
|
||||
).toHaveLength(0);
|
||||
await flush(() => {
|
||||
button('Confirm experiment').click();
|
||||
button('Confirm experiment').click();
|
||||
});
|
||||
const post = request('/api/v2/experiments', 'POST');
|
||||
expect(post.body).toEqual({ ...value.input, previewHash: value.previewHash });
|
||||
expect(post.headers.get('Idempotency-Key')).toBeTruthy();
|
||||
expect(post.credentials).toBe('include');
|
||||
expect(
|
||||
requests.filter(item => item.path === '/api/v2/experiments' && item.method === 'POST')
|
||||
).toHaveLength(1);
|
||||
await flush(() => reply(post, { experiment: detail(value) }, 202));
|
||||
expect(location).toBe(`/experiments/${experimentId}`);
|
||||
});
|
||||
test('every form change invalidates the preview and rejects a late response for the old input', async () => {
|
||||
const value = await ready();
|
||||
await flush(() => change('Experiment name', 'Edited study'));
|
||||
expect(host.textContent).not.toContain('Confirm experiment');
|
||||
await flush(() => button('Preview experiment').click());
|
||||
const stale = request('/api/v2/experiments/preview', 'POST');
|
||||
await flush(() => change('Parameter grid (JSON)', '{}'));
|
||||
const old = structuredClone(value);
|
||||
old.input.name = 'Edited study';
|
||||
await flush(() => reply(stale, { preview: old }));
|
||||
expect(host.textContent).not.toContain('Confirm experiment');
|
||||
expect(host.querySelector('[aria-label="Frozen experiment inputs"]')).toBeNull();
|
||||
});
|
||||
test('invalid JSON and reserved keys are rejected before preview; server validation stays visible', async () => {
|
||||
await list();
|
||||
await flush(() => {
|
||||
change('Experiment name', 'Trend study');
|
||||
change('Parameter grid (JSON)', '{');
|
||||
});
|
||||
await flush(() => button('Preview experiment').click());
|
||||
expect(host.querySelector('[role="alert"]')).not.toBeNull();
|
||||
expect(requests.filter(item => item.method === 'POST')).toHaveLength(0);
|
||||
await flush(() => change('Parameter grid (JSON)', '{"__proto__":[1]}'));
|
||||
await flush(() => button('Preview experiment').click());
|
||||
expect(host.textContent).toContain('Invalid parameter name');
|
||||
expect(requests.filter(item => item.method === 'POST')).toHaveLength(0);
|
||||
await flush(() => change('Parameter grid (JSON)', '{"fastPeriod":[20],"slowPeriod":[10]}'));
|
||||
await flush(() => button('Preview experiment').click());
|
||||
await flush(() =>
|
||||
reply(
|
||||
request('/api/v2/experiments/preview', 'POST'),
|
||||
{ error: 'fastPeriod must be below slowPeriod' },
|
||||
400
|
||||
)
|
||||
);
|
||||
expect(host.textContent).toContain('fastPeriod must be below slowPeriod');
|
||||
expect(host.textContent).not.toContain('Confirm experiment');
|
||||
});
|
||||
test.each(['network', 'malformed', 'foreign', 'server'] as const)(
|
||||
'%s create ambiguity retains byte-identical body/key and locks editing until explicit retry',
|
||||
async failure => {
|
||||
const value = await ready();
|
||||
await flush(() => button('Confirm experiment').click());
|
||||
const first = request('/api/v2/experiments', 'POST');
|
||||
await flush(() => {
|
||||
if (failure === 'network') {
|
||||
first.settled = true;
|
||||
first.reject(new Error('response lost'));
|
||||
} else if (failure === 'malformed') {
|
||||
reply(first, { experiment: { id: experimentId } }, 202);
|
||||
} else if (failure === 'foreign') {
|
||||
reply(first, { experiment: detail(preview(2, otherBacktestId)) }, 202);
|
||||
} else {
|
||||
reply(first, { error: 'Temporary failure' }, 500);
|
||||
}
|
||||
});
|
||||
expect(host.textContent).toContain('Acceptance is unconfirmed');
|
||||
expect(field('Experiment name').disabled).toBe(true);
|
||||
expect(field('Saved backtest').disabled).toBe(true);
|
||||
expect(button('Preview experiment').disabled).toBe(true);
|
||||
expect(location).toBe(`/experiments?backtestId=${backtestId}`);
|
||||
await flush(() => button('Refresh experiments').click());
|
||||
await flush(() =>
|
||||
reply(request(`/api/v2/experiments?backtestId=${backtestId}`), { experiments: [] })
|
||||
);
|
||||
await flush(() => button('Retry experiment submission').click());
|
||||
const second = request('/api/v2/experiments', 'POST');
|
||||
expect(second.rawBody).toBe(first.rawBody);
|
||||
expect(second.headers.get('Idempotency-Key')).toBe(first.headers.get('Idempotency-Key'));
|
||||
await flush(() => reply(second, { experiment: detail(value) }, 202));
|
||||
expect(location).toBe(`/experiments/${experimentId}`);
|
||||
}
|
||||
);
|
||||
test('stale-preview conflict does not silently replace intent and explicit new intent requires a fresh preview', async () => {
|
||||
const value = await ready();
|
||||
await flush(() => button('Confirm experiment').click());
|
||||
const first = request('/api/v2/experiments', 'POST');
|
||||
await flush(() => reply(first, { error: 'Preview changed; refresh inputs' }, 409));
|
||||
expect(host.textContent).toContain('Preview changed; refresh inputs');
|
||||
expect(
|
||||
requests.filter(item => item.path === '/api/v2/experiments' && item.method === 'POST')
|
||||
).toHaveLength(1);
|
||||
Object.defineProperty(browser, 'confirm', { configurable: true, value: () => false });
|
||||
await flush(() => button('Start new experiment').click());
|
||||
expect(field('Experiment name').disabled).toBe(true);
|
||||
Object.defineProperty(browser, 'confirm', { configurable: true, value: () => true });
|
||||
await flush(() => button('Start new experiment').click());
|
||||
expect(host.textContent).not.toContain('Confirm experiment');
|
||||
expect(field('Experiment name').disabled).toBe(false);
|
||||
await flush(() => button('Preview experiment').click());
|
||||
await flush(() => reply(request('/api/v2/experiments/preview', 'POST'), { preview: value }));
|
||||
await flush(() => button('Confirm experiment').click());
|
||||
expect(request('/api/v2/experiments', 'POST').headers.get('Idempotency-Key')).not.toBe(
|
||||
first.headers.get('Idempotency-Key')
|
||||
);
|
||||
});
|
||||
test('old create completion cannot navigate after selecting a different backtest', async () => {
|
||||
const value = await ready();
|
||||
await flush(() => button('Confirm experiment').click());
|
||||
const old = request('/api/v2/experiments', 'POST');
|
||||
await flush(() => navigate(`/experiments?backtestId=${otherBacktestId}`));
|
||||
await flush(() => reply(old, { experiment: detail(value) }, 202));
|
||||
expect(location).toBe(`/experiments?backtestId=${otherBacktestId}`);
|
||||
expect(field('Experiment name').value).toBe('');
|
||||
expect(host.textContent).not.toContain('Retry experiment submission');
|
||||
});
|
||||
test.each([
|
||||
'wrong-parent',
|
||||
'duplicate-trial',
|
||||
'wrong-dataset',
|
||||
'invalid-date',
|
||||
'wrong-series',
|
||||
] as const)('malformed %s preview never enables admission', async kind => {
|
||||
await list();
|
||||
const value = preview();
|
||||
await flush(() => {
|
||||
change('Experiment name', value.input.name);
|
||||
change('Parameter grid (JSON)', JSON.stringify(value.input.grid));
|
||||
});
|
||||
await flush(() => button('Preview experiment').click());
|
||||
if (kind === 'wrong-parent') {
|
||||
value.input.backtestId = otherBacktestId;
|
||||
}
|
||||
if (kind === 'duplicate-trial') {
|
||||
value.candidates[1]!.trialKey = value.candidates[0]!.trialKey;
|
||||
}
|
||||
if (kind === 'wrong-dataset') {
|
||||
value.dataset = { ...value.dataset, hash: 'f'.repeat(64) };
|
||||
}
|
||||
if (kind === 'invalid-date') {
|
||||
value.dataset = { ...value.dataset, bounds: { ...value.dataset.bounds, tradeEnd: 9e15 } };
|
||||
}
|
||||
if (kind === 'wrong-series') {
|
||||
value.dataset = { ...value.dataset, series: [] };
|
||||
}
|
||||
await flush(() => reply(request('/api/v2/experiments/preview', 'POST'), { preview: value }));
|
||||
expect(host.textContent).toContain('could not be verified');
|
||||
expect(host.textContent).not.toContain('Confirm experiment');
|
||||
});
|
||||
test('owned links require deliberate discard and keep ambiguous body/key when navigation is declined', async () => {
|
||||
const value = await ready();
|
||||
await flush(() => button('Confirm experiment').click());
|
||||
const first = request('/api/v2/experiments', 'POST');
|
||||
await flush(() => {
|
||||
first.settled = true;
|
||||
first.reject(new Error('lost'));
|
||||
});
|
||||
await flush(() => button('Refresh experiments').click());
|
||||
await flush(() =>
|
||||
reply(request(`/api/v2/experiments?backtestId=${backtestId}`), {
|
||||
experiments: [detail(value)],
|
||||
})
|
||||
);
|
||||
let prompts = 0;
|
||||
Object.defineProperty(browser, 'confirm', {
|
||||
configurable: true,
|
||||
value: () => {
|
||||
prompts++;
|
||||
return false;
|
||||
},
|
||||
});
|
||||
await flush(() =>
|
||||
(host.querySelector(`a[href="/experiments/${experimentId}"]`) as HTMLAnchorElement).click()
|
||||
);
|
||||
await flush(() => (host.querySelector('a[href="/experiments"]') as HTMLAnchorElement).click());
|
||||
expect(prompts).toBe(2);
|
||||
expect(location).toBe(`/experiments?backtestId=${backtestId}`);
|
||||
expect(field('Experiment name').disabled).toBe(true);
|
||||
await flush(() => button('Retry experiment submission').click());
|
||||
const retry = request('/api/v2/experiments', 'POST');
|
||||
expect(retry.rawBody).toBe(first.rawBody);
|
||||
expect(retry.headers.get('Idempotency-Key')).toBe(first.headers.get('Idempotency-Key'));
|
||||
await flush(() => reply(retry, { experiment: detail(value) }, 202));
|
||||
expect(location).toBe(`/experiments/${experimentId}`);
|
||||
});
|
||||
test('list loading/error/empty states recover and saved links preserve missing counts', async () => {
|
||||
await render(createElement(ExperimentListPage), '/experiments');
|
||||
expect(host.textContent).toContain('Loading experiments...');
|
||||
await flush(() => {
|
||||
reply(request('/api/v2/experiments'), { error: 'Read unavailable' }, 500);
|
||||
reply(request('/api/v2/backtests?limit=50&offset=0'), []);
|
||||
});
|
||||
expect(host.textContent).toContain('No saved canonical backtests');
|
||||
expect(host.textContent).toContain('Read unavailable');
|
||||
await flush(() => button('Refresh experiments').click());
|
||||
const value = detail(preview(2), ['completed', 'missing']);
|
||||
await flush(() => reply(request('/api/v2/experiments'), { experiments: [value] }));
|
||||
expect(host.textContent).toContain('missing: 1');
|
||||
expect(host.querySelector(`a[href="/experiments/${experimentId}"]`)).not.toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe('experiment outcomes and cancellation', () => {
|
||||
test('all states, null reasons, exact zero, mismatches, provenance and exact run links remain visible', async () => {
|
||||
const value = detail(preview(8), [
|
||||
'completed',
|
||||
'failed',
|
||||
'missing',
|
||||
'cancelled',
|
||||
'running',
|
||||
'paused',
|
||||
'pending',
|
||||
'completed',
|
||||
]);
|
||||
value.trials[7]!.comparable = false;
|
||||
value.trials[7]!.diagnostic = 'Retained request does not match the candidate';
|
||||
value.trials[7]!.limitations = ['Result cannot be compared'];
|
||||
value.trials[7]!.metrics = null;
|
||||
value.trials[7]!.unavailable = null;
|
||||
await showDetail(value);
|
||||
expect(host.querySelectorAll('tbody tr')).toHaveLength(8);
|
||||
expect(host.textContent).toContain('missing: 1');
|
||||
expect(host.textContent).toContain('Strategy callback failed');
|
||||
expect(host.textContent).toContain('Child run missing');
|
||||
expect(host.textContent).toContain('Incomparable');
|
||||
expect(host.textContent).toContain('Retained request does not match');
|
||||
expect(host.textContent).toContain('Unavailable: insufficient-periods');
|
||||
const first = host.querySelector('tbody tr')!;
|
||||
expect(first.querySelectorAll('td')[3]!.textContent).toBe('0');
|
||||
expect(first.querySelectorAll('td')[4]!.textContent).toBe('0');
|
||||
expect(host.querySelector(`a[href="/backtests/${backtestId}/run/${runId(0)}"]`)).not.toBeNull();
|
||||
expect(host.querySelectorAll('tbody a')).toHaveLength(7);
|
||||
expect(host.textContent).toContain(value.previewHash);
|
||||
expect(host.textContent).toContain(value.preview.request.build.engineBinarySha256);
|
||||
expect(host.textContent).not.toContain('Retry failed');
|
||||
});
|
||||
test('cancel is explicit and duplicate-safe, retains terminal outcomes and distinguishes requested running work', async () => {
|
||||
const value = detail(preview(3), ['completed', 'running', 'pending']);
|
||||
await showDetail(value);
|
||||
await flush(() => {
|
||||
button('Cancel remaining trials').click();
|
||||
button('Cancel remaining trials').click();
|
||||
});
|
||||
const post = request(`/api/v2/experiments/${experimentId}/cancel`, 'POST');
|
||||
expect(post.body).toEqual({});
|
||||
expect(requests.filter(item => item.method === 'POST')).toHaveLength(1);
|
||||
const cancelled = detail(value.preview, ['completed', 'running', 'cancelled']);
|
||||
cancelled.cancelRequested = true;
|
||||
cancelled.trials[1]!.cancelRequested = true;
|
||||
await flush(() => reply(post, { experiment: cancelled }));
|
||||
expect(host.textContent).toContain('Cancellation requested. Running trials may still finish');
|
||||
expect(host.textContent).toContain('completed: 1');
|
||||
expect(host.textContent).toContain('running: 1');
|
||||
expect(host.textContent).toContain('cancelled: 1');
|
||||
expect(host.textContent).not.toContain('Cancel remaining trials');
|
||||
});
|
||||
test('cancellation response loss is visible and refresh verifies persisted state', async () => {
|
||||
const value = detail();
|
||||
await showDetail(value);
|
||||
await flush(() => button('Cancel remaining trials').click());
|
||||
const post = request(`/api/v2/experiments/${experimentId}/cancel`, 'POST');
|
||||
await flush(() => {
|
||||
post.settled = true;
|
||||
post.reject(new Error('lost'));
|
||||
});
|
||||
expect(host.textContent).toContain('Refresh to verify the saved state');
|
||||
await flush(() => button('Refresh experiment').click());
|
||||
const cancelled = detail(value.preview, ['cancelled', 'cancelled']);
|
||||
cancelled.cancelRequested = true;
|
||||
await flush(() =>
|
||||
reply(request(`/api/v2/experiments/${experimentId}`), { experiment: cancelled })
|
||||
);
|
||||
expect(host.textContent).toContain('cancelled: 2');
|
||||
});
|
||||
test('old detail and cancel responses never overwrite a different selected experiment', async () => {
|
||||
const value = detail();
|
||||
await showDetail(value);
|
||||
await flush(() => button('Cancel remaining trials').click());
|
||||
const oldCancel = request(`/api/v2/experiments/${experimentId}/cancel`, 'POST');
|
||||
await flush(() => navigate(`/experiments/${otherExperimentId}`));
|
||||
const other = detail(preview(1));
|
||||
other.id = otherExperimentId;
|
||||
other.name = 'Other experiment';
|
||||
other.preview.input.name = other.name;
|
||||
await flush(() =>
|
||||
reply(request(`/api/v2/experiments/${otherExperimentId}`), { experiment: other })
|
||||
);
|
||||
const cancelled = detail(value.preview, ['cancelled', 'cancelled']);
|
||||
cancelled.cancelRequested = true;
|
||||
await flush(() => reply(oldCancel, { experiment: cancelled }));
|
||||
expect(host.querySelector('h1')!.textContent).toBe('Other experiment');
|
||||
await flush(() => button('Refresh experiment').click());
|
||||
const stale = request(`/api/v2/experiments/${otherExperimentId}`);
|
||||
await flush(() => navigate(`/experiments/${experimentId}`));
|
||||
await flush(() => reply(stale, { experiment: other }));
|
||||
expect(host.textContent).not.toContain('Other experiment');
|
||||
await flush(() => reply(request(`/api/v2/experiments/${experimentId}`), { experiment: value }));
|
||||
expect(host.querySelector('h1')!.textContent).toBe('Trend study');
|
||||
});
|
||||
test.each([
|
||||
'identity',
|
||||
'missing-row',
|
||||
'wrong-parameters',
|
||||
'count-mismatch',
|
||||
'malformed-metrics',
|
||||
] as const)('malformed %s detail fails closed and recovers after refresh', async kind => {
|
||||
await showDetail();
|
||||
const value = detail(preview(), ['completed', 'pending']);
|
||||
if (kind === 'identity') {
|
||||
value.id = otherExperimentId;
|
||||
}
|
||||
if (kind === 'missing-row') {
|
||||
value.trials.pop();
|
||||
}
|
||||
if (kind === 'wrong-parameters') {
|
||||
value.trials[0]!.parameters = { fastPeriod: 19 };
|
||||
}
|
||||
if (kind === 'count-mismatch') {
|
||||
value.counts.completed = 0;
|
||||
}
|
||||
if (kind === 'malformed-metrics') {
|
||||
(value.trials[0]!.metrics as unknown as Record<string, unknown>).totalReturn = '0';
|
||||
}
|
||||
await flush(() => reply(request(`/api/v2/experiments/${experimentId}`), { experiment: value }));
|
||||
expect(host.textContent).toContain('could not be verified');
|
||||
expect(host.querySelector('tbody')).toBeNull();
|
||||
await flush(() => button('Refresh experiment').click());
|
||||
await flush(() =>
|
||||
reply(request(`/api/v2/experiments/${experimentId}`), { experiment: detail() })
|
||||
);
|
||||
expect(host.querySelectorAll('tbody tr')).toHaveLength(2);
|
||||
});
|
||||
test('not-found/read failures show recovery controls without claiming an empty result', async () => {
|
||||
await showDetail();
|
||||
expect(host.textContent).toContain('Loading experiment...');
|
||||
await flush(() =>
|
||||
reply(request(`/api/v2/experiments/${experimentId}`), { error: 'Experiment not found' }, 404)
|
||||
);
|
||||
expect(host.textContent).toContain('Experiment not found');
|
||||
expect(button('Refresh experiment').disabled).toBe(false);
|
||||
expect(host.querySelector('tbody')).toBeNull();
|
||||
});
|
||||
});
|
||||
|
|
@ -63,6 +63,7 @@ async function fixture(options: { corruptDataset?: boolean; buildMismatch?: bool
|
|||
'18-backtest-strategy-versions.sql',
|
||||
'19-canonical-research.sql',
|
||||
'21-run-reproduction.sql',
|
||||
'22-experiments.sql',
|
||||
]) {
|
||||
await pool.query(
|
||||
readFileSync(new URL(`../../database/postgres/init/${filename}`, import.meta.url), 'utf8')
|
||||
|
|
|
|||
|
|
@ -62,6 +62,7 @@ async function fixture(dataset = canonicalSmaFixture().dataset) {
|
|||
'18-backtest-strategy-versions.sql',
|
||||
'19-canonical-research.sql',
|
||||
'21-run-reproduction.sql',
|
||||
'22-experiments.sql',
|
||||
]) {
|
||||
await pool.query(
|
||||
readFileSync(new URL(`../../database/postgres/init/${name}`, import.meta.url), 'utf8')
|
||||
|
|
|
|||
|
|
@ -101,6 +101,7 @@ async function fixture() {
|
|||
'18-backtest-strategy-versions.sql',
|
||||
'19-canonical-research.sql',
|
||||
'21-run-reproduction.sql',
|
||||
'22-experiments.sql',
|
||||
]) {
|
||||
await pool.query(sql(name));
|
||||
}
|
||||
|
|
|
|||
|
|
@ -74,6 +74,7 @@ async function fixture() {
|
|||
'18-backtest-strategy-versions.sql',
|
||||
'19-canonical-research.sql',
|
||||
'21-run-reproduction.sql',
|
||||
'22-experiments.sql',
|
||||
]) {
|
||||
await pool.query(
|
||||
readFileSync(new URL(`../../database/postgres/init/${name}`, import.meta.url), 'utf8')
|
||||
|
|
|
|||
|
|
@ -85,6 +85,7 @@ async function fixture() {
|
|||
'18-backtest-strategy-versions.sql',
|
||||
'19-canonical-research.sql',
|
||||
'21-run-reproduction.sql',
|
||||
'22-experiments.sql',
|
||||
]) {
|
||||
await pool.query(
|
||||
readFileSync(new URL(`../../database/postgres/init/${filename}`, import.meta.url), 'utf8')
|
||||
|
|
|
|||
712
test/postgres/experiments.test.ts
Normal file
712
test/postgres/experiments.test.ts
Normal file
|
|
@ -0,0 +1,712 @@
|
|||
import { randomUUID } from 'node:crypto';
|
||||
import { readFileSync } from 'node:fs';
|
||||
import { afterEach, describe, expect, test } from 'bun:test';
|
||||
import { Hono } from 'hono';
|
||||
import { Pool } from 'pg';
|
||||
import { getLogger, setLoggerConfig } from '@stock-bot/logger';
|
||||
import { PostgreSQLClient } from '@stock-bot/postgres';
|
||||
import type {
|
||||
CanonicalRunRequest,
|
||||
CanonicalRunResult,
|
||||
} from '@stock-bot/stock-config/canonical-research';
|
||||
import { BacktestRunner } from '../../apps/stock/orchestrator/src/backtest/BacktestRunner';
|
||||
import { PostgresBacktestRunRepository } from '../../apps/stock/orchestrator/src/backtest/PostgresBacktestRunRepository';
|
||||
import { RustBacktestAdapter } from '../../apps/stock/orchestrator/src/backtest/RustBacktestAdapter';
|
||||
import { createExperimentRoutes } from '../../apps/stock/web-api/src/routes/experiments.routes';
|
||||
import { BacktestServiceV2 } from '../../apps/stock/web-api/src/services/backtest-v2.service';
|
||||
import { experimentTrialRequest } from '../../apps/stock/web-api/src/services/experiment-input';
|
||||
import { ExperimentsService } from '../../apps/stock/web-api/src/services/experiments.service';
|
||||
import { StrategyCatalogService } from '../../apps/stock/web-api/src/services/strategy-catalog.service';
|
||||
import { retainResearchDataset } from '../../scripts/import-research-dataset';
|
||||
import { packageBuiltinStrategies } from '../../scripts/package-builtin-strategies';
|
||||
import { canonicalSettings } from '../fixtures/canonical-research';
|
||||
import { canonicalSmaFixture } from '../fixtures/canonical-sma';
|
||||
|
||||
setLoggerConfig({ logLevel: 'fatal', logConsole: false });
|
||||
const logger = getLogger('experiments');
|
||||
const url = process.env.PIPELINE_TEST_DATABASE_URL;
|
||||
const cleanup: (() => Promise<void>)[] = [];
|
||||
let packages: ReturnType<typeof packageBuiltinStrategies> | undefined;
|
||||
afterEach(async () => {
|
||||
for (const close of cleanup.splice(0).reverse()) {
|
||||
await close();
|
||||
}
|
||||
});
|
||||
async function fixture(poolMax = 4, withExperiments = true) {
|
||||
const dataset = canonicalSmaFixture().dataset;
|
||||
if (!url || !new URL(url).pathname.startsWith('/stock_bot_safety')) {
|
||||
throw new Error('Disposable safety database required');
|
||||
}
|
||||
const schema = 'stock_bot_safety_experiments_' + randomUUID().replaceAll('-', '');
|
||||
const admin = new Pool({ connectionString: url });
|
||||
await admin.query(`CREATE SCHEMA ${schema}`);
|
||||
const pool = new Pool({
|
||||
connectionString: url,
|
||||
application_name: schema,
|
||||
max: poolMax,
|
||||
options: `-c search_path=${schema} -c statement_timeout=10000`,
|
||||
});
|
||||
cleanup.push(async () => {
|
||||
await pool.end();
|
||||
await admin.query(`DROP SCHEMA ${schema} CASCADE`);
|
||||
await admin.end();
|
||||
});
|
||||
for (const name of [
|
||||
'06-create-backtest-tables.sql',
|
||||
'07-fix-execution-time-type.sql',
|
||||
'08-create-runs-table.sql',
|
||||
'09-backtest-run-contract.sql',
|
||||
'10-durable-backtest-dispatch.sql',
|
||||
'12-historical-datasets.sql',
|
||||
'14-backtest-submission.sql',
|
||||
'16-strategy-catalog.sql',
|
||||
'17-research-retention.sql',
|
||||
'18-backtest-strategy-versions.sql',
|
||||
'19-canonical-research.sql',
|
||||
'21-run-reproduction.sql',
|
||||
...(withExperiments ? ['22-experiments.sql'] : []),
|
||||
]) {
|
||||
await pool.query(
|
||||
readFileSync(new URL(`../../database/postgres/init/${name}`, import.meta.url), 'utf8')
|
||||
);
|
||||
}
|
||||
const postgres = new PostgreSQLClient(
|
||||
{ host: 'unused', port: 5432, database: 'unused', username: 'unused', password: 'unused' },
|
||||
logger
|
||||
);
|
||||
Object.defineProperty(postgres, 'connectionPool', { get: () => pool });
|
||||
Object.defineProperty(postgres, 'query', { value: pool.query.bind(pool) });
|
||||
const container = { postgres, logger };
|
||||
const api = new BacktestServiceV2(container);
|
||||
const experiments = new ExperimentsService(container);
|
||||
const repository = new PostgresBacktestRunRepository(postgres);
|
||||
const catalog = new StrategyCatalogService(container);
|
||||
const pkg = (await (packages ??= packageBuiltinStrategies()))[0]!;
|
||||
const version = await catalog.seedBuiltin('Retained SMA', pkg, 'seed');
|
||||
await retainResearchDataset(pool, dataset);
|
||||
const definition = {
|
||||
name: 'Canonical API',
|
||||
strategy: 'catalog',
|
||||
strategyVersionId: version.id,
|
||||
strategyParameters: { fastPeriod: 2, slowPeriod: 3 },
|
||||
symbols: dataset.manifest.executionSeries.map(s => s.instrumentId),
|
||||
startDate: new Date(dataset.manifest.bounds.tradeStart).toISOString(),
|
||||
endDate: new Date(dataset.manifest.bounds.tradeEnd).toISOString(),
|
||||
initialCapital: 10000,
|
||||
config: {
|
||||
datasetHash: dataset.manifest.hash,
|
||||
dataFrequency: dataset.manifest.series[0]!.interval,
|
||||
canonical: canonicalSettings,
|
||||
},
|
||||
};
|
||||
const draft = await api.createBacktest(definition, { autoStart: false });
|
||||
const approve = async () => {
|
||||
await catalog.reviewVersion(
|
||||
version.id,
|
||||
{ decision: 'approve', reason: 'Reviewed retained builtin' },
|
||||
'operator'
|
||||
);
|
||||
return (await catalog.getVersionReviews(version.id)).at(-1)!;
|
||||
};
|
||||
const execute = async (id: string) => {
|
||||
const engine = new RustBacktestAdapter({
|
||||
logger,
|
||||
storage: {
|
||||
async getHistoricalBars() {
|
||||
throw new Error('Canonical execution must never load provider data');
|
||||
},
|
||||
},
|
||||
});
|
||||
const runner = new BacktestRunner({
|
||||
engine,
|
||||
engineName: 'native',
|
||||
repository: new PostgresBacktestRunRepository(postgres),
|
||||
logger,
|
||||
});
|
||||
try {
|
||||
await runner.runQueued(id);
|
||||
} finally {
|
||||
await runner.shutdown();
|
||||
}
|
||||
};
|
||||
return {
|
||||
pool,
|
||||
schema,
|
||||
api,
|
||||
experiments,
|
||||
repository,
|
||||
catalog,
|
||||
pkg,
|
||||
version,
|
||||
draft,
|
||||
definition,
|
||||
dataset,
|
||||
approve,
|
||||
execute,
|
||||
app: new Hono().route('/', createExperimentRoutes(container)),
|
||||
};
|
||||
}
|
||||
|
||||
const receipt = (key: string = randomUUID()) => ({ principal: 'operator' as const, key });
|
||||
async function prepare(
|
||||
f: Awaited<ReturnType<typeof fixture>>,
|
||||
grid: Record<string, (string | number | boolean)[]> = { fastPeriod: [1, 2] }
|
||||
) {
|
||||
await f.approve();
|
||||
const input = { backtestId: f.draft.id, name: 'Retained SMA search', grid };
|
||||
const preview = await f.experiments.preview(input);
|
||||
const submission = { ...input, previewHash: preview.previewHash };
|
||||
return { input, preview, submission };
|
||||
}
|
||||
async function totals(f: Awaited<ReturnType<typeof fixture>>) {
|
||||
return (
|
||||
await f.pool.query(`SELECT (SELECT count(*)::int FROM research_experiments) AS experiments,
|
||||
(SELECT count(*)::int FROM runs) AS runs,(SELECT count(*)::int FROM backtest_dispatch) AS dispatch`)
|
||||
).rows[0];
|
||||
}
|
||||
async function rawTrial(
|
||||
f: Awaited<ReturnType<typeof fixture>>,
|
||||
experiment: Awaited<ReturnType<ExperimentsService['get']>>,
|
||||
changes: Record<string, unknown> = {}
|
||||
) {
|
||||
const id = randomUUID();
|
||||
const candidate = experiment.preview.candidates[0]!;
|
||||
const request = experimentTrialRequest(experiment.preview, candidate, id);
|
||||
const row = {
|
||||
id,
|
||||
backtest: f.draft.id,
|
||||
request,
|
||||
dataset: request.datasetHash,
|
||||
experiment: experiment.id,
|
||||
key: candidate.trialKey,
|
||||
index: candidate.index,
|
||||
original: null,
|
||||
principal: null,
|
||||
receiptKey: null,
|
||||
hash: null,
|
||||
...changes,
|
||||
};
|
||||
return f.pool.query(
|
||||
`INSERT INTO runs(id,backtest_id,run_number,status,speed_multiplier,request_snapshot,dataset_hash,experiment_id,trial_key,trial_index,original_run_id,submission_principal,submission_key,submission_hash)
|
||||
SELECT $1,$2,COALESCE(MAX(run_number),0)+1,'pending',NULL,$3,$4,$5,$6,$7,$8,$9,$10,$11 FROM runs WHERE backtest_id=$2`,
|
||||
[
|
||||
row.id,
|
||||
row.backtest,
|
||||
row.request,
|
||||
row.dataset,
|
||||
row.experiment,
|
||||
row.key,
|
||||
row.index,
|
||||
row.original,
|
||||
row.principal,
|
||||
row.receiptKey,
|
||||
row.hash,
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
describe.skipIf(!url)('retained-input experiments', () => {
|
||||
test('deterministic_grid validates every combination, duplicates, unknown/reserved axes and bounded expansion', async () => {
|
||||
const f = await fixture(1);
|
||||
const { preview } = await prepare(f, { slowPeriod: [4, 3], fastPeriod: [1, 2] });
|
||||
const reordered = await f.experiments.preview({
|
||||
...preview.input,
|
||||
grid: { fastPeriod: [1, 2], slowPeriod: [4, 3] },
|
||||
});
|
||||
expect(reordered).toEqual(preview);
|
||||
expect(preview.candidates.map(c => c.parameters)).toEqual([
|
||||
{ fastPeriod: 1, slowPeriod: 4 },
|
||||
{ fastPeriod: 1, slowPeriod: 3 },
|
||||
{ fastPeriod: 2, slowPeriod: 4 },
|
||||
{ fastPeriod: 2, slowPeriod: 3 },
|
||||
]);
|
||||
expect(preview.candidates.map(c => c.index)).toEqual([0, 1, 2, 3]);
|
||||
expect(preview.dataset).toEqual(f.dataset.manifest);
|
||||
expect((await f.experiments.preview({ ...preview.input, grid: {} })).candidates).toHaveLength(
|
||||
1
|
||||
);
|
||||
for (const grid of [
|
||||
{ fastPeriod: [1, 1] },
|
||||
{ fastPeriod: [2, 3] },
|
||||
{ unknown: [1] },
|
||||
{ fastPeriod: [] },
|
||||
{
|
||||
fastPeriod: Array.from({ length: 10 }, (_, i) => i + 1),
|
||||
slowPeriod: Array.from({ length: 11 }, (_, i) => i + 20),
|
||||
},
|
||||
JSON.parse('{"__proto__":[1]}'),
|
||||
{ constructor: [1] },
|
||||
]) {
|
||||
await expect(f.experiments.preview({ ...preview.input, grid })).rejects.toMatchObject({
|
||||
status: 400,
|
||||
});
|
||||
}
|
||||
expect(await totals(f)).toEqual({ experiments: 0, runs: 0, dispatch: 0 });
|
||||
});
|
||||
|
||||
test('frozen trials execute real Rust with distinct parameters and exact template/data/policy/build; compact saved summaries reopen', async () => {
|
||||
const f = await fixture(1);
|
||||
const before = await f.api.getBacktest(f.draft.id);
|
||||
const { preview, submission } = await prepare(f, { fastPeriod: [1], slowPeriod: [3, 10] });
|
||||
const experiment = await f.experiments.submit(submission, receipt());
|
||||
expect(experiment.trialCount).toBe(2);
|
||||
expect(experiment.counts.pending).toBe(2);
|
||||
expect(experiment.trials.every(t => !t.comparable && t.metrics === null)).toBe(true);
|
||||
const rows = (await f.pool.query('SELECT * FROM runs ORDER BY trial_index')).rows;
|
||||
for (const row of rows) {
|
||||
expect(row.submission_key).toBeNull();
|
||||
expect(row.original_run_id).toBeNull();
|
||||
expect(row.request_snapshot).toEqual(
|
||||
experimentTrialRequest(preview, preview.candidates[row.trial_index]!, row.id)
|
||||
);
|
||||
await f.execute(row.id);
|
||||
}
|
||||
const detail = await f.experiments.get(experiment.id);
|
||||
expect(detail.counts).toEqual({
|
||||
pending: 0,
|
||||
running: 0,
|
||||
paused: 0,
|
||||
completed: 2,
|
||||
failed: 0,
|
||||
cancelled: 0,
|
||||
});
|
||||
expect(detail.trials.every(t => t.comparable)).toBe(true);
|
||||
for (const trial of detail.trials) {
|
||||
const result = await f.api.getRunResults(trial.runId!);
|
||||
expect(result && 'kind' in result && result.financialEngine).toBe('rust');
|
||||
if (!result || !('kind' in result)) {
|
||||
throw new Error('Canonical result expected');
|
||||
}
|
||||
expect(trial.metrics).toEqual(result.analytics.metrics);
|
||||
expect(trial.unavailable).toEqual(result.analytics.unavailable);
|
||||
expect(trial.metrics!.alpha).toBeNull();
|
||||
expect(trial.limitations).toEqual([
|
||||
...result.financial.limitations,
|
||||
...result.financial.modelLimitations,
|
||||
]);
|
||||
}
|
||||
expect(detail.trials[0]!.metrics!.totalReturn).not.toEqual(
|
||||
detail.trials[1]!.metrics!.totalReturn
|
||||
);
|
||||
expect(detail.trials[1]!.metrics!.totalReturn).toBe(0);
|
||||
expect(detail.trials[1]!.unavailable!.totalReturn).toBeUndefined();
|
||||
expect(await f.api.getBacktest(f.draft.id)).toEqual(before);
|
||||
expect(await totals(f)).toEqual({ experiments: 1, runs: 2, dispatch: 2 });
|
||||
expect((await f.experiments.list(f.draft.id))[0]).toMatchObject({
|
||||
id: experiment.id,
|
||||
trialCount: 2,
|
||||
counts: { completed: 2 },
|
||||
});
|
||||
expect(await f.experiments.list(randomUUID())).toEqual([]);
|
||||
expect(JSON.stringify(detail.trials)).not.toContain('sessionReturns');
|
||||
expect(JSON.stringify(detail.trials)).not.toContain('equity_curve');
|
||||
});
|
||||
|
||||
test('stale preview refuses edits/reviews and accepted receipt survives archive and review changes', async () => {
|
||||
const f = await fixture();
|
||||
const { input, submission } = await prepare(f);
|
||||
await f.api.updateBacktest(f.draft.id, { name: 'Changed template' });
|
||||
await expect(f.experiments.submit(submission, receipt())).rejects.toMatchObject({
|
||||
status: 409,
|
||||
});
|
||||
expect(await totals(f)).toEqual({ experiments: 0, runs: 0, dispatch: 0 });
|
||||
const next = await f.experiments.preview(input);
|
||||
await f.approve();
|
||||
await expect(
|
||||
f.experiments.submit({ ...input, previewHash: next.previewHash }, receipt())
|
||||
).rejects.toMatchObject({ status: 409 });
|
||||
const current = { ...input, previewHash: (await f.experiments.preview(input)).previewHash };
|
||||
const key = receipt();
|
||||
const accepted = await f.experiments.submit(current, key);
|
||||
await f.catalog.reviewVersion(
|
||||
f.version.id,
|
||||
{ decision: 'revoke', reason: 'No new admissions' },
|
||||
'operator'
|
||||
);
|
||||
await f.pool.query('UPDATE backtests SET archived_at=NOW() WHERE id=$1', [f.draft.id]);
|
||||
await f.pool.query('UPDATE strategies SET archived_at=NOW() WHERE id=$1', [
|
||||
f.version.strategyId,
|
||||
]);
|
||||
expect((await f.experiments.submit(current, key)).id).toBe(accepted.id);
|
||||
await expect(f.experiments.submit(current, receipt())).rejects.toMatchObject({ status: 409 });
|
||||
await expect(
|
||||
f.experiments.submit({ ...current, name: 'Different' }, key)
|
||||
).rejects.toMatchObject({ status: 409 });
|
||||
expect(await totals(f)).toEqual({ experiments: 1, runs: 2, dispatch: 2 });
|
||||
});
|
||||
|
||||
test('duplicate_expand_race and cross-parent global receipt conflict admit exactly one atomic batch', async () => {
|
||||
const f = await fixture();
|
||||
const { submission } = await prepare(f);
|
||||
const key = receipt();
|
||||
const [a, b] = await Promise.all([
|
||||
f.experiments.submit(submission, key),
|
||||
f.experiments.submit(submission, key),
|
||||
]);
|
||||
expect(a.id).toBe(b.id);
|
||||
expect(await totals(f)).toEqual({ experiments: 1, runs: 2, dispatch: 2 });
|
||||
const other = await f.api.createBacktest(
|
||||
{ ...f.definition, name: 'Other parent' },
|
||||
{ autoStart: false }
|
||||
);
|
||||
const input = { ...submission, backtestId: other.id };
|
||||
const otherPreview = await f.experiments.preview({
|
||||
backtestId: other.id,
|
||||
name: submission.name,
|
||||
grid: submission.grid,
|
||||
});
|
||||
input.previewHash = otherPreview.previewHash;
|
||||
const raceKey = receipt();
|
||||
const result = await Promise.allSettled([
|
||||
f.experiments.submit(submission, raceKey),
|
||||
f.experiments.submit(input, raceKey),
|
||||
]);
|
||||
expect(result.filter(r => r.status === 'fulfilled')).toHaveLength(1);
|
||||
expect(
|
||||
result
|
||||
.filter(r => r.status === 'rejected')
|
||||
.map(r => (r as PromiseRejectedResult).reason.status)
|
||||
).toEqual([409]);
|
||||
expect(await totals(f)).toEqual({ experiments: 2, runs: 4, dispatch: 4 });
|
||||
});
|
||||
|
||||
test('dispatch insertion failure rolls the manifest, every trial and every outbox entry back', async () => {
|
||||
const f = await fixture();
|
||||
const { submission } = await prepare(f);
|
||||
await f.pool
|
||||
.query(`CREATE FUNCTION fail_second_dispatch() RETURNS trigger LANGUAGE plpgsql AS $$ BEGIN
|
||||
IF (SELECT trial_index FROM runs WHERE id=NEW.run_id)=1 THEN RAISE EXCEPTION 'fixture dispatch failure'; END IF; RETURN NEW; END $$;
|
||||
CREATE TRIGGER fixture_dispatch_failure BEFORE INSERT ON backtest_dispatch FOR EACH ROW EXECUTE FUNCTION fail_second_dispatch()`);
|
||||
const key = receipt();
|
||||
await expect(f.experiments.submit(submission, key)).rejects.toThrow('fixture dispatch failure');
|
||||
expect(await totals(f)).toEqual({ experiments: 0, runs: 0, dispatch: 0 });
|
||||
await f.pool.query('DROP TRIGGER fixture_dispatch_failure ON backtest_dispatch');
|
||||
expect((await f.experiments.submit(submission, key)).trialCount).toBe(2);
|
||||
});
|
||||
|
||||
test('SQL guards reject manifest/receipt/linkage mutation, direct altered requests and missing identity', async () => {
|
||||
const f = await fixture();
|
||||
const { preview, submission } = await prepare(f);
|
||||
const experiment = await f.experiments.submit(submission, receipt());
|
||||
const id = experiment.trials[0]!.runId!;
|
||||
for (const sql of [
|
||||
"UPDATE research_experiments SET name='changed' WHERE id=$1",
|
||||
"UPDATE research_experiments SET preview_hash=repeat('a',64) WHERE id=$1",
|
||||
"UPDATE research_experiments SET submission_key='other' WHERE id=$1",
|
||||
"UPDATE research_experiments SET preview=preview-'candidates' WHERE id=$1",
|
||||
'DELETE FROM research_experiments WHERE id=$1',
|
||||
]) {
|
||||
await expect(f.pool.query(sql, [experiment.id])).rejects.toMatchObject({ code: '23514' });
|
||||
}
|
||||
await expect(f.pool.query('TRUNCATE research_experiments CASCADE')).rejects.toMatchObject({
|
||||
code: '23514',
|
||||
});
|
||||
for (const assignment of [
|
||||
'experiment_id=NULL',
|
||||
'trial_index=4',
|
||||
"trial_key=repeat('a',64)",
|
||||
"request_snapshot=request_snapshot-'policy'",
|
||||
]) {
|
||||
await expect(
|
||||
f.pool.query(`UPDATE runs SET ${assignment} WHERE id=$1`, [id])
|
||||
).rejects.toMatchObject({ code: '23514' });
|
||||
}
|
||||
for (const changes of [
|
||||
{ index: 99 },
|
||||
{ key: 'a'.repeat(64) },
|
||||
{ dataset: 'a'.repeat(64) },
|
||||
{ original: id },
|
||||
{ principal: 'operator', receiptKey: 'key', hash: 'a'.repeat(64) },
|
||||
{ request: { ...preview.request, name: 'changed' } },
|
||||
{ request: null },
|
||||
{ backtest: randomUUID() },
|
||||
{ experiment: null },
|
||||
]) {
|
||||
await expect(rawTrial(f, experiment, changes)).rejects.toBeDefined();
|
||||
}
|
||||
for (const mutate of [
|
||||
(p: typeof preview) => {
|
||||
delete (p.request as unknown as Record<string, unknown>).build;
|
||||
},
|
||||
(p: typeof preview) => {
|
||||
p.candidates[0]!.parameters = {};
|
||||
},
|
||||
(p: typeof preview) => {
|
||||
p.request.policy.matching.risk.feeRate =
|
||||
'0.00000000' as typeof p.request.policy.matching.risk.feeRate;
|
||||
},
|
||||
]) {
|
||||
const altered = structuredClone(preview);
|
||||
mutate(altered);
|
||||
await expect(
|
||||
f.pool.query(
|
||||
`INSERT INTO research_experiments(id,backtest_id,name,preview,preview_hash,submission_principal,submission_key,submission_hash)
|
||||
VALUES($1,$2,$3,$4,$5,'operator',$6,$7)`,
|
||||
[
|
||||
randomUUID(),
|
||||
f.draft.id,
|
||||
preview.input.name,
|
||||
altered,
|
||||
preview.previewHash,
|
||||
randomUUID(),
|
||||
'a'.repeat(64),
|
||||
]
|
||||
)
|
||||
).rejects.toBeDefined();
|
||||
}
|
||||
await f.pool.query(
|
||||
readFileSync(
|
||||
new URL('../../database/postgres/init/22-experiments.sql', import.meta.url),
|
||||
'utf8'
|
||||
)
|
||||
);
|
||||
expect((await f.experiments.get(experiment.id)).preview).toEqual(preview);
|
||||
});
|
||||
|
||||
test('cancel_batch is idempotent, preserves completed results and fences running/paused completion and pending claims', async () => {
|
||||
const f = await fixture();
|
||||
const { submission } = await prepare(f, { fastPeriod: [1, 2], slowPeriod: [3, 4] });
|
||||
const experiment = await f.experiments.submit(submission, receipt());
|
||||
await f.execute(experiment.trials[0]!.runId!);
|
||||
const completedBefore = await f.api.getRunResults(experiment.trials[0]!.runId!);
|
||||
const requests = (
|
||||
await f.pool.query(
|
||||
'SELECT request_snapshot FROM runs WHERE experiment_id=$1 ORDER BY trial_index',
|
||||
[experiment.id]
|
||||
)
|
||||
).rows.map(r => r.request_snapshot as CanonicalRunRequest);
|
||||
const active = await f.repository.startCanonical(requests[1]!);
|
||||
await f.repository.startCanonical(requests[2]!);
|
||||
await f.pool.query("UPDATE runs SET status='paused' WHERE id=$1", [requests[2]!.runId]);
|
||||
const engine = new RustBacktestAdapter({
|
||||
logger,
|
||||
storage: {
|
||||
async getHistoricalBars() {
|
||||
throw new Error('Provider access forbidden');
|
||||
},
|
||||
},
|
||||
});
|
||||
let computed;
|
||||
try {
|
||||
computed = await engine.runCanonical(requests[1]!, async () => f.dataset);
|
||||
} finally {
|
||||
await engine.shutdown();
|
||||
}
|
||||
const result: CanonicalRunResult = {
|
||||
kind: 'canonical-result/v1',
|
||||
runId: active.runId,
|
||||
backtestId: f.draft.id,
|
||||
status: 'completed',
|
||||
completedAt: new Date().toISOString(),
|
||||
executionTime: 0,
|
||||
financialEngine: 'rust',
|
||||
strategyExecution: 'typescript-retained-builtin/v1',
|
||||
request: requests[1]!,
|
||||
...computed,
|
||||
};
|
||||
const cancelled = await f.experiments.cancel(experiment.id);
|
||||
expect(cancelled.counts).toEqual({
|
||||
pending: 0,
|
||||
running: 1,
|
||||
paused: 1,
|
||||
completed: 1,
|
||||
failed: 0,
|
||||
cancelled: 1,
|
||||
});
|
||||
expect(cancelled.trials.map(t => t.cancelRequested)).toEqual([false, true, true, true]);
|
||||
expect(await f.experiments.cancel(experiment.id)).toEqual(cancelled);
|
||||
await expect(f.repository.completeCanonical(result, active.attemptId)).rejects.toThrow(
|
||||
'Backtest cancelled'
|
||||
);
|
||||
expect(
|
||||
(await f.pool.query('SELECT 1 FROM backtest_results WHERE run_id=$1', [active.runId])).rows
|
||||
).toHaveLength(0);
|
||||
await f.repository.cancel(active.runId, active.attemptId);
|
||||
expect((await f.experiments.get(experiment.id)).trials[1]!.status).toBe('cancelled');
|
||||
await expect(f.repository.startCanonical(requests[3]!)).rejects.toThrow();
|
||||
await expect(
|
||||
f.repository.loadCanonicalDataset(active.runId, active.attemptId, requests[1]!.datasetHash)
|
||||
).rejects.toThrow();
|
||||
await expect(
|
||||
f.pool.query('UPDATE research_experiments SET cancel_requested=FALSE WHERE id=$1', [
|
||||
experiment.id,
|
||||
])
|
||||
).rejects.toMatchObject({ code: '23514' });
|
||||
await expect(rawTrial(f, experiment)).rejects.toMatchObject({ code: '23514' });
|
||||
expect(await f.api.getRunResults(experiment.trials[0]!.runId!)).toEqual(completedBefore);
|
||||
// A claim racing cancellation either loses admission or becomes a cancel-requested active run.
|
||||
const fresh = await f.experiments.submit(submission, receipt());
|
||||
const request = (
|
||||
await f.pool.query('SELECT request_snapshot FROM runs WHERE id=$1', [fresh.trials[0]!.runId])
|
||||
).rows[0].request_snapshot;
|
||||
await Promise.allSettled([
|
||||
f.repository.startCanonical(request),
|
||||
f.experiments.cancel(fresh.id),
|
||||
]);
|
||||
const raced = (await f.experiments.get(fresh.id)).trials[0]!;
|
||||
expect(['running', 'cancelled']).toContain(raced.status);
|
||||
expect(raced.cancelRequested).toBe(true);
|
||||
});
|
||||
|
||||
test('missing/null/failed/incomparable outcomes remain visible and summaries select no full result or financial arrays', async () => {
|
||||
const f = await fixture();
|
||||
const { submission } = await prepare(f, { fastPeriod: [1, 2], slowPeriod: [3, 4] });
|
||||
const experiment = await f.experiments.submit(submission, receipt());
|
||||
await f.execute(experiment.trials[0]!.runId!);
|
||||
await f.pool.query("UPDATE runs SET status='failed',error='fixture failure' WHERE id=$1", [
|
||||
experiment.trials[1]!.runId,
|
||||
]);
|
||||
// Deliberate corruption is restricted to this disposable schema and verifies fail-closed reads.
|
||||
await f.pool.query('ALTER TABLE backtest_results DISABLE TRIGGER USER');
|
||||
const originalResult = (
|
||||
await f.pool.query('SELECT canonical_result FROM backtest_results WHERE run_id=$1', [
|
||||
experiment.trials[0]!.runId,
|
||||
])
|
||||
).rows[0].canonical_result;
|
||||
for (const [path, value] of [
|
||||
['{analytics,version}', 2],
|
||||
['{analytics,policy,sampling}', 'unsupported'],
|
||||
['{analytics,policy,variance}', 'population'],
|
||||
['{financial,policy,matching,risk,feeRate}', '0.00000000'],
|
||||
['{financial,identity,datasetHash}', 'a'.repeat(64)],
|
||||
['{analytics,metrics,totalReturn}', null],
|
||||
]) {
|
||||
await f.pool.query(
|
||||
'UPDATE backtest_results SET canonical_result=jsonb_set($1::jsonb,$2::text[],$3::jsonb) WHERE run_id=$4',
|
||||
[originalResult, path, JSON.stringify(value), experiment.trials[0]!.runId]
|
||||
);
|
||||
const trial = (await f.experiments.get(experiment.id)).trials[0]!;
|
||||
expect(trial.comparable).toBe(false);
|
||||
expect(trial.metrics).toBeNull();
|
||||
expect(trial.diagnostic).not.toBeNull();
|
||||
}
|
||||
await f.pool.query('UPDATE backtest_results SET canonical_result=$1 WHERE run_id=$2', [
|
||||
originalResult,
|
||||
experiment.trials[0]!.runId,
|
||||
]);
|
||||
await f.pool.query(
|
||||
`UPDATE backtest_results SET canonical_result=jsonb_set(canonical_result,'{analytics,policy,periodsPerYear}','1') WHERE run_id=$1`,
|
||||
[experiment.trials[0]!.runId]
|
||||
);
|
||||
await f.pool.query('ALTER TABLE backtest_results ENABLE TRIGGER USER');
|
||||
await f.pool.query('ALTER TABLE runs DISABLE TRIGGER ALL');
|
||||
await f.pool.query('ALTER TABLE backtest_dispatch DISABLE TRIGGER ALL');
|
||||
await f.pool.query('DELETE FROM backtest_dispatch WHERE run_id=$1', [
|
||||
experiment.trials[3]!.runId,
|
||||
]);
|
||||
await f.pool.query('DELETE FROM runs WHERE id=$1', [experiment.trials[3]!.runId]);
|
||||
await f.pool.query('ALTER TABLE runs ENABLE TRIGGER ALL');
|
||||
await f.pool.query('ALTER TABLE backtest_dispatch ENABLE TRIGGER ALL');
|
||||
const detail = await f.experiments.get(experiment.id);
|
||||
expect(detail.trialCount).toBe(4);
|
||||
expect(detail.trials.map(t => t.status)).toEqual(['completed', 'failed', 'pending', 'missing']);
|
||||
expect(detail.trials.every(t => t.metrics === null && !t.comparable)).toBe(true);
|
||||
expect(detail.trials[1]!.error).toBe('fixture failure');
|
||||
expect(detail.trials[3]!.runId).toBeNull();
|
||||
const source = readFileSync(
|
||||
new URL('../../apps/stock/web-api/src/services/experiments.service.ts', import.meta.url),
|
||||
'utf8'
|
||||
);
|
||||
const projection = source.slice(
|
||||
source.indexOf('SELECT r.id'),
|
||||
source.indexOf('ORDER BY r.trial_index')
|
||||
);
|
||||
expect(projection).not.toMatch(/canonical_result\s*(?:,|AS\s+\w+)/i);
|
||||
expect(projection).not.toContain("->'financial'");
|
||||
expect(projection).not.toContain('sessionReturns');
|
||||
});
|
||||
|
||||
test('current original-family archive lock serializes preview and new admission without rewriting accepted receipts', async () => {
|
||||
const f = await fixture();
|
||||
const { input, submission } = await prepare(f);
|
||||
const key = receipt();
|
||||
const accepted = await f.experiments.submit(submission, key);
|
||||
const blocker = await f.pool.connect();
|
||||
let pending: Promise<unknown> | undefined;
|
||||
try {
|
||||
await blocker.query('BEGIN');
|
||||
await blocker.query('UPDATE strategies SET archived_at=NOW() WHERE id=$1', [
|
||||
f.version.strategyId,
|
||||
]);
|
||||
pending = f.experiments.preview(input).then(
|
||||
value => ({ value }),
|
||||
error => ({ error })
|
||||
);
|
||||
let waiting = false;
|
||||
for (let attempt = 0; attempt < 100; attempt++) {
|
||||
const rows = (
|
||||
await f.pool.query(
|
||||
"SELECT 1 FROM pg_stat_activity WHERE application_name=$1 AND wait_event_type='Lock'",
|
||||
[f.schema]
|
||||
)
|
||||
).rows;
|
||||
if (rows.length) {
|
||||
waiting = true;
|
||||
break;
|
||||
}
|
||||
await new Promise(resolve => setTimeout(resolve, 10));
|
||||
}
|
||||
expect(waiting).toBe(true);
|
||||
await blocker.query('COMMIT');
|
||||
expect(await pending).toMatchObject({ error: { status: 409 } });
|
||||
} finally {
|
||||
await blocker.query('ROLLBACK');
|
||||
blocker.release();
|
||||
await pending;
|
||||
}
|
||||
await expect(f.experiments.submit(submission, receipt())).rejects.toMatchObject({
|
||||
status: 409,
|
||||
});
|
||||
expect((await f.experiments.submit(submission, key)).id).toBe(accepted.id);
|
||||
expect(await totals(f)).toEqual({ experiments: 1, runs: 2, dispatch: 2 });
|
||||
});
|
||||
|
||||
test('first SQL22 upgrade preserves ordinary and reproduction snapshots, receipts, leases and results', async () => {
|
||||
const f = await fixture(4, false);
|
||||
await f.approve();
|
||||
const original = await f.api.createRun({ backtestId: f.draft.id }, receipt());
|
||||
await f.execute(original.id);
|
||||
const reproduction = await f.api.reproduceRun(original.id, receipt());
|
||||
const leased = await f.api.createRun({ backtestId: f.draft.id }, receipt());
|
||||
await f.repository.startCanonical(
|
||||
(await f.repository.load(leased.id))!.config as CanonicalRunRequest
|
||||
);
|
||||
const before = (await f.pool.query('SELECT * FROM runs ORDER BY run_number')).rows;
|
||||
const results = (await f.pool.query('SELECT * FROM backtest_results')).rows;
|
||||
const outbox = (await f.pool.query('SELECT * FROM backtest_dispatch ORDER BY run_id')).rows;
|
||||
await f.pool.query(
|
||||
readFileSync(
|
||||
new URL('../../database/postgres/init/22-experiments.sql', import.meta.url),
|
||||
'utf8'
|
||||
)
|
||||
);
|
||||
const after = (await f.pool.query('SELECT * FROM runs ORDER BY run_number')).rows;
|
||||
expect(
|
||||
after.map(
|
||||
({
|
||||
experiment_id: _experimentId,
|
||||
trial_key: _trialKey,
|
||||
trial_index: _trialIndex,
|
||||
...row
|
||||
}) => row
|
||||
)
|
||||
).toEqual(before);
|
||||
expect(
|
||||
after.every(r => r.experiment_id === null && r.trial_key === null && r.trial_index === null)
|
||||
).toBe(true);
|
||||
expect((await f.pool.query('SELECT * FROM backtest_results')).rows).toEqual(results);
|
||||
expect((await f.pool.query('SELECT * FROM backtest_dispatch ORDER BY run_id')).rows).toEqual(
|
||||
outbox
|
||||
);
|
||||
await f.execute(reproduction.id);
|
||||
expect((await f.api.getReproductionComparison(reproduction.id)).status).toBe('match');
|
||||
const ordinary = await f.api.createRun({ backtestId: f.draft.id }, receipt());
|
||||
expect(ordinary.status).toBe('pending');
|
||||
const input = { backtestId: f.draft.id, name: 'After upgrade', grid: {} };
|
||||
const preview = await f.experiments.preview(input);
|
||||
expect(
|
||||
(await f.experiments.submit({ ...input, previewHash: preview.previewHash }, receipt()))
|
||||
.trialCount
|
||||
).toBe(1);
|
||||
});
|
||||
});
|
||||
|
|
@ -24,6 +24,7 @@ const migrations = [
|
|||
'19-canonical-research.sql',
|
||||
'20-research-workspace.sql',
|
||||
'21-run-reproduction.sql',
|
||||
'22-experiments.sql',
|
||||
];
|
||||
const cleanup: (() => Promise<void>)[] = [];
|
||||
afterEach(async () => {
|
||||
|
|
|
|||
|
|
@ -26,7 +26,8 @@ const retention =
|
|||
'\n' +
|
||||
sql('19-canonical-research.sql') +
|
||||
'\n' +
|
||||
sql('21-run-reproduction.sql');
|
||||
sql('21-run-reproduction.sql') +
|
||||
sql('22-experiments.sql');
|
||||
const request = {
|
||||
name: 'Retained evidence',
|
||||
strategy: 'sma-crossover',
|
||||
|
|
|
|||
|
|
@ -70,6 +70,7 @@ async function fixture() {
|
|||
'18-backtest-strategy-versions.sql',
|
||||
'19-canonical-research.sql',
|
||||
'21-run-reproduction.sql',
|
||||
'22-experiments.sql',
|
||||
]) {
|
||||
await pool.query(
|
||||
readFileSync(new URL(`../../database/postgres/init/${filename}`, import.meta.url), 'utf8')
|
||||
|
|
|
|||
|
|
@ -61,6 +61,7 @@ async function fixture(applyWorkspace = true, maxConnections = 10) {
|
|||
'18-backtest-strategy-versions.sql',
|
||||
'19-canonical-research.sql',
|
||||
'21-run-reproduction.sql',
|
||||
'22-experiments.sql',
|
||||
]) {
|
||||
await pool.query(sql(name));
|
||||
}
|
||||
|
|
|
|||
|
|
@ -61,7 +61,7 @@ async function fixture(poolMax = 4, withReproduction = true) {
|
|||
'17-research-retention.sql',
|
||||
'18-backtest-strategy-versions.sql',
|
||||
'19-canonical-research.sql',
|
||||
...(withReproduction ? ['21-run-reproduction.sql'] : []),
|
||||
...(withReproduction ? ['21-run-reproduction.sql', '22-experiments.sql'] : []),
|
||||
]) {
|
||||
await pool.query(
|
||||
readFileSync(new URL(`../../database/postgres/init/${name}`, import.meta.url), 'utf8')
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue