fix(research): honor retained candidate parameter defaults (RP17)
This commit is contained in:
parent
f185f2e253
commit
1502ab41dc
9 changed files with 727 additions and 7 deletions
|
|
@ -284,6 +284,7 @@ export async function fixture(browser: Browser, native = false) {
|
|||
'29-isolated-candidates.sql',
|
||||
'30-paper-deployments.sql',
|
||||
'31-research-agent-project-links.sql',
|
||||
'32-candidate-parameter-defaults.sql',
|
||||
]) {
|
||||
await pool.query(
|
||||
readFileSync(new URL(`../../database/postgres/init/${name}`, import.meta.url), 'utf8')
|
||||
|
|
|
|||
|
|
@ -3873,7 +3873,8 @@ test('isolated_candidate_publication_research_validation_and_reviewed_paper_hist
|
|||
await f.page.waitForURL(`${f.origin}/backtests/${draft.id}/run/${runId}`);
|
||||
|
||||
// Real immutable validation and cost evidence prepare the human promotion screen.
|
||||
const candidate = { versionId: version.id, parameters: { fastPeriod: 2, slowPeriod: 3 } };
|
||||
// Preserve partial input while the retained package supplies fastPeriod's default.
|
||||
const candidate = { versionId: version.id, parameters: { slowPeriod: 6 } };
|
||||
const validationInput = {
|
||||
backtestId: draft.id,
|
||||
name: 'Browser candidate holdouts',
|
||||
|
|
@ -3896,6 +3897,15 @@ test('isolated_candidate_publication_research_validation_and_reviewed_paper_hist
|
|||
)
|
||||
).validation as ChronologicalValidationDetail;
|
||||
expect(preview.policy.model).toBe('unverified-candidate');
|
||||
expect(validation.preview.input.candidate).toEqual(candidate);
|
||||
expect(validation.phases[0]!.experiment!.preview.input.candidate?.parameters).toEqual({
|
||||
fastPeriod: 5,
|
||||
slowPeriod: 6,
|
||||
});
|
||||
await f.page.goto(`${f.origin}/experiments/validation/${validation.id}`);
|
||||
await visible(f.page, 'Training candidates admitted · selection not yet frozen');
|
||||
await f.page.reload();
|
||||
await visible(f.page, 'Training candidates admitted · selection not yet frozen');
|
||||
await completeExperiment(validation.phases[0]!.experimentId!);
|
||||
const selected = (await f.request(
|
||||
`/api/v2/experiments/validation/${validation.id}/select`,
|
||||
|
|
@ -3916,6 +3926,8 @@ test('isolated_candidate_publication_research_validation_and_reviewed_paper_hist
|
|||
{ 'Idempotency-Key': randomUUID() }
|
||||
)) as ChronologicalValidationActionResult;
|
||||
expect(finished.validation.report).not.toBeNull();
|
||||
await f.page.reload();
|
||||
await visible(f.page, 'Execution complete · report saved');
|
||||
const costInput = {
|
||||
backtestId: draft.id,
|
||||
name: 'Browser candidate costs',
|
||||
|
|
|
|||
|
|
@ -1,8 +1,36 @@
|
|||
import { expect, test } from 'bun:test';
|
||||
import type { PoolClient } from 'pg';
|
||||
import type { IServiceContainer } from '@stock-bot/services';
|
||||
import { candidateSandboxLimits } from '@stock-bot/stock-config/candidate-execution';
|
||||
import { canonicalRunRequestSchema } from '@stock-bot/stock-config/canonical-research';
|
||||
import type {
|
||||
ChronologicalValidationPreview,
|
||||
ValidationResultEvidence,
|
||||
} from '@stock-bot/stock-config/chronological-validation';
|
||||
import type { ExperimentPreview } from '@stock-bot/stock-config/experiments';
|
||||
import { validateStrategyParameters } from '@stock-bot/stock-config/strategy';
|
||||
import type { WalkForwardDetail } from '@stock-bot/stock-config/walk-forward';
|
||||
import type { StrategyParameterValue } from '@stock-bot/types';
|
||||
import { parseExperimentPreview } from '../../apps/stock/config/src/contracts/research-responses/experiment';
|
||||
import { parseValidationDetail } from '../../apps/stock/config/src/contracts/research-responses/validation';
|
||||
import { parseChronologicalValidationPreview } from '../../apps/stock/config/src/contracts/research-responses/validation-preview';
|
||||
import { parseWalkForwardDetail } from '../../apps/stock/config/src/contracts/research-responses/walk-forward';
|
||||
import { canonicalRiskSessionClock } from '../../apps/stock/web-api/src/services/canonical-risk-clock';
|
||||
import { ChronologicalValidationService } from '../../apps/stock/web-api/src/services/chronological-validation.service';
|
||||
import {
|
||||
buildExperimentPreview,
|
||||
experimentHash,
|
||||
experimentTrialRequest,
|
||||
} from '../../apps/stock/web-api/src/services/experiment-input';
|
||||
import { ExperimentsService } from '../../apps/stock/web-api/src/services/experiments.service';
|
||||
import {
|
||||
selectValidationWinner,
|
||||
validationPhasePreview,
|
||||
} from '../../apps/stock/web-api/src/services/validation-evidence';
|
||||
import { prepareChronologicalValidation } from '../../apps/stock/web-api/src/services/validation-preview';
|
||||
import { prepareWalkForward } from '../../apps/stock/web-api/src/services/walk-forward-input';
|
||||
import { tableFixture } from '../../scripts/benchmark-experiment-tables';
|
||||
import { walkForwardDataset } from '../fixtures/walk-forward';
|
||||
|
||||
function candidatePreview() {
|
||||
const value = structuredClone(tableFixture(1).preview);
|
||||
|
|
@ -61,3 +89,282 @@ test('candidate parameter defaults are accepted when they exactly match the reta
|
|||
value.input.candidate!.parameters.fastPeriod = 1;
|
||||
expect(() => parseExperimentPreview(value)).toThrow('could not be verified');
|
||||
});
|
||||
|
||||
const validationId = '11111111-1111-4111-8111-111111111111';
|
||||
const childIds = {
|
||||
validation: '22222222-2222-4222-8222-222222222222',
|
||||
test: '33333333-3333-4333-8333-333333333333',
|
||||
};
|
||||
const createdAt = '2026-10-27T12:00:00Z';
|
||||
|
||||
function validationPreparation(
|
||||
parameters: Record<string, StrategyParameterValue> = {},
|
||||
builtin = false
|
||||
) {
|
||||
const data = walkForwardDataset();
|
||||
const prototype = builtin ? tableFixture(1).preview : candidatePreview();
|
||||
const request = structuredClone(prototype.request);
|
||||
request.datasetHash = data.dataset.manifest.hash;
|
||||
request.strategy.selection.parameters = validateStrategyParameters(
|
||||
request.strategy.package,
|
||||
builtin ? { fastPeriod: 2, slowPeriod: 3 } : parameters
|
||||
);
|
||||
const clock = canonicalRiskSessionClock(data.dataset);
|
||||
request.policy.matching.risk.ledger.riskSession = clock.riskSession;
|
||||
request.policy.risk_boundaries = clock.riskBoundaries;
|
||||
const input = {
|
||||
backtestId: request.backtestId,
|
||||
name: 'Candidate default validation',
|
||||
grid: { fastPeriod: [1, 2] },
|
||||
...(!builtin ? { candidate: { versionId: request.strategy.versionId, parameters } } : {}),
|
||||
};
|
||||
const source = buildExperimentPreview(
|
||||
input,
|
||||
canonicalRunRequestSchema.parse(request),
|
||||
data.dataset.manifest
|
||||
);
|
||||
const prepared = prepareChronologicalValidation(
|
||||
{ ...input, recipe: data.windows[0]! },
|
||||
source,
|
||||
data.dataset
|
||||
);
|
||||
return { input, source, data, prepared };
|
||||
}
|
||||
|
||||
/** Read-only stored rows derived from real child builders; no admission or financial simulation. */
|
||||
function pendingStorage(preview: ExperimentPreview, id: string) {
|
||||
const row: Record<string, unknown> = {
|
||||
id,
|
||||
backtest_id: preview.input.backtestId,
|
||||
name: preview.input.name,
|
||||
created_at: createdAt,
|
||||
cancel_requested: false,
|
||||
preview,
|
||||
preview_hash: preview.previewHash,
|
||||
trial_count: preview.candidates.length,
|
||||
dataset_hash: preview.request.datasetHash,
|
||||
strategy_version_id: preview.request.strategy.versionId,
|
||||
};
|
||||
const runs = preview.candidates.map(candidate => {
|
||||
const runId = `77777777-7777-4777-8777-${String(candidate.index + 1).padStart(12, '0')}`;
|
||||
return {
|
||||
id: runId,
|
||||
backtest_id: preview.input.backtestId,
|
||||
trial_index: candidate.index,
|
||||
trial_key: candidate.trialKey,
|
||||
status: 'pending',
|
||||
attempt_number: 0,
|
||||
manual_retry_count: 0,
|
||||
progress: 0,
|
||||
cancel_requested: false,
|
||||
error: null,
|
||||
dataset_hash: preview.request.datasetHash,
|
||||
request_snapshot: experimentTrialRequest(preview, candidate, runId),
|
||||
};
|
||||
});
|
||||
const database = {
|
||||
async query(sql: string) {
|
||||
return { rows: sql.includes('FROM runs r LEFT JOIN backtest_results') ? runs : [row] };
|
||||
},
|
||||
};
|
||||
return {
|
||||
row,
|
||||
database,
|
||||
container: { postgres: database } as unknown as IServiceContainer,
|
||||
client: database as unknown as PoolClient,
|
||||
};
|
||||
}
|
||||
async function pendingValidation(preview: ChronologicalValidationPreview, id = validationId) {
|
||||
const stored = pendingStorage(validationPhasePreview(preview, 'train'), id);
|
||||
Object.assign(stored.row, {
|
||||
validation_manifest: preview,
|
||||
validation_selection: null,
|
||||
validation_report: null,
|
||||
});
|
||||
return new ChronologicalValidationService(stored.container).readDetail(stored.client, id);
|
||||
}
|
||||
|
||||
for (const [label, parameters] of [
|
||||
['omitted defaults', {}],
|
||||
['partial defaults', { fastPeriod: 4 }],
|
||||
['explicit parameters', { fastPeriod: 4, slowPeriod: 9 }],
|
||||
] as const) {
|
||||
test(`actual candidate validation detail accepts ${label} without changing retained inputs or hashes`, async () => {
|
||||
const { prepared } = validationPreparation(parameters);
|
||||
const original = structuredClone(prepared.preview);
|
||||
expect(
|
||||
parseChronologicalValidationPreview({ preview: prepared.preview }, prepared.preview.input)
|
||||
.input.candidate?.parameters
|
||||
).toEqual(parameters);
|
||||
const detail = await pendingValidation(prepared.preview);
|
||||
const before = structuredClone(detail);
|
||||
const decoded = parseValidationDetail(detail);
|
||||
expect(decoded.phases[0]!.experiment!.preview.input.candidate?.parameters).toEqual(
|
||||
prepared.preview.partitions[0].request.strategy.selection.parameters
|
||||
);
|
||||
expect(decoded.preview.input.candidate?.parameters).toEqual(parameters);
|
||||
expect(decoded.preview.previewHash).toBe(original.previewHash);
|
||||
expect(decoded.phases[0]!.experiment!.previewHash).toBe(
|
||||
before.phases[0].experiment!.previewHash
|
||||
);
|
||||
expect(detail).toEqual(before);
|
||||
expect(prepared.preview).toEqual(original);
|
||||
});
|
||||
}
|
||||
|
||||
test('built-in validation retains its existing no-candidate contract', async () => {
|
||||
const { prepared } = validationPreparation({}, true);
|
||||
const detail = await pendingValidation(prepared.preview);
|
||||
expect(parseValidationDetail(detail).id).toBe(validationId);
|
||||
expect(detail.phases[0].experiment!.preview.input.candidate).toBeUndefined();
|
||||
});
|
||||
|
||||
test('candidate defaults do not permit altered child parameters, version, or retained request', async () => {
|
||||
const { prepared } = validationPreparation({ fastPeriod: 4 });
|
||||
const detail = await pendingValidation(prepared.preview);
|
||||
expect(parseValidationDetail(detail).id).toBe(validationId);
|
||||
for (const changed of ['parameters', 'version', 'request'] as const) {
|
||||
const modified = structuredClone(detail);
|
||||
const child = modified.phases[0].experiment!.preview;
|
||||
if (child.request.strategy.origin !== 'candidate') {
|
||||
throw new Error('Expected candidate fixture');
|
||||
}
|
||||
if (changed === 'parameters') {
|
||||
child.input.candidate!.parameters.fastPeriod = 3;
|
||||
} else if (changed === 'version') {
|
||||
child.input.candidate!.versionId = '99999999-9999-4999-8999-999999999999';
|
||||
} else {
|
||||
// Internally consistent child inputs still cannot replace the retained phase request.
|
||||
child.request.strategy.selection.parameters.fastPeriod = 3;
|
||||
child.input.candidate!.parameters.fastPeriod = 3;
|
||||
}
|
||||
expect(() => parseValidationDetail(modified)).toThrow();
|
||||
}
|
||||
});
|
||||
|
||||
test('candidate holdouts bind to the frozen winner rather than raw defaults or the training base', async () => {
|
||||
const { prepared } = validationPreparation({ fastPeriod: 4 });
|
||||
const detail = await pendingValidation(prepared.preview);
|
||||
const train = detail.phases[0].experiment!;
|
||||
// Synthetic completed metrics enable response-contract checks, not financial correctness claims.
|
||||
const metrics = tableFixture(1).trials[0]!.metrics!;
|
||||
for (const trial of train.trials) {
|
||||
Object.assign(trial, {
|
||||
status: 'completed',
|
||||
comparable: true,
|
||||
diagnostic: null,
|
||||
metrics: { ...metrics, totalReturn: trial.index },
|
||||
unavailable: {},
|
||||
});
|
||||
}
|
||||
train.counts.pending = 0;
|
||||
train.counts.completed = train.trialCount;
|
||||
const training: ValidationResultEvidence[] = train.trials.map(trial => ({
|
||||
phase: 'train',
|
||||
experimentId: train.id,
|
||||
runId: trial.runId!,
|
||||
sourceCandidateIndex: trial.index,
|
||||
trialKey: trial.trialKey,
|
||||
parameters: trial.parameters,
|
||||
datasetHash: train.datasetHash,
|
||||
requestHash: experimentHash(experimentTrialRequest(train.preview, trial, trial.runId!)),
|
||||
economicHash: 'e'.repeat(64),
|
||||
metrics: trial.metrics!,
|
||||
unavailable: trial.unavailable!,
|
||||
completePeriodCount: 0,
|
||||
periodicSampleCount: 0,
|
||||
fillCount: 0,
|
||||
limitations: [],
|
||||
}));
|
||||
const winner = selectValidationWinner(prepared.preview.source.candidates, training);
|
||||
detail.selection = {
|
||||
version: 'chronological-validation-selection/v1',
|
||||
id: '44444444-4444-4444-8444-444444444444',
|
||||
validationId,
|
||||
previewHash: prepared.preview.previewHash,
|
||||
selectionHash: 'd'.repeat(64),
|
||||
createdAt,
|
||||
principal: 'operator',
|
||||
reviewId: null,
|
||||
winner,
|
||||
training,
|
||||
holdoutExperimentIds: childIds,
|
||||
};
|
||||
detail.stage = 'holdouts';
|
||||
for (const [index, phase] of (['validation', 'test'] as const).entries()) {
|
||||
const preview = validationPhasePreview(prepared.preview, phase, winner, null);
|
||||
const stored = pendingStorage(preview, childIds[phase]);
|
||||
detail.phases[index + 1] = {
|
||||
phase,
|
||||
status: 'admitted',
|
||||
experimentId: childIds[phase],
|
||||
experiment: await new ExperimentsService(stored.container).readParameterDetail(
|
||||
stored.database,
|
||||
childIds[phase]
|
||||
),
|
||||
};
|
||||
}
|
||||
const decoded = parseValidationDetail(detail);
|
||||
expect(decoded.selection!.winner.parameters.fastPeriod).toBe(2);
|
||||
expect(decoded.phases[0]!.experiment!.preview.input.candidate?.parameters.fastPeriod).toBe(4);
|
||||
for (const phase of decoded.phases.slice(1)) {
|
||||
expect(phase.experiment!.preview.input.candidate?.parameters).toEqual(winner.parameters);
|
||||
}
|
||||
const wrongWinner = structuredClone(detail);
|
||||
wrongWinner.selection!.winner = prepared.preview.source.candidates[0]!;
|
||||
expect(() => parseValidationDetail(wrongWinner)).toThrow();
|
||||
const wrongHoldout = structuredClone(detail);
|
||||
const child = wrongHoldout.phases[1].experiment!.preview;
|
||||
if (child.request.strategy.origin !== 'candidate') {
|
||||
throw new Error('Expected candidate fixture');
|
||||
}
|
||||
child.input.candidate!.parameters.fastPeriod = 4;
|
||||
child.request.strategy.selection.parameters.fastPeriod = 4;
|
||||
expect(() => parseValidationDetail(wrongHoldout)).toThrow();
|
||||
});
|
||||
|
||||
test('nested walk-forward validation accepts defaulted candidate children and rejects changed window inputs', async () => {
|
||||
const { source, data, input } = validationPreparation();
|
||||
const prepared = prepareWalkForward({ ...input, windows: data.windows }, source, data.dataset);
|
||||
const original = structuredClone(prepared.preview);
|
||||
const windows = await Promise.all(
|
||||
prepared.prepared.map(async (member, index) => {
|
||||
const validationId = `88888888-8888-4888-8888-${String(index + 1).padStart(12, '0')}`;
|
||||
return {
|
||||
index,
|
||||
validationId,
|
||||
status: 'admitted' as const,
|
||||
validation: await pendingValidation(member.preview, validationId),
|
||||
};
|
||||
})
|
||||
);
|
||||
const detail: WalkForwardDetail = {
|
||||
id: '99999999-9999-4999-8999-999999999999',
|
||||
backtestId: input.backtestId,
|
||||
name: input.name,
|
||||
createdAt,
|
||||
cancelRequested: false,
|
||||
previewHash: prepared.preview.previewHash,
|
||||
windowCount: windows.length,
|
||||
reportedWindowCount: 0,
|
||||
trainingRunCount: prepared.preview.counts.trainingRuns,
|
||||
plannedRunCount: prepared.preview.counts.totalRuns,
|
||||
stage: 'windows',
|
||||
preview: prepared.preview,
|
||||
windows,
|
||||
report: null,
|
||||
actions: { finalize: { available: false, reason: 'Training is pending' } },
|
||||
};
|
||||
const decoded = parseWalkForwardDetail(detail);
|
||||
expect(decoded.windows).toHaveLength(2);
|
||||
for (const window of decoded.windows) {
|
||||
expect(window.validation!.preview.input.candidate?.parameters).toEqual({});
|
||||
expect(window.validation!.phases[0]!.experiment!.preview.input.candidate?.parameters).toEqual(
|
||||
source.request.strategy.selection.parameters
|
||||
);
|
||||
}
|
||||
expect(prepared.preview).toEqual(original);
|
||||
const changed = structuredClone(detail);
|
||||
changed.windows[1]!.validation!.phases[0].experiment!.preview.input.candidate!.parameters.fastPeriod = 3;
|
||||
expect(() => parseWalkForwardDetail(changed)).toThrow();
|
||||
});
|
||||
|
|
|
|||
|
|
@ -68,6 +68,7 @@ async function fixture() {
|
|||
'28-research-agents.sql',
|
||||
'29-isolated-candidates.sql',
|
||||
'31-research-agent-project-links.sql',
|
||||
'32-candidate-parameter-defaults.sql',
|
||||
]) {
|
||||
await pool.query(
|
||||
readFileSync(new URL(`../../database/postgres/init/${name}`, import.meta.url), 'utf8')
|
||||
|
|
@ -211,7 +212,8 @@ async function fixture() {
|
|||
name: 'Trend candidate',
|
||||
rationale: 'Short/long trend signals',
|
||||
package: trend,
|
||||
parameters: { fastPeriod: 2, slowPeriod: 3 },
|
||||
// Exercise default expansion throughout training, holdouts and saved evidence.
|
||||
parameters: { slowPeriod: 6 },
|
||||
grid: { fastPeriod: [1, 2] },
|
||||
},
|
||||
{
|
||||
|
|
@ -253,6 +255,64 @@ async function fixture() {
|
|||
}
|
||||
|
||||
describe.skipIf(!url)('AI research workflow through authenticated APIs and Rust', () => {
|
||||
test('defaulted candidate validation accepts, reopens and replays the exact original input', async () => {
|
||||
const f = await fixture();
|
||||
const plan = f.suggestions();
|
||||
const family = await f.client.createStrategy({
|
||||
name: 'Defaulted validation candidate',
|
||||
description: 'Omitted and partial parameter defaults',
|
||||
});
|
||||
const version = await f.client.publishVersion(
|
||||
family.id,
|
||||
plan.candidates[0]!.package,
|
||||
'defaults:version'
|
||||
);
|
||||
const cases: { parameters: Record<string, number>; normalized: Record<string, number> }[] = [
|
||||
{ parameters: {}, normalized: { fastPeriod: 5, slowPeriod: 15 } },
|
||||
{ parameters: { slowPeriod: 6 }, normalized: { fastPeriod: 5, slowPeriod: 6 } },
|
||||
];
|
||||
for (const [index, item] of cases.entries()) {
|
||||
const input = {
|
||||
backtestId: plan.backtestId,
|
||||
name: `Defaulted candidate ${index}`,
|
||||
candidate: { versionId: version.id, parameters: item.parameters },
|
||||
grid: {},
|
||||
recipe: plan.candidates[0]!.recipe,
|
||||
};
|
||||
const preview = await f.client.previewValidation(input);
|
||||
expect(preview.input).toEqual(input);
|
||||
expect(preview.partitions[0].request.strategy.selection.parameters).toEqual(item.normalized);
|
||||
const submission = { ...preview.input, previewHash: preview.previewHash };
|
||||
const key = `defaults:validation:${index}`;
|
||||
const saved = await f.client.submitValidation(submission, key);
|
||||
expect(saved.preview.input).toEqual(input);
|
||||
expect(saved.phases[0]!.experiment!.preview.input.candidate).toEqual({
|
||||
versionId: version.id,
|
||||
parameters: item.normalized,
|
||||
});
|
||||
const reopened = await f.client.waitForValidation(saved.id, {
|
||||
timeoutMs: 60000,
|
||||
intervalMs: 20,
|
||||
});
|
||||
expect(reopened.previewHash).toBe(preview.previewHash);
|
||||
expect(reopened.preview.input).toEqual(input);
|
||||
expect(reopened.phases[0]!.experiment!.trials[0]!.status).toBe('completed');
|
||||
const replayed = await f.client.submitValidation(submission, key);
|
||||
expect(replayed.id).toBe(saved.id);
|
||||
expect(replayed.previewHash).toBe(preview.previewHash);
|
||||
expect(replayed.phases[0]!.experiment!.trials[0]!.runId).toBe(
|
||||
reopened.phases[0]!.experiment!.trials[0]!.runId!
|
||||
);
|
||||
const writes = f.requests.filter(request => request.key === key);
|
||||
expect(writes).toHaveLength(2);
|
||||
expect(writes[0]).toEqual(writes[1]!);
|
||||
expect(writes[0]!.body).toEqual(submission);
|
||||
expect(writes[0]!.status).toBe(202);
|
||||
}
|
||||
expect((await f.pool.query('SELECT count(*)::int AS count FROM runs')).rows[0].count).toBe(2);
|
||||
expect(f.executionErrors).toEqual([]);
|
||||
}, 60000);
|
||||
|
||||
test('candidate revisions retain automatic and explicit lineage across delayed receipt replay', async () => {
|
||||
const f = await fixture();
|
||||
const family = await f.client.createStrategy({
|
||||
|
|
|
|||
228
test/postgres/candidate-parameter-defaults.test.ts
Normal file
228
test/postgres/candidate-parameter-defaults.test.ts
Normal file
|
|
@ -0,0 +1,228 @@
|
|||
import { randomUUID } from 'node:crypto';
|
||||
import { readFileSync } from 'node:fs';
|
||||
import { afterEach, describe, expect, test } from 'bun:test';
|
||||
import { Pool } from 'pg';
|
||||
import { getLogger, setLoggerConfig } from '@stock-bot/logger';
|
||||
import { PostgreSQLClient } from '@stock-bot/postgres';
|
||||
import { ExperimentsService } from '../../apps/stock/web-api/src/services/experiments.service';
|
||||
import { canonicalAdmissionFixture } from '../fixtures/canonical-admission';
|
||||
|
||||
setLoggerConfig({ logLevel: 'fatal', logConsole: false });
|
||||
const logger = getLogger('candidate-parameter-defaults-test');
|
||||
const url = process.env.PIPELINE_TEST_DATABASE_URL;
|
||||
const cleanups: (() => Promise<void>)[] = [];
|
||||
afterEach(async () => {
|
||||
for (const close of cleanups.splice(0).reverse()) {
|
||||
await close();
|
||||
}
|
||||
});
|
||||
const migrations = [
|
||||
'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',
|
||||
'20-research-workspace.sql',
|
||||
'21-run-reproduction.sql',
|
||||
'22-experiments.sql',
|
||||
'23-experiment-retries.sql',
|
||||
'24-chronological-validation.sql',
|
||||
'25-walk-forward.sql',
|
||||
'26-cost-sensitivity.sql',
|
||||
'27-research-evidence-sources.sql',
|
||||
'28-research-agents.sql',
|
||||
'29-isolated-candidates.sql',
|
||||
];
|
||||
async function fixture() {
|
||||
if (!url || !new URL(url).pathname.startsWith('/stock_bot_safety')) {
|
||||
throw new Error('Disposable safety database required');
|
||||
}
|
||||
const schema = 'stock_bot_safety_defaults_' + randomUUID().replaceAll('-', '');
|
||||
const admin = new Pool({ connectionString: url });
|
||||
await admin.query(`CREATE SCHEMA ${schema}`);
|
||||
const pool = new Pool({
|
||||
connectionString: url,
|
||||
max: 4,
|
||||
options: `-c search_path=${schema} -c statement_timeout=10000`,
|
||||
});
|
||||
cleanups.push(async () => {
|
||||
await pool.end();
|
||||
await admin.query(`DROP SCHEMA ${schema} CASCADE`);
|
||||
await admin.end();
|
||||
});
|
||||
const apply = (file = '32-candidate-parameter-defaults.sql') =>
|
||||
pool.query(
|
||||
readFileSync(new URL(`../../database/postgres/init/${file}`, import.meta.url), 'utf8')
|
||||
);
|
||||
for (const file of migrations) {
|
||||
await apply(file);
|
||||
}
|
||||
const postgres = new PostgreSQLClient(
|
||||
{ host: 'unused', port: 5432, database: 'unused', username: 'unused', password: 'unused' },
|
||||
logger
|
||||
);
|
||||
Object.defineProperty(postgres, 'connectionPool', { get: () => pool });
|
||||
const base = await canonicalAdmissionFixture(pool, postgres, false);
|
||||
const family = await base.catalog.createStrategy(
|
||||
{ name: 'Defaulted SMA', description: 'SQL admission fixture; never executed' },
|
||||
'operator'
|
||||
);
|
||||
const candidate = await base.catalog.publishVersion(
|
||||
family.id,
|
||||
{
|
||||
...(await base.catalog.getVersionArtifact(base.version.id)),
|
||||
execution: { kind: 'isolated-candidate/v1', warmupBars: 0 },
|
||||
},
|
||||
null,
|
||||
'operator',
|
||||
randomUUID()
|
||||
);
|
||||
const experiments = new ExperimentsService({ postgres, logger });
|
||||
const readManifest = async (id: string) =>
|
||||
(await pool.query('SELECT to_jsonb(e) AS value FROM research_experiments e WHERE id=$1', [id]))
|
||||
.rows[0].value;
|
||||
const validate = (row: unknown) =>
|
||||
pool.query(
|
||||
'SELECT validate_experiment_manifest(jsonb_populate_record(NULL::research_experiments,$1))',
|
||||
[row]
|
||||
);
|
||||
const snapshot = async () =>
|
||||
(
|
||||
await pool.query(`SELECT
|
||||
(SELECT jsonb_agg(to_jsonb(e) ORDER BY id) FROM research_experiments e) AS experiments,
|
||||
(SELECT jsonb_agg(to_jsonb(r) ORDER BY id) FROM runs r) AS runs,
|
||||
(SELECT jsonb_agg(to_jsonb(v) ORDER BY id) FROM strategy_versions v) AS versions`)
|
||||
).rows;
|
||||
return { ...base, pool, candidate, experiments, apply, readManifest, validate, snapshot };
|
||||
}
|
||||
const suite = url ? describe : describe.skip;
|
||||
suite('candidate parameter default SQL admission', () => {
|
||||
test('SQL32 preserves retained rows and admits empty/partial defaults without rewriting input', async () => {
|
||||
const f = await fixture();
|
||||
const explicit = await f.experiments.preview({
|
||||
name: 'Explicit before upgrade',
|
||||
backtestId: f.draft.id,
|
||||
grid: {},
|
||||
candidate: { versionId: f.candidate.id, parameters: { fastPeriod: 2, slowPeriod: 3 } },
|
||||
});
|
||||
const existing = await f.experiments.submit(
|
||||
{ ...explicit.input, previewHash: explicit.previewHash },
|
||||
{ principal: 'operator', key: 'explicit' }
|
||||
);
|
||||
const builtin = await f.experiments.preview({
|
||||
name: 'Builtin before upgrade',
|
||||
backtestId: f.draft.id,
|
||||
grid: {},
|
||||
});
|
||||
const existingBuiltin = await f.experiments.submit(
|
||||
{ ...builtin.input, previewHash: builtin.previewHash },
|
||||
{ principal: 'operator', key: 'builtin' }
|
||||
);
|
||||
const empty = await f.experiments.preview({
|
||||
...explicit.input,
|
||||
name: 'Empty defaults',
|
||||
candidate: { versionId: f.candidate.id, parameters: {} },
|
||||
});
|
||||
const row = await f.readManifest(existing.id);
|
||||
const defaulted = {
|
||||
...row,
|
||||
name: empty.input.name,
|
||||
preview_hash: empty.previewHash,
|
||||
preview: empty,
|
||||
};
|
||||
// Demonstrate the old guard rejects this otherwise valid service-produced manifest.
|
||||
await expect(f.validate(defaulted)).rejects.toMatchObject({ code: '23514' });
|
||||
const before = await f.snapshot();
|
||||
await f.apply();
|
||||
await f.apply();
|
||||
expect(await f.snapshot()).toEqual(before);
|
||||
await f.validate(row);
|
||||
await f.validate(await f.readManifest(existingBuiltin.id));
|
||||
await f.validate(defaulted);
|
||||
|
||||
const inputs: Record<string, number>[] = [{}, { fastPeriod: 2 }];
|
||||
for (const parameters of inputs) {
|
||||
const preview = await f.experiments.preview({
|
||||
...empty.input,
|
||||
candidate: { versionId: f.candidate.id, parameters },
|
||||
});
|
||||
expect(preview.input.candidate!.parameters).toEqual(parameters);
|
||||
expect(preview.request.strategy.selection.parameters).toEqual({
|
||||
fastPeriod: 5,
|
||||
slowPeriod: 15,
|
||||
...parameters,
|
||||
});
|
||||
const submission = { ...preview.input, previewHash: preview.previewHash };
|
||||
const receipt = { principal: 'operator', key: randomUUID() };
|
||||
const admitted = await f.experiments.submit(submission, receipt);
|
||||
const retained = await f.readManifest(admitted.id);
|
||||
expect(retained.preview).toEqual(preview);
|
||||
expect(retained.preview_hash).toBe(preview.previewHash);
|
||||
expect((await f.experiments.submit(submission, receipt)).id).toBe(admitted.id);
|
||||
expect(
|
||||
(await f.pool.query('SELECT id FROM runs WHERE experiment_id=$1', [admitted.id])).rows
|
||||
).toHaveLength(1);
|
||||
}
|
||||
}, 30000);
|
||||
|
||||
test('SQL32 still rejects altered explicit/default values, malformed input and forged schema defaults', async () => {
|
||||
const f = await fixture();
|
||||
await f.apply();
|
||||
const preview = await f.experiments.preview({
|
||||
name: 'Partial defaults guard',
|
||||
backtestId: f.draft.id,
|
||||
grid: {},
|
||||
candidate: { versionId: f.candidate.id, parameters: { fastPeriod: 2 } },
|
||||
});
|
||||
const admitted = await f.experiments.submit(
|
||||
{ ...preview.input, previewHash: preview.previewHash },
|
||||
{ principal: 'operator', key: 'partial' }
|
||||
);
|
||||
const row = await f.readManifest(admitted.id);
|
||||
await f.validate(row);
|
||||
for (const [path, value] of [
|
||||
[['input', 'candidate', 'parameters', 'fastPeriod'], 3],
|
||||
[['input', 'candidate', 'parameters', 'undeclared'], 1],
|
||||
[['input', 'candidate', 'parameters'], null],
|
||||
[['input', 'candidate', 'parameters'], []],
|
||||
[['input', 'candidate', 'parameters'], undefined],
|
||||
[['request', 'strategy', 'selection', 'parameters', 'fastPeriod'], 4],
|
||||
[['request', 'strategy', 'selection', 'parameters', 'slowPeriod'], 14],
|
||||
[['request', 'strategy', 'selection', 'parameters', 'slowPeriod'], undefined],
|
||||
[['request', 'strategy', 'selection', 'parameters', 'undeclared'], 1],
|
||||
] as const) {
|
||||
const forged = structuredClone(row);
|
||||
let parent = forged.preview;
|
||||
for (const key of path.slice(0, -1)) {
|
||||
parent = parent[key];
|
||||
}
|
||||
parent[path.at(-1)!] = value;
|
||||
await expect(f.validate(forged)).rejects.toMatchObject({ code: '23514' });
|
||||
}
|
||||
const forgedPackage = structuredClone(row);
|
||||
forgedPackage.preview.request.strategy.package.parameterSchema.properties.slowPeriod.default = 14;
|
||||
forgedPackage.preview.request.strategy.selection.parameters.slowPeriod = 14;
|
||||
await expect(f.validate(forgedPackage)).rejects.toMatchObject({ code: '23514' });
|
||||
|
||||
const builtin = await f.experiments.preview({
|
||||
name: 'No candidate equality',
|
||||
backtestId: f.draft.id,
|
||||
grid: {},
|
||||
});
|
||||
const builtinRow = {
|
||||
...row,
|
||||
name: builtin.input.name,
|
||||
preview_hash: builtin.previewHash,
|
||||
preview: builtin,
|
||||
};
|
||||
await f.validate(builtinRow);
|
||||
builtinRow.preview.request.strategy.selection.parameters = { fastPeriod: 5, slowPeriod: 15 };
|
||||
await expect(f.validate(builtinRow)).rejects.toMatchObject({ code: '23514' });
|
||||
}, 30000);
|
||||
});
|
||||
|
|
@ -34,6 +34,7 @@ const migrations = [
|
|||
'29-isolated-candidates.sql',
|
||||
'30-paper-deployments.sql',
|
||||
'31-research-agent-project-links.sql',
|
||||
'32-candidate-parameter-defaults.sql',
|
||||
];
|
||||
const cleanup: (() => Promise<void>)[] = [];
|
||||
afterEach(async () => {
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue