439 lines
17 KiB
TypeScript
439 lines
17 KiB
TypeScript
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 { parseFinancialDecimal, type StrategyVersionPackage } from '@stock-bot/types';
|
|
import { ExperimentsService } from '../../apps/stock/web-api/src/services/experiments.service';
|
|
import { packageBuiltinStrategies } from '../../scripts/package-builtin-strategies';
|
|
import { canonicalAdmissionFixture } from '../fixtures/canonical-admission';
|
|
import { canonicalRegimeSelection } from '../fixtures/canonical-regime-research';
|
|
|
|
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(kind: 'sma' | 'mean-reversion' | 'string' = 'sma') {
|
|
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'
|
|
);
|
|
let pkg = await base.catalog.getVersionArtifact(base.version.id);
|
|
if (kind === 'mean-reversion') {
|
|
pkg = (await packageBuiltinStrategies()).find(
|
|
item => item.program.strategyId === 'mean_reversion'
|
|
)!;
|
|
} else if (kind === 'string') {
|
|
pkg = {
|
|
...pkg,
|
|
program: {
|
|
strategyId: 'mean_reversion',
|
|
strategyVersion: 'custom-string/v1',
|
|
apiVersion: 'canonical-ts/v1',
|
|
checkpointVersion: '1',
|
|
},
|
|
parameterSchema: {
|
|
version: 1,
|
|
type: 'object',
|
|
additionalProperties: false,
|
|
properties: {
|
|
minNotionalVolume: { type: 'string' },
|
|
label: { type: 'string', default: '0' },
|
|
note: { type: 'string' },
|
|
},
|
|
required: ['minNotionalVolume'],
|
|
},
|
|
} satisfies StrategyVersionPackage;
|
|
}
|
|
const candidate = await base.catalog.publishVersion(
|
|
family.id,
|
|
{
|
|
...pkg,
|
|
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();
|
|
await f.apply('33-candidate-decimal-normalization.sql');
|
|
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();
|
|
await f.apply('33-candidate-decimal-normalization.sql');
|
|
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);
|
|
|
|
test('SQL33 admits the exact failed raw mean-reversion receipt and preserves decimal input spellings', async () => {
|
|
const f = await fixture('mean-reversion');
|
|
await f.apply();
|
|
const input = (minNotionalVolume: string) => ({
|
|
name: `Notional ${minNotionalVolume}`,
|
|
backtestId: f.draft.id,
|
|
grid: {},
|
|
candidate: {
|
|
versionId: f.candidate.id,
|
|
parameters: { ...canonicalRegimeSelection().parameters, minNotionalVolume },
|
|
},
|
|
});
|
|
const canonical = await f.experiments.preview(input('0.00000000'));
|
|
const existing = await f.experiments.submit(
|
|
{ ...canonical.input, previewHash: canonical.previewHash },
|
|
{ principal: 'operator', key: 'before-decimal-migration' }
|
|
);
|
|
const raw = await f.experiments.preview(input('0'));
|
|
const submission = { ...raw.input, previewHash: raw.previewHash };
|
|
const receipt = { principal: 'operator', key: 'raw-zero-original-receipt' };
|
|
const original = JSON.stringify(submission);
|
|
const before = await f.snapshot();
|
|
await expect(f.experiments.submit(submission, receipt)).rejects.toMatchObject({
|
|
code: '23514',
|
|
});
|
|
expect(await f.snapshot()).toEqual(before);
|
|
await f.apply('33-candidate-decimal-normalization.sql');
|
|
await f.apply('33-candidate-decimal-normalization.sql');
|
|
expect(await f.snapshot()).toEqual(before);
|
|
await f.validate(await f.readManifest(existing.id));
|
|
const admitted = await f.experiments.submit(submission, receipt);
|
|
const replayed = await f.experiments.submit(submission, receipt);
|
|
expect(JSON.stringify(submission)).toBe(original);
|
|
expect(replayed.id).toBe(admitted.id);
|
|
expect(replayed.trials.map(trial => trial.runId)).toEqual(
|
|
admitted.trials.map(trial => trial.runId)
|
|
);
|
|
expect(admitted.preview.input).toEqual(raw.input);
|
|
expect(admitted.previewHash).toBe(raw.previewHash);
|
|
expect(admitted.preview.request.strategy.selection.parameters).toMatchObject({
|
|
minNotionalVolume: '0.00000000',
|
|
});
|
|
expect(
|
|
(await f.pool.query('SELECT id FROM runs WHERE experiment_id=$1', [admitted.id])).rows
|
|
).toHaveLength(1);
|
|
|
|
for (const value of [
|
|
'12.3',
|
|
'-0',
|
|
'-0.000',
|
|
'0.00000000',
|
|
'0.00000001',
|
|
'792281625142643375935.43950335',
|
|
]) {
|
|
const preview = await f.experiments.preview(input(value));
|
|
const saved = await f.experiments.submit(
|
|
{ ...preview.input, previewHash: preview.previewHash },
|
|
{ principal: 'operator', key: randomUUID() }
|
|
);
|
|
expect(saved.preview.input.candidate!.parameters.minNotionalVolume).toBe(value);
|
|
expect(saved.preview.request.strategy.selection.parameters).toMatchObject({
|
|
minNotionalVolume: parseFinancialDecimal(value),
|
|
});
|
|
expect((await f.readManifest(saved.id)).preview).toEqual(preview);
|
|
}
|
|
const after = await f.snapshot();
|
|
await f.apply('33-candidate-decimal-normalization.sql');
|
|
expect(await f.snapshot()).toEqual(after);
|
|
expect((await f.experiments.submit(submission, receipt)).id).toBe(admitted.id);
|
|
}, 30000);
|
|
|
|
test('SQL33 rejects decimal coercion, altered amounts and missing or extra parameters', async () => {
|
|
const f = await fixture('mean-reversion');
|
|
await f.apply();
|
|
await f.apply('33-candidate-decimal-normalization.sql');
|
|
const preview = await f.experiments.preview({
|
|
name: 'Strict decimal guard',
|
|
backtestId: f.draft.id,
|
|
grid: {},
|
|
candidate: {
|
|
versionId: f.candidate.id,
|
|
parameters: { ...canonicalRegimeSelection().parameters, minNotionalVolume: '0' },
|
|
},
|
|
});
|
|
const saved = await f.experiments.submit(
|
|
{ ...preview.input, previewHash: preview.previewHash },
|
|
{ principal: 'operator', key: randomUUID() }
|
|
);
|
|
const row = await f.readManifest(saved.id);
|
|
for (const value of [
|
|
'1',
|
|
'-1',
|
|
'-0.00000001',
|
|
'1e0',
|
|
'+0',
|
|
'00',
|
|
'.1',
|
|
'1.',
|
|
'0.000000000',
|
|
'792281625142643375935.43950336',
|
|
'1000000000000000000000',
|
|
'0\n',
|
|
'\n0',
|
|
' 0',
|
|
'0 ',
|
|
0,
|
|
true,
|
|
null,
|
|
{},
|
|
[],
|
|
undefined,
|
|
]) {
|
|
const forged = structuredClone(row);
|
|
forged.preview.input.candidate.parameters.minNotionalVolume = value;
|
|
await expect(f.validate(forged)).rejects.toMatchObject({ code: '23514' });
|
|
}
|
|
// Keep both sides equal after naive padding/sign stripping, so only the strict
|
|
// lexical/range checks reject these rows rather than an unrelated value mismatch.
|
|
for (const [raw, padded] of [
|
|
['792281625142643375935.43950336', '792281625142643375935.43950336'],
|
|
['1000000000000000000000', '1000000000000000000000.00000000'],
|
|
['-1', '1.00000000'],
|
|
['-0.00000001', '0.00000001'],
|
|
['1e0', '1e0.00000000'],
|
|
['00', '00.00000000'],
|
|
['+0', '+0.00000000'],
|
|
['0.000000000', '0.00000000'],
|
|
['0\n', '0\n.00000000'],
|
|
]) {
|
|
const forged = structuredClone(row);
|
|
forged.preview.input.candidate.parameters.minNotionalVolume = raw;
|
|
forged.preview.request.strategy.selection.parameters.minNotionalVolume = padded;
|
|
forged.preview.candidates[0].parameters.minNotionalVolume = padded;
|
|
await expect(f.validate(forged)).rejects.toMatchObject({ code: '23514' });
|
|
}
|
|
for (const [key, value] of [
|
|
['minNotionalVolume', '1.00000000'],
|
|
['minNotionalVolume', undefined],
|
|
['unknown', '0'],
|
|
] as const) {
|
|
const forged = structuredClone(row);
|
|
forged.preview.request.strategy.selection.parameters[key] = value;
|
|
await expect(f.validate(forged)).rejects.toMatchObject({ code: '23514' });
|
|
}
|
|
const extra = structuredClone(row);
|
|
extra.preview.input.candidate.parameters.unknown = '0';
|
|
await expect(f.validate(extra)).rejects.toMatchObject({ code: '23514' });
|
|
const forgedProgram = structuredClone(row);
|
|
forgedProgram.preview.request.strategy.package.program.strategyVersion = 'custom-string/v1';
|
|
await expect(f.validate(forgedProgram)).rejects.toMatchObject({ code: '23514' });
|
|
}, 30000);
|
|
|
|
test('SQL33 leaves other candidate string semantics, defaults and omitted optional values unchanged', async () => {
|
|
const f = await fixture('string');
|
|
await f.apply();
|
|
await f.apply('33-candidate-decimal-normalization.sql');
|
|
const preview = await f.experiments.preview({
|
|
name: 'Literal candidate strings',
|
|
backtestId: f.draft.id,
|
|
grid: {},
|
|
candidate: { versionId: f.candidate.id, parameters: { minNotionalVolume: '0' } },
|
|
});
|
|
const saved = await f.experiments.submit(
|
|
{ ...preview.input, previewHash: preview.previewHash },
|
|
{ principal: 'operator', key: randomUUID() }
|
|
);
|
|
expect(saved.preview.request.strategy.selection.parameters).toEqual({
|
|
minNotionalVolume: '0',
|
|
label: '0',
|
|
});
|
|
const row = await f.readManifest(saved.id);
|
|
await f.validate(row);
|
|
for (const key of ['minNotionalVolume', 'label']) {
|
|
const forged = structuredClone(row);
|
|
forged.preview.request.strategy.selection.parameters[key] = '0.00000000';
|
|
await expect(f.validate(forged)).rejects.toMatchObject({ code: '23514' });
|
|
}
|
|
}, 30000);
|
|
});
|