fix(research): normalize known candidate decimals at admission (RP22)
This commit is contained in:
parent
b51612e57f
commit
b7116473e6
5 changed files with 346 additions and 3 deletions
|
|
@ -4,8 +4,11 @@ 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');
|
||||
|
|
@ -39,7 +42,7 @@ const migrations = [
|
|||
'28-research-agents.sql',
|
||||
'29-isolated-candidates.sql',
|
||||
];
|
||||
async function fixture() {
|
||||
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');
|
||||
}
|
||||
|
|
@ -73,10 +76,37 @@ async function fixture() {
|
|||
{ 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,
|
||||
{
|
||||
...(await base.catalog.getVersionArtifact(base.version.id)),
|
||||
...pkg,
|
||||
execution: { kind: 'isolated-candidate/v1', warmupBars: 0 },
|
||||
},
|
||||
null,
|
||||
|
|
@ -141,6 +171,7 @@ suite('candidate parameter default SQL admission', () => {
|
|||
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));
|
||||
|
|
@ -174,6 +205,7 @@ suite('candidate parameter default SQL admission', () => {
|
|||
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,
|
||||
|
|
@ -225,4 +257,183 @@ suite('candidate parameter default SQL admission', () => {
|
|||
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);
|
||||
});
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue