feat(research): compare immutable fee and slippage scenarios
This commit is contained in:
parent
3ed7b98f7c
commit
397cd0e160
41 changed files with 3234 additions and 144 deletions
|
|
@ -37,6 +37,10 @@
|
|||
"types": "./dist/contracts/chronological-validation.d.ts",
|
||||
"default": "./dist/contracts/chronological-validation.js"
|
||||
},
|
||||
"./cost-sensitivity": {
|
||||
"types": "./dist/contracts/cost-sensitivity.d.ts",
|
||||
"default": "./dist/contracts/cost-sensitivity.js"
|
||||
},
|
||||
"./walk-forward": {
|
||||
"types": "./dist/contracts/walk-forward.d.ts",
|
||||
"default": "./dist/contracts/walk-forward.js"
|
||||
|
|
|
|||
64
apps/stock/config/src/contracts/cost-sensitivity.ts
Normal file
64
apps/stock/config/src/contracts/cost-sensitivity.ts
Normal file
|
|
@ -0,0 +1,64 @@
|
|||
/** Cost diagnostics reuse ordinary experiments and the authoritative Rust matcher. */
|
||||
import { z } from 'zod';
|
||||
import type { financialDecimal } from '@stock-bot/types';
|
||||
import { canonicalResearchSettingsSchema, type CanonicalRunRequest } from './canonical-research';
|
||||
import {
|
||||
MAX_EXPERIMENT_TRIALS,
|
||||
type ExperimentCandidate,
|
||||
type ExperimentDetail,
|
||||
type ExperimentPreview,
|
||||
type ExperimentRetryResult,
|
||||
type ExperimentTrial,
|
||||
} from './experiments';
|
||||
|
||||
export type { financialDecimal };
|
||||
|
||||
/** Exact decimal fractions: 0.001 is 10 basis points, not 0.001 percent. */
|
||||
export const costScenarioSchema = canonicalResearchSettingsSchema
|
||||
.pick({ feeRate: true, slippageRate: true })
|
||||
.strict();
|
||||
export const costSensitivityInputSchema = z
|
||||
.object({
|
||||
backtestId: z.string().uuid(),
|
||||
name: z.string().trim().min(1),
|
||||
/** Baseline is automatic and consumes one of the existing 100 trial slots. */
|
||||
scenarios: z
|
||||
.array(costScenarioSchema)
|
||||
.min(1)
|
||||
.max(MAX_EXPERIMENT_TRIALS - 1),
|
||||
})
|
||||
.strict();
|
||||
export const costSensitivitySubmissionSchema = costSensitivityInputSchema.extend({
|
||||
previewHash: z.string().regex(/^[a-f0-9]{64}$/),
|
||||
});
|
||||
export type CostScenario = z.input<typeof costScenarioSchema>;
|
||||
export type CostSensitivityInput = z.input<typeof costSensitivityInputSchema>;
|
||||
export type CostSensitivitySubmission = z.input<typeof costSensitivitySubmissionSchema>;
|
||||
export interface CostSensitivityCandidate extends ExperimentCandidate {
|
||||
/** Index zero is the unchanged-cost baseline; later indexes follow input order. */
|
||||
costs: CostScenario;
|
||||
}
|
||||
export interface CostSensitivityPreview {
|
||||
version: 'cost-sensitivity-preview/v1';
|
||||
previewHash: string;
|
||||
input: CostSensitivityInput;
|
||||
/** Original approved template and empty parameter grid, before cost overrides. */
|
||||
source: ExperimentPreview;
|
||||
/** Exact mirrors of the source, for existing experiment provenance consumers. */
|
||||
request: CanonicalRunRequest;
|
||||
dataset: ExperimentPreview['dataset'];
|
||||
candidates: CostSensitivityCandidate[];
|
||||
}
|
||||
export interface CostSensitivityTrial extends ExperimentTrial {
|
||||
costs: CostScenario;
|
||||
}
|
||||
export interface CostSensitivityDetail extends Omit<ExperimentDetail, 'preview' | 'trials'> {
|
||||
preview: CostSensitivityPreview;
|
||||
trials: CostSensitivityTrial[];
|
||||
}
|
||||
/** Only the ordinary workbench accepts both kinds. Validation sources stay v1. */
|
||||
export type WorkbenchExperimentPreview = ExperimentPreview | CostSensitivityPreview;
|
||||
export type WorkbenchExperimentDetail = ExperimentDetail | CostSensitivityDetail;
|
||||
export type WorkbenchExperimentRetryResult = Omit<ExperimentRetryResult, 'experiment'> & {
|
||||
experiment: WorkbenchExperimentDetail;
|
||||
};
|
||||
|
|
@ -99,6 +99,8 @@ export type ExperimentRunStatus =
|
|||
| 'cancelled';
|
||||
export type ExperimentCounts = Record<ExperimentRunStatus, number>;
|
||||
export interface ExperimentSummary {
|
||||
/** Optional for older clients/fixtures; absent means a parameter experiment. */
|
||||
kind?: 'parameters' | 'cost-sensitivity';
|
||||
id: string;
|
||||
name: string;
|
||||
backtestId: string;
|
||||
|
|
|
|||
|
|
@ -65,7 +65,8 @@ export async function runMigrations(container: IServiceContainer): Promise<void>
|
|||
f === '22-experiments.sql' ||
|
||||
f === '23-experiment-retries.sql' ||
|
||||
f === '24-chronological-validation.sql' ||
|
||||
f === '25-walk-forward.sql')
|
||||
f === '25-walk-forward.sql' ||
|
||||
f === '26-cost-sensitivity.sql')
|
||||
) // Explicit additive migration allowlist; never replay destructive init migrations
|
||||
.sort();
|
||||
|
||||
|
|
|
|||
|
|
@ -4,6 +4,10 @@ import { getCredentialHttpPrincipal } from '@stock-bot/di';
|
|||
import { getLogger } from '@stock-bot/logger';
|
||||
import type { IServiceContainer } from '@stock-bot/services';
|
||||
import { ChronologicalValidationService } from '../services/chronological-validation.service';
|
||||
import {
|
||||
parseCostSensitivityInput,
|
||||
parseCostSensitivitySubmission,
|
||||
} from '../services/cost-sensitivity-input';
|
||||
import {
|
||||
ExperimentError,
|
||||
experimentId,
|
||||
|
|
@ -57,6 +61,23 @@ export function createExperimentRoutes(container: IServiceContainer) {
|
|||
throw new ExperimentError(400, 'Invalid JSON request');
|
||||
}
|
||||
};
|
||||
app.post('/api/v2/experiments/cost-sensitivity/preview', async c =>
|
||||
c.json({
|
||||
preview: await service.previewCosts(parseCostSensitivityInput(await body(c.req.raw))),
|
||||
})
|
||||
);
|
||||
app.post('/api/v2/experiments/cost-sensitivity', async c => {
|
||||
const input = parseCostSensitivitySubmission(await body(c.req.raw));
|
||||
const experiment = await service.submitCosts(
|
||||
input,
|
||||
experimentReceipt({
|
||||
principal: getCredentialHttpPrincipal(c.req.raw) ?? '',
|
||||
key: c.req.header('Idempotency-Key') ?? '',
|
||||
})
|
||||
);
|
||||
c.header('Location', `/api/v2/experiments/${experiment.id}`);
|
||||
return c.json({ experiment }, 202);
|
||||
});
|
||||
app.post('/api/v2/experiments/walk-forward/preview', async c =>
|
||||
c.json({ preview: await walkForwards.preview(parseWalkForwardInput(await body(c.req.raw))) })
|
||||
);
|
||||
|
|
|
|||
|
|
@ -606,7 +606,7 @@ export class ChronologicalValidationService {
|
|||
phase: ValidationPhase,
|
||||
sourceIndex?: number
|
||||
): Promise<ValidationResultEvidence[]> {
|
||||
const detail = await this.experiments.readDetail(client, id);
|
||||
const detail = await this.experiments.readParameterDetail(client, id);
|
||||
if (
|
||||
detail.cancelRequested ||
|
||||
detail.trials.some(
|
||||
|
|
@ -698,7 +698,7 @@ export class ChronologicalValidationService {
|
|||
phase,
|
||||
status: exists ? 'admitted' : 'missing',
|
||||
experimentId: expected,
|
||||
experiment: exists ? await this.experiments.readDetail(client, expected) : null,
|
||||
experiment: exists ? await this.experiments.readParameterDetail(client, expected) : null,
|
||||
});
|
||||
}
|
||||
const ready = (phase: ValidationPhaseState) =>
|
||||
|
|
|
|||
119
apps/stock/web-api/src/services/cost-sensitivity-input.ts
Normal file
119
apps/stock/web-api/src/services/cost-sensitivity-input.ts
Normal file
|
|
@ -0,0 +1,119 @@
|
|||
import { z } from 'zod';
|
||||
import {
|
||||
canonicalRunRequestSchema,
|
||||
type CanonicalRunRequest,
|
||||
} from '@stock-bot/stock-config/canonical-research';
|
||||
import {
|
||||
costScenarioSchema,
|
||||
costSensitivityInputSchema,
|
||||
costSensitivitySubmissionSchema,
|
||||
type CostSensitivityCandidate,
|
||||
type CostSensitivityInput,
|
||||
type CostSensitivityPreview,
|
||||
type WorkbenchExperimentPreview,
|
||||
} from '@stock-bot/stock-config/cost-sensitivity';
|
||||
import type { ExperimentCandidate, ExperimentPreview } from '@stock-bot/stock-config/experiments';
|
||||
import { assertStrategyJsonText, canonicalStrategyJson } from '@stock-bot/stock-config/strategy';
|
||||
import {
|
||||
ExperimentError,
|
||||
experimentHash,
|
||||
experimentTrialRequest,
|
||||
retainedExperimentPreview,
|
||||
} from './experiment-input';
|
||||
|
||||
function parse<T extends z.ZodTypeAny>(schema: T, raw: unknown): z.infer<T> {
|
||||
try {
|
||||
assertStrategyJsonText(raw);
|
||||
return schema.parse(raw);
|
||||
} catch {
|
||||
throw new ExperimentError(400, 'Invalid cost-sensitivity input');
|
||||
}
|
||||
}
|
||||
export const parseCostSensitivityInput = (raw: unknown) => parse(costSensitivityInputSchema, raw);
|
||||
export const parseCostSensitivitySubmission = (raw: unknown) =>
|
||||
parse(costSensitivitySubmissionSchema, raw);
|
||||
const equal = (a: unknown, b: unknown) => canonicalStrategyJson(a) === canonicalStrategyJson(b);
|
||||
export function buildCostSensitivityPreview(
|
||||
raw: CostSensitivityInput,
|
||||
baseline: ExperimentPreview
|
||||
): CostSensitivityPreview {
|
||||
const input = parseCostSensitivityInput(raw),
|
||||
source = retainedExperimentPreview(baseline);
|
||||
if (
|
||||
!equal(source.input, { backtestId: input.backtestId, name: input.name, grid: {} }) ||
|
||||
source.candidates.length !== 1
|
||||
) {
|
||||
throw new Error('Cost sensitivity requires the unchanged empty-grid source');
|
||||
}
|
||||
const parameters = source.request.strategy.selection.parameters;
|
||||
const costs = [
|
||||
costScenarioSchema.parse({
|
||||
feeRate: source.request.policy.matching.risk.feeRate,
|
||||
slippageRate: source.request.policy.matching.slippageRate,
|
||||
}),
|
||||
...input.scenarios,
|
||||
];
|
||||
const keys = new Set<string>();
|
||||
const candidates = costs.map((costs, index) => {
|
||||
const trialKey = experimentHash({ version: 1, kind: 'cost-sensitivity', parameters, costs });
|
||||
if (keys.has(trialKey)) {
|
||||
throw new ExperimentError(400, 'Duplicate normalized cost scenario, including baseline');
|
||||
}
|
||||
keys.add(trialKey);
|
||||
return { index, trialKey, parameters, costs };
|
||||
});
|
||||
const manifest = {
|
||||
version: 'cost-sensitivity-preview/v1' as const,
|
||||
input,
|
||||
source,
|
||||
request: source.request,
|
||||
dataset: source.dataset,
|
||||
candidates,
|
||||
};
|
||||
return { ...manifest, previewHash: experimentHash(manifest) };
|
||||
}
|
||||
export function retainedCostSensitivityPreview(raw: unknown): CostSensitivityPreview {
|
||||
const value = raw as CostSensitivityPreview;
|
||||
let expected: CostSensitivityPreview;
|
||||
try {
|
||||
expected = buildCostSensitivityPreview(value.input, value.source);
|
||||
} catch {
|
||||
throw new Error('Retained cost-sensitivity source or scenarios failed integrity validation');
|
||||
}
|
||||
if (!equal(value, expected)) {
|
||||
throw new Error('Retained cost-sensitivity preview integrity failure');
|
||||
}
|
||||
return expected;
|
||||
}
|
||||
export function retainedWorkbenchPreview(value: unknown): WorkbenchExperimentPreview {
|
||||
if (
|
||||
value &&
|
||||
typeof value === 'object' &&
|
||||
'version' in value &&
|
||||
value.version === 'cost-sensitivity-preview/v1'
|
||||
) {
|
||||
return retainedCostSensitivityPreview(value);
|
||||
}
|
||||
return retainedExperimentPreview(value);
|
||||
}
|
||||
/** One immutable request recipe per trial; Rust remains the financial authority. */
|
||||
export function workbenchTrialRequest(
|
||||
preview: WorkbenchExperimentPreview,
|
||||
candidate: ExperimentCandidate | CostSensitivityCandidate,
|
||||
runId: string
|
||||
): CanonicalRunRequest {
|
||||
if (preview.version === 'research-experiment-preview/v1') {
|
||||
return experimentTrialRequest(preview, candidate, runId);
|
||||
}
|
||||
if (
|
||||
!('costs' in candidate) ||
|
||||
!equal(candidate.parameters, preview.source.request.strategy.selection.parameters)
|
||||
) {
|
||||
throw new Error('Cost candidate must preserve fixed source parameters and explicit costs');
|
||||
}
|
||||
const costs = costScenarioSchema.parse(candidate.costs),
|
||||
request = experimentTrialRequest(preview.source, candidate, runId);
|
||||
request.policy.matching.risk.feeRate = costs.feeRate;
|
||||
request.policy.matching.slippageRate = costs.slippageRate;
|
||||
return canonicalRunRequestSchema.parse(request);
|
||||
}
|
||||
|
|
@ -2,12 +2,17 @@ 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 {
|
||||
CostSensitivityInput,
|
||||
WorkbenchExperimentDetail,
|
||||
WorkbenchExperimentPreview,
|
||||
WorkbenchExperimentRetryResult,
|
||||
} from '@stock-bot/stock-config/cost-sensitivity';
|
||||
import type {
|
||||
ExperimentCounts,
|
||||
ExperimentDetail,
|
||||
ExperimentInput,
|
||||
ExperimentPreview,
|
||||
ExperimentRetryResult,
|
||||
ExperimentSummary,
|
||||
ExperimentTrial,
|
||||
ExperimentTrialRetry,
|
||||
|
|
@ -15,17 +20,22 @@ import type {
|
|||
import { canonicalStrategyJson } from '@stock-bot/stock-config/strategy';
|
||||
import { HistoricalDataRequestError, type CanonicalBacktestAnalytics } from '@stock-bot/types';
|
||||
import { admitCanonicalRequest, readCanonicalDataset } from './canonical-research.service';
|
||||
import {
|
||||
buildCostSensitivityPreview,
|
||||
parseCostSensitivityInput,
|
||||
parseCostSensitivitySubmission,
|
||||
retainedWorkbenchPreview,
|
||||
workbenchTrialRequest,
|
||||
} from './cost-sensitivity-input';
|
||||
import {
|
||||
buildExperimentPreview,
|
||||
ExperimentError,
|
||||
experimentHash,
|
||||
experimentId,
|
||||
experimentReceipt,
|
||||
experimentTrialRequest,
|
||||
parseExperimentInput,
|
||||
parseExperimentSubmission,
|
||||
PREVIEW_RUN_ID,
|
||||
retainedExperimentPreview,
|
||||
} from './experiment-input';
|
||||
import { mapExperimentRetry, parseExperimentRetry, retryColumns } from './experiment-retry';
|
||||
import { RunReproductionError, verifyReproductionInputs } from './run-reproduction';
|
||||
|
|
@ -76,13 +86,14 @@ const reasons = z.enum([
|
|||
'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,
|
||||
const summaryColumns = `CASE WHEN e.preview->>'version'='cost-sensitivity-preview/v1' THEN 'cost-sensitivity' ELSE 'parameters' END AS kind,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,
|
||||
kind: row.kind ?? 'parameters',
|
||||
name: row.name,
|
||||
backtestId: row.backtest_id,
|
||||
createdAt: new Date(row.created_at).toISOString(),
|
||||
|
|
@ -109,6 +120,18 @@ export class ExperimentsService {
|
|||
const input = parseExperimentInput(raw);
|
||||
return this.database.transaction(client => this.lockedPreview(client, input));
|
||||
}
|
||||
async previewCosts(raw: unknown) {
|
||||
const input = parseCostSensitivityInput(raw);
|
||||
return this.database.transaction(client => this.lockedCostPreview(client, input));
|
||||
}
|
||||
private async lockedCostPreview(client: PoolClient, input: CostSensitivityInput) {
|
||||
const source = await this.lockedPreview(client, {
|
||||
backtestId: input.backtestId,
|
||||
name: input.name,
|
||||
grid: {},
|
||||
});
|
||||
return buildCostSensitivityPreview(input, source);
|
||||
}
|
||||
async previewValidation(raw: unknown) {
|
||||
const input = parseChronologicalValidation(raw);
|
||||
const { recipe: _recipe, ...sourceInput } = input;
|
||||
|
|
@ -174,10 +197,29 @@ export class ExperimentsService {
|
|||
);
|
||||
}
|
||||
async submit(raw: unknown, actor: { principal: string; key: string }): Promise<ExperimentDetail> {
|
||||
const submission = parseExperimentSubmission(raw);
|
||||
const detail = await this.submitWorkbench(raw, actor, 'parameters');
|
||||
return this.parameterDetail(detail);
|
||||
}
|
||||
async submitCosts(
|
||||
raw: unknown,
|
||||
actor: { principal: string; key: string }
|
||||
): Promise<WorkbenchExperimentDetail> {
|
||||
return this.submitWorkbench(raw, actor, 'cost-sensitivity');
|
||||
}
|
||||
private async submitWorkbench(
|
||||
raw: unknown,
|
||||
actor: { principal: string; key: string },
|
||||
kind: 'parameters' | 'cost-sensitivity'
|
||||
): Promise<WorkbenchExperimentDetail> {
|
||||
const submission =
|
||||
kind === 'parameters' ? parseExperimentSubmission(raw) : parseCostSensitivitySubmission(raw);
|
||||
const receipt = experimentReceipt(actor);
|
||||
const { previewHash, ...input } = submission;
|
||||
const hash = experimentHash({ version: 1, operation: 'create-experiment', submission });
|
||||
const hash = experimentHash({
|
||||
version: 1,
|
||||
operation: kind === 'parameters' ? 'create-experiment' : 'create-cost-sensitivity',
|
||||
submission,
|
||||
});
|
||||
return this.database.transaction(async client => {
|
||||
const replay = async () => {
|
||||
const row = (
|
||||
|
|
@ -204,7 +246,10 @@ export class ExperimentsService {
|
|||
if (concurrent) {
|
||||
return concurrent;
|
||||
}
|
||||
const preview = await this.lockedPreview(client, input);
|
||||
const preview: WorkbenchExperimentPreview =
|
||||
'scenarios' in input
|
||||
? await this.lockedCostPreview(client, input)
|
||||
: await this.lockedPreview(client, input);
|
||||
if (preview.previewHash !== previewHash) {
|
||||
throw new ExperimentError(
|
||||
409,
|
||||
|
|
@ -243,7 +288,7 @@ export class ExperimentsService {
|
|||
);
|
||||
for (const candidate of preview.candidates) {
|
||||
const runId = randomUUID();
|
||||
const request = experimentTrialRequest(preview, candidate, runId);
|
||||
const request = workbenchTrialRequest(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)`,
|
||||
|
|
@ -274,11 +319,11 @@ export class ExperimentsService {
|
|||
);
|
||||
return rows.rows.map(summary);
|
||||
}
|
||||
async get(id: string): Promise<ExperimentDetail> {
|
||||
async get(id: string): Promise<WorkbenchExperimentDetail> {
|
||||
experimentId(id);
|
||||
return this.readDetail(this.database, id);
|
||||
}
|
||||
async cancel(id: string): Promise<ExperimentDetail> {
|
||||
async cancel(id: string): Promise<WorkbenchExperimentDetail> {
|
||||
experimentId(id);
|
||||
return this.database.transaction(async client => {
|
||||
const row = (
|
||||
|
|
@ -329,7 +374,7 @@ export class ExperimentsService {
|
|||
runId: string,
|
||||
raw: unknown,
|
||||
actor: { principal: string; key: string }
|
||||
): Promise<ExperimentRetryResult> {
|
||||
): Promise<WorkbenchExperimentRetryResult> {
|
||||
experimentId(id);
|
||||
experimentId(runId);
|
||||
const input = parseExperimentRetry(raw);
|
||||
|
|
@ -342,7 +387,7 @@ export class ExperimentsService {
|
|||
...input,
|
||||
});
|
||||
return this.database.transaction(async client => {
|
||||
const replay = async (): Promise<ExperimentRetryResult | null> => {
|
||||
const replay = async (): Promise<WorkbenchExperimentRetryResult | null> => {
|
||||
const saved = (
|
||||
await client.query(
|
||||
`SELECT ${retryColumns} FROM experiment_trial_retries h WHERE h.principal=$1 AND h.submission_key=$2`,
|
||||
|
|
@ -425,12 +470,12 @@ export class ExperimentsService {
|
|||
) {
|
||||
throw new ExperimentError(409, 'A run with a retained result cannot be retried');
|
||||
}
|
||||
const preview = retainedExperimentPreview(experiment.preview);
|
||||
const preview = retainedWorkbenchPreview(experiment.preview);
|
||||
const candidate = preview.candidates[run.trial_index];
|
||||
if (!candidate || candidate.trialKey !== run.trial_key || run.backtest_id !== parent.id) {
|
||||
throw new ExperimentError(409, 'Trial does not match its retained experiment candidate');
|
||||
}
|
||||
const request = experimentTrialRequest(preview, candidate, runId);
|
||||
const request = workbenchTrialRequest(preview, candidate, runId);
|
||||
if (!equal(request, run.request_snapshot) || request.datasetHash !== run.dataset_hash) {
|
||||
throw new ExperimentError(409, 'Trial frozen request does not match its experiment');
|
||||
}
|
||||
|
|
@ -479,7 +524,16 @@ export class ExperimentsService {
|
|||
return { retry: mapExperimentRetry(saved), experiment: await this.readDetail(client, id) };
|
||||
});
|
||||
}
|
||||
async readDetail(database: Query, id: string): Promise<ExperimentDetail> {
|
||||
private parameterDetail(detail: WorkbenchExperimentDetail): ExperimentDetail {
|
||||
if (detail.preview.version !== 'research-experiment-preview/v1') {
|
||||
throw new Error('Chronological validation requires a parameter experiment');
|
||||
}
|
||||
return detail as ExperimentDetail;
|
||||
}
|
||||
async readParameterDetail(database: Query, id: string): Promise<ExperimentDetail> {
|
||||
return this.parameterDetail(await this.readDetail(database, id));
|
||||
}
|
||||
async readDetail(database: Query, id: string): Promise<WorkbenchExperimentDetail> {
|
||||
const row = (
|
||||
await database.query(
|
||||
`SELECT ${summaryColumns},e.preview FROM research_experiments e WHERE e.id=$1`,
|
||||
|
|
@ -489,7 +543,7 @@ export class ExperimentsService {
|
|||
if (!row) {
|
||||
throw new ExperimentError(404, 'Experiment not found');
|
||||
}
|
||||
const preview = retainedExperimentPreview(row.preview);
|
||||
const preview = retainedWorkbenchPreview(row.preview);
|
||||
// Deliberately project only compact result metadata; never load financial, trades, OHLC or return arrays.
|
||||
const runs = (
|
||||
await database.query(
|
||||
|
|
@ -508,7 +562,7 @@ export class ExperimentsService {
|
|||
).rows;
|
||||
const trials = preview.candidates.map(candidate => {
|
||||
const run = runs.find(item => item.trial_index === candidate.index);
|
||||
const trial: ExperimentTrial = {
|
||||
const trial: ExperimentTrial & { costs?: unknown } = {
|
||||
...candidate,
|
||||
runId: run?.id ?? null,
|
||||
attemptNumber: run ? Number(run.attempt_number) : 0,
|
||||
|
|
@ -527,7 +581,7 @@ export class ExperimentsService {
|
|||
trial.diagnostic = 'Expected trial run is missing';
|
||||
return trial;
|
||||
}
|
||||
const expected = experimentTrialRequest(preview, candidate, run.id);
|
||||
const expected = workbenchTrialRequest(preview, candidate, run.id);
|
||||
if (
|
||||
run.trial_key !== candidate.trialKey ||
|
||||
run.backtest_id !== preview.input.backtestId ||
|
||||
|
|
@ -607,6 +661,6 @@ export class ExperimentsService {
|
|||
counts[run.status as keyof ExperimentCounts]++;
|
||||
}
|
||||
}
|
||||
return { ...summary(row), counts, preview, trials };
|
||||
return { ...summary(row), counts, preview, trials } as WorkbenchExperimentDetail;
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -6,7 +6,10 @@ import { useUnsavedWarning } from '@/features/strategies/components/useUnsavedWa
|
|||
import { ExperimentCounts } from './components/ExperimentCounts';
|
||||
import { ExperimentInputs } from './components/ExperimentInputs';
|
||||
import { ExperimentTrialRecovery } from './components/ExperimentTrialRecovery';
|
||||
import { experimentApi, type ExperimentDetailView as Detail } from './services/experimentApi';
|
||||
import {
|
||||
experimentApi,
|
||||
type WorkbenchExperimentDetailView as Detail,
|
||||
} from './services/experimentApi';
|
||||
|
||||
export function ExperimentDetailPage() {
|
||||
const { experimentId = '' } = useParams<{ experimentId: string }>();
|
||||
|
|
@ -21,6 +24,7 @@ function metricText(trial: ExperimentTrial, key: keyof NonNullable<ExperimentTri
|
|||
function ExperimentDetailView({ experimentId }: { experimentId: string }) {
|
||||
const alive = useRef(false);
|
||||
const pending = useRef(false);
|
||||
const reading = useRef(true);
|
||||
const generation = useRef(0);
|
||||
const readRequest = useRef<AbortController | null>(null);
|
||||
const [experiment, setExperiment] = useState<Detail | null>(null);
|
||||
|
|
@ -58,6 +62,7 @@ function ExperimentDetailView({ experimentId }: { experimentId: string }) {
|
|||
const revision = ++generation.current;
|
||||
const controller = new AbortController();
|
||||
readRequest.current = controller;
|
||||
reading.current = true;
|
||||
setLoading(true);
|
||||
setError('');
|
||||
void experimentApi
|
||||
|
|
@ -74,6 +79,7 @@ function ExperimentDetailView({ experimentId }: { experimentId: string }) {
|
|||
})
|
||||
.finally(() => {
|
||||
if (current && revision === generation.current) {
|
||||
reading.current = false;
|
||||
setLoading(false);
|
||||
}
|
||||
});
|
||||
|
|
@ -83,7 +89,7 @@ function ExperimentDetailView({ experimentId }: { experimentId: string }) {
|
|||
};
|
||||
}, [experimentId, reload]);
|
||||
const beginMutation = () => {
|
||||
if (pending.current) {
|
||||
if (pending.current || reading.current) {
|
||||
return false;
|
||||
}
|
||||
pending.current = true;
|
||||
|
|
@ -159,7 +165,8 @@ function ExperimentDetailView({ experimentId }: { experimentId: string }) {
|
|||
size="sm"
|
||||
disabled={loading || mutating}
|
||||
onClick={() => {
|
||||
if (!pending.current) {
|
||||
if (!pending.current && !reading.current) {
|
||||
reading.current = true;
|
||||
generation.current++;
|
||||
readRequest.current?.abort();
|
||||
setReload(value => value + 1);
|
||||
|
|
@ -201,16 +208,22 @@ function ExperimentDetailView({ experimentId }: { experimentId: string }) {
|
|||
<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.
|
||||
Rows retain{' '}
|
||||
{experiment.preview.version === 'cost-sensitivity-preview/v1'
|
||||
? 'baseline/scenario'
|
||||
: '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',
|
||||
experiment.preview.version === 'cost-sensitivity-preview/v1'
|
||||
? 'Scenario / costs / fixed parameters'
|
||||
: 'Trial / parameters',
|
||||
'Status',
|
||||
'Comparability',
|
||||
'Total return',
|
||||
|
|
@ -228,7 +241,19 @@ function ExperimentDetailView({ experimentId }: { experimentId: string }) {
|
|||
{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>
|
||||
<span>
|
||||
{'costs' in trial
|
||||
? trial.index === 0
|
||||
? 'Baseline'
|
||||
: `Scenario ${trial.index}`
|
||||
: `Trial ${trial.index + 1}`}
|
||||
</span>
|
||||
{'costs' in trial && (
|
||||
<p className="text-xs">
|
||||
Fee rate: {trial.costs.feeRate} · Slippage rate:{' '}
|
||||
{trial.costs.slippageRate} (fractions)
|
||||
</p>
|
||||
)}
|
||||
<pre className="whitespace-pre-wrap text-xs">
|
||||
{JSON.stringify(trial.parameters, null, 2)}
|
||||
</pre>
|
||||
|
|
|
|||
|
|
@ -110,6 +110,9 @@ function ExperimentList({ backtestId }: { backtestId: string }) {
|
|||
>
|
||||
{item.name}
|
||||
</Link>
|
||||
{item.kind === 'cost-sensitivity' && (
|
||||
<p className="text-sm">Cost sensitivity · template diagnostics</p>
|
||||
)}
|
||||
<p className="text-xs text-text-secondary">Created {item.createdAt}</p>
|
||||
<ExperimentCounts experiment={item} />
|
||||
</article>
|
||||
|
|
|
|||
|
|
@ -1,6 +1,11 @@
|
|||
import { useCallback, useEffect, useRef, useState } from 'react';
|
||||
import { Link, useNavigate } from 'react-router-dom';
|
||||
import { z } from 'zod';
|
||||
import {
|
||||
costSensitivityInputSchema,
|
||||
type CostScenario,
|
||||
type CostSensitivitySubmission,
|
||||
} from '@stock-bot/stock-config/cost-sensitivity';
|
||||
import {
|
||||
experimentInputSchema,
|
||||
MAX_EXPERIMENT_TRIALS,
|
||||
|
|
@ -12,7 +17,7 @@ import { useUnsavedWarning } from '@/features/strategies/components/useUnsavedWa
|
|||
import {
|
||||
experimentApi,
|
||||
ExperimentApiError,
|
||||
type ExperimentPreviewView,
|
||||
type WorkbenchExperimentPreviewView,
|
||||
} from '../services/experimentApi';
|
||||
import { ChronologicalValidationPreflight } from './ChronologicalValidationPreflight';
|
||||
import { ExperimentInputs } from './ExperimentInputs';
|
||||
|
|
@ -47,15 +52,25 @@ export function ExperimentEditor({
|
|||
const navigate = useNavigate();
|
||||
const alive = useRef(false);
|
||||
const generation = useRef(0);
|
||||
const previewRevision = useRef<number | null>(null);
|
||||
const previewRequest = useRef<AbortController | null>(null);
|
||||
const pending = useRef(false);
|
||||
const intent = useRef<{ body: ExperimentSubmission; key: string } | null>(null);
|
||||
type Intent =
|
||||
| { kind: 'parameters'; body: ExperimentSubmission; key: string }
|
||||
| { kind: 'cost-sensitivity'; body: CostSensitivitySubmission; key: string };
|
||||
const intent = useRef<Intent | null>(null);
|
||||
const [mode, setMode] = useState<'parameters' | 'cost-sensitivity'>('parameters');
|
||||
const modeRef = useRef(mode);
|
||||
const [scenarios, setScenarios] = useState<CostScenario[]>([{ feeRate: '', slippageRate: '' }]);
|
||||
const submissionOwner = useRef<'ordinary' | 'chronological' | 'walk-forward' | null>(null);
|
||||
const [lockedBy, setLockedBy] = useState<'ordinary' | 'chronological' | 'walk-forward' | null>(
|
||||
null
|
||||
);
|
||||
const claimSubmission = useCallback((owner: 'ordinary' | 'chronological' | 'walk-forward') => {
|
||||
if (submissionOwner.current && submissionOwner.current !== owner) {
|
||||
if (
|
||||
(owner !== 'ordinary' && modeRef.current === 'cost-sensitivity') ||
|
||||
(submissionOwner.current && submissionOwner.current !== owner)
|
||||
) {
|
||||
return false;
|
||||
}
|
||||
submissionOwner.current = owner;
|
||||
|
|
@ -63,6 +78,7 @@ export function ExperimentEditor({
|
|||
if (owner !== 'ordinary') {
|
||||
generation.current++;
|
||||
previewRequest.current?.abort();
|
||||
previewRevision.current = null;
|
||||
setPreview(null);
|
||||
setPreviewLoading(false);
|
||||
}
|
||||
|
|
@ -84,7 +100,7 @@ export function ExperimentEditor({
|
|||
const [templateReload, setTemplateReload] = useState(0);
|
||||
const [limit, setLimit] = useState(50);
|
||||
const [moreTemplates, setMoreTemplates] = useState(false);
|
||||
const [preview, setPreview] = useState<ExperimentPreviewView | null>(null);
|
||||
const [preview, setPreview] = useState<WorkbenchExperimentPreviewView | null>(null);
|
||||
const [previewLoading, setPreviewLoading] = useState(false);
|
||||
const [error, setError] = useState('');
|
||||
const [submitting, setSubmitting] = useState(false);
|
||||
|
|
@ -95,7 +111,14 @@ export function ExperimentEditor({
|
|||
hasIntent ||
|
||||
validationDirty ||
|
||||
walkForwardDirty ||
|
||||
Boolean(name || grid !== '{}' || backtestId !== initialBacktestId);
|
||||
Boolean(
|
||||
name ||
|
||||
grid !== '{}' ||
|
||||
backtestId !== initialBacktestId ||
|
||||
mode !== 'parameters' ||
|
||||
scenarios.length !== 1 ||
|
||||
scenarios.some(item => item.feeRate || item.slippageRate)
|
||||
);
|
||||
useUnsavedWarning(dirty);
|
||||
useEffect(() => {
|
||||
onDirty(dirty);
|
||||
|
|
@ -149,6 +172,7 @@ export function ExperimentEditor({
|
|||
}
|
||||
generation.current++;
|
||||
previewRequest.current?.abort();
|
||||
previewRevision.current = null;
|
||||
setPreview(null);
|
||||
setPreviewLoading(false);
|
||||
setError('');
|
||||
|
|
@ -162,13 +186,23 @@ export function ExperimentEditor({
|
|||
previewRequest.current?.abort();
|
||||
const controller = new AbortController();
|
||||
previewRequest.current = controller;
|
||||
previewRevision.current = null;
|
||||
setPreview(null);
|
||||
setError('');
|
||||
setPreviewLoading(true);
|
||||
try {
|
||||
const input = experimentInputSchema.parse({ backtestId, name, grid: JSON.parse(grid) });
|
||||
const value = await experimentApi.preview(input, controller.signal);
|
||||
const value =
|
||||
modeRef.current === 'cost-sensitivity'
|
||||
? await experimentApi.costPreview(
|
||||
costSensitivityInputSchema.parse({ backtestId, name, scenarios }),
|
||||
controller.signal
|
||||
)
|
||||
: await experimentApi.preview(
|
||||
experimentInputSchema.parse({ backtestId, name, grid: JSON.parse(grid) }),
|
||||
controller.signal
|
||||
);
|
||||
if (alive.current && current === generation.current) {
|
||||
previewRevision.current = current;
|
||||
setPreview(value);
|
||||
}
|
||||
} catch (cause) {
|
||||
|
|
@ -182,17 +216,29 @@ export function ExperimentEditor({
|
|||
}
|
||||
};
|
||||
const submit = async () => {
|
||||
if (pending.current || (!intent.current && !preview) || !claimSubmission('ordinary')) {
|
||||
if (
|
||||
pending.current ||
|
||||
(!intent.current && (!preview || previewRevision.current !== generation.current)) ||
|
||||
!claimSubmission('ordinary')
|
||||
) {
|
||||
return;
|
||||
}
|
||||
if (!intent.current) {
|
||||
if (!preview) {
|
||||
return;
|
||||
}
|
||||
intent.current = {
|
||||
key: crypto.randomUUID(),
|
||||
body: { ...preview.input, previewHash: preview.previewHash },
|
||||
};
|
||||
intent.current =
|
||||
preview.version === 'cost-sensitivity-preview/v1'
|
||||
? {
|
||||
kind: 'cost-sensitivity',
|
||||
key: crypto.randomUUID(),
|
||||
body: { ...preview.input, previewHash: preview.previewHash },
|
||||
}
|
||||
: {
|
||||
kind: 'parameters',
|
||||
key: crypto.randomUUID(),
|
||||
body: { ...preview.input, previewHash: preview.previewHash },
|
||||
};
|
||||
}
|
||||
const captured = intent.current;
|
||||
pending.current = true;
|
||||
|
|
@ -200,7 +246,10 @@ export function ExperimentEditor({
|
|||
setSubmitting(true);
|
||||
setError('');
|
||||
try {
|
||||
const accepted = await experimentApi.create(captured.body, captured.key);
|
||||
const accepted =
|
||||
captured.kind === 'cost-sensitivity'
|
||||
? await experimentApi.costSubmit(captured.body, captured.key)
|
||||
: await experimentApi.create(captured.body, captured.key);
|
||||
if (alive.current) {
|
||||
intent.current = null;
|
||||
setHasIntent(false);
|
||||
|
|
@ -232,6 +281,7 @@ export function ExperimentEditor({
|
|||
setHasIntent(false);
|
||||
releaseSubmission('ordinary');
|
||||
setAmbiguous(false);
|
||||
previewRevision.current = null;
|
||||
setPreview(null);
|
||||
setError('');
|
||||
};
|
||||
|
|
@ -240,10 +290,13 @@ export function ExperimentEditor({
|
|||
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>
|
||||
<h2 className="font-semibold text-text-primary">
|
||||
{mode === 'parameters' ? 'New parameter sweep' : 'New cost sensitivity experiment'}
|
||||
</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.
|
||||
{mode === 'parameters'
|
||||
? 'Choose a saved canonical backtest and vary its strategy parameters. Preview validates every combination before any trials are submitted.'
|
||||
: 'Compare explicit execution costs using fixed saved strategy parameters and dataset. Every scenario reruns the authoritative financial engine.'}
|
||||
</p>
|
||||
{templateLoading && <p role="status">Loading saved backtests...</p>}
|
||||
{templateError && (
|
||||
|
|
@ -304,27 +357,113 @@ export function ExperimentEditor({
|
|||
</Button>
|
||||
)}
|
||||
<label className="block text-sm">
|
||||
Parameter grid (JSON)
|
||||
<textarea
|
||||
className={`${fieldClass} font-mono`}
|
||||
rows={4}
|
||||
value={grid}
|
||||
Experiment type
|
||||
<select
|
||||
className={fieldClass}
|
||||
value={mode}
|
||||
disabled={Boolean(lockedBy)}
|
||||
onChange={event => invalidate(() => setGrid(event.target.value))}
|
||||
aria-describedby="experiment-grid-help"
|
||||
/>
|
||||
onChange={event =>
|
||||
invalidate(() => {
|
||||
const next =
|
||||
event.target.value === 'cost-sensitivity' ? 'cost-sensitivity' : 'parameters';
|
||||
modeRef.current = next;
|
||||
setMode(next);
|
||||
})
|
||||
}
|
||||
>
|
||||
<option value="parameters">Parameter sweep</option>
|
||||
<option value="cost-sensitivity">Cost sensitivity</option>
|
||||
</select>
|
||||
</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>
|
||||
<h3 className="font-semibold text-text-primary">Ordinary parameter sweep</h3>
|
||||
<p className="text-xs text-text-secondary">
|
||||
Ordinary submission uses the template's retained window. Chronological preflight below does
|
||||
not change or execute this sweep.
|
||||
</p>
|
||||
{mode === 'parameters' ? (
|
||||
<>
|
||||
<label className="block text-sm">
|
||||
Parameter grid (JSON)
|
||||
<textarea
|
||||
className={`${fieldClass} font-mono`}
|
||||
rows={4}
|
||||
value={grid}
|
||||
disabled={Boolean(lockedBy)}
|
||||
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>
|
||||
<h3 className="font-semibold text-text-primary">Ordinary parameter sweep</h3>
|
||||
<p className="text-xs text-text-secondary">
|
||||
Ordinary submission uses the template's retained window. Chronological preflight below
|
||||
does not change or execute this sweep.
|
||||
</p>
|
||||
</>
|
||||
) : (
|
||||
<section aria-label="Cost scenarios" className="space-y-3">
|
||||
<h3 className="font-semibold">Cost sensitivity · template diagnostics</h3>
|
||||
<p className="text-sm">
|
||||
Baseline is automatic and uses the saved template's original costs. Add up to{' '}
|
||||
{MAX_EXPERIMENT_TRIALS - 1} explicit fee/slippage pairs; no parameter grid or held-out
|
||||
selection is performed.
|
||||
</p>
|
||||
<p className="text-xs text-text-secondary">
|
||||
Rates are decimal fractions: 0.001 is 10 basis points (0.1%). Fees are charged once per
|
||||
fill; slippage is an adverse price fraction. Strategy parameters, half-spread, capital
|
||||
and risk limits stay fixed. Duplicate cost pairs, including baseline, are rejected.
|
||||
</p>
|
||||
{scenarios.map((scenario, index) => (
|
||||
<fieldset
|
||||
key={index}
|
||||
disabled={Boolean(lockedBy)}
|
||||
className="grid gap-2 sm:grid-cols-3 rounded border border-border p-3"
|
||||
>
|
||||
<legend className="px-1">Scenario {index + 1}</legend>
|
||||
{(['feeRate', 'slippageRate'] as const).map(key => (
|
||||
<label className="text-sm" key={key}>
|
||||
Scenario {index + 1} {key === 'feeRate' ? 'fee rate' : 'slippage rate'}
|
||||
<input
|
||||
type="text"
|
||||
inputMode="decimal"
|
||||
className={fieldClass}
|
||||
value={scenario[key]}
|
||||
onChange={event =>
|
||||
invalidate(() =>
|
||||
setScenarios(current =>
|
||||
current.map((item, i) =>
|
||||
i === index ? { ...item, [key]: event.target.value } : item
|
||||
)
|
||||
)
|
||||
)
|
||||
}
|
||||
/>
|
||||
</label>
|
||||
))}
|
||||
<Button
|
||||
variant="outline"
|
||||
disabled={Boolean(lockedBy) || scenarios.length === 1}
|
||||
onClick={() =>
|
||||
invalidate(() => setScenarios(current => current.filter((_, i) => i !== index)))
|
||||
}
|
||||
>
|
||||
Remove scenario {index + 1}
|
||||
</Button>
|
||||
</fieldset>
|
||||
))}
|
||||
<Button
|
||||
variant="outline"
|
||||
disabled={Boolean(lockedBy) || scenarios.length >= MAX_EXPERIMENT_TRIALS - 1}
|
||||
onClick={() =>
|
||||
invalidate(() =>
|
||||
setScenarios(current => [...current, { feeRate: '', slippageRate: '' }])
|
||||
)
|
||||
}
|
||||
>
|
||||
Add cost scenario
|
||||
</Button>
|
||||
</section>
|
||||
)}
|
||||
<Button
|
||||
variant="outline"
|
||||
disabled={
|
||||
|
|
@ -370,26 +509,28 @@ export function ExperimentEditor({
|
|||
)}
|
||||
</div>
|
||||
)}
|
||||
<ChronologicalValidationPreflight
|
||||
backtestId={backtestId}
|
||||
name={name}
|
||||
grid={grid}
|
||||
disabled={lockedBy !== null && lockedBy !== 'chronological'}
|
||||
eligible={!templateLoading && backtests.some(item => item.id === backtestId)}
|
||||
onDirty={setValidationDirty}
|
||||
claimSubmission={claimSubmission}
|
||||
releaseSubmission={releaseSubmission}
|
||||
/>
|
||||
<WalkForwardPreflight
|
||||
backtestId={backtestId}
|
||||
name={name}
|
||||
grid={grid}
|
||||
disabled={lockedBy !== null && lockedBy !== 'walk-forward'}
|
||||
eligible={!templateLoading && backtests.some(item => item.id === backtestId)}
|
||||
onDirty={setWalkForwardDirty}
|
||||
claimSubmission={claimSubmission}
|
||||
releaseSubmission={releaseSubmission}
|
||||
/>
|
||||
<div hidden={mode !== 'parameters'}>
|
||||
<ChronologicalValidationPreflight
|
||||
backtestId={backtestId}
|
||||
name={name}
|
||||
grid={grid}
|
||||
disabled={mode !== 'parameters' || (lockedBy !== null && lockedBy !== 'chronological')}
|
||||
eligible={!templateLoading && backtests.some(item => item.id === backtestId)}
|
||||
onDirty={setValidationDirty}
|
||||
claimSubmission={claimSubmission}
|
||||
releaseSubmission={releaseSubmission}
|
||||
/>
|
||||
<WalkForwardPreflight
|
||||
backtestId={backtestId}
|
||||
name={name}
|
||||
grid={grid}
|
||||
disabled={mode !== 'parameters' || (lockedBy !== null && lockedBy !== 'walk-forward')}
|
||||
eligible={!templateLoading && backtests.some(item => item.id === backtestId)}
|
||||
onDirty={setWalkForwardDirty}
|
||||
claimSubmission={claimSubmission}
|
||||
releaseSubmission={releaseSubmission}
|
||||
/>
|
||||
</div>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,7 +1,8 @@
|
|||
import type { ExperimentPreviewView } from '../services/experimentApi';
|
||||
import type { WorkbenchExperimentPreviewView } from '../services/experimentApi';
|
||||
|
||||
export function ExperimentInputs({ preview }: { preview: ExperimentPreviewView }) {
|
||||
export function ExperimentInputs({ preview }: { preview: WorkbenchExperimentPreviewView }) {
|
||||
const { request, dataset } = preview;
|
||||
const costs = preview.version === 'cost-sensitivity-preview/v1';
|
||||
const series = dataset.series.find(item => item.id === request.strategy.selection.seriesId);
|
||||
return (
|
||||
<section
|
||||
|
|
@ -50,9 +51,36 @@ export function ExperimentInputs({ preview }: { preview: ExperimentPreviewView }
|
|||
</div>
|
||||
</dl>
|
||||
<p>
|
||||
Only strategy parameters vary. Every trial retains this dataset, strategy version, capital,
|
||||
costs and risk policy.
|
||||
{costs
|
||||
? 'Template cost diagnostics only. Strategy parameters, dataset, seed, capital, half-spread and risk limits remain fixed; each fee/slippage scenario executes independently. No strategy selection or ranking is performed.'
|
||||
: 'Only strategy parameters vary. Every trial retains this dataset, strategy version, capital, costs and risk policy.'}
|
||||
</p>
|
||||
{preview.version === 'cost-sensitivity-preview/v1' && (
|
||||
<section aria-label="Prepared cost scenarios" className="space-y-2">
|
||||
<h3 className="font-semibold">Baseline and explicit cost scenarios</h3>
|
||||
<p>Fixed parameters: {JSON.stringify(request.strategy.selection.parameters)}</p>
|
||||
<p>Fixed half-spread rate: {request.policy.matching.halfSpreadRate}</p>
|
||||
<table className="w-full text-left">
|
||||
<thead>
|
||||
<tr>
|
||||
<th>Scenario</th>
|
||||
<th>Fee rate (fraction)</th>
|
||||
<th>Slippage rate (fraction)</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{preview.candidates.map(candidate => (
|
||||
<tr key={candidate.trialKey}>
|
||||
<td>{candidate.index === 0 ? 'Baseline' : `Scenario ${candidate.index}`}</td>
|
||||
<td>{candidate.costs.feeRate}</td>
|
||||
<td>{candidate.costs.slippageRate}</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
<p className="break-all">Source preview {preview.source.previewHash}</p>
|
||||
</section>
|
||||
)}
|
||||
<details>
|
||||
<summary className="cursor-pointer text-primary-500">
|
||||
Exact parameters, policies and provenance
|
||||
|
|
@ -62,6 +90,9 @@ export function ExperimentInputs({ preview }: { preview: ExperimentPreviewView }
|
|||
{
|
||||
previewHash: preview.previewHash,
|
||||
input: preview.input,
|
||||
...(preview.version === 'cost-sensitivity-preview/v1'
|
||||
? { source: preview.source }
|
||||
: {}),
|
||||
candidates: preview.candidates,
|
||||
strategy: {
|
||||
versionId: request.strategy.versionId,
|
||||
|
|
|
|||
|
|
@ -8,8 +8,8 @@ import { Button } from '@/components/ui/Button';
|
|||
import {
|
||||
experimentApi,
|
||||
ExperimentApiError,
|
||||
type ExperimentDetailView,
|
||||
type ExperimentRetryTarget,
|
||||
type WorkbenchExperimentDetailView,
|
||||
} from '../services/experimentApi';
|
||||
|
||||
interface Props {
|
||||
|
|
@ -20,7 +20,7 @@ interface Props {
|
|||
trial: ExperimentTrial;
|
||||
disabled: boolean;
|
||||
beginMutation: () => boolean;
|
||||
acceptMutation: (experiment: ExperimentDetailView) => void;
|
||||
acceptMutation: (experiment: WorkbenchExperimentDetailView) => void;
|
||||
endMutation: () => void;
|
||||
onIntentChange: (trialKey: string, active: boolean) => void;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,5 +1,13 @@
|
|||
import { z } from 'zod';
|
||||
import { canonicalRunRequestSchema } from '@stock-bot/stock-config/canonical-research';
|
||||
import {
|
||||
costScenarioSchema,
|
||||
costSensitivityInputSchema,
|
||||
type CostSensitivityDetail,
|
||||
type CostSensitivityInput,
|
||||
type CostSensitivityPreview,
|
||||
type CostSensitivitySubmission,
|
||||
} from '@stock-bot/stock-config/cost-sensitivity';
|
||||
import {
|
||||
experimentInputSchema,
|
||||
experimentRetrySchema,
|
||||
|
|
@ -30,11 +38,13 @@ const hash = z.string().regex(/^[a-f0-9]{64}$/);
|
|||
const count = z.number().int().nonnegative().max(MAX_EXPERIMENT_TRIALS);
|
||||
const counter = z.number().int().nonnegative().max(2147483647);
|
||||
const scalar = z.union([z.string(), z.number().finite(), z.boolean()]);
|
||||
const candidate = z.object({
|
||||
index: count,
|
||||
trialKey: hash,
|
||||
parameters: z.record(scalar),
|
||||
});
|
||||
const candidate = z
|
||||
.object({
|
||||
index: count,
|
||||
trialKey: hash,
|
||||
parameters: z.record(scalar),
|
||||
})
|
||||
.strict();
|
||||
const statuses = ['pending', 'running', 'paused', 'completed', 'failed', 'cancelled'] as const;
|
||||
const counts = z.object({
|
||||
pending: count,
|
||||
|
|
@ -45,6 +55,7 @@ const counts = z.object({
|
|||
cancelled: count,
|
||||
});
|
||||
const summary = z.object({
|
||||
kind: z.enum(['parameters', 'cost-sensitivity']).optional(),
|
||||
id: z.string().uuid(),
|
||||
name: z.string().min(1),
|
||||
backtestId: z.string().uuid(),
|
||||
|
|
@ -78,14 +89,25 @@ export type ExperimentPreviewView = Omit<ExperimentPreview, '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),
|
||||
});
|
||||
export type CostSensitivityPreviewView = Omit<CostSensitivityPreview, 'dataset' | 'source'> & {
|
||||
dataset: ExperimentPreviewView['dataset'];
|
||||
source: ExperimentPreviewView;
|
||||
};
|
||||
export type WorkbenchExperimentPreviewView = ExperimentPreviewView | CostSensitivityPreviewView;
|
||||
export type CostSensitivityDetailView = Omit<CostSensitivityDetail, 'preview'> & {
|
||||
preview: CostSensitivityPreviewView;
|
||||
};
|
||||
export type WorkbenchExperimentDetailView = ExperimentDetailView | CostSensitivityDetailView;
|
||||
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),
|
||||
})
|
||||
.strict();
|
||||
const metric = z.number().finite().nullable();
|
||||
export const experimentMetricsSchema = z.object({
|
||||
totalReturn: metric,
|
||||
|
|
@ -185,10 +207,60 @@ export function parseExperimentPreview(value: unknown): ExperimentPreviewView {
|
|||
// The server retains and verifies the complete manifest; the browser only renders its identity/window.
|
||||
return parsed;
|
||||
}
|
||||
export function parseExperimentDetail(value: unknown): ExperimentDetailView {
|
||||
const parsed = detail.parse(value);
|
||||
const costCandidate = candidate.extend({ costs: costScenarioSchema });
|
||||
const costPreview = preview
|
||||
.omit({ version: true, input: true, candidates: true })
|
||||
.extend({
|
||||
version: z.literal('cost-sensitivity-preview/v1'),
|
||||
input: costSensitivityInputSchema,
|
||||
source: z.unknown(),
|
||||
candidates: z.array(costCandidate).min(2).max(MAX_EXPERIMENT_TRIALS),
|
||||
})
|
||||
.strict();
|
||||
const costDetail = summary.extend({
|
||||
kind: z.literal('cost-sensitivity'),
|
||||
preview: z.unknown(),
|
||||
trials: z.array(trial.extend({ costs: costScenarioSchema })).max(MAX_EXPERIMENT_TRIALS),
|
||||
});
|
||||
export function parseCostSensitivityPreview(raw: unknown): CostSensitivityPreviewView {
|
||||
const parsed = costPreview.parse(raw),
|
||||
source = parseExperimentPreview(parsed.source);
|
||||
const costs = [
|
||||
{
|
||||
feeRate: source.request.policy.matching.risk.feeRate,
|
||||
slippageRate: source.request.policy.matching.slippageRate,
|
||||
},
|
||||
...parsed.input.scenarios,
|
||||
];
|
||||
if (
|
||||
!same(source.input, {
|
||||
backtestId: parsed.input.backtestId,
|
||||
name: parsed.input.name,
|
||||
grid: {},
|
||||
}) ||
|
||||
source.candidates.length !== 1 ||
|
||||
!same(source.candidates[0]?.parameters, source.request.strategy.selection.parameters) ||
|
||||
!same(parsed.request, source.request) ||
|
||||
!same(parsed.dataset, source.dataset) ||
|
||||
parsed.candidates.length !== costs.length ||
|
||||
new Set(costs.map(canonicalStrategyJson)).size !== costs.length ||
|
||||
new Set(parsed.candidates.map(item => item.trialKey)).size !== costs.length ||
|
||||
parsed.candidates.some(
|
||||
(item, index) =>
|
||||
item.index !== index ||
|
||||
!same(item.parameters, source.request.strategy.selection.parameters) ||
|
||||
!same(item.costs, costs[index])
|
||||
)
|
||||
) {
|
||||
throw invalid();
|
||||
}
|
||||
return { ...parsed, source } as CostSensitivityPreviewView;
|
||||
}
|
||||
function checkDetail(
|
||||
parsed: z.infer<typeof detail> | z.infer<typeof costDetail>,
|
||||
retained: WorkbenchExperimentPreviewView
|
||||
) {
|
||||
parseSummary(parsed);
|
||||
const retained = parseExperimentPreview(parsed.preview);
|
||||
if (
|
||||
parsed.backtestId !== retained.input.backtestId ||
|
||||
parsed.name !== retained.input.name ||
|
||||
|
|
@ -200,6 +272,13 @@ export function parseExperimentDetail(value: unknown): ExperimentDetailView {
|
|||
) {
|
||||
throw invalid();
|
||||
}
|
||||
const costKind = retained.version === 'cost-sensitivity-preview/v1';
|
||||
if (
|
||||
(costKind && parsed.kind !== 'cost-sensitivity') ||
|
||||
(!costKind && parsed.kind === 'cost-sensitivity')
|
||||
) {
|
||||
throw invalid();
|
||||
}
|
||||
const runIds = new Set<string>();
|
||||
for (const [index, item] of parsed.trials.entries()) {
|
||||
const expected = retained.candidates[index];
|
||||
|
|
@ -208,6 +287,8 @@ export function parseExperimentDetail(value: unknown): ExperimentDetailView {
|
|||
item.index !== expected.index ||
|
||||
item.trialKey !== expected.trialKey ||
|
||||
!same(item.parameters, expected.parameters) ||
|
||||
(costKind &&
|
||||
(!('costs' in item) || !('costs' in expected) || !same(item.costs, expected.costs))) ||
|
||||
(item.status === 'missing') !== (item.runId === null) ||
|
||||
(item.status === 'missing' && (item.attemptNumber !== 0 || item.retryCount !== 0)) ||
|
||||
(item.comparable && (item.status !== 'completed' || !item.metrics || !item.unavailable)) ||
|
||||
|
|
@ -227,7 +308,27 @@ export function parseExperimentDetail(value: unknown): ExperimentDetailView {
|
|||
) {
|
||||
throw invalid();
|
||||
}
|
||||
return { ...parsed, preview: retained } as ExperimentDetailView;
|
||||
|
||||
return { ...parsed, preview: retained };
|
||||
}
|
||||
export function parseExperimentDetail(value: unknown): ExperimentDetailView {
|
||||
const parsed = detail.parse(value);
|
||||
return checkDetail(parsed, parseExperimentPreview(parsed.preview)) as ExperimentDetailView;
|
||||
}
|
||||
export function parseWorkbenchExperimentDetail(value: unknown): WorkbenchExperimentDetailView {
|
||||
const version = z.object({ preview: z.object({ version: z.string() }) }).parse(value)
|
||||
.preview.version;
|
||||
if (version === 'research-experiment-preview/v1') {
|
||||
return parseExperimentDetail(value);
|
||||
}
|
||||
if (version !== 'cost-sensitivity-preview/v1') {
|
||||
throw invalid();
|
||||
}
|
||||
const parsed = costDetail.parse(value);
|
||||
return checkDetail(
|
||||
parsed,
|
||||
parseCostSensitivityPreview(parsed.preview)
|
||||
) as CostSensitivityDetailView;
|
||||
}
|
||||
async function request<T>(
|
||||
path: string,
|
||||
|
|
@ -272,6 +373,37 @@ const json = (body: unknown): RequestInit => ({
|
|||
body: JSON.stringify(body),
|
||||
});
|
||||
export const experimentApi = {
|
||||
costPreview: (input: CostSensitivityInput, signal?: AbortSignal) =>
|
||||
request(
|
||||
'/cost-sensitivity/preview',
|
||||
{ ...json(costSensitivityInputSchema.parse(input)), signal },
|
||||
200,
|
||||
body => {
|
||||
const value = parseCostSensitivityPreview(envelope(body, 'preview'));
|
||||
if (!same(value.input, costSensitivityInputSchema.parse(input))) {
|
||||
throw invalid();
|
||||
}
|
||||
return value;
|
||||
}
|
||||
),
|
||||
costSubmit: (input: CostSensitivitySubmission, key: string) =>
|
||||
request(
|
||||
'/cost-sensitivity',
|
||||
{ ...json(input), headers: { 'Content-Type': 'application/json', 'Idempotency-Key': key } },
|
||||
202,
|
||||
body => {
|
||||
const value = parseWorkbenchExperimentDetail(envelope(body, 'experiment'));
|
||||
const { previewHash, ...original } = input;
|
||||
if (
|
||||
value.preview.version !== 'cost-sensitivity-preview/v1' ||
|
||||
value.previewHash !== previewHash ||
|
||||
!same(value.preview.input, costSensitivityInputSchema.parse(original))
|
||||
) {
|
||||
throw invalid();
|
||||
}
|
||||
return value;
|
||||
}
|
||||
),
|
||||
retryTrial: (target: ExperimentRetryTarget, input: ExperimentRetryInput, key: string) =>
|
||||
request(
|
||||
`/${encodeURIComponent(target.experimentId)}/trials/${encodeURIComponent(target.runId)}/retry`,
|
||||
|
|
@ -282,7 +414,7 @@ export const experimentApi = {
|
|||
202,
|
||||
body => {
|
||||
const receipt = retryReceipt.parse(envelope(body, 'retry'));
|
||||
const experiment = parseExperimentDetail(envelope(body, 'experiment'));
|
||||
const experiment = parseWorkbenchExperimentDetail(envelope(body, 'experiment'));
|
||||
const current = experiment.trials.find(
|
||||
item => item.trialKey === target.trialKey && item.runId === target.runId
|
||||
);
|
||||
|
|
@ -370,7 +502,7 @@ export const experimentApi = {
|
|||
),
|
||||
get: (id: string, signal?: AbortSignal) =>
|
||||
request(`/${encodeURIComponent(id)}`, { signal }, 200, body => {
|
||||
const value = parseExperimentDetail(envelope(body, 'experiment'));
|
||||
const value = parseWorkbenchExperimentDetail(envelope(body, 'experiment'));
|
||||
if (value.id !== id) {
|
||||
throw invalid();
|
||||
}
|
||||
|
|
@ -378,7 +510,7 @@ export const experimentApi = {
|
|||
}),
|
||||
cancel: (id: string) =>
|
||||
request(`/${encodeURIComponent(id)}/cancel`, json({}), 200, body => {
|
||||
const value = parseExperimentDetail(envelope(body, 'experiment'));
|
||||
const value = parseWorkbenchExperimentDetail(envelope(body, 'experiment'));
|
||||
if (value.id !== id || !value.cancelRequested) {
|
||||
throw invalid();
|
||||
}
|
||||
|
|
|
|||
311
database/postgres/init/26-cost-sensitivity.sql
Normal file
311
database/postgres/init/26-cost-sensitivity.sql
Normal file
|
|
@ -0,0 +1,311 @@
|
|||
-- Explicit cost diagnostics reuse one immutable experiment and the canonical Rust runner.
|
||||
-- SQL24's callable v1 validator remains unchanged for chronological/walk-forward admission.
|
||||
CREATE OR REPLACE FUNCTION assert_cost_scenario(costs JSONB) RETURNS void LANGUAGE plpgsql IMMUTABLE AS $$ BEGIN
|
||||
IF (jsonb_typeof(costs)='object' AND costs-ARRAY['feeRate','slippageRate']='{}'::jsonb
|
||||
AND jsonb_typeof(costs->'feeRate')='string' AND costs->>'feeRate' ~ '^(0|1)\.[0-9]{8}$'
|
||||
AND (costs->>'feeRate')::numeric BETWEEN 0 AND 1
|
||||
AND jsonb_typeof(costs->'slippageRate')='string' AND costs->>'slippageRate' ~ '^0\.[0-9]{8}$') IS NOT TRUE THEN
|
||||
RAISE EXCEPTION 'Costs must be normalized eight-place fee/slippage fractions within canonical bounds' USING ERRCODE='23514';
|
||||
END IF;
|
||||
END $$;
|
||||
|
||||
CREATE OR REPLACE FUNCTION validate_cost_manifest(candidate_row research_experiments) RETURNS void LANGUAGE plpgsql AS $$
|
||||
DECLARE source_row research_experiments; manifest JSONB:=candidate_row.preview; source JSONB:=manifest->'source'; candidate JSONB; costs JSONB; idx INTEGER:=0; size INTEGER;
|
||||
BEGIN
|
||||
IF (manifest->>'version'='cost-sensitivity-preview/v1' AND manifest->>'previewHash'=candidate_row.preview_hash
|
||||
AND manifest-ARRAY['version','previewHash','input','source','request','dataset','candidates']='{}'::jsonb
|
||||
AND manifest#>>'{input,name}'=candidate_row.name AND manifest#>>'{input,backtestId}'=candidate_row.backtest_id::text
|
||||
AND (manifest->'input')-ARRAY['name','backtestId','scenarios']='{}'::jsonb
|
||||
AND manifest->'request'=source->'request' AND manifest->'dataset'=source->'dataset'
|
||||
AND source->'input'=jsonb_build_object('name',candidate_row.name,'backtestId',candidate_row.backtest_id::text,'grid','{}'::jsonb)
|
||||
AND source->>'version'='research-experiment-preview/v1' AND source->>'previewHash' ~ '^[a-f0-9]{64}$'
|
||||
AND jsonb_typeof(source->'candidates')='array' AND jsonb_array_length(source->'candidates')=1
|
||||
AND source#>'{candidates,0,parameters}'=source#>'{request,strategy,selection,parameters}'
|
||||
AND (source#>'{candidates,0}')-ARRAY['index','trialKey','parameters']='{}'::jsonb
|
||||
AND jsonb_typeof(manifest#>'{input,scenarios}')='array' AND jsonb_array_length(manifest#>'{input,scenarios}') BETWEEN 1 AND 99
|
||||
AND jsonb_typeof(manifest->'candidates')='array') IS NOT TRUE THEN
|
||||
RAISE EXCEPTION 'Cost experiment requires an exact fixed-parameter empty-grid source and explicit ordered scenarios' USING ERRCODE='23514';
|
||||
END IF;
|
||||
source_row:=candidate_row; source_row.preview:=source; source_row.preview_hash:=source->>'previewHash';
|
||||
PERFORM validate_experiment_manifest(source_row);
|
||||
size:=jsonb_array_length(manifest->'candidates');
|
||||
IF size<>jsonb_array_length(manifest#>'{input,scenarios}')+1 THEN
|
||||
RAISE EXCEPTION 'Every cost scenario and the automatic baseline require one candidate' USING ERRCODE='23514';
|
||||
END IF;
|
||||
FOR candidate IN SELECT value FROM jsonb_array_elements(manifest->'candidates') LOOP
|
||||
costs:=CASE WHEN idx=0 THEN jsonb_build_object('feeRate',source#>'{request,policy,matching,risk,feeRate}','slippageRate',source#>'{request,policy,matching,slippageRate}') ELSE manifest#>ARRAY['input','scenarios',(idx-1)::text] END;
|
||||
PERFORM assert_cost_scenario(costs);
|
||||
IF (candidate-ARRAY['index','trialKey','parameters','costs']='{}'::jsonb AND candidate->>'index'=idx::text
|
||||
AND candidate->>'trialKey' ~ '^[a-f0-9]{64}$' AND candidate->'parameters'=source#>'{request,strategy,selection,parameters}'
|
||||
AND candidate->'costs'=costs) IS NOT TRUE THEN
|
||||
RAISE EXCEPTION 'Cost candidates must preserve fixed parameters, exact ordered costs and contiguous identities' USING ERRCODE='23514';
|
||||
END IF;
|
||||
idx:=idx+1;
|
||||
END LOOP;
|
||||
IF (SELECT count(DISTINCT value->'costs') FROM jsonb_array_elements(manifest->'candidates'))<>size
|
||||
OR (SELECT count(DISTINCT value->>'trialKey') FROM jsonb_array_elements(manifest->'candidates'))<>size THEN
|
||||
RAISE EXCEPTION 'Normalized cost pairs and trial identities must be distinct, including baseline' USING ERRCODE='23514';
|
||||
END IF;
|
||||
END $$;
|
||||
|
||||
CREATE OR REPLACE FUNCTION require_experiment_manifest() RETURNS trigger LANGUAGE plpgsql AS $$ BEGIN
|
||||
IF NEW.preview->>'version'='cost-sensitivity-preview/v1' THEN
|
||||
PERFORM validate_cost_manifest(NEW);
|
||||
ELSE
|
||||
IF (NEW.preview-ARRAY['version','previewHash','input','request','dataset','candidates']='{}'::jsonb
|
||||
AND (NEW.preview->'input')-ARRAY['backtestId','name','grid']='{}'::jsonb
|
||||
AND NOT EXISTS(SELECT 1 FROM jsonb_array_elements(NEW.preview->'candidates') c WHERE c-ARRAY['index','trialKey','parameters']<>'{}'::jsonb)) IS NOT TRUE THEN
|
||||
RAISE EXCEPTION 'Parameter experiments cannot contain cost-scenario fields' USING ERRCODE='23514';
|
||||
END IF;
|
||||
PERFORM validate_experiment_manifest(NEW);
|
||||
END IF;
|
||||
RETURN NEW;
|
||||
END $$;
|
||||
|
||||
-- Shared immutable expected request for initial admission AND manual retry. No financial arithmetic.
|
||||
CREATE OR REPLACE FUNCTION experiment_trial_request(manifest JSONB, candidate_index INTEGER, run_id UUID) RETURNS JSONB LANGUAGE plpgsql IMMUTABLE AS $$
|
||||
DECLARE candidate JSONB:=manifest->'candidates'->candidate_index; expected JSONB;
|
||||
BEGIN
|
||||
IF (candidate_index>=0 AND candidate->>'index'=candidate_index::text AND candidate->>'trialKey' ~ '^[a-f0-9]{64}$'
|
||||
AND jsonb_typeof(candidate->'parameters')='object' AND run_id IS NOT NULL) IS NOT TRUE THEN
|
||||
RAISE EXCEPTION 'Trial requires its exact frozen candidate' USING ERRCODE='23514';
|
||||
END IF;
|
||||
expected:=jsonb_set(manifest->'request','{runId}',to_jsonb(run_id::text));
|
||||
expected:=jsonb_set(expected,'{policy,matching,risk,ledger,sessionId}',to_jsonb(run_id::text));
|
||||
expected:=jsonb_set(expected,'{policy,matching,risk,ledger,accountId}',to_jsonb('research:'||run_id::text));
|
||||
expected:=jsonb_set(expected,'{strategy,selection,parameters}',candidate->'parameters');
|
||||
IF manifest->>'version'='cost-sensitivity-preview/v1' THEN
|
||||
IF (manifest->'request'=manifest#>'{source,request}' AND candidate->'parameters'=manifest#>'{source,request,strategy,selection,parameters}') IS NOT TRUE THEN
|
||||
RAISE EXCEPTION 'Cost trial must preserve its exact common source and parameters' USING ERRCODE='23514';
|
||||
END IF;
|
||||
PERFORM assert_cost_scenario(candidate->'costs');
|
||||
expected:=jsonb_set(expected,'{policy,matching,risk,feeRate}',candidate#>'{costs,feeRate}');
|
||||
expected:=jsonb_set(expected,'{policy,matching,slippageRate}',candidate#>'{costs,slippageRate}');
|
||||
ELSIF manifest->>'version'='research-experiment-preview/v1' THEN
|
||||
IF candidate ? 'costs' THEN RAISE EXCEPTION 'Parameter trials cannot override costs' USING ERRCODE='23514'; END IF;
|
||||
ELSE RAISE EXCEPTION 'Unknown experiment preview kind' USING ERRCODE='23514';
|
||||
END IF;
|
||||
RETURN expected;
|
||||
END $$;
|
||||
|
||||
-- Original SQL22 guards, with only trial request reconstruction delegated.
|
||||
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 := experiment_trial_request(experiment.preview,NEW.trial_index,NEW.id);
|
||||
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 $$;
|
||||
|
||||
|
||||
-- Original SQL23 failure/history/approval guards, with the same request recipe.
|
||||
CREATE OR REPLACE FUNCTION require_experiment_retry_failure() RETURNS trigger LANGUAGE plpgsql AS $$
|
||||
DECLARE parent RECORD; experiment RECORD; original RECORD; selected RECORD; approval RECORD; expected JSONB; candidate JSONB; retained JSONB;
|
||||
BEGIN
|
||||
-- Match the API lock order; worker-owned updates only need the run lock.
|
||||
SELECT * INTO parent FROM backtests WHERE id=(SELECT backtest_id FROM research_experiments WHERE id=NEW.experiment_id) FOR UPDATE;
|
||||
SELECT * INTO experiment FROM research_experiments WHERE id=NEW.experiment_id FOR UPDATE;
|
||||
SELECT * INTO original FROM runs WHERE id=NEW.run_id AND experiment_id=NEW.experiment_id FOR UPDATE;
|
||||
IF (parent.id IS NOT NULL AND parent.archived_at IS NULL AND experiment.id IS NOT NULL AND NOT experiment.cancel_requested
|
||||
AND original.id IS NOT NULL AND original.backtest_id=parent.id AND original.status='failed' AND NOT original.cancel_requested
|
||||
AND NEW.recorded_at=NOW() AND original.trial_key=NEW.trial_key AND original.manual_retry_count<2147483647 AND original.attempt_number<2147483647
|
||||
AND NEW.retry_number=original.manual_retry_count+1 AND NEW.previous_attempt_number=original.attempt_number
|
||||
AND NEW.previous_attempt_id IS NOT DISTINCT FROM original.attempt_id
|
||||
AND NEW.error IS NOT DISTINCT FROM original.error AND NEW.progress IS NOT DISTINCT FROM original.progress
|
||||
AND NEW.current_simulation_date IS NOT DISTINCT FROM original.current_simulation_date
|
||||
AND NEW.started_at IS NOT DISTINCT FROM original.started_at AND NEW.completed_at IS NOT DISTINCT FROM original.completed_at
|
||||
AND NEW.paused_at IS NOT DISTINCT FROM original.paused_at AND NEW.failure_updated_at=original.updated_at
|
||||
AND NOT EXISTS (SELECT 1 FROM backtest_results WHERE run_id=original.id)) IS NOT TRUE THEN
|
||||
RAISE EXCEPTION 'Retry requires the exact current failed experiment trial without cancellation or retained result' USING ERRCODE='23514';
|
||||
END IF;
|
||||
candidate := experiment.preview->'candidates'->original.trial_index;
|
||||
expected := experiment_trial_request(experiment.preview,original.trial_index,original.id);
|
||||
IF (candidate->>'index'=original.trial_index::text AND candidate->>'trialKey'=original.trial_key
|
||||
AND expected=original.request_snapshot AND expected->>'kind'='canonical-research/v1'
|
||||
AND expected->>'backtestId'=original.backtest_id::text AND expected->>'datasetHash'=original.dataset_hash
|
||||
AND original.original_run_id IS NULL AND original.speed_multiplier IS NULL) IS NOT TRUE THEN
|
||||
RAISE EXCEPTION 'Retry must preserve its exact immutable experiment request and candidate' 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=expected#>>'{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 NEW.review_id=approval.id AND expected#>>'{strategy,origin}'='builtin'
|
||||
AND expected#>>'{strategy,familyId}'=selected.strategy_id::text
|
||||
AND expected#>'{strategy,package}'=selected.envelope) IS NOT TRUE THEN
|
||||
RAISE EXCEPTION 'Retry requires current approval of the original retained built-in version' USING ERRCODE='23514';
|
||||
END IF;
|
||||
SELECT payload INTO retained FROM backtest_datasets WHERE hash=original.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 expected#>>'{strategy,selection,instrumentId}'=retained#>>'{manifest,executionSeries,0,instrumentId}'
|
||||
AND expected#>>'{strategy,selection,seriesId}'=retained#>>'{manifest,executionSeries,0,seriesId}') IS NOT TRUE THEN
|
||||
RAISE EXCEPTION 'Retry requires its retained eligible original dataset' USING ERRCODE='23514';
|
||||
END IF;
|
||||
RETURN NEW;
|
||||
END $$;
|
||||
|
||||
-- Cost admission cannot retain a receipt with missing children or dispatch work.
|
||||
CREATE OR REPLACE FUNCTION require_complete_cost_admission() RETURNS trigger LANGUAGE plpgsql AS $$
|
||||
DECLARE experiment research_experiments; expected_count INTEGER;
|
||||
BEGIN
|
||||
IF TG_TABLE_NAME='research_experiments' THEN experiment:=NEW;
|
||||
ELSE SELECT * INTO experiment FROM research_experiments WHERE id=NEW.experiment_id; END IF;
|
||||
IF experiment.preview->>'version' IS DISTINCT FROM 'cost-sensitivity-preview/v1' THEN RETURN NULL; END IF;
|
||||
expected_count:=jsonb_array_length(experiment.preview->'candidates');
|
||||
IF (SELECT count(*) FROM runs WHERE experiment_id=experiment.id)<>expected_count
|
||||
OR EXISTS(SELECT 1 FROM runs r LEFT JOIN backtest_dispatch d ON d.run_id=r.id WHERE r.experiment_id=experiment.id
|
||||
AND (d.run_id IS NULL OR r.request_snapshot IS DISTINCT FROM experiment_trial_request(experiment.preview,r.trial_index,r.id))) THEN
|
||||
RAISE EXCEPTION 'Cost experiment must atomically admit every exact trial and durable dispatch' USING ERRCODE='23514';
|
||||
END IF;
|
||||
RETURN NULL;
|
||||
END $$;
|
||||
DROP TRIGGER IF EXISTS cost_experiment_complete ON research_experiments;
|
||||
CREATE CONSTRAINT TRIGGER cost_experiment_complete AFTER INSERT ON research_experiments DEFERRABLE INITIALLY DEFERRED FOR EACH ROW EXECUTE FUNCTION require_complete_cost_admission();
|
||||
DROP TRIGGER IF EXISTS cost_trial_complete ON runs;
|
||||
CREATE CONSTRAINT TRIGGER cost_trial_complete AFTER INSERT ON runs DEFERRABLE INITIALLY DEFERRED FOR EACH ROW EXECUTE FUNCTION require_complete_cost_admission();
|
||||
|
|
@ -1,8 +1,8 @@
|
|||
# Revised development roadmap
|
||||
|
||||
**First thirty waves committed; the walk-forward component is validated and awaiting commit.** Durable single-window validation is committed as `abd1c5b`; **35 of 45 scheduled tasks are fully committed (78% by count)**. Repeated windows now freeze and execute through the existing durable paths, with immutable reset-segment reports in the web workbench. Full R08 still needs bounded cost sensitivity; R05/R07 remain partial. Performance work stays paused.
|
||||
**First thirty-one waves committed; full R08 is validated and awaiting commit.** Walk-forward is committed as `3ed7b98`; **35 of 45 scheduled tasks are fully committed (78% by count), with R08 ready for acceptance**. Fee/slippage diagnostics now reuse the existing experiment workbench. R05/R07 remain partial; performance work stays paused.
|
||||
|
||||
Authorization update: the owner requested “commit and continue”. The single chronological workflow is accepted and committed as `abd1c5b`; the walk-forward component is now independently reviewed and validated. No performance work, cost overrides, new-wave commits/pushes/PRs, candidate execution or trading/default activation are included.
|
||||
Authorization update: the owner requested “commit and continue”. Walk-forward is committed as `3ed7b98`; bounded fee/slippage sensitivity is now implemented and independently validated. No performance work, new-wave commits/pushes/PRs, candidate execution or trading/default activation is included.
|
||||
|
||||
## Strategy and review outcome
|
||||
|
||||
|
|
@ -644,7 +644,7 @@ Next after acceptance/commit: finish R08 with repeated nonoverlapping walk-forwa
|
|||
|
||||
## Thirty-first wave handoff — 2026-10-24
|
||||
|
||||
R08's bounded walk-forward component is independently accepted and `component_validated_uncommitted` on base `abd1c5b`. Full R08 remains `in_progress` for bounded cost sensitivity; R09 remains blocked. Forty-one source/test/config files and four existing planning files comprise this wave.
|
||||
R08's bounded walk-forward component is independently accepted and committed as `3ed7b98` on base `abd1c5b`. At this wave's completion, full R08 remained `in_progress` for bounded cost sensitivity; R09 remained blocked. Forty-one source/test/config files and four existing planning files comprise this wave.
|
||||
|
||||
- **Frozen series:** A focused `research_walk_forwards` header owns 2–10 ordered recipes and immutable train-root memberships. Every source/grid/build/policy is frozen before training. Total promised work includes all candidates and both future holdouts, capped at 100 runs. Training cutoffs increase and heldout intervals cannot overlap.
|
||||
- **Reuse and integrity:** Existing chronological validations, per-window actions, durable runs/outbox and retries execute every member. SQL25 is additive; SQL22–24 are unchanged. All training roots/slices/runs/outbox admit in one transaction, including a pool-size-one proof. Exact membership, write-once reports and receipts resist direct SQL mutation. Series cancellation reaches all remaining member work; member cancellation stays local and completed evidence is preserved.
|
||||
|
|
@ -656,3 +656,18 @@ Validation: 93 tooling, 43 utility, 44 calculation, **882 integration** and **15
|
|||
Independent backend/frontend reviews accepted the exact eight/eleven-file overlays; root composition and browser coverage were independently reviewed. Source archive, 41 file hashes, native identities, commands and local logs: `manifest.json` → `thirty_first_wave_validation`, under `/tmp/stock-bot-wave31.QqUT6Z/`. Release addon was restored for final database/browser tests. Both disposable fixture containers were removed after validation; development services were untouched. No new-wave commit, push, PR or trading operation occurred.
|
||||
|
||||
Next: bounded fee/slippage sensitivity with an explicit immutable financial-policy admission contract, reusing the authoritative Rust engine. Do not encode costs as strategy parameters or mutate saved templates. Keep cost scenarios separate from frozen walk-forward selection unless an explicit later study requires their combination. Performance, candidate/AI execution and multi-asset/default/paper/live activation remain gated.
|
||||
|
||||
## Thirty-second wave handoff — 2026-10-24
|
||||
|
||||
Full supported R08 is independently accepted and `validated_uncommitted` on base `3ed7b98`; task status is `review` pending owner acceptance/commit. Thirty-seven source/test/config files and four existing planning files comprise this wave. The earlier chronological preflight, durable single-window and reset-window workflows remain intact.
|
||||
|
||||
- **Cost diagnostics:** One existing experiment stores a versioned fixed-template cost preview. Automatic original-cost baseline plus 1–99 explicit distinct normalized fee/slippage pairs; parameters and every other financial/data/build policy remain frozen. Each scenario reruns Rust, including fee reservation, funding, fills and subsequent strategy decisions. No cost-as-parameter trick, adjusted-P&L subtraction, ranking or universal monotonic-profit claim.
|
||||
- **Reuse and SQL integrity:** Existing submission receipts, runs/outbox, cancellation, retries/results and original-run reproduction handle cost studies. SQL26 introduces no tables or columns. It leaves SQL22–25 and the callable v1 manifest validator unchanged, adds explicit version dispatch and one request reconstruction helper for admission/retry, and preserves all remaining guard bodies. Deferred checks require every scenario and dispatch row to commit together. Chronological/walk-forward sources remain v1-only.
|
||||
- **Web:** Cost mode uses the ordinary experiment submission owner and existing list/detail/retry/history screens. Normalized rates, original baseline, fixed inputs and scenario order are visible; failed/missing/incomparable/null outcomes stay explicit. The detail page now synchronously owns refresh before a competing mutation. Exact ambiguous body/key and late-route protections are preserved. No new report lifecycle, scheduler or financial engine.
|
||||
- **Evidence:** Hand-derived native fixtures assert exact execution prices, fees and terminal equity, including fee-inclusive funding rejection. The baseline reproduces the ordinary empty-grid economic hash. Original scenario inputs survive template edits, retry and reproduction. SQL tampering, atomic rollback, cross-kind receipts, observed lock contention and first/idempotent migration preservation pass. The actual browser verifies native policy/identity and metrics after template changes, then receipt replay, saved reopening and run drilldown.
|
||||
|
||||
All repository gates passed: **926 integration /150 Rust** tests, plus 93 tooling, 43 utility and 44 calculation cases; build, types, contracts, lint and secret audit. Final release **PostgreSQL/Redis: 224 tests /1967 assertions**; **Chromium: 15 workflows /457 assertions**. Authored-test strict types/lint, changed-source formatting and diff checks pass. Existing four ignored Rust tests and build warnings remain. No performance measurements ran.
|
||||
|
||||
Independent reviewer accepted exact backend/frontend eight-file overlays; root composition/browser/migration-chain fixes were independently reviewed. Source archive, 37 file hashes, native identities and logs are recorded in `manifest.json` → `thirty_second_wave_validation`, under `/tmp/stock-bot-wave32.Dg3iwI/`. The release engine was restored before database/browser validation. Both disposable fixture containers were removed after validation; development services remain untouched. New wave is uncommitted; no push, PR or trading operation occurred.
|
||||
|
||||
R08 completion covers deterministic unfitted strategies, explicit zero label horizon, frozen chronological selection, separate reset segments and bounded template cost diagnostics. Unsupported trainable/nonzero-horizon models reject; no purge/fitting framework or global OOS certification is claimed. Next non-performance slice: R07 comparisons across saved experiments with explicit policy/window/cost compatibility. Table measurements stay paused. R09 still also depends on partial R07; do not declare all downstream work ready merely because R08 is validated.
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
# Canonical development backlog
|
||||
|
||||
**First thirty waves committed; the walk-forward component is validated and awaiting commit.** Durable single-window validation is committed as `abd1c5b`; **35 of 45 scheduled tasks are fully committed (78% by count)**. Repeated windows now freeze and execute through the existing durable paths, with immutable reset-segment reports in the web workbench. Full R08 still needs bounded cost sensitivity; R05/R07 remain partial. Performance work stays paused.
|
||||
**First thirty-one waves committed; full R08 is validated and awaiting commit.** Walk-forward is committed as `3ed7b98`; **35 of 45 scheduled tasks are fully committed (78% by count), with R08 ready for acceptance**. Fee/slippage diagnostics now reuse the existing experiment workbench. R05/R07 remain partial; performance work stays paused.
|
||||
|
||||
## One source of truth
|
||||
|
||||
|
|
@ -79,7 +79,7 @@ Relative size: S narrow correction, M coherent boundary, L sensitive owner-contr
|
|||
| [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 / done | 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 / in_progress (walk-forward) | R06, ADR-006 | — | Quantitative research integrity / M |
|
||||
| [R08 Add bounded chronological and reset-segment validation](tasks/R08.md) | P1 / review (validated, awaiting commit) | 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 |
|
||||
|
|
@ -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.
|
||||
|
||||
R06 is complete and committed as `b373410`; the durable single-recipe R08 component is committed as `abd1c5b`. Repeated walk-forward windows are in progress; bounded cost sensitivity remains a separate next slice. R05/R07 remain partial; R09 and AI/default/trading activation retain their gates. Provider preparation is independent of experiments over retained data, and performance work remains paused.
|
||||
R06 is complete and committed as `b373410`; R08's walk-forward component is committed as `3ed7b98`. Bounded cost sensitivity now completes supported R08 implementation, independently validated and awaiting acceptance/commit. Next non-performance work is R07 comparison across saved experiments. R05/R07 remain partial; R09 also depends on R07, and AI/default/trading activation retain their gates. Provider preparation is independent of experiments over retained data; performance work remains paused.
|
||||
|
|
|
|||
|
|
@ -1,14 +1,14 @@
|
|||
{
|
||||
"schema_version": 1,
|
||||
"plan_revision": "2026-10-24.66",
|
||||
"plan_revision": "2026-10-24.68",
|
||||
"repository_base": "b7aeca4",
|
||||
"plan_status": "thirty_first_wave_validated_awaiting_commit",
|
||||
"plan_status": "thirty_second_wave_validated_awaiting_commit",
|
||||
"execution_authorized": true,
|
||||
"execution_scope": {
|
||||
"authorized_by": "User: commit and continue; accepted durable chronological workflow committed abd1c5b83d55ad49b562408cb3a87a1c7b7f952e",
|
||||
"authorized_by": "User: commit and continue; accepted walk-forward workflow committed 3ed7b98f7cf0e7e1da8f00fc990c3511bd875ce9",
|
||||
"tasks": ["R08"],
|
||||
"permissions": [
|
||||
"R08 bounded walk-forward series: freeze all ordered recipes/common inputs, atomically admit existing training windows, reuse per-window actions and save an immutable reset-segment report with integrated web workflow"
|
||||
"Complete R08 bounded fee/slippage sensitivity as an existing experiment mode with immutable fixed-template inputs, Rust simulation and integrated web results/retry/reproduction"
|
||||
],
|
||||
"excluded": [
|
||||
"performance_profiling_or_optimization",
|
||||
|
|
@ -25,7 +25,9 @@
|
|||
"historical_binary_provisioning",
|
||||
"cross_experiment_ranking",
|
||||
"strategy_performance_conclusions",
|
||||
"cost_sensitivity_execution"
|
||||
"cost_parameter_cartesian_optimization",
|
||||
"cost_source_run_selector",
|
||||
"cost_walk_forward_joint_studies"
|
||||
],
|
||||
"pending_policy_decisions": [
|
||||
"ADR-007",
|
||||
|
|
@ -1428,7 +1430,7 @@
|
|||
"epic": "E6",
|
||||
"priority": "P1",
|
||||
"severity": "High",
|
||||
"status": "in_progress",
|
||||
"status": "review",
|
||||
"dependencies": ["R06"],
|
||||
"decision_dependencies": ["ADR-006"],
|
||||
"task_file": "backlog/tasks/R08.md",
|
||||
|
|
@ -1443,34 +1445,36 @@
|
|||
"completed_commit": null,
|
||||
"blocker": null,
|
||||
"release_gates": [],
|
||||
"integration_state": "component_validated_uncommitted",
|
||||
"integration_base": "abd1c5b83d55ad49b562408cb3a87a1c7b7f952e",
|
||||
"integration_state": "validated_uncommitted",
|
||||
"integration_base": "3ed7b98f7cf0e7e1da8f00fc990c3511bd875ce9",
|
||||
"worktree": "/home/boki/repos/stock-bot",
|
||||
"execution_component": "Bounded repeated walk-forward windows and immutable independent reset-segment reports",
|
||||
"execution_component": "Bounded immutable fee/slippage diagnostics in the existing experiment lifecycle",
|
||||
"component_exclusions": [
|
||||
"bounded cost-sensitivity execution",
|
||||
"completed-source-run cost studies",
|
||||
"cost-by-parameter or cost-by-window searches",
|
||||
"findings/regime evidence integration"
|
||||
],
|
||||
"reviewed_by": "/root/r04_review",
|
||||
"verification_reference": "ROADMAP.md#thirty-first-wave-handoff--2026-10-24",
|
||||
"review_notes": "Independent backend/frontend/root integration reviews accepted exact snapshots. Native all-window admission, immutable reports, no future suffix leakage, cancellation and receipt races, existing flow preservation and complete browser lifecycle pass. Full R08 remains partial for bounded cost sensitivity.",
|
||||
"verification_reference": "ROADMAP.md#thirty-second-wave-handoff--2026-10-24",
|
||||
"review_notes": "Full supported R08 scope independently accepted: chronological preflight, durable fixed-winner validation, repeated reset-segment walk-forward and bounded template cost sensitivity. All root repository/PostgreSQL/Chromium gates pass. Awaiting owner acceptance/commit; unsupported trained/nonzero-horizon models remain explicit refusals, not missing purge infrastructure.",
|
||||
"implementation_slices": [
|
||||
{
|
||||
"owner": "/root/r12_backend",
|
||||
"worktree": "/tmp/stock-bot-wave31.QqUT6Z/backend",
|
||||
"scope": "SQL25 header/membership guards, walk-forward service/preparation/routes, narrow transaction-scoped chronological admission/report reuse, new pure/API/PostgreSQL tests"
|
||||
"worktree": "/tmp/stock-bot-wave32.Dg3iwI/backend",
|
||||
"scope": "SQL26, cost preview/request helpers, existing experiments service/routes and narrow v1 chrono reader, pure/API/native PostgreSQL tests"
|
||||
},
|
||||
{
|
||||
"owner": "/root/r12_frontend",
|
||||
"worktree": "/tmp/stock-bot-wave31.QqUT6Z/frontend",
|
||||
"scope": "Explicit window editor with shared submission ownership, series detail/list/report UI and focused regressions"
|
||||
"worktree": "/tmp/stock-bot-wave32.Dg3iwI/frontend",
|
||||
"scope": "Existing editor cost mode, kind-aware detail/list/inputs/retry decoder and focused UI tests"
|
||||
},
|
||||
{
|
||||
"owner": "/root",
|
||||
"scope": "Shared DTO/export and fixture, migration registry/old fixture chains, App/index composition, actual native browser lifecycle, final gates and planning"
|
||||
"scope": "Shared DTO/export, old migration chains/registry, actual native browser lifecycle, integration gates and planning"
|
||||
}
|
||||
],
|
||||
"partial_commit": "abd1c5b83d55ad49b562408cb3a87a1c7b7f952e"
|
||||
"partial_commit": "3ed7b98f7cf0e7e1da8f00fc990c3511bd875ce9",
|
||||
"completion_scope": "Deterministic unfitted registered strategies; chronological selection and immutable reports; bounded reset-window series; fixed-template fee/slippage diagnostics."
|
||||
},
|
||||
{
|
||||
"id": "R09",
|
||||
|
|
@ -7031,7 +7035,7 @@
|
|||
"Performance remains paused. Full R08 stays partial for cost sensitivity; R09 and candidate/AI/multi-asset/default/trading activation gates unchanged."
|
||||
],
|
||||
"thirty_first_wave_validation": {
|
||||
"state": "component_validated_uncommitted",
|
||||
"state": "component_committed",
|
||||
"scope": "R08 bounded repeated walk-forward windows and immutable independent reset-segment reports; full R08 remains in_progress for cost sensitivity and R09 blocked",
|
||||
"integration_base": "abd1c5b83d55ad49b562408cb3a87a1c7b7f952e",
|
||||
"log_directory": "/tmp/stock-bot-wave31.QqUT6Z",
|
||||
|
|
@ -7142,6 +7146,118 @@
|
|||
"Performance work, R09 evidence integration and candidate/AI/multi-asset/default/paper/live activation gates remain unchanged."
|
||||
],
|
||||
"fixture_cleanup": "Removed both exact disposable PostgreSQL/Redis containers after all final gates; development services untouched. Worktrees and local evidence retained.",
|
||||
"commits": "Previous wave committed as abd1c5b. This validated component remains uncommitted; no push or PR."
|
||||
"commits": "Committed as 3ed7b98f7cf0e7e1da8f00fc990c3511bd875ce9 following owner authorization. No push or PR.",
|
||||
"completed_commit": "3ed7b98f7cf0e7e1da8f00fc990c3511bd875ce9"
|
||||
},
|
||||
"thirty_second_wave": ["R08"],
|
||||
"thirty_second_wave_base": "3ed7b98f7cf0e7e1da8f00fc990c3511bd875ce9",
|
||||
"thirty_second_wave_notes": [
|
||||
"One existing research_experiments row with cost-sensitivity-preview/v1; no new table, run column, report lifecycle or scheduler.",
|
||||
"Source is current approved template through ordinary empty-grid preview. Automatic unchanged-cost baseline plus1–99 explicit normalized distinct fee/slippage pairs; fixed parameters and every other financial/data/build policy.",
|
||||
"Existing Rust engine reruns each scenario; costs can change funding/fills/decisions. No adjusted-P&L shortcut, ranking or universal monotonicity claim.",
|
||||
"SQL26 preserves v1 callable and old SQL22–25 files; one expected-request helper used by existing run/retry guards. All other ordinary/reproduction guards preserved.",
|
||||
"Web cost mode shares ordinary editor owner, list/detail/retry/history and exact receipt flow. Strict v1 chronological/walkforward decoders remain separate.",
|
||||
"R08 completion subject to native cost/funding/baseline parity, SQL/adversarial/upgrade, retry/reproduction and real browser gates. R09 also depends on partial R07; no blanket readiness claim.",
|
||||
"Performance and candidate/AI/multiasset/default/paper/live activation remain paused or gated."
|
||||
],
|
||||
"thirty_second_wave_validation": {
|
||||
"state": "validated_uncommitted",
|
||||
"scope": "Completes supported R08 implementation; owner acceptance/commit pending. R09 also depends on partial R07.",
|
||||
"integration_base": "3ed7b98f7cf0e7e1da8f00fc990c3511bd875ce9",
|
||||
"log_directory": "/tmp/stock-bot-wave32.Dg3iwI",
|
||||
"source_archive": "/tmp/stock-bot-wave32.Dg3iwI/validated-source.tar.gz",
|
||||
"source_archive_sha256": "f8e1f155b91eaaec95c7e8d7e60c7ccbb3700f35976b84af25b3faeda431dc34",
|
||||
"source_files": {
|
||||
"apps/stock/config/package.json": "e55394c7e8097f83ce1a063e3d14ec7f8a3018d8db67fa2b711cbd76072110cc",
|
||||
"apps/stock/config/src/contracts/cost-sensitivity.ts": "b813d61402097f113d2c546dc82b7f3eee7c0eeffde2d3374849fd38cb77ace3",
|
||||
"apps/stock/config/src/contracts/experiments.ts": "a815acbd53f51a1f30c21f877df45b298033336a40957abd1f5b5bfacb4bfa9d",
|
||||
"apps/stock/web-api/src/migrations/migration-runner.ts": "3b0287922e9bc01570c23684ac3d801ee4b932bd23923cc06ff42964625b359c",
|
||||
"apps/stock/web-api/src/routes/experiments.routes.ts": "8bf96923e11a36bfc090c4610622c39403c13a6e057db6363d4989a5c167fa5f",
|
||||
"apps/stock/web-api/src/services/chronological-validation.service.ts": "c744a370353c550ecaa3ad57cdcd333604d3a1e3c0cec1cce4d4168beac18294",
|
||||
"apps/stock/web-api/src/services/cost-sensitivity-input.ts": "aa6c022736f5e03fca5a08dbc0e69c4e61b82e43c530edcfd60fe7e5f17ed2e9",
|
||||
"apps/stock/web-api/src/services/experiments.service.ts": "ff5a73ceae61873d5aeaabe5167386c6287dd4f1348baa4eac9819c5626ff9b4",
|
||||
"apps/stock/web-app/src/features/experiments/ExperimentDetailPage.tsx": "9aef5c87fac0148d6f7ccc4bfdf8fba20589ba62e0a0eadd6e1533f743e4a1e9",
|
||||
"apps/stock/web-app/src/features/experiments/ExperimentListPage.tsx": "77454cbbebdf8ed7586b7836cc7f5b4cfcbc1afbd900e2a57c339c6de99d0263",
|
||||
"apps/stock/web-app/src/features/experiments/components/ExperimentEditor.tsx": "f25645212eb324ff2f282c25eb23ff0580b93d6b7f0d22ff33abcf51897177ee",
|
||||
"apps/stock/web-app/src/features/experiments/components/ExperimentInputs.tsx": "2d8dddfca2ff3eda66f759ff727292288a856198466960d57823f25fb4a70162",
|
||||
"apps/stock/web-app/src/features/experiments/components/ExperimentTrialRecovery.tsx": "921dec1609c4ba6d19fd13457f55ed68cbf264c6ecc6d2231fb7f197f0bf60cb",
|
||||
"apps/stock/web-app/src/features/experiments/services/experimentApi.ts": "1e2c8be957a7c0af1a0cb88e9ada6edc5f306907063d0ea1e1bdc624363fc622",
|
||||
"database/postgres/init/26-cost-sensitivity.sql": "a9c8c2b698507d5ed12aa01548d9319111437c84126a8c6d03d1e709d7c47bae",
|
||||
"test/e2e/fixture.ts": "4b83bbec2733fb95d75d62325d8b159ac035f52ec25663dfd397dd31f44cdd95",
|
||||
"test/e2e/workbench.test.ts": "75b4cd7c8af1ccce9883b3d7161e28040aa6c1c0ab03dcf17dfd7a8615f06232",
|
||||
"test/integration/cost-sensitivity-api.test.ts": "5c9156210a9292c659472e51a51753edc5db00330e826d187c572b6928f4f12d",
|
||||
"test/integration/cost-sensitivity-ui.test.tsx": "04bf1eefd9f2462de847f28f8e53d9a39147f48e896179fc3cb58116dc0c69b6",
|
||||
"test/integration/cost-sensitivity.test.ts": "4c1cebc37ec469597745cef8290b3ef4b6e63a31fd2767608ac88ae123fdd3e6",
|
||||
"test/integration/experiment-retries-ui.test.tsx": "07517358d50eb94d477e8f966605714fc9dde012d8f58fdd75cfb41715fa9d32",
|
||||
"test/postgres/canonical-durable-backtest.test.ts": "061ac5de9fc69d64f7a1fba0d350db909a3a4408068abf8cf14f598004cb6c18",
|
||||
"test/postgres/canonical-research.test.ts": "b1275d034cb817bbafe9fbd7a36d0d35be698855f3cbfae88bec4fe86e3a0106",
|
||||
"test/postgres/catalog-backtest-drafts.test.ts": "66ebe25f82fea58664a0a9c0707e4eab1749ef0904e19ecda11d8567a6a768c6",
|
||||
"test/postgres/chronological-validation-durable.test.ts": "e961f4b16979563c7495bf314b13aa2e7c27caa2d77aa9ae04e521e3fa4ffb92",
|
||||
"test/postgres/chronological-validation.test.ts": "27c72d9d41b665396b5b253429f0ab67c4deb3feb4d67d5fd80a92b0a6c096b2",
|
||||
"test/postgres/cost-sensitivity.test.ts": "187fe117b85266b19f6f3c7a9e515020419053166c8b34cda98d6f6cef7e18d2",
|
||||
"test/postgres/dataset-catalog.test.ts": "e09f3ac167aabfc825b31728b339fc7c0ac25be02e96169092643efdbf1635c9",
|
||||
"test/postgres/durable-backtest.test.ts": "6820c928541ad1c64b2cdb3e80eb16551813955dea4e33122f36be4ee2b24819",
|
||||
"test/postgres/experiment-retries.test.ts": "c152655d8a3a03180f3b0a4bb8557143482bf7f153119763fcb4a34f6528cc2a",
|
||||
"test/postgres/experiments.test.ts": "d339f36502ced9f8237d695699a7226c79b681ca8386993522032b54ff72bbd1",
|
||||
"test/postgres/migration-runner.test.ts": "4614b1df7663c22dc8d9902950ee7c3c6ed64ce45ec9fcdef9f397a80dd59a3a",
|
||||
"test/postgres/research-retention.test.ts": "926b138534f7f099f0934f64cb0fae572a06fa1981a5ddba0e71bccd5c2fd3a2",
|
||||
"test/postgres/research-runtime-isolation.test.ts": "3e468bb341186544d694f495231fb9e03a91b6ddf62282fa868d0460588c6c91",
|
||||
"test/postgres/research-workspace.test.ts": "c051507fdecf6d58435f716fcf7a84a5415d4b74014656a49adbfaabdc723cae",
|
||||
"test/postgres/run-reproduction.test.ts": "8b894282fa6512a6d1adf7c2da9b1a14d62c2294d9245a647dc42a5ef342a592",
|
||||
"test/postgres/walk-forward.test.ts": "7d6fd3f4c41bad6ea03b2d6214348c90dcf4e6a636df57ec8e851d5adc11d480"
|
||||
},
|
||||
"checks": [
|
||||
{
|
||||
"command": "CARGO_BUILD_JOBS=2 bun run check",
|
||||
"log": "integration-check.log",
|
||||
"result": "Passed every repository gate: secret audit/build/types/contracts/lint; 93 tooling, 43 utility, 44 calculation, 926 integration and 150 Rust tests; zero failures. Four preexisting Rust cases remain ignored."
|
||||
},
|
||||
{
|
||||
"command": "bun run test:postgres",
|
||||
"log": "integration-postgres-final.log",
|
||||
"result": "224 passed, 1967 assertions, zero failures against disposable PostgreSQL and Redis DB15. All current-schema fixture chains include SQL26; intentional historical-upgrade chains remain scoped."
|
||||
},
|
||||
{
|
||||
"command": "bun run test:e2e",
|
||||
"log": "integration-browser-final.log",
|
||||
"result": "15 passed, 457 assertions, zero failures using same-origin production build, Chromium and native release engine."
|
||||
},
|
||||
{
|
||||
"command": "Strict authored-test TypeScript and explicit authored source/test ESLint",
|
||||
"logs": ["root-tests-types-final.log", "authored-lint-final.log"],
|
||||
"result": "Passed, including all new tests and modified browser/retry UI tests."
|
||||
},
|
||||
{
|
||||
"command": "Changed-source Prettier, git diff --check, manifest references and dependency DAG",
|
||||
"logs": ["source-format-final.log"],
|
||||
"result": "Passed; all55 unique task references exist and implementation dependency graph is acyclic."
|
||||
}
|
||||
],
|
||||
"review": {
|
||||
"independent_reviewer": "/root/r04_review",
|
||||
"backend": "Accepted exact eight-file source/test overlay; independent pure/API7/77, reviewed native PostgreSQL9/86 including hand-derived fees/slippage/equity/funding, baseline parity, original-policy retry/reproduction, SQL26 guard-body comparison, atomicity and races.",
|
||||
"backend_archive": "/tmp/stock-bot-wave32.Dg3iwI/backend-final.tar",
|
||||
"backend_archive_sha256": "adfd6aa464f5251ec18b47a060a0ce94d1c96295f28c139a088e3208783c8227",
|
||||
"frontend": "Accepted exact eight-file overlay; independent cost/retry74/317; owner combined UI322/1438. Cost mode shares ordinary owner and existing detail/recovery lifecycle.",
|
||||
"frontend_archive": "/tmp/stock-bot-wave32.Dg3iwI/frontend-final.tar.gz",
|
||||
"frontend_archive_sha256": "d7eae27357a7c5bdcb55d051ab2f403ddf17c5b96953ed4a88b53873810a411e",
|
||||
"root": "Read-only integration review caught two missing SQL26 fixture-chain entries, corrected before final full gates. Shared DTO and actual native browser approved, including exact native financial policy/identity after template edits.",
|
||||
"task_completion": "Reviewer checked all R08 acceptance across waves29–32; no completed-source selector, joint cost/window optimizer or trainable-model framework is required to close supported scope."
|
||||
},
|
||||
"engine": {
|
||||
"debug_sha256": "75e33ffdd1e2738537879e62243a9d8f63665864835a58c46087bb4b78f274ff",
|
||||
"release_sha256": "ef00eed556f5c32332d36a9a00ef710682e90deb00b54552e4b5c8bfdfbe8103",
|
||||
"note": "Existing authoritative Rust engine unchanged; release restored before final database/browser gates."
|
||||
},
|
||||
"limits": [
|
||||
"One current-approved saved template, fixed parameters and retained dataset; automatic original-cost baseline plus1–99 explicit normalized distinct fee/slippage pairs.",
|
||||
"Template diagnostics only; not a completed-source-run study or heldout/OOS validation. No joint cost×parameter/window search, ranking or best-cost selection.",
|
||||
"Only feeRate and slippageRate vary. Spread, latency, participation, all other risk/capital/ownership, seed, package/build/data and analytics policy remain fixed.",
|
||||
"Costs can alter affordability, fills and future strategy decisions; no general monotonic-profit claim or TS adjusted-P&L calculation.",
|
||||
"Chronological/walk-forward models remain deterministic-unfitted with zero label horizon. Unsupported nonzero/missing horizon/trainable inputs reject; no purge/fitting infrastructure is claimed.",
|
||||
"Performance work stays paused. R07 comparison remains partial and R09 retains its R07 dependency; candidate/AI/multiasset/default/paper/live gates unchanged."
|
||||
],
|
||||
"fixture_cleanup": "Both exact disposable PostgreSQL and Redis containers removed after all final gates. Development services untouched; isolated worktrees and local evidence retained.",
|
||||
"commits": "Wave31 committed3ed7b98. Wave32 remains uncommitted; no push or PR."
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -12,7 +12,7 @@ Scheduling source of truth: [manifest entry R08](../manifest.json). No task is a
|
|||
|
||||
## Intended behavior and implementation scope
|
||||
|
||||
First implement bounded chronological parameter selection and nonoverlapping walk-forward recipes for deterministic registered strategies. Explicit warmup and evaluation windows; each validation segment starts from its declared initial capital and empty positions with warmed indicators, not carried money/state. Aggregate segment returns as a labelled reset-segment research series, never claim one continuous tradable equity curve. Parameter sensitivity reuses the existing bounded grid. Cost sensitivity needs a separate explicit immutable financial-policy admission contract; costs are not strategy parameters and must not mutate saved templates. Reject trainable/overlapping-label models until their fit-artifact and declared horizon/embargo contracts are supplied; do not invent general ML infrastructure for SMA.
|
||||
First implement bounded chronological parameter selection and nonoverlapping walk-forward recipes for deterministic registered strategies. Explicit warmup and evaluation windows; each validation segment starts from its declared initial capital and empty positions with warmed indicators, not carried money/state. Present ordered segment returns as a labelled reset-segment research series; do not compound, average risk-adjusted metrics or claim one continuous tradable equity curve. Parameter sensitivity reuses the existing bounded grid. Cost sensitivity needs a separate explicit immutable financial-policy admission contract; costs are not strategy parameters and must not mutate saved templates. Reject trainable/overlapping-label models until their fit-artifact and declared horizon/embargo contracts are supplied; do not invent general ML infrastructure for SMA.
|
||||
|
||||
Persist the immutable validation manifest/report as experiment-owned JSON on the R06 experiment (or a focused child row if immutability requires it), keyed by experiment/report version and containing every contributing run ID, selection rule and segment policy. This is not R03 research-findings storage. Reopening an experiment must recover the same report; new inputs require a new experiment/report identity.
|
||||
|
||||
|
|
@ -109,8 +109,22 @@ The web provides explicit windows, preview, submission, member links, report sav
|
|||
|
||||
### Validated walk-forward handoff
|
||||
|
||||
The repeated-window component is independently accepted and `component_validated_uncommitted`. Forty-one source/test/config files preserve the existing Rust financial engine, worker/run/outbox model and SQL22–24 behavior. New SQL25 headers and exact train-root membership guards keep all-window admission atomic; full native evidence is checked again before sealing an immutable ordered reset-segment report. Member cancellation stays local; series cancellation prevents new member actions without changing completed evidence.
|
||||
The repeated-window component is independently accepted and committed as `3ed7b98`. Forty-one source/test/config files preserve the existing Rust financial engine, worker/run/outbox model and SQL22–24 behavior. New SQL25 headers and exact train-root membership guards keep all-window admission atomic; full native evidence is checked again before sealing an immutable ordered reset-segment report. Member cancellation stays local; series cancellation prevents new member actions without changing completed evidence.
|
||||
|
||||
The web supports explicit 2–10-window recipes, full promised-run counts, synchronous shared submission ownership, member actions through existing pages, and saved report reopen. Native tests prove future-suffix independence, unchanged old migrations/receipts/leases, partial-admission rollback, actual lock contention, finalization receipt races and rejection of corrupted financial/analytics evidence. Repository test gates pass (882 integration /150 Rust), PostgreSQL/Redis 215 tests /1881 assertions, Chromium 14 workflows /412 assertions; final source and authored-test lint/types pass. Exact commands, formatting-only corrections and old fixture lint limitations are recorded in `manifest.json` → `thirty_first_wave_validation`.
|
||||
|
||||
Full R08 remains partial for bounded cost sensitivity; R09 remains blocked. Next scope should define supported fee/slippage scenarios as immutable execution-policy inputs and reuse canonical runs/results, without template mutation, strategy-parameter hacks, a second simulator or a window×cost scheduler. No regime/finding integration, performance work or AI/default/trading activation is included.
|
||||
|
||||
## Authorized cost-sensitivity component — 2026-10-24
|
||||
|
||||
Complete the remaining bounded-cost diagnostic requirement using one existing experiment row with a versioned cost manifest. Its baseline is the current approved saved template and empty parameter grid; trial 0 preserves original costs, while1–99 explicit normalized distinct fee/slippage pairs vary only those two canonical rate fields. Every trial reruns Rust with independent account state. Preserve all other strategy/data/build/risk/execution/analysis inputs. Costs can change fills and funding decisions, so do not subtract estimates from old P&L or assume monotonic returns.
|
||||
|
||||
Reuse the existing editor ordinary owner, list/detail/retry/history and receipt APIs; no new header/report/scheduler. Preserve strict v1 validation sources, ordinary parameter keys, old SQL22–25 and all reproduction guards. Add SQL26 version dispatch and one expected-request helper for run/retry insertion. Require native baseline economic parity, controlled fee/slippage/funding fixtures, original-policy retry/reproduction after template edits, direct SQL/atomicity/receipt/cancel races, upgrade preservation and actual browser reopen. This template study makes no heldout/OOS claim; a completed-source selector and joint cost×parameter/window studies are excluded.
|
||||
|
||||
### Validated full-task handoff — 2026-10-24
|
||||
|
||||
Full supported R08 is independently reviewed and `validated_uncommitted`, awaiting owner acceptance/commit. Waves 29–31 provide frozen chronological input preparation, durable fixed-winner selection, immutable reports and bounded nonoverlapping heldout reset-window series. Wave 32 closes bounded cost diagnostics with one existing experiment type, automatic original-cost baseline and 1–99 explicit fee/slippage pairs. Fixed parameters/data/capital/other risk/build settings and the authoritative Rust engine are preserved; existing retry/reproduction and web workbench flows are reused.
|
||||
|
||||
Every repository gate passed (926 integration /150 Rust), final PostgreSQL/Redis 224 tests /1967 assertions and Chromium 15 workflows /457 assertions. Exact sources, independent reviews, controlled native fee/slippage/funding oracles, baseline economic parity, SQL/admission/recovery proofs and root browser evidence: `manifest.json` → `thirty_second_wave_validation`.
|
||||
|
||||
The unsupported-model acceptance is implemented as explicit rejection of trained/nonzero/missing-horizon inputs, not general purge/embargo fitting. Template cost diagnostics do not claim heldout/OOS validation or automatic ranking. Completed-source selectors, cost×parameter/window studies and fitted-model infrastructure remain optional future scope. No performance work, AI/candidate or trading/default activation occurred. R09 also depends on partial R07; next non-performance work is cross-experiment comparison, with table measurements still paused.
|
||||
|
|
|
|||
|
|
@ -297,6 +297,7 @@ export async function fixture(browser: Browser, native = false) {
|
|||
'23-experiment-retries.sql',
|
||||
'24-chronological-validation.sql',
|
||||
'25-walk-forward.sql',
|
||||
'26-cost-sensitivity.sql',
|
||||
]) {
|
||||
await pool.query(
|
||||
readFileSync(new URL(`../../database/postgres/init/${name}`, import.meta.url), 'utf8')
|
||||
|
|
|
|||
|
|
@ -11,6 +11,11 @@ import type {
|
|||
ChronologicalValidationPreview,
|
||||
ChronologicalValidationReport,
|
||||
} from '@stock-bot/stock-config/chronological-validation';
|
||||
import {
|
||||
costScenarioSchema,
|
||||
type CostSensitivityDetail,
|
||||
type CostSensitivityPreview,
|
||||
} from '@stock-bot/stock-config/cost-sensitivity';
|
||||
import type {
|
||||
ExperimentDetail,
|
||||
ExperimentPreview,
|
||||
|
|
@ -49,6 +54,158 @@ afterAll(async () => {
|
|||
});
|
||||
const fixture = (native = false) => createFixture(browser, native);
|
||||
|
||||
test('cost_sensitivity_freezes_policy_runs_native_scenarios_and_reopens_existing_experiment_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 version = (await f.seedCatalog()).find(
|
||||
item => item.package.program.strategyId === 'sma_crossover'
|
||||
)!;
|
||||
await f.request(`/api/v2/strategy-versions/${version.id}/reviews`, 'POST', {
|
||||
decision: 'approve',
|
||||
reason: 'Reviewed native cost sensitivity fixture',
|
||||
});
|
||||
const definition = {
|
||||
name: 'Fixed cost study template',
|
||||
strategy: 'catalog',
|
||||
strategyVersionId: version.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}/experiments?backtestId=${backtest.id}`);
|
||||
await f.page.getByLabel('Saved backtest').selectOption(backtest.id);
|
||||
await f.page
|
||||
.getByLabel('Experiment name', { exact: true })
|
||||
.fill('Fixed fee and slippage study');
|
||||
await f.page.getByLabel('Experiment type').selectOption({ label: 'Cost sensitivity' });
|
||||
expect(await f.page.getByLabel('Parameter grid').isVisible()).toBe(false);
|
||||
await f.page.getByLabel('Scenario 1 fee rate', { exact: true }).fill('0.02');
|
||||
await f.page.getByLabel('Scenario 1 slippage rate', { exact: true }).fill('0');
|
||||
await f.page.getByRole('button', { name: 'Add cost scenario', exact: true }).click();
|
||||
await f.page.getByLabel('Scenario 2 fee rate', { exact: true }).fill('0.01');
|
||||
await f.page.getByLabel('Scenario 2 slippage rate', { exact: true }).fill('0.02');
|
||||
const preparing = f.page.waitForResponse(response =>
|
||||
response.url().endsWith('/api/v2/experiments/cost-sensitivity/preview')
|
||||
);
|
||||
await f.page.getByRole('button', { name: 'Preview experiment', exact: true }).click();
|
||||
const prepared = await preparing;
|
||||
expect(prepared.status()).toBe(200);
|
||||
const { preview } = (await prepared.json()) as { preview: CostSensitivityPreview };
|
||||
expect(preview.version).toBe('cost-sensitivity-preview/v1');
|
||||
expect(preview.source.input.grid).toEqual({});
|
||||
expect(preview.candidates.map(candidate => candidate.costs)).toEqual([
|
||||
{ feeRate: '0.01000000', slippageRate: '0.00000000' },
|
||||
{ feeRate: '0.02000000', slippageRate: '0.00000000' },
|
||||
{ feeRate: '0.01000000', slippageRate: '0.02000000' },
|
||||
]);
|
||||
expect(
|
||||
preview.candidates.every(
|
||||
candidate =>
|
||||
JSON.stringify(candidate.parameters) === JSON.stringify(definition.strategyParameters)
|
||||
)
|
||||
).toBe(true);
|
||||
expect((await f.pool.query('SELECT * FROM research_experiments')).rowCount).toBe(0);
|
||||
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/cost-sensitivity')
|
||||
);
|
||||
await f.page.getByRole('button', { name: 'Confirm experiment', exact: true }).click();
|
||||
const submitted = await submitting;
|
||||
expect(submitted.status()).toBe(202);
|
||||
const { experiment } = (await submitted.json()) as { experiment: CostSensitivityDetail };
|
||||
expect(submitted.headers().location).toBe(`/api/v2/experiments/${experiment.id}`);
|
||||
expect(experiment.preview).toEqual(preview);
|
||||
expect(experiment.kind).toBe('cost-sensitivity');
|
||||
expect(experiment.trialCount).toBe(3);
|
||||
expect((await f.pool.query('SELECT * FROM backtest_dispatch')).rowCount).toBe(3);
|
||||
await f.request(`/api/v2/backtests/${backtest.id}`, 'PUT', {
|
||||
...definition,
|
||||
name: 'Edited after cost admission',
|
||||
strategyParameters: { fastPeriod: 1, slowPeriod: 2 },
|
||||
initialCapital: 20000,
|
||||
config: {
|
||||
...definition.config,
|
||||
canonical: { ...canonicalSettings, feeRate: '0.3', slippageRate: '0.4' },
|
||||
},
|
||||
});
|
||||
f.dispatcher.start();
|
||||
await until(
|
||||
async () =>
|
||||
(await f.pool.query("SELECT count(*)::int AS n FROM runs WHERE status='completed'")).rows[0]
|
||||
.n === 3,
|
||||
'all three fixed-input cost scenarios complete through the native runner'
|
||||
);
|
||||
await f.page.getByRole('button', { name: 'Refresh experiment', exact: true }).click();
|
||||
await visible(f.page, /completed: 3/);
|
||||
expect(await f.page.getByRole('cell', { name: 'Comparable', exact: true }).count()).toBe(3);
|
||||
const outcomes = f.page.locator('section[aria-label="Experiment trial outcomes"] tbody tr');
|
||||
expect(await outcomes.count()).toBe(3);
|
||||
for (const [index, trial] of experiment.trials.entries()) {
|
||||
const result = (await f.request(`/api/v2/runs/${trial.runId}/results`)) as CanonicalRunResult;
|
||||
const expected = structuredClone(preview.request);
|
||||
expected.runId = trial.runId!;
|
||||
expected.policy.matching.risk.ledger.sessionId = trial.runId!;
|
||||
expected.policy.matching.risk.ledger.accountId = `research:${trial.runId}`;
|
||||
const costs = costScenarioSchema.parse(trial.costs);
|
||||
expected.policy.matching.risk.feeRate = costs.feeRate;
|
||||
expected.policy.matching.slippageRate = costs.slippageRate;
|
||||
expect(result.request).toEqual(expected);
|
||||
expect(result.financialEngine).toBe('rust');
|
||||
expect(result.financial.policy).toEqual(expected.policy);
|
||||
expect(result.financial.identity).toEqual({
|
||||
version: 1,
|
||||
sessionId: trial.runId!,
|
||||
datasetHash: expected.datasetHash,
|
||||
});
|
||||
const text = await outcomes.nth(index).innerText();
|
||||
expect(text).toContain(index === 0 ? 'Baseline' : `Scenario ${index}`);
|
||||
expect(text).toContain(trial.costs.feeRate);
|
||||
expect(text).toContain(trial.costs.slippageRate);
|
||||
expect(text).toContain(String(result.analytics.metrics.totalReturn));
|
||||
}
|
||||
await f.request(`/api/v2/backtests/${backtest.id}/archive`, 'POST', { archived: true });
|
||||
const replay = (await f.request(
|
||||
'/api/v2/experiments/cost-sensitivity',
|
||||
'POST',
|
||||
submitted.request().postDataJSON(),
|
||||
{ 'Idempotency-Key': submitted.request().headers()['idempotency-key']! }
|
||||
)) as { experiment: CostSensitivityDetail };
|
||||
expect(replay.experiment.id).toBe(experiment.id);
|
||||
expect(replay.experiment.preview).toEqual(preview);
|
||||
expect((await f.pool.query('SELECT * FROM runs')).rowCount).toBe(3);
|
||||
await f.page.reload();
|
||||
await visible(f.page, /completed: 3/);
|
||||
await f.page.getByRole('link', { name: 'All experiments', exact: true }).click();
|
||||
await f.page.getByRole('link', { name: 'Fixed fee and slippage study', exact: true }).click();
|
||||
await visible(f.page, /completed: 3/);
|
||||
await f.page
|
||||
.locator(`a[href="/backtests/${backtest.id}/run/${experiment.trials[2]!.runId}"]`)
|
||||
.click();
|
||||
await visible(f.page, 'Canonical research result');
|
||||
expect(f.historicalDataReads).toEqual([]);
|
||||
expect(f.unexpectedNetwork).toEqual([]);
|
||||
} finally {
|
||||
await f.close();
|
||||
}
|
||||
});
|
||||
|
||||
test('walk_forward_freezes_all_windows_runs_native_members_and_reopens_reset_report_browser', async () => {
|
||||
const f = await fixture(true);
|
||||
f.page.on('dialog', dialog => void dialog.accept());
|
||||
|
|
|
|||
118
test/integration/cost-sensitivity-api.test.ts
Normal file
118
test/integration/cost-sensitivity-api.test.ts
Normal file
|
|
@ -0,0 +1,118 @@
|
|||
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 { createExperimentRoutes } from '../../apps/stock/web-api/src/routes/experiments.routes';
|
||||
|
||||
const tokens = {
|
||||
operator: 'validation-admin-fixture-not-a-real-secret-1234',
|
||||
service: 'validation-service-fixture-not-a-real-secret-1234',
|
||||
read: 'validation-read-fixture-not-a-real-secret-1234',
|
||||
};
|
||||
const input = {
|
||||
backtestId: randomUUID(),
|
||||
name: 'Validation preview',
|
||||
scenarios: [{ feeRate: '0', slippageRate: '0' }],
|
||||
};
|
||||
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 ? { 'Idempotency-Key': key } : {}),
|
||||
},
|
||||
...(body === undefined ? {} : { body }),
|
||||
});
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
const id = randomUUID(),
|
||||
previewHash = 'a'.repeat(64);
|
||||
|
||||
const actions = [
|
||||
['/cost-sensitivity/preview', JSON.stringify(input)],
|
||||
['/cost-sensitivity', JSON.stringify({ ...input, previewHash })],
|
||||
];
|
||||
describe('cost-sensitivity HTTP gates', () => {
|
||||
test('cost mutation requires verified operator/service even in disabled auth mode', async () => {
|
||||
for (const mode of ['enabled', 'disabled', 'absent'] as const) {
|
||||
const f = fixture(mode);
|
||||
for (const [path, body] of actions) {
|
||||
expect((await f.request(path, 'POST', body, undefined, 'key')).status).toBe(401);
|
||||
}
|
||||
expect(f.database.transaction.mock.calls).toHaveLength(0);
|
||||
}
|
||||
const f = fixture();
|
||||
for (const [path, body] of actions) {
|
||||
expect((await f.request(path, 'POST', body, 'read', 'key')).status).toBe(403);
|
||||
}
|
||||
expect((await f.request('', 'GET', undefined, 'read')).status).toBe(200);
|
||||
});
|
||||
test('strict mixed modes, costs, malformed JSON and missing receipt fail before storage', async () => {
|
||||
for (const [path, body, key] of [
|
||||
['/cost-sensitivity/preview', '{', 'key'],
|
||||
['/cost-sensitivity/preview', JSON.stringify({ ...input, grid: {} }), 'key'],
|
||||
[
|
||||
'/cost-sensitivity/preview',
|
||||
JSON.stringify({ ...input, scenarios: [{ feeRate: '0', slippageRate: '1' }] }),
|
||||
'key',
|
||||
],
|
||||
['/cost-sensitivity', JSON.stringify({ ...input, previewHash }), undefined],
|
||||
['/cost-sensitivity', JSON.stringify({ ...input, previewHash, mode: 'ordinary' }), 'key'],
|
||||
]) {
|
||||
const f = fixture();
|
||||
expect((await f.request(path, 'POST', body, 'operator', key)).status).toBe(400);
|
||||
expect(f.database.transaction.mock.calls).toHaveLength(0);
|
||||
}
|
||||
});
|
||||
test('correct operation routes return404 or sanitized500; existing detail/cancel routes stay shared', async () => {
|
||||
for (const role of ['operator', 'service'] as const) {
|
||||
const f = fixture();
|
||||
for (const [path, body] of actions) {
|
||||
expect((await f.request(path, 'POST', body, role, 'key')).status).toBe(404);
|
||||
}
|
||||
expect((await f.request(`/${id}`, 'GET', undefined, role)).status).toBe(404);
|
||||
}
|
||||
for (const error of [new Error('private database failure'), new z.ZodError([])]) {
|
||||
const f = fixture('enabled', async () => {
|
||||
throw error;
|
||||
});
|
||||
const response = await f.request(
|
||||
'/cost-sensitivity/preview',
|
||||
'POST',
|
||||
JSON.stringify(input),
|
||||
'operator'
|
||||
);
|
||||
expect(response.status).toBe(500);
|
||||
expect(await response.json()).toEqual({ error: 'Experiment operation unavailable' });
|
||||
}
|
||||
});
|
||||
});
|
||||
846
test/integration/cost-sensitivity-ui.test.tsx
Normal file
846
test/integration/cost-sensitivity-ui.test.tsx
Normal file
|
|
@ -0,0 +1,846 @@
|
|||
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 {
|
||||
costSensitivityInputSchema,
|
||||
type CostSensitivityDetail,
|
||||
type CostSensitivityPreview,
|
||||
} from '@stock-bot/stock-config/cost-sensitivity';
|
||||
import type {
|
||||
ExperimentDetail,
|
||||
ExperimentPreview,
|
||||
ExperimentTrial,
|
||||
ExperimentTrialRetry,
|
||||
} 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 || item.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: ExperimentPreview | CostSensitivityPreview = preview(),
|
||||
statuses: ExperimentTrial['status'][] = source.candidates.map(() => 'pending')
|
||||
): ExperimentDetail | CostSensitivityDetail {
|
||||
const trials: ExperimentTrial[] = source.candidates.map((item, index) => ({
|
||||
...item,
|
||||
runId: statuses[index] === 'missing' ? null : runId(index),
|
||||
attemptNumber: 0,
|
||||
retryCount: 0,
|
||||
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 {
|
||||
kind: source.version === 'cost-sensitivity-preview/v1' ? 'cost-sensitivity' : 'parameters',
|
||||
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,
|
||||
} as ExperimentDetail | CostSensitivityDetail;
|
||||
}
|
||||
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: [] });
|
||||
});
|
||||
}
|
||||
const costPath = '/api/v2/experiments/cost-sensitivity';
|
||||
const detailPath = `/api/v2/experiments/${experimentId}`;
|
||||
function costs(
|
||||
scenarios = [{ feeRate: '0.00100000', slippageRate: '0.00200000' }]
|
||||
): CostSensitivityPreview {
|
||||
const source = preview(1);
|
||||
source.input.grid = {};
|
||||
const input = costSensitivityInputSchema.parse({
|
||||
backtestId: source.input.backtestId,
|
||||
name: source.input.name,
|
||||
scenarios,
|
||||
});
|
||||
const pairs = [
|
||||
{
|
||||
feeRate: source.request.policy.matching.risk.feeRate,
|
||||
slippageRate: source.request.policy.matching.slippageRate,
|
||||
},
|
||||
...input.scenarios,
|
||||
];
|
||||
return {
|
||||
version: 'cost-sensitivity-preview/v1',
|
||||
previewHash: 'f'.repeat(64),
|
||||
input,
|
||||
source,
|
||||
request: structuredClone(source.request),
|
||||
dataset: structuredClone(source.dataset),
|
||||
candidates: pairs.map((costs, index) => ({
|
||||
index,
|
||||
trialKey: String(index + 3).padStart(64, '0'),
|
||||
parameters: { ...source.request.strategy.selection.parameters },
|
||||
costs,
|
||||
})),
|
||||
};
|
||||
}
|
||||
async function ready(value = costs()) {
|
||||
await list();
|
||||
await flush(() => {
|
||||
change('Experiment name', value.input.name);
|
||||
change('Experiment type', 'cost-sensitivity');
|
||||
});
|
||||
for (let i = 1; i < value.input.scenarios.length; i++) {
|
||||
await flush(() => button('Add cost scenario').click());
|
||||
}
|
||||
await flush(() =>
|
||||
value.input.scenarios.forEach((scenario, index) => {
|
||||
change(`Scenario ${index + 1} fee rate`, scenario.feeRate);
|
||||
change(`Scenario ${index + 1} slippage rate`, scenario.slippageRate);
|
||||
})
|
||||
);
|
||||
await flush(() => button('Preview experiment').click());
|
||||
await flush(() => reply(request(`${costPath}/preview`, 'POST'), { preview: value }));
|
||||
return value;
|
||||
}
|
||||
async function lose(item: Pending) {
|
||||
await flush(() => {
|
||||
item.settled = true;
|
||||
item.reject(new Error('Response lost'));
|
||||
});
|
||||
}
|
||||
async function showDetail(value?: ExperimentDetail | CostSensitivityDetail) {
|
||||
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('cost sensitivity in the existing experiment editor', () => {
|
||||
test('normalizes fraction spellings, previews baseline without writes, and submits the same frozen cost body', async () => {
|
||||
await list();
|
||||
await flush(() => {
|
||||
change('Experiment name', 'Trend study');
|
||||
change('Experiment type', 'cost-sensitivity');
|
||||
});
|
||||
expect(field('Scenario 1 fee rate').value).toBe('');
|
||||
expect(host.querySelector('textarea')).toBeNull();
|
||||
await flush(() => {
|
||||
change('Scenario 1 fee rate', '0.001');
|
||||
change('Scenario 1 slippage rate', '0.0020');
|
||||
});
|
||||
await flush(() => button('Preview experiment').click());
|
||||
const preparing = request(`${costPath}/preview`, 'POST');
|
||||
expect(preparing.body).toEqual(costs().input);
|
||||
expect(requests.filter(item => item.path === costPath && item.method === 'POST')).toHaveLength(
|
||||
0
|
||||
);
|
||||
await flush(() => reply(preparing, { preview: costs() }));
|
||||
expect(host.textContent).toContain('Baseline');
|
||||
expect(host.textContent).toContain('0.00100000');
|
||||
expect(host.textContent).toContain('2 trials');
|
||||
expect(host.textContent).toContain('Fixed half-spread rate:');
|
||||
const confirm = button('Confirm experiment');
|
||||
await flush(() => {
|
||||
confirm.click();
|
||||
confirm.click();
|
||||
});
|
||||
const post = request(costPath, 'POST');
|
||||
expect(post.body).toEqual({ ...costs().input, previewHash: costs().previewHash });
|
||||
expect(post.credentials).toBe('include');
|
||||
expect(requests.filter(item => item.path === costPath && item.method === 'POST')).toHaveLength(
|
||||
1
|
||||
);
|
||||
await flush(() => reply(post, { experiment: detail(costs()) }, 202));
|
||||
expect(location).toBe(`/experiments/${experimentId}`);
|
||||
});
|
||||
test('normalized duplicate pairs receive explicit preview failure and preserve editable inputs', async () => {
|
||||
await list();
|
||||
await flush(() => {
|
||||
change('Experiment name', 'Trend study');
|
||||
change('Experiment type', 'cost-sensitivity');
|
||||
});
|
||||
await flush(() => button('Add cost scenario').click());
|
||||
await flush(() => {
|
||||
change('Scenario 1 fee rate', '0.001');
|
||||
change('Scenario 1 slippage rate', '0.002');
|
||||
change('Scenario 2 fee rate', '0.00100000');
|
||||
change('Scenario 2 slippage rate', '0.00200000');
|
||||
});
|
||||
await flush(() => button('Preview experiment').click());
|
||||
const previewRequest = request(`${costPath}/preview`, 'POST');
|
||||
const input = previewRequest.body as { scenarios: unknown[] };
|
||||
expect(input.scenarios[0]).toEqual(input.scenarios[1]);
|
||||
await flush(() => reply(previewRequest, { error: 'Duplicate normalized cost pair' }, 400));
|
||||
expect(host.textContent).toContain('Duplicate normalized cost pair');
|
||||
expect(field('Scenario 1 fee rate').value).toBe('0.001');
|
||||
expect(field('Experiment type').disabled).toBe(false);
|
||||
});
|
||||
test.each(['-0.01', '1.00000001', 'not-a-number'])(
|
||||
'invalid fee %s never sends preview',
|
||||
async value => {
|
||||
await ready();
|
||||
await flush(() => change('Scenario 1 fee rate', value));
|
||||
const before = requests.length;
|
||||
await flush(() => button('Preview experiment').click());
|
||||
expect(requests).toHaveLength(before);
|
||||
expect(host.querySelector('[role="alert"]')).not.toBeNull();
|
||||
}
|
||||
);
|
||||
test('slippage one is rejected while fee one is accepted as a fraction', async () => {
|
||||
await ready();
|
||||
await flush(() => {
|
||||
change('Scenario 1 fee rate', '1');
|
||||
change('Scenario 1 slippage rate', '1');
|
||||
});
|
||||
const before = requests.length;
|
||||
await flush(() => button('Preview experiment').click());
|
||||
expect(requests).toHaveLength(before);
|
||||
await flush(() => change('Scenario 1 slippage rate', '0.99999999'));
|
||||
await flush(() => button('Preview experiment').click());
|
||||
expect(
|
||||
(request(`${costPath}/preview`, 'POST').body as { scenarios: unknown[] }).scenarios
|
||||
).toEqual([{ feeRate: '1.00000000', slippageRate: '0.99999999' }]);
|
||||
});
|
||||
test.each(['network', 'malformed', 'wrong-kind', 'foreign'] as const)(
|
||||
'%s submission retains mode, body and key for exact retry',
|
||||
async kind => {
|
||||
await ready();
|
||||
await flush(() => button('Confirm experiment').click());
|
||||
const original = request(costPath, 'POST');
|
||||
if (kind === 'network') {
|
||||
await lose(original);
|
||||
} else {
|
||||
const value = detail(costs());
|
||||
if (kind === 'foreign') {
|
||||
value.backtestId = otherBacktestId;
|
||||
}
|
||||
await flush(() =>
|
||||
reply(
|
||||
original,
|
||||
kind === 'malformed'
|
||||
? { experiment: {} }
|
||||
: { experiment: kind === 'wrong-kind' ? detail() : value },
|
||||
202
|
||||
)
|
||||
);
|
||||
}
|
||||
expect(host.textContent).toContain('Acceptance is unconfirmed.');
|
||||
expect(field('Experiment type').disabled).toBe(true);
|
||||
expect(
|
||||
field('Scenario 1 fee rate').disabled ||
|
||||
field('Scenario 1 fee rate').closest('fieldset')!.disabled
|
||||
).toBe(true);
|
||||
await flush(() => change('Experiment type', 'parameters'));
|
||||
expect(field('Experiment type').value).toBe('cost-sensitivity');
|
||||
await flush(() => button('Retry experiment submission').click());
|
||||
const retry = request(costPath, 'POST');
|
||||
expect(retry.rawBody).toBe(original.rawBody);
|
||||
expect(retry.headers.get('Idempotency-Key')).toBe(original.headers.get('Idempotency-Key'));
|
||||
expect(
|
||||
requests.some(item => item.path === '/api/v2/experiments' && item.method === 'POST')
|
||||
).toBe(false);
|
||||
await flush(() =>
|
||||
reply(retry, { experiment: detail(costs(), ['completed', 'completed']) }, 202)
|
||||
);
|
||||
expect(location).toBe(`/experiments/${experimentId}`);
|
||||
}
|
||||
);
|
||||
test('releasing uncertain intent is explicit and requires a fresh preview', async () => {
|
||||
await ready();
|
||||
await flush(() => button('Confirm experiment').click());
|
||||
await lose(request(costPath, 'POST'));
|
||||
Object.defineProperty(browser, 'confirm', { configurable: true, value: () => false });
|
||||
await flush(() => button('Start new experiment').click());
|
||||
expect(field('Experiment type').disabled).toBe(true);
|
||||
Object.defineProperty(browser, 'confirm', { configurable: true, value: () => true });
|
||||
await flush(() => button('Start new experiment').click());
|
||||
expect(field('Experiment type').disabled).toBe(false);
|
||||
expect(host.querySelector('[aria-label="Prepared cost scenarios"]')).toBeNull();
|
||||
});
|
||||
test('same-event mode change cannot submit the previously prepared ordinary experiment', async () => {
|
||||
await list();
|
||||
await flush(() => {
|
||||
change('Experiment name', 'Trend study');
|
||||
change('Parameter grid (JSON)', JSON.stringify(preview().input.grid));
|
||||
});
|
||||
await flush(() => button('Preview experiment').click());
|
||||
await flush(() =>
|
||||
reply(request('/api/v2/experiments/preview', 'POST'), { preview: preview() })
|
||||
);
|
||||
const submit = button('Confirm experiment');
|
||||
await flush(() => {
|
||||
change('Experiment type', 'cost-sensitivity');
|
||||
submit.click();
|
||||
});
|
||||
expect(
|
||||
requests.filter(item => item.method === 'POST' && !item.path.endsWith('/preview'))
|
||||
).toHaveLength(0);
|
||||
expect(field('Experiment type').value).toBe('cost-sensitivity');
|
||||
});
|
||||
test('mode changes fence pending reads, retain drafts and disable parameter-only panels', async () => {
|
||||
await ready();
|
||||
await flush(() => button('Preview experiment').click());
|
||||
const stale = request(`${costPath}/preview`, 'POST');
|
||||
await flush(() => change('Experiment type', 'parameters'));
|
||||
expect(stale.signal?.aborted).toBe(true);
|
||||
await flush(() => reply(stale, { preview: costs() }));
|
||||
expect(host.querySelector('[aria-label="Prepared cost scenarios"]')).toBeNull();
|
||||
await flush(() => change('Parameter grid (JSON)', '{"fastPeriod":[3]}'));
|
||||
await flush(() => change('Experiment type', 'cost-sensitivity'));
|
||||
expect(field('Scenario 1 fee rate').value).toBe('0.00100000');
|
||||
expect(button('Preview chronological validation').disabled).toBe(true);
|
||||
expect(button('Preview walk-forward').disabled).toBe(true);
|
||||
await flush(() => change('Experiment type', 'parameters'));
|
||||
expect(field('Parameter grid (JSON)').value).toBe('{"fastPeriod":[3]}');
|
||||
});
|
||||
test('adding/removing scenarios invalidates preview and preserves order', async () => {
|
||||
await ready();
|
||||
expect(button('Remove scenario 1').disabled).toBe(true);
|
||||
await flush(() => button('Add cost scenario').click());
|
||||
expect(host.querySelector('[aria-label="Prepared cost scenarios"]')).toBeNull();
|
||||
await flush(() => {
|
||||
change('Scenario 2 fee rate', '0.02');
|
||||
change('Scenario 2 slippage rate', '0.03');
|
||||
});
|
||||
await flush(() => button('Remove scenario 1').click());
|
||||
expect(field('Scenario 1 fee rate').value).toBe('0.02');
|
||||
expect(button('Remove scenario 1').disabled).toBe(true);
|
||||
});
|
||||
test('unconfirmed cost submission guards owned links and ignores late completion after source navigation', async () => {
|
||||
await ready();
|
||||
await flush(() => button('Confirm experiment').click());
|
||||
const original = request(costPath, 'POST');
|
||||
await lose(original);
|
||||
Object.defineProperty(browser, 'confirm', { configurable: true, value: () => false });
|
||||
await flush(() =>
|
||||
[...host.querySelectorAll('a')]
|
||||
.find(item => item.textContent === 'Show all experiments')!
|
||||
.click()
|
||||
);
|
||||
expect(location).toContain(backtestId);
|
||||
await flush(() => button('Retry experiment submission').click());
|
||||
const retry = request(costPath, 'POST');
|
||||
await flush(() => navigate(`/experiments?backtestId=${otherBacktestId}`));
|
||||
await flush(() => reply(retry, { experiment: detail(costs()) }, 202));
|
||||
expect(location).toContain(otherBacktestId);
|
||||
});
|
||||
test.each([
|
||||
'baseline',
|
||||
'parameters',
|
||||
'source-grid',
|
||||
'source-request',
|
||||
'source-dataset',
|
||||
'order',
|
||||
'missing-costs',
|
||||
'duplicates',
|
||||
'extra-grid',
|
||||
] as const)('malformed %s preview fails closed', async kind => {
|
||||
await ready();
|
||||
await flush(() => button('Preview experiment').click());
|
||||
const value = costs();
|
||||
if (kind === 'baseline') {
|
||||
value.candidates[0]!.costs.feeRate = '0.05000000';
|
||||
}
|
||||
if (kind === 'parameters') {
|
||||
value.candidates[1]!.parameters.fastPeriod = 3;
|
||||
}
|
||||
if (kind === 'source-grid') {
|
||||
value.source.input.grid = { fastPeriod: [2] };
|
||||
}
|
||||
if (kind === 'source-request') {
|
||||
value.request.policy.matching.halfSpreadRate = '0.50000000' as never;
|
||||
}
|
||||
if (kind === 'source-dataset') {
|
||||
value.dataset = { ...value.dataset, hash: '1'.repeat(64) };
|
||||
}
|
||||
if (kind === 'order') {
|
||||
value.candidates.reverse();
|
||||
}
|
||||
if (kind === 'missing-costs') {
|
||||
delete (value.candidates[1] as Partial<(typeof value.candidates)[number]>).costs;
|
||||
}
|
||||
if (kind === 'duplicates') {
|
||||
value.input.scenarios[0] = { ...value.candidates[0]!.costs };
|
||||
value.candidates[1]!.costs = { ...value.candidates[0]!.costs };
|
||||
}
|
||||
if (kind === 'extra-grid') {
|
||||
Object.assign(value.input, { grid: {} });
|
||||
}
|
||||
await flush(() => reply(request(`${costPath}/preview`, 'POST'), { preview: value }));
|
||||
expect(host.textContent).toContain('could not be verified');
|
||||
expect(host.querySelector('[aria-label="Prepared cost scenarios"]')).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe('cost outcomes on the ordinary detail and retry routes', () => {
|
||||
test('all outcomes keep exact costs, null reasons and zero without ranking', async () => {
|
||||
const value = detail(
|
||||
costs([
|
||||
{ feeRate: '0.001', slippageRate: '0.002' },
|
||||
{ feeRate: '0.002', slippageRate: '0.003' },
|
||||
{ feeRate: '0.003', slippageRate: '0.004' },
|
||||
{ feeRate: '0.004', slippageRate: '0.005' },
|
||||
]),
|
||||
['completed', 'failed', 'missing', 'cancelled', 'completed']
|
||||
);
|
||||
value.trials[4]!.comparable = false;
|
||||
value.trials[4]!.diagnostic = 'Policy mismatch';
|
||||
await showDetail(value);
|
||||
expect(host.textContent).toContain('Scenario / costs / fixed parameters');
|
||||
expect(host.textContent).toContain('Baseline');
|
||||
expect(host.textContent).toContain('Scenario 4');
|
||||
expect(host.textContent).toContain('Fee rate: 0.00100000');
|
||||
expect(host.textContent).toContain('Unavailable: insufficient-periods');
|
||||
expect(host.textContent).toContain('Strategy callback failed');
|
||||
expect(host.textContent).toContain('Expected child run is missing');
|
||||
expect(host.textContent).toContain('Incomparable');
|
||||
expect(host.textContent).toContain('Policy mismatch');
|
||||
expect([...host.querySelectorAll('td')].some(item => item.textContent === '0')).toBe(true);
|
||||
expect(requests.every(item => item.method === 'GET')).toBe(true);
|
||||
});
|
||||
test.each([
|
||||
'wrong-kind',
|
||||
'missing-kind',
|
||||
'unknown-kind',
|
||||
'trial-costs',
|
||||
'fixed-parameters',
|
||||
'trial-order',
|
||||
'missing-row',
|
||||
'ordinary-cost-injection',
|
||||
] as const)('malformed %s detail cannot display results', async kind => {
|
||||
await showDetail();
|
||||
const value = detail(costs(), ['completed', 'completed']);
|
||||
if (kind === 'wrong-kind') {
|
||||
value.kind = 'parameters';
|
||||
}
|
||||
if (kind === 'missing-kind') {
|
||||
delete value.kind;
|
||||
}
|
||||
if (kind === 'unknown-kind') {
|
||||
Object.assign(value, { kind: 'unknown' });
|
||||
}
|
||||
if (kind === 'trial-costs') {
|
||||
Object.assign(value.trials[1]!, { costs: { feeRate: '0.9', slippageRate: '0.9' } });
|
||||
}
|
||||
if (kind === 'fixed-parameters') {
|
||||
value.trials[1]!.parameters.fastPeriod = 7;
|
||||
}
|
||||
if (kind === 'trial-order') {
|
||||
value.trials.reverse();
|
||||
}
|
||||
if (kind === 'missing-row') {
|
||||
value.trials.pop();
|
||||
}
|
||||
let raw: unknown = value;
|
||||
if (kind === 'ordinary-cost-injection') {
|
||||
const ordinary = detail();
|
||||
Object.assign(ordinary.trials[0]!, { costs: { feeRate: '0', slippageRate: '0' } });
|
||||
raw = ordinary;
|
||||
}
|
||||
await flush(() => reply(request(detailPath), { experiment: raw }));
|
||||
expect(host.textContent).toContain('could not be verified');
|
||||
expect(host.textContent).not.toContain('Every trial outcome');
|
||||
});
|
||||
test('same-event refresh blocks cancellation until the readonly response resolves', async () => {
|
||||
await showDetail(detail(costs()));
|
||||
const cancel = button('Cancel remaining trials');
|
||||
await flush(() => {
|
||||
button('Refresh experiment').click();
|
||||
cancel.click();
|
||||
});
|
||||
expect(requests.filter(item => item.method === 'POST')).toHaveLength(0);
|
||||
await flush(() => reply(request(detailPath), { experiment: detail(costs()) }));
|
||||
await flush(() => button('Cancel remaining trials').click());
|
||||
const value = detail(costs());
|
||||
value.cancelRequested = true;
|
||||
await flush(() => reply(request(`${detailPath}/cancel`, 'POST'), { experiment: value }));
|
||||
expect(host.textContent).toContain('Cancellation requested');
|
||||
});
|
||||
test('failed cost trial reuses existing retry and lazy failure history with exact captured receipt', async () => {
|
||||
const value = detail(costs(), ['completed', 'failed']) as CostSensitivityDetail;
|
||||
await showDetail(value);
|
||||
await flush(() => button('Retry trial 2').click());
|
||||
await flush(() => button('Confirm retry trial 2').click());
|
||||
const path = `${detailPath}/trials/${runId(1)}/retry`,
|
||||
original = request(path, 'POST');
|
||||
expect(original.body).toEqual({ expectedAttemptNumber: 0, expectedRetryCount: 0 });
|
||||
await lose(original);
|
||||
await flush(() => button('Refresh experiment').click());
|
||||
const newer = detail(costs(), ['completed', 'completed']) as CostSensitivityDetail;
|
||||
newer.trials[1]!.attemptNumber = 1;
|
||||
newer.trials[1]!.retryCount = 1;
|
||||
await flush(() => reply(request(detailPath), { experiment: newer }));
|
||||
const saved: ExperimentTrialRetry = {
|
||||
id: 'aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa',
|
||||
experimentId,
|
||||
runId: runId(1),
|
||||
trialKey: value.trials[1]!.trialKey,
|
||||
retryNumber: 1,
|
||||
previousAttemptNumber: 0,
|
||||
previousAttemptId: null,
|
||||
error: 'Strategy callback failed',
|
||||
progress: 0,
|
||||
currentDate: null,
|
||||
startedAt: null,
|
||||
completedAt: null,
|
||||
pausedAt: null,
|
||||
failureUpdatedAt: '2026-10-24T10:00:00Z',
|
||||
recordedAt: '2026-10-24T11:00:00Z',
|
||||
principal: 'operator',
|
||||
reviewId: '88888888-8888-4888-8888-888888888888',
|
||||
};
|
||||
await flush(() => button('Retry same request for trial 2').click());
|
||||
const retry = request(path, 'POST');
|
||||
expect(retry.rawBody).toBe(original.rawBody);
|
||||
expect(retry.headers.get('Idempotency-Key')).toBe(original.headers.get('Idempotency-Key'));
|
||||
await flush(() => reply(retry, { retry: saved, experiment: newer }, 202));
|
||||
expect(host.textContent).toContain('Retry 1 accepted');
|
||||
expect(host.textContent).toContain('Fee rate: 0.00100000');
|
||||
await flush(() => button('Show retry history for trial 2').click());
|
||||
await flush(() =>
|
||||
reply(request(`${detailPath}/trials/${runId(1)}/retries`), { retries: [saved] })
|
||||
);
|
||||
expect(host.textContent).toContain('Strategy callback failed');
|
||||
expect(host.textContent).toContain('previous attempt 0');
|
||||
});
|
||||
test('late detail cannot replace a different saved experiment', async () => {
|
||||
await showDetail();
|
||||
const stale = request(detailPath);
|
||||
await flush(() => navigate(`/experiments/${otherExperimentId}`));
|
||||
const other = detail(costs());
|
||||
other.id = otherExperimentId;
|
||||
await flush(() =>
|
||||
reply(request(`/api/v2/experiments/${otherExperimentId}`), { experiment: other })
|
||||
);
|
||||
await flush(() => reply(stale, { experiment: detail(costs(), ['completed', 'completed']) }));
|
||||
expect(location).toBe(`/experiments/${otherExperimentId}`);
|
||||
expect(host.textContent).toContain('pending');
|
||||
});
|
||||
test('saved list identifies cost diagnostics and opens the existing detail route', async () => {
|
||||
await render(createElement(ExperimentListPage), `/experiments?backtestId=${backtestId}`);
|
||||
await flush(() =>
|
||||
reply(request(`/api/v2/experiments?backtestId=${backtestId}`), {
|
||||
experiments: [detail(costs())],
|
||||
})
|
||||
);
|
||||
expect(host.textContent).toContain('Cost sensitivity · template diagnostics');
|
||||
const link = [...host.querySelectorAll('a')].find(item => item.textContent === 'Trend study')!;
|
||||
expect(link.getAttribute('href')).toBe(`/experiments/${experimentId}`);
|
||||
await flush(() => link.click());
|
||||
expect(location).toBe(`/experiments/${experimentId}`);
|
||||
});
|
||||
});
|
||||
224
test/integration/cost-sensitivity.test.ts
Normal file
224
test/integration/cost-sensitivity.test.ts
Normal file
|
|
@ -0,0 +1,224 @@
|
|||
import { describe, expect, test } from 'bun:test';
|
||||
import { canonicalRunRequestSchema } from '@stock-bot/stock-config/canonical-research';
|
||||
import type { CostSensitivityInput } from '@stock-bot/stock-config/cost-sensitivity';
|
||||
import { builtinCatalogDescriptors } from '@stock-bot/stock-config/strategy';
|
||||
import type { HistoricalDatasetV2 } from '@stock-bot/types';
|
||||
import { canonicalRiskSessionClock } from '../../apps/stock/web-api/src/services/canonical-risk-clock';
|
||||
import {
|
||||
buildCostSensitivityPreview,
|
||||
parseCostSensitivityInput,
|
||||
retainedCostSensitivityPreview,
|
||||
retainedWorkbenchPreview,
|
||||
workbenchTrialRequest,
|
||||
} from '../../apps/stock/web-api/src/services/cost-sensitivity-input';
|
||||
import {
|
||||
buildExperimentPreview,
|
||||
ExperimentError,
|
||||
experimentHash,
|
||||
experimentTrialRequest,
|
||||
PREVIEW_RUN_ID,
|
||||
retainedExperimentPreview,
|
||||
} from '../../apps/stock/web-api/src/services/experiment-input';
|
||||
import { canonicalSmaFixture } from '../fixtures/canonical-sma';
|
||||
import { nativeReplayFixture } from '../fixtures/native-replay';
|
||||
|
||||
const backtestId = '10000000-0000-4000-8000-000000000001';
|
||||
const versionId = '20000000-0000-4000-8000-000000000001';
|
||||
const owner = `strategy:${versionId}`;
|
||||
const input = (): CostSensitivityInput => ({
|
||||
backtestId,
|
||||
name: 'Cost diagnostics',
|
||||
scenarios: [
|
||||
{ feeRate: '0', slippageRate: '0' },
|
||||
{ feeRate: '0.02', slippageRate: '0.01' },
|
||||
],
|
||||
});
|
||||
function source(dataset: HistoricalDatasetV2, raw = input()) {
|
||||
const experiment = { backtestId: raw.backtestId, name: raw.name, grid: {} };
|
||||
const descriptor = builtinCatalogDescriptors[0]!;
|
||||
const policy = structuredClone(nativeReplayFixture(36, 1, [owner]).config);
|
||||
const clock = canonicalRiskSessionClock(dataset);
|
||||
policy.matching.risk.ledger.sessionId = PREVIEW_RUN_ID;
|
||||
policy.matching.risk.ledger.accountId = `research:${PREVIEW_RUN_ID}`;
|
||||
policy.matching.risk.ledger.riskSession = clock.riskSession;
|
||||
policy.risk_boundaries = clock.riskBoundaries;
|
||||
const request = canonicalRunRequestSchema.parse({
|
||||
kind: 'canonical-research/v1',
|
||||
runId: PREVIEW_RUN_ID,
|
||||
backtestId,
|
||||
name: 'Template',
|
||||
strategy: {
|
||||
familyId: '30000000-0000-4000-8000-000000000001',
|
||||
versionId,
|
||||
origin: 'builtin',
|
||||
reviewId: '40000000-0000-4000-8000-000000000001',
|
||||
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: {
|
||||
strategyId: descriptor.program.strategyId,
|
||||
strategyVersion: descriptor.program.strategyVersion,
|
||||
ownerId: owner,
|
||||
seed: 42,
|
||||
instrumentId: 'X0.US',
|
||||
seriesId: 'X0.US:1m',
|
||||
ownerBudget: '40',
|
||||
parameters: { fastPeriod: 2, slowPeriod: 3 },
|
||||
},
|
||||
},
|
||||
datasetHash: 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(experiment, request, dataset.manifest);
|
||||
}
|
||||
|
||||
describe('cost-sensitivity immutable preparation', () => {
|
||||
test('normalizes explicit fractions, preserves ordered implicit baseline and deterministic identity', () => {
|
||||
const raw = input(),
|
||||
baseline = source(canonicalSmaFixture().dataset),
|
||||
before = structuredClone({ raw, baseline });
|
||||
const preview = buildCostSensitivityPreview(raw, baseline);
|
||||
expect(buildCostSensitivityPreview(raw, baseline)).toEqual(preview);
|
||||
expect(retainedCostSensitivityPreview(preview)).toEqual(preview);
|
||||
expect(retainedWorkbenchPreview(preview)).toEqual(preview);
|
||||
expect({ raw, baseline }).toEqual(before);
|
||||
expect(preview.source).toEqual(baseline);
|
||||
expect(preview.candidates.map(c => c.index)).toEqual([0, 1, 2]);
|
||||
expect(preview.candidates.map(c => c.costs)).toEqual([
|
||||
{
|
||||
feeRate: baseline.request.policy.matching.risk.feeRate,
|
||||
slippageRate: baseline.request.policy.matching.slippageRate,
|
||||
},
|
||||
{ feeRate: '0.00000000', slippageRate: '0.00000000' },
|
||||
{ feeRate: '0.02000000', slippageRate: '0.01000000' },
|
||||
]);
|
||||
const equivalent = {
|
||||
...raw,
|
||||
scenarios: [
|
||||
{ feeRate: '0.00000000', slippageRate: '0.0' },
|
||||
{ feeRate: '0.020', slippageRate: '0.0100' },
|
||||
],
|
||||
};
|
||||
expect(buildCostSensitivityPreview(equivalent, baseline)).toEqual(preview);
|
||||
const reordered = buildCostSensitivityPreview(
|
||||
{ ...raw, scenarios: [...raw.scenarios].reverse() },
|
||||
baseline
|
||||
);
|
||||
expect(reordered.previewHash).not.toBe(preview.previewHash);
|
||||
expect(reordered.candidates[1]!.trialKey).toBe(preview.candidates[2]!.trialKey);
|
||||
});
|
||||
test('rejects malformed/mixed input, out-of-bounds or excess precision, duplicate normalized pairs and baseline duplication', () => {
|
||||
const baseline = source(canonicalSmaFixture().dataset),
|
||||
raw = input();
|
||||
for (const scenario of [
|
||||
{ feeRate: '-0.1', slippageRate: '0' },
|
||||
{ feeRate: '1.00000001', slippageRate: '0' },
|
||||
{ feeRate: '0', slippageRate: '1' },
|
||||
{ feeRate: '0', slippageRate: '0.000000001' },
|
||||
{ feeRate: 0, slippageRate: '0' },
|
||||
{ feeRate: '0', slippageRate: '0', halfSpreadRate: '0' },
|
||||
]) {
|
||||
expect(() => parseCostSensitivityInput({ ...raw, scenarios: [scenario] })).toThrow(
|
||||
ExperimentError
|
||||
);
|
||||
}
|
||||
expect(() => parseCostSensitivityInput({ ...raw, grid: {} })).toThrow();
|
||||
expect(() => parseCostSensitivityInput({ ...raw, scenarios: [] })).toThrow();
|
||||
expect(() =>
|
||||
parseCostSensitivityInput({ ...raw, scenarios: Array(100).fill(raw.scenarios[0]) })
|
||||
).toThrow();
|
||||
expect(() =>
|
||||
buildCostSensitivityPreview(
|
||||
{ ...raw, scenarios: [raw.scenarios[0]!, { feeRate: '0.000', slippageRate: '0.0' }] },
|
||||
baseline
|
||||
)
|
||||
).toThrow('Duplicate');
|
||||
expect(() =>
|
||||
buildCostSensitivityPreview(
|
||||
{
|
||||
...raw,
|
||||
scenarios: [
|
||||
{
|
||||
feeRate: baseline.request.policy.matching.risk.feeRate,
|
||||
slippageRate: baseline.request.policy.matching.slippageRate,
|
||||
},
|
||||
],
|
||||
},
|
||||
baseline
|
||||
)
|
||||
).toThrow('Duplicate');
|
||||
expect<unknown>(
|
||||
parseCostSensitivityInput({
|
||||
...raw,
|
||||
scenarios: [{ feeRate: '1', slippageRate: '0.99999999' }],
|
||||
}).scenarios
|
||||
).toEqual([{ feeRate: '1.00000000', slippageRate: '0.99999999' }]);
|
||||
});
|
||||
test('only two cost paths change; ordinary reconstruction is byte-equivalent and validation source stays v1', () => {
|
||||
const baseline = source(canonicalSmaFixture().dataset),
|
||||
preview = buildCostSensitivityPreview(input(), baseline),
|
||||
id = '50000000-0000-4000-8000-000000000001';
|
||||
const original = experimentTrialRequest(baseline, baseline.candidates[0]!, id);
|
||||
expect(JSON.stringify(workbenchTrialRequest(baseline, baseline.candidates[0]!, id))).toBe(
|
||||
JSON.stringify(original)
|
||||
);
|
||||
expect(workbenchTrialRequest(preview, preview.candidates[0]!, id)).toEqual(original);
|
||||
for (const candidate of preview.candidates) {
|
||||
const request = workbenchTrialRequest(preview, candidate, id);
|
||||
expect(request.strategy.selection.parameters).toEqual(original.strategy.selection.parameters);
|
||||
expect(String(request.policy.matching.risk.feeRate)).toBe(candidate.costs.feeRate);
|
||||
expect(String(request.policy.matching.slippageRate)).toBe(candidate.costs.slippageRate);
|
||||
request.policy.matching.risk.feeRate = original.policy.matching.risk.feeRate;
|
||||
request.policy.matching.slippageRate = original.policy.matching.slippageRate;
|
||||
expect(request).toEqual(original);
|
||||
}
|
||||
expect(() => retainedExperimentPreview(preview)).toThrow();
|
||||
});
|
||||
test('retained tamper is server integrity failure even with a rehashed outer manifest', () => {
|
||||
const baseline = source(canonicalSmaFixture().dataset),
|
||||
preview = buildCostSensitivityPreview(input(), baseline);
|
||||
for (const mutate of [
|
||||
(p: typeof preview) => (p.candidates[1]!.costs.feeRate = '0.9'),
|
||||
(p: typeof preview) => p.candidates.reverse(),
|
||||
(p: typeof preview) => (p.request = structuredClone({ ...p.request, name: 'foreign' })),
|
||||
(p: typeof preview) => (p.candidates[1]!.parameters = { fastPeriod: 1, slowPeriod: 3 }),
|
||||
]) {
|
||||
const changed = structuredClone(preview);
|
||||
mutate(changed);
|
||||
const { previewHash: _hash, ...manifest } = changed;
|
||||
changed.previewHash = experimentHash(manifest);
|
||||
let error: unknown;
|
||||
try {
|
||||
retainedCostSensitivityPreview(changed);
|
||||
} catch (cause) {
|
||||
error = cause;
|
||||
}
|
||||
expect(error).toBeInstanceOf(Error);
|
||||
expect(error).not.toBeInstanceOf(ExperimentError);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
|
@ -682,12 +682,17 @@ describe('retry coordination and navigation', () => {
|
|||
await flush(() => reply(oldRead, { experiment: other }));
|
||||
expect(host.querySelector('h1')!.textContent).toBe('Trend study');
|
||||
});
|
||||
test('refresh and confirmation in one event cannot install a stale read over accepted retry state', async () => {
|
||||
test('refresh and confirmation in one event serialize the read before retry acceptance', async () => {
|
||||
const value = await start();
|
||||
await flush(() => {
|
||||
button('Refresh experiment').click();
|
||||
button('Confirm retry trial 1').click();
|
||||
});
|
||||
expect(
|
||||
requests.filter(item => item.path === retryPath() && item.method === 'POST')
|
||||
).toHaveLength(0);
|
||||
await flush(() => reply(request(`/api/v2/experiments/${experimentId}`), { experiment: value }));
|
||||
await flush(() => button('Confirm retry trial 1').click());
|
||||
const post = request(retryPath(), 'POST');
|
||||
await flush(() => reply(post, accepted(value), 202));
|
||||
expect(host.textContent).toContain('Retry 1 accepted');
|
||||
|
|
|
|||
|
|
@ -67,6 +67,7 @@ async function fixture(options: { corruptDataset?: boolean; buildMismatch?: bool
|
|||
'23-experiment-retries.sql',
|
||||
'24-chronological-validation.sql',
|
||||
'25-walk-forward.sql',
|
||||
'26-cost-sensitivity.sql',
|
||||
]) {
|
||||
await pool.query(
|
||||
readFileSync(new URL(`../../database/postgres/init/${filename}`, import.meta.url), 'utf8')
|
||||
|
|
|
|||
|
|
@ -66,6 +66,7 @@ async function fixture(dataset = canonicalSmaFixture().dataset) {
|
|||
'23-experiment-retries.sql',
|
||||
'24-chronological-validation.sql',
|
||||
'25-walk-forward.sql',
|
||||
'26-cost-sensitivity.sql',
|
||||
]) {
|
||||
await pool.query(
|
||||
readFileSync(new URL(`../../database/postgres/init/${name}`, import.meta.url), 'utf8')
|
||||
|
|
|
|||
|
|
@ -105,6 +105,7 @@ async function fixture() {
|
|||
'23-experiment-retries.sql',
|
||||
'24-chronological-validation.sql',
|
||||
'25-walk-forward.sql',
|
||||
'26-cost-sensitivity.sql',
|
||||
]) {
|
||||
await pool.query(sql(name));
|
||||
}
|
||||
|
|
|
|||
|
|
@ -79,7 +79,9 @@ async function fixture(poolMax = 1, withValidation = true) {
|
|||
'21-run-reproduction.sql',
|
||||
'22-experiments.sql',
|
||||
'23-experiment-retries.sql',
|
||||
...(withValidation ? ['24-chronological-validation.sql', '25-walk-forward.sql'] : []),
|
||||
...(withValidation
|
||||
? ['24-chronological-validation.sql', '25-walk-forward.sql', '26-cost-sensitivity.sql']
|
||||
: []),
|
||||
]) {
|
||||
await pool.query(
|
||||
readFileSync(new URL(`../../database/postgres/init/${name}`, import.meta.url), 'utf8')
|
||||
|
|
|
|||
|
|
@ -70,6 +70,7 @@ async function fixture() {
|
|||
'23-experiment-retries.sql',
|
||||
'24-chronological-validation.sql',
|
||||
'25-walk-forward.sql',
|
||||
'26-cost-sensitivity.sql',
|
||||
]) {
|
||||
await pool.query(
|
||||
readFileSync(new URL(`../../database/postgres/init/${name}`, import.meta.url), 'utf8')
|
||||
|
|
|
|||
666
test/postgres/cost-sensitivity.test.ts
Normal file
666
test/postgres/cost-sensitivity.test.ts
Normal file
|
|
@ -0,0 +1,666 @@
|
|||
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 { createHttpSecurity } from '@stock-bot/di';
|
||||
import { getLogger, setLoggerConfig } from '@stock-bot/logger';
|
||||
import { PostgreSQLClient } from '@stock-bot/postgres';
|
||||
import type { CanonicalRunResult } from '@stock-bot/stock-config/canonical-research';
|
||||
import type { CostSensitivityInput } from '@stock-bot/stock-config/cost-sensitivity';
|
||||
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 { ChronologicalValidationService } from '../../apps/stock/web-api/src/services/chronological-validation.service';
|
||||
import { ExperimentError } from '../../apps/stock/web-api/src/services/experiment-input';
|
||||
import { ExperimentsService } from '../../apps/stock/web-api/src/services/experiments.service';
|
||||
import { canonicalReproductionHash } from '../../apps/stock/web-api/src/services/reproduction-comparison';
|
||||
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('chronological-validation');
|
||||
const url = process.env.PIPELINE_TEST_DATABASE_URL;
|
||||
const cleanup: (() => Promise<void>)[] = [];
|
||||
let packages: ReturnType<typeof packageBuiltinStrategies> | undefined;
|
||||
const tokens = {
|
||||
operator: 'chronological-operator-fixture-not-a-real-secret-1234',
|
||||
service: 'chronological-service-fixture-not-a-real-secret-1234',
|
||||
};
|
||||
afterEach(async () => {
|
||||
for (const close of cleanup.splice(0).reverse()) {
|
||||
await close();
|
||||
}
|
||||
});
|
||||
async function fixture(poolMax = 1, withCosts = true, capital = 10000) {
|
||||
if (!url || !new URL(url).pathname.startsWith('/stock_bot_safety')) {
|
||||
throw new Error('Disposable safety database required');
|
||||
}
|
||||
const schema = 'stock_bot_safety_validation_' + randomUUID().replaceAll('-', '');
|
||||
const admin = new Pool({ connectionString: url });
|
||||
await admin.query(`CREATE SCHEMA ${schema}`);
|
||||
// A single connection detects accidental nested pool reads while the admission lock is held.
|
||||
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',
|
||||
'22-experiments.sql',
|
||||
'23-experiment-retries.sql',
|
||||
'24-chronological-validation.sql',
|
||||
'25-walk-forward.sql',
|
||||
...(withCosts ? ['26-cost-sensitivity.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 },
|
||||
api = new BacktestServiceV2(container),
|
||||
experiments = new ExperimentsService(container),
|
||||
catalog = new StrategyCatalogService(container);
|
||||
const version = await catalog.seedBuiltin(
|
||||
'Validation SMA',
|
||||
(await (packages ??= packageBuiltinStrategies()))[0]!,
|
||||
'seed'
|
||||
);
|
||||
const data = canonicalSmaFixture(),
|
||||
dataset = data.dataset;
|
||||
await retainResearchDataset(pool, dataset);
|
||||
const draft = await api.createBacktest(
|
||||
{
|
||||
name: 'Validation template',
|
||||
strategy: 'catalog',
|
||||
strategyVersionId: version.id,
|
||||
strategyParameters: { fastPeriod: 2, slowPeriod: 3 },
|
||||
symbols: ['X0.US'],
|
||||
startDate: new Date(dataset.manifest.bounds.tradeStart).toISOString(),
|
||||
endDate: new Date(dataset.manifest.bounds.tradeEnd).toISOString(),
|
||||
initialCapital: capital,
|
||||
config: {
|
||||
datasetHash: dataset.manifest.hash,
|
||||
dataFrequency: '1m',
|
||||
canonical: canonicalSettings,
|
||||
},
|
||||
},
|
||||
{ autoStart: false }
|
||||
);
|
||||
const input: CostSensitivityInput = {
|
||||
backtestId: draft.id,
|
||||
name: 'Explicit cost diagnostics',
|
||||
scenarios: [
|
||||
{ feeRate: '0.001', slippageRate: '0' },
|
||||
{ feeRate: '0', slippageRate: '0.01' },
|
||||
],
|
||||
};
|
||||
const app = new Hono();
|
||||
createHttpSecurity({
|
||||
adminToken: tokens.operator,
|
||||
serviceToken: tokens.service,
|
||||
environment: 'test',
|
||||
hostname: '127.0.0.1',
|
||||
}).mount(app);
|
||||
app.route('/', createExperimentRoutes(container));
|
||||
const request = (raw: unknown = input, role: keyof typeof tokens = 'operator') =>
|
||||
app.request('/api/v2/experiments/cost-sensitivity/preview', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${tokens[role]}` },
|
||||
body: JSON.stringify(raw),
|
||||
});
|
||||
const review = async (decision: 'approve' | 'revoke' = 'approve') => {
|
||||
await catalog.reviewVersion(
|
||||
version.id,
|
||||
{ decision, reason: 'Disposable validation proof' },
|
||||
'operator'
|
||||
);
|
||||
return (await catalog.getVersionReviews(version.id)).at(-1)!;
|
||||
};
|
||||
const snapshot = async () => {
|
||||
const tables = (
|
||||
await pool.query('SELECT tablename FROM pg_tables WHERE schemaname=$1 ORDER BY tablename', [
|
||||
schema,
|
||||
])
|
||||
).rows;
|
||||
const rows: Record<string, unknown> = {};
|
||||
for (const { tablename } of tables) {
|
||||
const quoted = '"' + String(tablename).replaceAll('"', '""') + '"';
|
||||
rows[String(tablename)] = (
|
||||
await pool.query(
|
||||
`SELECT COALESCE(jsonb_agg(to_jsonb(t) ORDER BY to_jsonb(t)::text),'[]'::jsonb) AS rows FROM ${quoted} t`
|
||||
)
|
||||
).rows[0].rows;
|
||||
}
|
||||
return rows;
|
||||
};
|
||||
const validations = new ChronologicalValidationService(container);
|
||||
const repository = new PostgresBacktestRunRepository(postgres);
|
||||
const execute = async (id: string) => {
|
||||
const engine = new RustBacktestAdapter({
|
||||
logger,
|
||||
storage: {
|
||||
async getHistoricalBars() {
|
||||
throw new Error('No provider reads allowed');
|
||||
},
|
||||
},
|
||||
});
|
||||
const runner = new BacktestRunner({ engine, engineName: 'native', repository, logger });
|
||||
try {
|
||||
await runner.runQueued(id);
|
||||
} finally {
|
||||
await runner.shutdown();
|
||||
}
|
||||
};
|
||||
return {
|
||||
cloneTemplate: async (sourceDataset = dataset) =>
|
||||
api.createBacktest(
|
||||
{
|
||||
name: 'Other validation template',
|
||||
strategy: 'catalog',
|
||||
strategyVersionId: version.id,
|
||||
strategyParameters: { fastPeriod: 2, slowPeriod: 3 },
|
||||
symbols: ['X0.US'],
|
||||
startDate: new Date(sourceDataset.manifest.bounds.tradeStart).toISOString(),
|
||||
endDate: new Date(sourceDataset.manifest.bounds.tradeEnd).toISOString(),
|
||||
initialCapital: capital,
|
||||
config: {
|
||||
datasetHash: sourceDataset.manifest.hash,
|
||||
dataFrequency: '1m',
|
||||
canonical: canonicalSettings,
|
||||
},
|
||||
},
|
||||
{ autoStart: false }
|
||||
),
|
||||
validations,
|
||||
repository,
|
||||
execute,
|
||||
api,
|
||||
pool,
|
||||
postgres,
|
||||
experiments,
|
||||
catalog,
|
||||
version,
|
||||
draft,
|
||||
dataset,
|
||||
input,
|
||||
request,
|
||||
review,
|
||||
snapshot,
|
||||
};
|
||||
}
|
||||
|
||||
const actor = (key = randomUUID()) => ({ principal: 'operator' as const, key });
|
||||
type Fixture = Awaited<ReturnType<typeof fixture>>;
|
||||
async function submit(f: Fixture, identity = actor()) {
|
||||
await f.review();
|
||||
const preview = await f.experiments.previewCosts(f.input),
|
||||
body = { ...f.input, previewHash: preview.previewHash };
|
||||
return { preview, body, identity, experiment: await f.experiments.submitCosts(body, identity) };
|
||||
}
|
||||
describe.skipIf(!url)('bounded cost-sensitivity experiments', () => {
|
||||
test('pool1 native baseline agrees with ordinary empty-grid; saved scenarios expose exact costs and immutable results', async () => {
|
||||
const f = await fixture(),
|
||||
start = await submit(f);
|
||||
expect(start.experiment.kind).toBe('cost-sensitivity');
|
||||
expect(start.experiment.trials).toHaveLength(3);
|
||||
const input = { backtestId: f.draft.id, name: 'Ordinary reference', grid: {} };
|
||||
const preview = await f.experiments.preview(input),
|
||||
ordinary = await f.experiments.submit(
|
||||
{ ...input, previewHash: preview.previewHash },
|
||||
actor()
|
||||
);
|
||||
for (const trial of [...start.experiment.trials, ...ordinary.trials]) {
|
||||
await f.execute(trial.runId!);
|
||||
}
|
||||
const detail = await f.experiments.get(start.experiment.id);
|
||||
expect(detail.counts.completed).toBe(3);
|
||||
expect(detail.trials.every(t => t.comparable)).toBe(true);
|
||||
const baseline = await f.api.getRunResults(detail.trials[0]!.runId!),
|
||||
reference = await f.api.getRunResults(ordinary.trials[0]!.runId!);
|
||||
expect(canonicalReproductionHash(baseline as CanonicalRunResult)).toBe(
|
||||
canonicalReproductionHash(reference as CanonicalRunResult)
|
||||
);
|
||||
expect(await f.experiments.get(detail.id)).toEqual(detail);
|
||||
expect((await f.experiments.list()).find(e => e.id === detail.id)!.kind).toBe(
|
||||
'cost-sensitivity'
|
||||
);
|
||||
expect((await f.experiments.submitCosts(start.body, start.identity)).id).toBe(detail.id);
|
||||
}, 60000);
|
||||
});
|
||||
|
||||
const result = async (f: Fixture, id: string) =>
|
||||
(await f.api.getRunResults(id)) as CanonicalRunResult;
|
||||
describe.skipIf(!url)('cost financial and recovery proofs', () => {
|
||||
test('Rust alone applies exact execution fees and adverse slippage, resetting capital for every scenario', async () => {
|
||||
const f = await fixture();
|
||||
f.input.scenarios.push({ feeRate: '0.02', slippageRate: '0.01' });
|
||||
const start = await submit(f);
|
||||
const oracle = [
|
||||
{ prices: ['5.00000000', '2.00000000'], fees: '0.70000000', equity: '9969.30000000' },
|
||||
{ prices: ['5.00000000', '2.00000000'], fees: '0.07000000', equity: '9969.93000000' },
|
||||
{ prices: ['5.05000000', '1.98000000'], fees: '0.00000000', equity: '9969.30000000' },
|
||||
{ prices: ['5.05000000', '1.98000000'], fees: '1.40600000', equity: '9967.89400000' },
|
||||
];
|
||||
for (const [index, trial] of start.experiment.trials.entries()) {
|
||||
await f.execute(trial.runId!);
|
||||
const saved = await result(f, trial.runId!),
|
||||
expected = oracle[index]!;
|
||||
expect(String(saved.financial.reporting.initialEquity)).toBe('10000.00000000');
|
||||
expect(saved.financial.projection.fills.map(fill => String(fill.price))).toEqual(
|
||||
expected.prices
|
||||
);
|
||||
expect(saved.financial.projection.fills.map(fill => String(fill.quantity))).toEqual([
|
||||
'10.00000000',
|
||||
'10.00000000',
|
||||
]);
|
||||
expect(String(saved.financial.projection.valuation.fees)).toBe(expected.fees);
|
||||
expect(String(saved.financial.projection.valuation.equity)).toBe(expected.equity);
|
||||
}
|
||||
}, 60000);
|
||||
test('fee-inclusive funding cannot be bypassed by a lower-cost scenario; unchanged risk may change fills', async () => {
|
||||
const f = await fixture(1, true, 50);
|
||||
f.input.scenarios = [{ feeRate: '0', slippageRate: '0' }];
|
||||
const start = await submit(f);
|
||||
for (const trial of start.experiment.trials) {
|
||||
await f.execute(trial.runId!);
|
||||
}
|
||||
const baseline = await result(f, start.experiment.trials[0]!.runId!),
|
||||
zero = await result(f, start.experiment.trials[1]!.runId!);
|
||||
expect(baseline.financial.projection.fills).toEqual([]);
|
||||
expect(String(baseline.financial.projection.valuation.cash)).toBe('50.00000000');
|
||||
expect(zero.financial.projection.fills).toHaveLength(2);
|
||||
expect(String(zero.financial.projection.valuation.cash)).toBe('20.00000000');
|
||||
expect(baseline.request.policy.matching.risk.maxGrossExposure).toBe(
|
||||
zero.request.policy.matching.risk.maxGrossExposure
|
||||
);
|
||||
}, 60000);
|
||||
test('frozen source survives template edit, manual retry retains costs and reproduction retains exact economics', async () => {
|
||||
const f = await fixture(),
|
||||
start = await submit(f),
|
||||
trial = start.experiment.trials[1]!,
|
||||
runId = trial.runId!;
|
||||
const snapshot = (await f.pool.query('SELECT request_snapshot FROM runs WHERE id=$1', [runId]))
|
||||
.rows[0].request_snapshot;
|
||||
const claim = await f.repository.startCanonical(snapshot);
|
||||
await f.repository.fail(runId, 'Cost attempt failure', claim.attemptId);
|
||||
await f.api.updateBacktest(f.draft.id, {
|
||||
name: 'Changed template',
|
||||
initialCapital: 12000,
|
||||
config: {
|
||||
datasetHash: f.dataset.manifest.hash,
|
||||
dataFrequency: '1m',
|
||||
canonical: { ...canonicalSettings, feeRate: '0.03', slippageRate: '0.04' },
|
||||
},
|
||||
});
|
||||
const newReview = await f.review();
|
||||
const retry = await f.experiments.retryTrial(
|
||||
start.experiment.id,
|
||||
runId,
|
||||
{ expectedAttemptNumber: 1, expectedRetryCount: 0 },
|
||||
actor()
|
||||
);
|
||||
expect(retry.retry.error).toBe('Cost attempt failure');
|
||||
expect(retry.retry.reviewId).toBe(newReview.id);
|
||||
expect(
|
||||
(await f.pool.query('SELECT request_snapshot FROM runs WHERE id=$1', [runId])).rows[0]
|
||||
.request_snapshot
|
||||
).toEqual(snapshot);
|
||||
await f.execute(runId);
|
||||
const original = await result(f, runId);
|
||||
expect(String(original.request.policy.matching.risk.feeRate)).toBe('0.00100000');
|
||||
const reproduction = await f.api.reproduceRun(runId, actor());
|
||||
await f.execute(reproduction.id);
|
||||
expect(canonicalReproductionHash(await result(f, reproduction.id))).toBe(
|
||||
canonicalReproductionHash(original)
|
||||
);
|
||||
expect((await f.experiments.get(start.experiment.id)).preview).toEqual(start.preview);
|
||||
await expect(f.repository.heartbeat(runId, claim.attemptId)).rejects.toThrow();
|
||||
await f.review('revoke');
|
||||
await f.pool.query('UPDATE backtests SET archived_at=NOW() WHERE id=$1', [f.draft.id]);
|
||||
expect((await f.experiments.submitCosts(start.body, start.identity)).id).toBe(
|
||||
start.experiment.id
|
||||
);
|
||||
await expect(f.experiments.submitCosts(start.body, actor())).rejects.toThrow();
|
||||
}, 60000);
|
||||
});
|
||||
|
||||
describe.skipIf(!url)('cost SQL and admission boundaries', () => {
|
||||
test('first/idempotent upgrade preserves old evidence/leases and leaves v1 callable and non-request guard bodies unchanged', async () => {
|
||||
const f = await fixture(1, false);
|
||||
await f.review();
|
||||
const input = { backtestId: f.draft.id, name: 'Old sweep', grid: { fastPeriod: [1, 2] } },
|
||||
preview = await f.experiments.preview(input),
|
||||
ordinary = await f.experiments.submit(
|
||||
{ ...input, previewHash: preview.previewHash },
|
||||
actor()
|
||||
);
|
||||
await f.execute(ordinary.trials[0]!.runId!);
|
||||
const pending = ordinary.trials[1]!.runId!,
|
||||
request = (await f.pool.query('SELECT request_snapshot FROM runs WHERE id=$1', [pending]))
|
||||
.rows[0].request_snapshot;
|
||||
await f.repository.startCanonical(request);
|
||||
const before = await f.snapshot();
|
||||
const functions = async () =>
|
||||
(
|
||||
await f.pool.query(
|
||||
'SELECT proname,pg_get_functiondef(oid) AS definition FROM pg_proc WHERE pronamespace=current_schema()::regnamespace ORDER BY proname'
|
||||
)
|
||||
).rows;
|
||||
const oldFunctions = await functions(),
|
||||
migration = readFileSync(
|
||||
new URL('../../database/postgres/init/26-cost-sensitivity.sql', import.meta.url),
|
||||
'utf8'
|
||||
);
|
||||
await f.pool.query(migration);
|
||||
expect(await f.snapshot()).toEqual(before);
|
||||
const changed = [
|
||||
'require_experiment_manifest',
|
||||
'require_active_backtest_for_new_run',
|
||||
'require_experiment_retry_failure',
|
||||
];
|
||||
expect(
|
||||
(await functions()).filter(
|
||||
row =>
|
||||
oldFunctions.some(old => old.proname === row.proname) && !changed.includes(row.proname)
|
||||
)
|
||||
).toEqual(oldFunctions.filter(row => !changed.includes(row.proname)));
|
||||
const expectedBlocks = {
|
||||
require_active_backtest_for_new_run: [
|
||||
" expected := jsonb_set(experiment.preview->'request','{runId}',to_jsonb(NEW.id::text));\n expected := jsonb_set(expected,'{policy,matching,risk,ledger,sessionId}',to_jsonb(NEW.id::text));\n expected := jsonb_set(expected,'{policy,matching,risk,ledger,accountId}',to_jsonb('research:'||NEW.id::text));\n expected := jsonb_set(expected,'{strategy,selection,parameters}',candidate->'parameters');",
|
||||
' expected := experiment_trial_request(experiment.preview,NEW.trial_index,NEW.id);',
|
||||
],
|
||||
require_experiment_retry_failure: [
|
||||
" expected := jsonb_set(experiment.preview->'request','{runId}',to_jsonb(original.id::text));\n expected := jsonb_set(expected,'{policy,matching,risk,ledger,sessionId}',to_jsonb(original.id::text));\n expected := jsonb_set(expected,'{policy,matching,risk,ledger,accountId}',to_jsonb('research:'||original.id::text));\n expected := jsonb_set(expected,'{strategy,selection,parameters}',candidate->'parameters');",
|
||||
' expected := experiment_trial_request(experiment.preview,original.trial_index,original.id);',
|
||||
],
|
||||
};
|
||||
const now = await functions();
|
||||
for (const [name, [oldBlock, newBlock]] of Object.entries(expectedBlocks)) {
|
||||
expect(now.find(r => r.proname === name)!.definition).toBe(
|
||||
oldFunctions.find(r => r.proname === name)!.definition.replace(oldBlock, newBlock)
|
||||
);
|
||||
}
|
||||
await f.pool.query(migration);
|
||||
expect(await f.snapshot()).toEqual(before);
|
||||
expect((await submit(f)).experiment.trials).toHaveLength(3);
|
||||
}, 60000);
|
||||
test('late candidate, outbox failure and omitted dispatch roll back all children and receipt', async () => {
|
||||
const f = await fixture();
|
||||
await f.review();
|
||||
const preview = await f.experiments.previewCosts(f.input),
|
||||
body = { ...f.input, previewHash: preview.previewHash };
|
||||
for (const [table, condition, action, message] of [
|
||||
['runs', 'NEW.trial_index=2', "RAISE EXCEPTION 'Injected failure';", 'Injected'],
|
||||
[
|
||||
'backtest_dispatch',
|
||||
'EXISTS(SELECT 1 FROM runs r WHERE r.id=NEW.run_id AND r.trial_index=2)',
|
||||
"RAISE EXCEPTION 'Injected failure';",
|
||||
'Injected',
|
||||
],
|
||||
['backtest_dispatch', 'TRUE', 'RETURN NULL;', 'atomically'],
|
||||
]) {
|
||||
await f.pool.query(
|
||||
`CREATE OR REPLACE FUNCTION cost_injection() RETURNS trigger LANGUAGE plpgsql AS $$ BEGIN IF ${condition} THEN ${action} END IF; RETURN NEW; END $$`
|
||||
);
|
||||
await f.pool.query(
|
||||
`CREATE TRIGGER cost_injection BEFORE INSERT ON ${table} FOR EACH ROW EXECUTE FUNCTION cost_injection()`
|
||||
);
|
||||
const before = await f.snapshot();
|
||||
await expect(f.experiments.submitCosts(body, actor())).rejects.toThrow(message);
|
||||
expect(await f.snapshot()).toEqual(before);
|
||||
await f.pool.query(`DROP TRIGGER cost_injection ON ${table}`);
|
||||
}
|
||||
expect((await f.experiments.submitCosts(body, actor())).trials).toHaveLength(3);
|
||||
}, 60000);
|
||||
test('same/cross-parent/cross-kind receipt races produce exactly one operation owner', async () => {
|
||||
const f = await fixture(5);
|
||||
await f.review();
|
||||
const preview = await f.experiments.previewCosts(f.input),
|
||||
body = { ...f.input, previewHash: preview.previewHash },
|
||||
identity = actor();
|
||||
const [first, replay] = await Promise.all([
|
||||
f.experiments.submitCosts(body, identity),
|
||||
f.experiments.submitCosts(body, identity),
|
||||
]);
|
||||
expect(first.id).toBe(replay.id);
|
||||
const other = await f.cloneTemplate(),
|
||||
otherInput = { ...f.input, backtestId: other.id },
|
||||
otherPreview = await f.experiments.previewCosts(otherInput),
|
||||
cross = actor();
|
||||
const race = await Promise.allSettled([
|
||||
f.experiments.submitCosts(body, cross),
|
||||
f.experiments.submitCosts({ ...otherInput, previewHash: otherPreview.previewHash }, cross),
|
||||
]);
|
||||
expect(race.filter(r => r.status === 'fulfilled')).toHaveLength(1);
|
||||
expect(race.filter(r => r.status === 'rejected')).toHaveLength(1);
|
||||
const normalInput = { backtestId: f.draft.id, name: 'Parameter sweep', grid: {} },
|
||||
normal = await f.experiments.preview(normalInput),
|
||||
mixed = actor();
|
||||
const mixedRace = await Promise.allSettled([
|
||||
f.experiments.submitCosts(body, mixed),
|
||||
f.experiments.submit({ ...normalInput, previewHash: normal.previewHash }, mixed),
|
||||
]);
|
||||
expect(mixedRace.filter(r => r.status === 'fulfilled')).toHaveLength(1);
|
||||
expect(mixedRace.filter(r => r.status === 'rejected')).toHaveLength(1);
|
||||
for (const item of [...race, ...mixedRace]) {
|
||||
if (item.status === 'rejected') {
|
||||
expect(item.reason).toBeInstanceOf(ExperimentError);
|
||||
expect(item.reason.status).toBe(409);
|
||||
}
|
||||
}
|
||||
expect((await f.pool.query('SELECT count(*)::int n FROM research_experiments')).rows[0].n).toBe(
|
||||
3
|
||||
);
|
||||
await expect(f.experiments.submitCosts({ ...body, name: 'Changed' }, identity)).rejects.toThrow(
|
||||
'different'
|
||||
);
|
||||
}, 60000);
|
||||
test('SQL targets exact source, baseline, cost shape, parameters and two-path request isolation', async () => {
|
||||
const f = await fixture(),
|
||||
start = await submit(f),
|
||||
row = (
|
||||
await f.pool.query('SELECT * FROM research_experiments WHERE id=$1', [start.experiment.id])
|
||||
).rows[0];
|
||||
const validate = async (preview: unknown) =>
|
||||
f.pool.query(
|
||||
'SELECT validate_cost_manifest(jsonb_populate_record(NULL::research_experiments,$1))',
|
||||
[{ ...row, preview }]
|
||||
);
|
||||
await validate(start.preview);
|
||||
for (const [mutate, message] of [
|
||||
[(p: typeof start.preview) => (p.source.input.grid = { fastPeriod: [1] }), 'empty-grid'],
|
||||
[
|
||||
(p: typeof start.preview) =>
|
||||
(p.request = structuredClone({ ...p.request, name: 'Foreign' })),
|
||||
'empty-grid',
|
||||
],
|
||||
[
|
||||
(p: typeof start.preview) => (p.candidates[0]!.costs = { feeRate: '0', slippageRate: '0' }),
|
||||
'exact ordered',
|
||||
],
|
||||
[
|
||||
(p: typeof start.preview) =>
|
||||
(p.candidates[1]!.parameters = { fastPeriod: 1, slowPeriod: 3 }),
|
||||
'fixed parameters',
|
||||
],
|
||||
[
|
||||
(p: typeof start.preview) =>
|
||||
(p.candidates[1]!.costs = { feeRate: '0.001', slippageRate: '0.00000000' }),
|
||||
'exact ordered',
|
||||
],
|
||||
[
|
||||
(p: typeof start.preview) => {
|
||||
p.input.scenarios[0]!.slippageRate = '1.00000000';
|
||||
p.candidates[1]!.costs.slippageRate = '1.00000000';
|
||||
},
|
||||
'canonical bounds',
|
||||
],
|
||||
[
|
||||
(p: typeof start.preview) => {
|
||||
p.input.scenarios[0] = { ...p.candidates[0]!.costs };
|
||||
p.candidates[1]!.costs = { ...p.candidates[0]!.costs };
|
||||
},
|
||||
'distinct',
|
||||
],
|
||||
] as const) {
|
||||
const preview = structuredClone(start.preview);
|
||||
mutate(preview);
|
||||
await expect(validate(preview)).rejects.toThrow(message);
|
||||
}
|
||||
const ordinaryInput = { backtestId: f.draft.id, name: 'Ordinary', grid: {} },
|
||||
normal = await f.experiments.preview(ordinaryInput);
|
||||
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,$6,$7,$8)',
|
||||
[
|
||||
randomUUID(),
|
||||
f.draft.id,
|
||||
ordinaryInput.name,
|
||||
{
|
||||
...normal,
|
||||
candidates: normal.candidates.map(c => ({
|
||||
...c,
|
||||
costs: { feeRate: '0', slippageRate: '0' },
|
||||
})),
|
||||
},
|
||||
normal.previewHash,
|
||||
'operator',
|
||||
randomUUID(),
|
||||
'a'.repeat(64),
|
||||
]
|
||||
)
|
||||
).rejects.toThrow('cannot contain');
|
||||
const clone = { ...row, id: randomUUID(), submission_key: randomUUID() };
|
||||
await expect(
|
||||
f.pool.query(
|
||||
'INSERT INTO research_experiments SELECT * FROM jsonb_populate_record(NULL::research_experiments,$1)',
|
||||
[clone]
|
||||
)
|
||||
).rejects.toThrow('atomically');
|
||||
const run = (
|
||||
await f.pool.query('SELECT * FROM runs WHERE id=$1', [start.experiment.trials[1]!.runId])
|
||||
).rows[0];
|
||||
const inserted = async (mutate: (r: Record<string, any>) => void) => {
|
||||
const client = await f.pool.connect();
|
||||
try {
|
||||
await client.query('BEGIN');
|
||||
const exp = { ...row, id: randomUUID(), submission_key: randomUUID() };
|
||||
await client.query(
|
||||
'INSERT INTO research_experiments SELECT * FROM jsonb_populate_record(NULL::research_experiments,$1)',
|
||||
[exp]
|
||||
);
|
||||
const id = randomUUID(),
|
||||
candidate = {
|
||||
...run,
|
||||
id,
|
||||
experiment_id: exp.id,
|
||||
run_number: 999,
|
||||
request_snapshot: structuredClone(run.request_snapshot),
|
||||
};
|
||||
candidate.request_snapshot.runId = id;
|
||||
candidate.request_snapshot.policy.matching.risk.ledger.sessionId = id;
|
||||
candidate.request_snapshot.policy.matching.risk.ledger.accountId = `research:${id}`;
|
||||
mutate(candidate);
|
||||
await client.query('INSERT INTO runs SELECT * FROM jsonb_populate_record(NULL::runs,$1)', [
|
||||
candidate,
|
||||
]);
|
||||
} finally {
|
||||
await client.query('ROLLBACK');
|
||||
client.release();
|
||||
}
|
||||
};
|
||||
await expect(
|
||||
inserted(r => (r.request_snapshot.policy.matching.risk.feeRate = '0.90000000'))
|
||||
).rejects.toThrow('exact frozen');
|
||||
await expect(
|
||||
inserted(r => (r.request_snapshot.policy.matching.halfSpreadRate = '0.10000000'))
|
||||
).rejects.toThrow('exact frozen');
|
||||
await expect(inserted(r => (r.trial_index = 99))).rejects.toThrow('exact candidate');
|
||||
expect((await f.experiments.get(start.experiment.id)).trials).toHaveLength(3);
|
||||
}, 60000);
|
||||
test('cancel overlaps a blocked manual retry, leaving no live work and retaining failure evidence', async () => {
|
||||
const f = await fixture(5),
|
||||
start = await submit(f),
|
||||
runId = start.experiment.trials[1]!.runId!;
|
||||
await f.pool.query(
|
||||
"UPDATE runs SET status='failed',error='Cost failure',completed_at=NOW() WHERE id=$1",
|
||||
[runId]
|
||||
);
|
||||
const before = (await f.pool.query('SELECT to_jsonb(r) row FROM runs r WHERE id=$1', [runId]))
|
||||
.rows;
|
||||
const blocker = await f.pool.connect();
|
||||
await blocker.query('BEGIN');
|
||||
await blocker.query('SELECT id FROM backtests WHERE id=$1 FOR UPDATE', [f.draft.id]);
|
||||
const pending = Promise.allSettled([
|
||||
f.experiments.retryTrial(
|
||||
start.experiment.id,
|
||||
runId,
|
||||
{ expectedAttemptNumber: 0, expectedRetryCount: 0 },
|
||||
actor()
|
||||
),
|
||||
]);
|
||||
try {
|
||||
let count = 0;
|
||||
for (let i = 0; i < 100; i++) {
|
||||
count = Number(
|
||||
(
|
||||
await f.pool.query(
|
||||
"SELECT count(*)::int n FROM pg_stat_activity WHERE application_name=current_schema() AND wait_event_type='Lock'"
|
||||
)
|
||||
).rows[0].n
|
||||
);
|
||||
if (count > 0) {
|
||||
break;
|
||||
}
|
||||
await new Promise(resolve => setTimeout(resolve, 10));
|
||||
}
|
||||
expect(count).toBeGreaterThan(0);
|
||||
await f.experiments.cancel(start.experiment.id);
|
||||
await blocker.query('COMMIT');
|
||||
} finally {
|
||||
await blocker.query('ROLLBACK');
|
||||
blocker.release();
|
||||
}
|
||||
const outcome = (await pending)[0]!;
|
||||
expect(outcome.status).toBe('rejected');
|
||||
if (outcome.status === 'rejected') {
|
||||
expect(outcome.reason).toBeInstanceOf(ExperimentError);
|
||||
expect(outcome.reason.status).toBe(409);
|
||||
}
|
||||
expect(
|
||||
(await f.pool.query('SELECT to_jsonb(r) row FROM runs r WHERE id=$1', [runId])).rows
|
||||
).toEqual(before);
|
||||
const detail = await f.experiments.get(start.experiment.id);
|
||||
expect(detail.cancelRequested).toBe(true);
|
||||
expect(detail.trials.filter(t => t.status === 'cancelled')).toHaveLength(2);
|
||||
}, 60000);
|
||||
});
|
||||
|
|
@ -78,6 +78,7 @@ async function fixture() {
|
|||
'23-experiment-retries.sql',
|
||||
'24-chronological-validation.sql',
|
||||
'25-walk-forward.sql',
|
||||
'26-cost-sensitivity.sql',
|
||||
]) {
|
||||
await pool.query(
|
||||
readFileSync(new URL(`../../database/postgres/init/${name}`, import.meta.url), 'utf8')
|
||||
|
|
|
|||
|
|
@ -89,6 +89,7 @@ async function fixture() {
|
|||
'23-experiment-retries.sql',
|
||||
'24-chronological-validation.sql',
|
||||
'25-walk-forward.sql',
|
||||
'26-cost-sensitivity.sql',
|
||||
]) {
|
||||
await pool.query(
|
||||
readFileSync(new URL(`../../database/postgres/init/${filename}`, import.meta.url), 'utf8')
|
||||
|
|
|
|||
|
|
@ -70,7 +70,12 @@ async function fixture(poolMax = 4, withRetries = true) {
|
|||
'21-run-reproduction.sql',
|
||||
'22-experiments.sql',
|
||||
...(withRetries
|
||||
? ['23-experiment-retries.sql', '24-chronological-validation.sql', '25-walk-forward.sql']
|
||||
? [
|
||||
'23-experiment-retries.sql',
|
||||
'24-chronological-validation.sql',
|
||||
'25-walk-forward.sql',
|
||||
'26-cost-sensitivity.sql',
|
||||
]
|
||||
: []),
|
||||
]) {
|
||||
await pool.query(
|
||||
|
|
|
|||
|
|
@ -70,6 +70,7 @@ async function fixture(poolMax = 4, withExperiments = true) {
|
|||
'23-experiment-retries.sql',
|
||||
'24-chronological-validation.sql',
|
||||
'25-walk-forward.sql',
|
||||
'26-cost-sensitivity.sql',
|
||||
]
|
||||
: []),
|
||||
]) {
|
||||
|
|
|
|||
|
|
@ -28,6 +28,7 @@ const migrations = [
|
|||
'23-experiment-retries.sql',
|
||||
'24-chronological-validation.sql',
|
||||
'25-walk-forward.sql',
|
||||
'26-cost-sensitivity.sql',
|
||||
];
|
||||
const cleanup: (() => Promise<void>)[] = [];
|
||||
afterEach(async () => {
|
||||
|
|
|
|||
|
|
@ -33,7 +33,9 @@ const retention =
|
|||
'\n' +
|
||||
sql('24-chronological-validation.sql') +
|
||||
'\n' +
|
||||
sql('25-walk-forward.sql');
|
||||
sql('25-walk-forward.sql') +
|
||||
'\n' +
|
||||
sql('26-cost-sensitivity.sql');
|
||||
const request = {
|
||||
name: 'Retained evidence',
|
||||
strategy: 'sma-crossover',
|
||||
|
|
|
|||
|
|
@ -74,6 +74,7 @@ async function fixture() {
|
|||
'23-experiment-retries.sql',
|
||||
'24-chronological-validation.sql',
|
||||
'25-walk-forward.sql',
|
||||
'26-cost-sensitivity.sql',
|
||||
]) {
|
||||
await pool.query(
|
||||
readFileSync(new URL(`../../database/postgres/init/${filename}`, import.meta.url), 'utf8')
|
||||
|
|
|
|||
|
|
@ -65,6 +65,7 @@ async function fixture(applyWorkspace = true, maxConnections = 10) {
|
|||
'23-experiment-retries.sql',
|
||||
'24-chronological-validation.sql',
|
||||
'25-walk-forward.sql',
|
||||
'26-cost-sensitivity.sql',
|
||||
]) {
|
||||
await pool.query(sql(name));
|
||||
}
|
||||
|
|
|
|||
|
|
@ -68,6 +68,7 @@ async function fixture(poolMax = 4, withReproduction = true) {
|
|||
'23-experiment-retries.sql',
|
||||
'24-chronological-validation.sql',
|
||||
'25-walk-forward.sql',
|
||||
'26-cost-sensitivity.sql',
|
||||
]
|
||||
: []),
|
||||
]) {
|
||||
|
|
|
|||
|
|
@ -71,7 +71,7 @@ async function fixture(poolMax = 1, withWalkForward = true) {
|
|||
'22-experiments.sql',
|
||||
'23-experiment-retries.sql',
|
||||
'24-chronological-validation.sql',
|
||||
...(withWalkForward ? ['25-walk-forward.sql'] : []),
|
||||
...(withWalkForward ? ['25-walk-forward.sql', '26-cost-sensitivity.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