feat(research): run durable chronological validation and retain reports
This commit is contained in:
parent
67ab30cb7a
commit
abd1c5b83d
42 changed files with 5345 additions and 74 deletions
133
test/integration/chronological-validation-durable-api.test.ts
Normal file
133
test/integration/chronological-validation-durable-api.test.ts
Normal file
|
|
@ -0,0 +1,133 @@
|
|||
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';
|
||||
import { chronologicalDataset } from '../fixtures/chronological-validation';
|
||||
|
||||
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',
|
||||
grid: { fastPeriod: [1, 2] },
|
||||
recipe: chronologicalDataset().recipe,
|
||||
};
|
||||
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/validation' + 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),
|
||||
selectionHash = 'b'.repeat(64);
|
||||
const actions = [
|
||||
['', JSON.stringify({ ...input, previewHash })],
|
||||
[`/${id}/select`, JSON.stringify({ previewHash })],
|
||||
[`/${id}/finalize`, JSON.stringify({ previewHash, selectionHash })],
|
||||
[`/${id}/cancel`, '{}'],
|
||||
];
|
||||
describe('durable validation HTTP gates', () => {
|
||||
test('all writes require real operator/service proof including disabled development auth; readers only inspect', 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);
|
||||
expect((await f.request(`/${id}`, 'GET', undefined, 'read')).status).toBe(404);
|
||||
expect((await f.request()).status).toBe(401);
|
||||
});
|
||||
test('strict bodies, unknown winners/actions, raw reserved grids and missing receipts reject before any transaction', async () => {
|
||||
for (const [path, body, key] of [
|
||||
['', '{', 'key'],
|
||||
['', JSON.stringify({ ...input, previewHash, winner: 1 }), 'key'],
|
||||
[
|
||||
'',
|
||||
JSON.stringify({ ...input, previewHash }).replace('"fastPeriod":[1,2]', '"__proto__":[1]'),
|
||||
'key',
|
||||
],
|
||||
[`/${id}/select`, JSON.stringify({ previewHash, winner: 0 }), 'key'],
|
||||
[`/${id}/select`, JSON.stringify({ previewHash }), undefined],
|
||||
[`/${id}/finalize`, JSON.stringify({ previewHash }), 'key'],
|
||||
[
|
||||
`/${id}/finalize`,
|
||||
JSON.stringify({ previewHash, selectionHash, operation: 'select' }),
|
||||
'key',
|
||||
],
|
||||
[`/${id}/cancel`, '{"restart":true}', undefined],
|
||||
['/bad/select', JSON.stringify({ previewHash }), 'key'],
|
||||
]) {
|
||||
const f = fixture();
|
||||
expect((await f.request(path, 'POST', body, 'operator', key)).status).toBe(400);
|
||||
expect(f.database.transaction.mock.calls).toHaveLength(0);
|
||||
expect(f.database.query.mock.calls).toHaveLength(0);
|
||||
}
|
||||
});
|
||||
test('correct operation routes return missing404 and sanitize unexpected database/schema errors500', 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);
|
||||
}
|
||||
}
|
||||
for (const error of [new Error('private storage failure'), new z.ZodError([])]) {
|
||||
const f = fixture('enabled', async () => {
|
||||
throw error;
|
||||
});
|
||||
const response = await f.request(
|
||||
`/${id}/select`,
|
||||
'POST',
|
||||
JSON.stringify({ previewHash }),
|
||||
'operator',
|
||||
'key'
|
||||
);
|
||||
expect(response.status).toBe(500);
|
||||
expect(await response.json()).toEqual({ error: 'Experiment operation unavailable' });
|
||||
}
|
||||
});
|
||||
});
|
||||
1029
test/integration/chronological-validation-durable-ui.test.tsx
Normal file
1029
test/integration/chronological-validation-durable-ui.test.tsx
Normal file
File diff suppressed because it is too large
Load diff
101
test/integration/chronological-validation-durable.test.ts
Normal file
101
test/integration/chronological-validation-durable.test.ts
Normal file
|
|
@ -0,0 +1,101 @@
|
|||
import { describe, expect, test } from 'bun:test';
|
||||
import type { ValidationResultEvidence } from '@stock-bot/stock-config/chronological-validation';
|
||||
import type { ExperimentCandidate } from '@stock-bot/stock-config/experiments';
|
||||
import {
|
||||
parseValidationFinalization,
|
||||
parseValidationSelection,
|
||||
selectValidationWinner,
|
||||
} from '../../apps/stock/web-api/src/services/validation-evidence';
|
||||
|
||||
function fixture(scores: (number | null)[]) {
|
||||
const candidates: ExperimentCandidate[] = scores.map((_, index) => ({
|
||||
index,
|
||||
trialKey: String(index).padStart(64, '0'),
|
||||
parameters: { fastPeriod: index + 1, slowPeriod: 5 },
|
||||
}));
|
||||
const evidence: ValidationResultEvidence[] = scores.map((totalReturn, index) => ({
|
||||
phase: 'train',
|
||||
experimentId: 'training',
|
||||
runId: String(index),
|
||||
sourceCandidateIndex: index,
|
||||
trialKey: candidates[index]!.trialKey,
|
||||
parameters: candidates[index]!.parameters,
|
||||
datasetHash: 'a'.repeat(64),
|
||||
requestHash: 'b'.repeat(64),
|
||||
economicHash: 'c'.repeat(64),
|
||||
metrics: {
|
||||
totalReturn,
|
||||
cagr: null,
|
||||
maxDrawdown: null,
|
||||
exposureTime: null,
|
||||
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,
|
||||
},
|
||||
unavailable: {},
|
||||
completePeriodCount: 0,
|
||||
periodicSampleCount: 0,
|
||||
fillCount: 0,
|
||||
limitations: [],
|
||||
}));
|
||||
return { candidates, evidence };
|
||||
}
|
||||
describe('sealed chronological selection contract', () => {
|
||||
test('maximizes finite zero/negative training scores, ties choose original index without reordering evidence', () => {
|
||||
for (const [scores, expected] of [
|
||||
[[-0.2, -0.1, -0.1], 1],
|
||||
[[0, -0.1, 0], 0],
|
||||
[[0.2, 0.4, 0.3], 1],
|
||||
] as const) {
|
||||
const { candidates, evidence } = fixture([...scores]),
|
||||
before = structuredClone(evidence);
|
||||
expect(selectValidationWinner(candidates, evidence)).toEqual(candidates[expected]!);
|
||||
expect(evidence).toEqual(before);
|
||||
}
|
||||
});
|
||||
test('missing/null/nonfinite/reordered or holdout evidence can never silently disappear from ranking', () => {
|
||||
for (const scores of [[1, null], [1, Infinity], [1, NaN], []]) {
|
||||
const f = fixture(scores);
|
||||
expect(() => selectValidationWinner(f.candidates, f.evidence)).toThrow();
|
||||
}
|
||||
const f = fixture([0, 1]);
|
||||
expect(() => selectValidationWinner(f.candidates, f.evidence.slice(1))).toThrow();
|
||||
expect(() => selectValidationWinner(f.candidates, [...f.evidence].reverse())).toThrow();
|
||||
f.evidence[0]!.phase = 'test';
|
||||
expect(() => selectValidationWinner(f.candidates, f.evidence)).toThrow();
|
||||
f.evidence[0]!.phase = 'train';
|
||||
f.evidence[0]!.parameters = { fastPeriod: 99 };
|
||||
expect(() => selectValidationWinner(f.candidates, f.evidence)).toThrow();
|
||||
});
|
||||
test('selection/finalization bodies cannot supply winners, scores, changed recipes or a different action', () => {
|
||||
const previewHash = 'a'.repeat(64),
|
||||
selectionHash = 'b'.repeat(64);
|
||||
expect(parseValidationSelection({ previewHash })).toEqual({ previewHash });
|
||||
expect(parseValidationFinalization({ previewHash, selectionHash })).toEqual({
|
||||
previewHash,
|
||||
selectionHash,
|
||||
});
|
||||
for (const extra of [
|
||||
{ winner: 1 },
|
||||
{ metrics: { totalReturn: 2 } },
|
||||
{ recipe: {} },
|
||||
{ operation: 'finalize-report' },
|
||||
]) {
|
||||
expect(() => parseValidationSelection({ previewHash, ...extra })).toThrow();
|
||||
expect(() => parseValidationFinalization({ previewHash, selectionHash, ...extra })).toThrow();
|
||||
}
|
||||
expect(() => parseValidationFinalization({ previewHash })).toThrow();
|
||||
});
|
||||
});
|
||||
|
|
@ -362,9 +362,7 @@ describe('chronological validation preflight', () => {
|
|||
test('explicit UTC preparation sends only read-only preview and displays all phase assumptions and counts', async () => {
|
||||
const value = await fill();
|
||||
expect(host.textContent).toContain('No chronological preview prepared');
|
||||
expect(host.textContent).toContain(
|
||||
'Preview only. No datasets, experiments or runs are saved. Staged execution and immutable reports are not available yet.'
|
||||
);
|
||||
expect(host.textContent).toContain('Previewing does not save datasets, experiments or runs.');
|
||||
expect(requests.filter(item => item.method === 'POST')).toHaveLength(0);
|
||||
await flush(() => {
|
||||
button('Preview chronological validation').click();
|
||||
|
|
@ -393,7 +391,7 @@ describe('chronological validation preflight', () => {
|
|||
host
|
||||
.querySelector('[aria-label="Chronological validation preflight"]')!
|
||||
.querySelectorAll('button')
|
||||
).toHaveLength(1);
|
||||
).toHaveLength(2);
|
||||
expect(host.textContent).not.toContain('Confirm experiment');
|
||||
expect(location).toBe(`/experiments?backtestId=${backtestId}`);
|
||||
});
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue