336 lines
14 KiB
TypeScript
336 lines
14 KiB
TypeScript
import { randomUUID } from 'node:crypto';
|
|
import { readFileSync } from 'node:fs';
|
|
import { afterEach, describe, expect, test } from 'bun:test';
|
|
import { Hono } from 'hono';
|
|
import { Pool, type PoolClient } from 'pg';
|
|
import { createHttpSecurity } from '@stock-bot/di';
|
|
import { getLogger, setLoggerConfig } from '@stock-bot/logger';
|
|
import { PostgreSQLClient } from '@stock-bot/postgres';
|
|
import type {
|
|
ChronologicalValidationInput,
|
|
ChronologicalValidationPreview,
|
|
} from '@stock-bot/stock-config/chronological-validation';
|
|
import { parseFinancialDecimal } from '@stock-bot/types';
|
|
import { createExperimentRoutes } from '../../apps/stock/web-api/src/routes/experiments.routes';
|
|
import { BacktestServiceV2 } from '../../apps/stock/web-api/src/services/backtest-v2.service';
|
|
import { ExperimentsService } from '../../apps/stock/web-api/src/services/experiments.service';
|
|
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 { chronologicalDataset } from '../fixtures/chronological-validation';
|
|
|
|
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() {
|
|
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: 1,
|
|
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',
|
|
'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 = chronologicalDataset(),
|
|
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: 10000,
|
|
config: {
|
|
datasetHash: dataset.manifest.hash,
|
|
dataFrequency: '1m',
|
|
canonical: canonicalSettings,
|
|
},
|
|
},
|
|
{ autoStart: false }
|
|
);
|
|
const input: ChronologicalValidationInput = {
|
|
backtestId: draft.id,
|
|
name: 'Three explicit windows',
|
|
grid: { fastPeriod: [1, 2], slowPeriod: [3] },
|
|
recipe: data.recipe,
|
|
};
|
|
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/validation/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;
|
|
};
|
|
return {
|
|
pool,
|
|
postgres,
|
|
experiments,
|
|
catalog,
|
|
version,
|
|
draft,
|
|
dataset,
|
|
input,
|
|
request,
|
|
review,
|
|
snapshot,
|
|
};
|
|
}
|
|
|
|
describe.skipIf(!url)('chronological validation PostgreSQL preflight', () => {
|
|
test('real approved retained preview uses one transaction/connection, writes no tables and leaves ordinary economic policy unchanged', async () => {
|
|
const f = await fixture(),
|
|
review = await f.review(),
|
|
before = await f.snapshot();
|
|
const observed: string[] = [],
|
|
transaction = f.postgres.transaction.bind(f.postgres);
|
|
Object.defineProperty(f.postgres, 'transaction', {
|
|
value: <T>(work: (client: PoolClient) => Promise<T>) =>
|
|
transaction(client =>
|
|
work(
|
|
new Proxy(client, {
|
|
get(target, property) {
|
|
if (property === 'query') {
|
|
return (sql: string, values?: unknown[]) => {
|
|
observed.push(sql);
|
|
return target.query(sql, values);
|
|
};
|
|
}
|
|
const value = Reflect.get(target, property);
|
|
return typeof value === 'function' ? value.bind(target) : value;
|
|
},
|
|
})
|
|
)
|
|
),
|
|
});
|
|
const response = await f.request();
|
|
expect(response.status).toBe(200);
|
|
expect(response.headers.get('Cache-Control')).toBe('no-store');
|
|
const { preview } = (await response.json()) as { preview: ChronologicalValidationPreview };
|
|
expect(preview.source.request.strategy.reviewId).toBe(review.id);
|
|
expect(preview.source.dataset).toEqual(f.dataset.manifest);
|
|
expect(preview.execution).toBe('preview-only');
|
|
expect(preview.source.candidates).toHaveLength(2);
|
|
expect(preview.partitions.map(p => p.phase)).toEqual(['train', 'validation', 'test']);
|
|
expect(preview.source.request.build.engineBinarySha256).toMatch(/^[a-f0-9]{64}$/);
|
|
expect(observed.length).toBeGreaterThan(0);
|
|
expect(observed.every(sql => sql.trimStart().startsWith('SELECT'))).toBe(true);
|
|
expect(observed[0]).toContain('FROM backtests WHERE id=$1 FOR UPDATE');
|
|
expect(observed[1]).toContain('FOR UPDATE OF s');
|
|
expect(await f.snapshot()).toEqual(before);
|
|
const ordinary = await f.experiments.preview({
|
|
backtestId: f.draft.id,
|
|
name: f.input.name,
|
|
grid: f.input.grid,
|
|
});
|
|
expect(preview.source).toEqual(ordinary);
|
|
expect(ordinary.request.policy.matching.risk).toEqual({
|
|
ledger: {
|
|
version: 1,
|
|
sessionId: ordinary.request.runId,
|
|
accountId: `research:${ordinary.request.runId}`,
|
|
baseCurrency: 'USD',
|
|
reserveOwnerId: 'reserve',
|
|
ownerIds: [`strategy:${f.version.id}`],
|
|
initialCapital: parseFinancialDecimal('10000'),
|
|
riskSession: {
|
|
calendarId: 'fixture-calendar',
|
|
calendarRevision: '1',
|
|
sessionId: '2024-01-01',
|
|
startsAt: f.dataset.manifest.bounds.warmupStart,
|
|
},
|
|
},
|
|
feeRate: parseFinancialDecimal(canonicalSettings.feeRate),
|
|
maxOrderQuantity: parseFinancialDecimal(canonicalSettings.maxOrderQuantity),
|
|
maxPositionQuantity: parseFinancialDecimal(canonicalSettings.maxPositionQuantity),
|
|
maxSymbolExposure: parseFinancialDecimal(canonicalSettings.maxSymbolExposure),
|
|
maxGrossExposure: parseFinancialDecimal(canonicalSettings.maxGrossExposure),
|
|
maxDailyLoss: parseFinancialDecimal(canonicalSettings.maxDailyLoss),
|
|
maxDrawdownAmount: parseFinancialDecimal(canonicalSettings.maxDrawdownAmount),
|
|
maxMarkAgeMs: canonicalSettings.maxMarkAgeMs,
|
|
});
|
|
expect(ordinary.request.policy.risk_boundaries).toEqual([]);
|
|
expect(await (await f.request(f.input, 'service')).json()).toEqual({ preview });
|
|
expect(await f.snapshot()).toEqual(before);
|
|
}, 30_000);
|
|
test('current approval, family/template availability and exact saved dataset remain authoritative', async () => {
|
|
const f = await fixture();
|
|
expect((await f.request()).status).toBe(409);
|
|
const first = await f.review(),
|
|
initial = (await (await f.request()).json()) as { preview: ChronologicalValidationPreview };
|
|
expect(initial.preview.source.request.strategy.reviewId).toBe(first.id);
|
|
await f.review('revoke');
|
|
expect((await f.request()).status).toBe(409);
|
|
const latest = await f.review(),
|
|
newer = (await (await f.request()).json()) as { preview: ChronologicalValidationPreview };
|
|
expect(newer.preview.source.request.strategy.reviewId).toBe(latest.id);
|
|
expect(newer.preview.previewHash).not.toBe(initial.preview.previewHash);
|
|
expect(newer.preview.partitions.map(p => p.dataset.hash)).toEqual(
|
|
initial.preview.partitions.map(p => p.dataset.hash)
|
|
);
|
|
await f.pool.query('UPDATE strategies SET archived_at=NOW() WHERE id=$1', [
|
|
f.version.strategyId,
|
|
]);
|
|
const archivedFamily = await f.snapshot();
|
|
expect((await f.request()).status).toBe(409);
|
|
expect(await f.snapshot()).toEqual(archivedFamily);
|
|
await f.pool.query('UPDATE strategies SET archived_at=NULL WHERE id=$1', [
|
|
f.version.strategyId,
|
|
]);
|
|
await f.pool.query('UPDATE backtests SET archived_at=NOW() WHERE id=$1', [f.draft.id]);
|
|
expect((await f.request()).status).toBe(409);
|
|
expect((await f.request({ ...f.input, backtestId: randomUUID() })).status).toBe(404);
|
|
expect((await f.pool.query('SELECT count(*)::int AS count FROM runs')).rows[0].count).toBe(0);
|
|
}, 30_000);
|
|
test('recipe cuts, insufficient candidate history and invalid or excessive grids reject without persistence', async () => {
|
|
const f = await fixture();
|
|
await f.review();
|
|
const before = await f.snapshot();
|
|
for (const raw of [
|
|
{
|
|
...f.input,
|
|
recipe: {
|
|
...f.input.recipe,
|
|
train: { ...f.input.recipe.train, tradeStart: f.input.recipe.train.tradeStart + 1 },
|
|
},
|
|
},
|
|
{
|
|
...f.input,
|
|
recipe: {
|
|
...f.input.recipe,
|
|
train: {
|
|
...f.input.recipe.train,
|
|
warmupStart: f.input.recipe.train.warmupStart - 60_000,
|
|
},
|
|
},
|
|
},
|
|
{ ...f.input, grid: { fastPeriod: [1], slowPeriod: [5] } },
|
|
{ ...f.input, grid: { unknown: [1] } },
|
|
{ ...f.input, grid: { fastPeriod: [1, 1] } },
|
|
{
|
|
...f.input,
|
|
grid: {
|
|
fastPeriod: Array.from({ length: 11 }, (_, i) => i + 1),
|
|
slowPeriod: Array.from({ length: 10 }, (_, i) => i + 20),
|
|
},
|
|
},
|
|
]) {
|
|
const response = await f.request(raw);
|
|
expect(response.status).toBe(400);
|
|
expect(await f.snapshot()).toEqual(before);
|
|
}
|
|
}, 30_000);
|
|
test('missing or corrupt retained input is unavailable, arbitrary storage failures remain sanitized500', async () => {
|
|
const f = await fixture();
|
|
await f.review();
|
|
await f.pool.query('ALTER TABLE backtest_datasets DISABLE TRIGGER USER');
|
|
await f.pool.query(
|
|
"UPDATE backtest_datasets SET payload=jsonb_set(payload,'{bars,0,close}','999') WHERE hash=$1",
|
|
[f.dataset.manifest.hash]
|
|
);
|
|
const corrupt = await f.snapshot();
|
|
expect((await f.request()).status).toBe(409);
|
|
expect(await f.snapshot()).toEqual(corrupt);
|
|
await f.pool.query('DELETE FROM backtest_datasets WHERE hash=$1', [f.dataset.manifest.hash]);
|
|
expect((await f.request()).status).toBe(409);
|
|
await f.pool.query('ALTER TABLE backtest_datasets RENAME TO unavailable_datasets');
|
|
const response = await f.request();
|
|
expect(response.status).toBe(500);
|
|
expect(await response.json()).toEqual({ error: 'Experiment operation unavailable' });
|
|
}, 30_000);
|
|
});
|