434 lines
18 KiB
TypeScript
434 lines
18 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 } from 'pg';
|
|
import 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 { CostSensitivityInput } from '@stock-bot/stock-config/cost-sensitivity';
|
|
import { BacktestRunner } from '../../apps/stock/orchestrator/src/backtest/BacktestRunner';
|
|
import { PostgresBacktestRunRepository } from '../../apps/stock/orchestrator/src/backtest/PostgresBacktestRunRepository';
|
|
import { RustBacktestAdapter } from '../../apps/stock/orchestrator/src/backtest/RustBacktestAdapter';
|
|
import { createExperimentRoutes } from '../../apps/stock/web-api/src/routes/experiments.routes';
|
|
import { BacktestServiceV2 } from '../../apps/stock/web-api/src/services/backtest-v2.service';
|
|
import { ChronologicalValidationService } from '../../apps/stock/web-api/src/services/chronological-validation.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 { canonicalSmaFixture } from '../fixtures/canonical-sma';
|
|
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 = {
|
|
read: 'comparison-read-fixture-not-a-real-secret-1234',
|
|
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(poolMax = 1, withCosts = true, capital = 10000) {
|
|
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: poolMax,
|
|
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',
|
|
...(withCosts ? ['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 = canonicalSmaFixture(),
|
|
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: capital,
|
|
config: {
|
|
datasetHash: dataset.manifest.hash,
|
|
dataFrequency: '1m',
|
|
canonical: canonicalSettings,
|
|
},
|
|
},
|
|
{ autoStart: false }
|
|
);
|
|
const input: CostSensitivityInput = {
|
|
backtestId: draft.id,
|
|
name: 'Explicit cost diagnostics',
|
|
scenarios: [
|
|
{ feeRate: '0.001', slippageRate: '0' },
|
|
{ feeRate: '0', slippageRate: '0.01' },
|
|
],
|
|
};
|
|
const app = new Hono();
|
|
createHttpSecurity({
|
|
adminToken: tokens.operator,
|
|
readToken: tokens.read,
|
|
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/cost-sensitivity/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;
|
|
};
|
|
const validations = new ChronologicalValidationService(container);
|
|
const repository = new PostgresBacktestRunRepository(postgres);
|
|
const execute = async (id: string) => {
|
|
const engine = new RustBacktestAdapter({
|
|
logger,
|
|
storage: {
|
|
async getHistoricalBars() {
|
|
throw new Error('No provider reads allowed');
|
|
},
|
|
},
|
|
});
|
|
const runner = new BacktestRunner({ engine, engineName: 'native', repository, logger });
|
|
try {
|
|
await runner.runQueued(id);
|
|
} finally {
|
|
await runner.shutdown();
|
|
}
|
|
};
|
|
return {
|
|
cloneTemplate: async (sourceDataset = dataset) =>
|
|
api.createBacktest(
|
|
{
|
|
name: 'Other validation template',
|
|
strategy: 'catalog',
|
|
strategyVersionId: version.id,
|
|
strategyParameters: { fastPeriod: 2, slowPeriod: 3 },
|
|
symbols: ['X0.US'],
|
|
startDate: new Date(sourceDataset.manifest.bounds.tradeStart).toISOString(),
|
|
endDate: new Date(sourceDataset.manifest.bounds.tradeEnd).toISOString(),
|
|
initialCapital: capital,
|
|
config: {
|
|
datasetHash: sourceDataset.manifest.hash,
|
|
dataFrequency: '1m',
|
|
canonical: canonicalSettings,
|
|
},
|
|
},
|
|
{ autoStart: false }
|
|
),
|
|
app,
|
|
validations,
|
|
repository,
|
|
execute,
|
|
api,
|
|
pool,
|
|
postgres,
|
|
experiments,
|
|
catalog,
|
|
version,
|
|
draft,
|
|
dataset,
|
|
input,
|
|
request,
|
|
review,
|
|
snapshot,
|
|
};
|
|
}
|
|
|
|
const actor = (key = randomUUID()) => ({ principal: 'operator' as const, key });
|
|
type Fixture = Awaited<ReturnType<typeof fixture>>;
|
|
async function pair(f: Fixture) {
|
|
await f.review();
|
|
const costPreview = await f.experiments.previewCosts(f.input),
|
|
left = await f.experiments.submitCosts(
|
|
{ ...f.input, previewHash: costPreview.previewHash },
|
|
actor()
|
|
);
|
|
const input = {
|
|
backtestId: f.draft.id,
|
|
name: 'Other parameters',
|
|
grid: { fastPeriod: [1, 2], slowPeriod: [3] },
|
|
},
|
|
preview = await f.experiments.preview(input),
|
|
right = await f.experiments.submit({ ...input, previewHash: preview.previewHash }, actor());
|
|
return { left, right, input: { leftId: left.id, rightId: right.id } };
|
|
}
|
|
const request = (f: Fixture, query: Record<string, string>) =>
|
|
f.app.request('/api/v2/experiments/compare?' + new URLSearchParams(query), {
|
|
headers: { Authorization: `Bearer ${tokens.read}` },
|
|
});
|
|
describe.skipIf(!url)('saved experiment comparison snapshot', () => {
|
|
test('pool1 native pair returns all compact summaries and actual scenario costs without writes; archive and template edits do not gate historical reopen', async () => {
|
|
const f = await fixture(),
|
|
p = await pair(f);
|
|
for (const trial of [...p.left.trials, ...p.right.trials]) {
|
|
await f.execute(trial.runId!);
|
|
}
|
|
const before = await f.snapshot();
|
|
const compared = await f.experiments.compare(p.input);
|
|
expect(await f.snapshot()).toEqual(before);
|
|
expect(compared.experiments.map(e => e.id)).toEqual([p.left.id, p.right.id]);
|
|
expect(compared.rows).toHaveLength(5);
|
|
expect(compared.rows.map(r => r.inputCompatibility)).toEqual([
|
|
'match',
|
|
'mismatch',
|
|
'mismatch',
|
|
'match',
|
|
'match',
|
|
]);
|
|
expect(compared.rows.map(r => r.ready)).toEqual([true, false, false, true, true]);
|
|
expect(compared.experiments[0].trials[0]!.metrics!.totalReturn).toBeCloseTo(-0.00307, 10);
|
|
expect(compared.experiments[0].trials[0]!.metrics!.sharpeRatio).toBeNull();
|
|
expect(compared.experiments[0].trials[0]!.unavailable!.sharpeRatio).toBeDefined();
|
|
expect(
|
|
compared.experiments[0].trials.every(
|
|
t => !('financial' in t) && !('trades' in t) && !('sessionReturns' in t)
|
|
)
|
|
).toBe(true);
|
|
const selected = await f.experiments.compare({
|
|
...p.input,
|
|
referenceTrialKey: p.left.trials[1]!.trialKey,
|
|
});
|
|
expect(selected.reference.index).toBe(1);
|
|
expect(selected.rows[1]!.ready).toBe(true);
|
|
expect(selected.rows[3]!.differences).toEqual(['costs']);
|
|
await f.api.updateBacktest(f.draft.id, {
|
|
name: 'Mutable presentation',
|
|
initialCapital: 12000,
|
|
config: {
|
|
datasetHash: f.dataset.manifest.hash,
|
|
dataFrequency: '1m',
|
|
canonical: { ...canonicalSettings, feeRate: '0.5' },
|
|
},
|
|
});
|
|
await f.review('revoke');
|
|
await f.pool.query('UPDATE backtests SET archived_at=NOW() WHERE id=$1', [f.draft.id]);
|
|
await f.pool.query('UPDATE strategies SET archived_at=NOW() WHERE id=$1', [
|
|
f.version.strategyId,
|
|
]);
|
|
const saved = await f.snapshot();
|
|
expect(await f.experiments.compare(p.input)).toEqual(compared);
|
|
expect(await f.snapshot()).toEqual(saved);
|
|
const response = await request(f, p.input);
|
|
expect(response.status).toBe(200);
|
|
expect(response.headers.get('Cache-Control')).toBe('no-store');
|
|
expect(await response.json()).toEqual({ comparison: compared });
|
|
const upperCaseResponse = await request(f, {
|
|
leftId: p.left.id.toUpperCase(),
|
|
rightId: p.right.id.toUpperCase(),
|
|
});
|
|
expect(upperCaseResponse.status).toBe(200);
|
|
expect(await upperCaseResponse.json()).toEqual({ comparison: compared });
|
|
}, 60000);
|
|
test('failed/missing/cancelled/inconsistent outcomes remain visible and never replace the unavailable default reference', async () => {
|
|
const f = await fixture(),
|
|
p = await pair(f);
|
|
await f.execute(p.left.trials[1]!.runId!);
|
|
await f.execute(p.right.trials[0]!.runId!);
|
|
await f.pool.query(
|
|
"UPDATE runs SET status='failed',error='Retained fixture failure',completed_at=NOW() WHERE id=$1",
|
|
[p.left.trials[0]!.runId]
|
|
);
|
|
await f.experiments.cancel(p.left.id);
|
|
let compared = await f.experiments.compare(p.input);
|
|
expect(compared.reference.index).toBe(0);
|
|
expect(compared.reference.diagnostic).toBe('Retained fixture failure');
|
|
expect(compared.rows.every(r => !r.ready)).toBe(true);
|
|
expect(compared.experiments[0].trials.map(t => t.status)).toEqual([
|
|
'failed',
|
|
'completed',
|
|
'cancelled',
|
|
]);
|
|
expect(compared.rows[1]!.summaryAvailable).toBe(true);
|
|
expect(compared.experiments[0].cancelRequested).toBe(true);
|
|
await f.pool.query('ALTER TABLE runs DISABLE TRIGGER USER');
|
|
await f.pool.query(
|
|
'UPDATE runs SET experiment_id=NULL,trial_key=NULL,trial_index=NULL WHERE id=$1',
|
|
[p.left.trials[0]!.runId]
|
|
);
|
|
await f.pool.query('ALTER TABLE runs ENABLE TRIGGER USER');
|
|
compared = await f.experiments.compare(p.input);
|
|
expect(compared.reference.runId).toBeNull();
|
|
expect(compared.experiments[0].trials[0]!.status).toBe('missing');
|
|
expect(compared.rows).toHaveLength(5);
|
|
await f.pool.query('ALTER TABLE backtest_results DISABLE TRIGGER USER');
|
|
await f.pool.query(
|
|
"UPDATE backtest_results SET canonical_result=jsonb_set(canonical_result,'{financial,policy,matching,slippageRate}',$2::jsonb) WHERE run_id=$1",
|
|
[p.right.trials[0]!.runId, JSON.stringify('0.50000000')]
|
|
);
|
|
await f.pool.query('ALTER TABLE backtest_results ENABLE TRIGGER USER');
|
|
compared = await f.experiments.compare(p.input);
|
|
expect(compared.rows[3]!.summaryAvailable).toBe(false);
|
|
expect(compared.rows[3]!.inputCompatibility).toBe('match');
|
|
expect(compared.experiments[1].trials[0]!.diagnostic).toContain('inconsistent');
|
|
await expect(
|
|
f.experiments.compare({ ...p.input, referenceTrialKey: 'f'.repeat(64) })
|
|
).rejects.toMatchObject({ status: 409 });
|
|
}, 60000);
|
|
test('read-only repeatable snapshot captures both sides before a controlled committed concurrent status change', async () => {
|
|
const f = await fixture(4),
|
|
p = await pair(f),
|
|
trace: string[] = [];
|
|
const transaction = f.postgres.transaction.bind(f.postgres);
|
|
let changed = false,
|
|
mode: unknown;
|
|
Object.defineProperty(f.postgres, 'transaction', {
|
|
value: (work: (client: PoolClient) => Promise<unknown>) =>
|
|
transaction(async client => {
|
|
const query = client.query.bind(client);
|
|
const proxy = Object.create(client) as PoolClient;
|
|
Object.defineProperty(proxy, 'query', {
|
|
value: async (sql: string, values?: unknown[]) => {
|
|
trace.push(sql);
|
|
const result = await query(sql, values);
|
|
if (sql.startsWith('SET TRANSACTION')) {
|
|
mode = (
|
|
await query(
|
|
"SELECT current_setting('transaction_isolation') AS isolation,current_setting('transaction_read_only') AS readonly"
|
|
)
|
|
).rows[0];
|
|
}
|
|
if (sql.startsWith('SELECT id,validation_phase') && !changed) {
|
|
changed = true;
|
|
await f.pool.query(
|
|
"UPDATE runs SET status='failed',error='Committed after snapshot',completed_at=NOW() WHERE id=$1",
|
|
[p.right.trials[0]!.runId]
|
|
);
|
|
}
|
|
return result;
|
|
},
|
|
});
|
|
return work(proxy);
|
|
}),
|
|
});
|
|
const compared = await f.experiments.compare(p.input);
|
|
expect(mode).toEqual({ isolation: 'repeatable read', readonly: 'on' });
|
|
expect(changed).toBe(true);
|
|
expect(trace[0]).toBe('SET TRANSACTION ISOLATION LEVEL REPEATABLE READ READ ONLY');
|
|
expect(compared.experiments[1].counts.pending).toBe(2);
|
|
expect(compared.experiments[1].counts.failed).toBe(0);
|
|
expect(compared.experiments[1].trials.map(t => t.status)).toEqual(['pending', 'pending']);
|
|
expect(compared.rows.every(r => !r.summaryAvailable)).toBe(true);
|
|
const fresh = await f.experiments.get(p.right.id);
|
|
expect(fresh.counts.failed).toBe(1);
|
|
expect(fresh.trials[0]!.error).toBe('Committed after snapshot');
|
|
expect(trace.filter(sql => /^(INSERT|UPDATE|DELETE|SELECT .*FOR UPDATE)/i.test(sql))).toEqual(
|
|
[]
|
|
);
|
|
expect(trace.some(sql => /SELECT .*canonical_result\s*(,|FROM)/i.test(sql))).toBe(false);
|
|
}, 60000);
|
|
test('standalone role, missing identity and retained corruption produce explicit409/404/sanitized500', async () => {
|
|
const f = await fixture(),
|
|
p = await pair(f),
|
|
data = chronologicalDataset();
|
|
await retainResearchDataset(f.pool, data.dataset);
|
|
const template = await f.cloneTemplate(data.dataset);
|
|
const input = {
|
|
backtestId: template.id,
|
|
name: 'Actual chronological phase',
|
|
grid: { fastPeriod: [1, 2], slowPeriod: [3] },
|
|
recipe: data.recipe,
|
|
},
|
|
preview = await f.experiments.previewValidation(input),
|
|
validation = await f.validations.submit(
|
|
{ ...input, previewHash: preview.previewHash },
|
|
actor()
|
|
);
|
|
expect((await request(f, { leftId: validation.id, rightId: p.right.id })).status).toBe(409);
|
|
expect((await request(f, { leftId: randomUUID(), rightId: p.right.id })).status).toBe(404);
|
|
await f.pool.query('ALTER TABLE research_experiments DISABLE TRIGGER USER');
|
|
await f.pool.query(
|
|
"UPDATE research_experiments SET preview=jsonb_set(preview,'{previewHash}',to_jsonb(repeat('f',64))) WHERE id=$1",
|
|
[p.left.id]
|
|
);
|
|
await f.pool.query('ALTER TABLE research_experiments ENABLE TRIGGER USER');
|
|
const response = await request(f, p.input);
|
|
expect(response.status).toBe(500);
|
|
expect(await response.json()).toEqual({ error: 'Experiment operation unavailable' });
|
|
}, 60000);
|
|
});
|