stock-bot/test/postgres/catalog-backtest-drafts.test.ts

378 lines
16 KiB
TypeScript

import { createHash, 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 { getLogger, setLoggerConfig } from '@stock-bot/logger';
import { PostgreSQLClient } from '@stock-bot/postgres';
import { parseBacktestRequest } from '@stock-bot/stock-config/backtest';
import type { StrategyVersionPackage } from '@stock-bot/types';
import { PostgresBacktestRunRepository } from '../../apps/stock/orchestrator/src/backtest/PostgresBacktestRunRepository';
import { createBacktestRoutes } from '../../apps/stock/web-api/src/routes/backtest.routes';
import { createBacktestV2Routes } from '../../apps/stock/web-api/src/routes/backtests-v2.routes';
import {
BacktestServiceV2,
type BacktestRequest,
} from '../../apps/stock/web-api/src/services/backtest-v2.service';
import { BacktestService } from '../../apps/stock/web-api/src/services/backtest.service';
import { StrategyCatalogService } from '../../apps/stock/web-api/src/services/strategy-catalog.service';
setLoggerConfig({ logLevel: 'fatal', logConsole: false });
const logger = getLogger('catalog-draft-test');
const url = process.env.PIPELINE_TEST_DATABASE_URL;
const cleanup: (() => Promise<void>)[] = [];
const sql = (name: string) =>
readFileSync(new URL(`../../database/postgres/init/${name}`, import.meta.url), 'utf8');
const hash = (text: string) => createHash('sha256').update(text).digest('hex');
function pkg(): StrategyVersionPackage {
const content = 'throw new Error("CANDIDATE_MUST_NOT_EXECUTE");';
const lock = '{"lockfileVersion":1}';
return {
version: 1,
program: {
strategyId: 'draft-fixture',
strategyVersion: 'v1',
apiVersion: 'canonical-ts/v1',
checkpointVersion: 'v1',
},
artifact: {
format: 'esm-bundle/v1',
entryExport: 'createStrategy',
content,
sha256: hash(content),
},
dependencyLock: { format: 'bun-lock/v1', content: lock, sha256: hash(lock) },
parameterSchema: {
version: 1,
type: 'object',
additionalProperties: false,
required: [],
properties: {
commission: { type: 'number', minimum: 0, default: 0 },
enabled: { type: 'boolean', default: false },
budget: { type: 'string', default: '100.25' },
lookback: { type: 'integer', minimum: 1, default: 3 },
label: { type: 'string', default: '📈' },
},
},
source: { revision: 'a'.repeat(40), dirty: false },
build: { tool: 'bun', version: 'fixture', target: 'browser' },
};
}
const common = {
name: 'Catalog draft',
symbols: ['FIXTURE.TEST'],
startDate: '2024-01-01T00:00:00.000Z',
endDate: '2024-01-05T00:00:00.000Z',
initialCapital: 1000,
config: { commission: 0.001, slippage: 0, dataFrequency: '1d' },
};
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('Dedicated safety database required');
}
const schema = 'stock_bot_safety_drafts_' + randomUUID().replaceAll('-', '');
const admin = new Pool({ connectionString: url });
await admin.query(`CREATE SCHEMA ${schema}`);
const pool = new Pool({
connectionString: url,
application_name: schema,
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',
'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',
]) {
await pool.query(sql(name));
}
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 api = new BacktestServiceV2({ postgres, logger });
const catalog = new StrategyCatalogService({ postgres, logger });
const family = await catalog.createStrategy({ name: 'Candidate' }, 'operator');
const version = await catalog.publishVersion(family.id, pkg(), null, 'operator', 'initial');
const second = await catalog.publishVersion(family.id, pkg(), null, 'operator', 'second');
const draft = () => ({
...common,
strategy: 'catalog',
strategyVersionId: version.id,
strategyParameters: {},
});
const app = new Hono()
.route('/', createBacktestV2Routes({ postgres, logger }))
.route('/', createBacktestRoutes({ postgres, logger }));
return { schema, pool, postgres, api, catalog, family, version, second, draft, app };
}
describe.skipIf(!url)('saved catalog backtest drafts on PostgreSQL', () => {
test('normalizes exact defaults and separates financial settings from arbitrary strategy parameter names', async () => {
const f = await fixture();
const saved = await f.api.createBacktest(f.draft(), { autoStart: false });
expect(saved.strategy).toBe('catalog');
expect(saved.strategyVersionId).toBe(f.version.id);
expect(saved.strategyParameters).toEqual({
commission: 0,
enabled: false,
budget: '100.25',
lookback: 3,
label: '📈',
});
expect(saved.config.commission).toBe(0.001);
expect((await f.api.getBacktest(saved.id))?.strategyParameters).toEqual(
saved.strategyParameters!
);
const edited = await f.api.updateBacktest(saved.id, { name: 'Edited' });
expect(edited?.strategyVersionId).toBe(f.version.id);
expect(edited?.strategyParameters).toEqual(saved.strategyParameters!);
const revised = await f.api.updateBacktest(saved.id, {
strategyParameters: {
commission: 0.04,
enabled: false,
budget: '0.00',
lookback: 1,
label: '東京',
},
});
expect(revised?.config.commission).toBe(0.001);
expect(revised?.strategyParameters?.budget).toBe('0.00');
expect((await f.pool.query('SELECT * FROM runs')).rows).toHaveLength(0);
expect((await f.pool.query('SELECT * FROM backtest_dispatch')).rows).toHaveLength(0);
});
test('strict save-only input, version integrity and invalid parameters fail atomically', async () => {
const f = await fixture();
for (const options of [{}, { autoStart: true }]) {
await expect(f.api.createBacktest(f.draft(), options)).rejects.toThrow('autoStart:false');
}
const invalidInputs: BacktestRequest[] = [
{ ...f.draft(), strategyVersionId: null },
{ ...f.draft(), strategyParameters: null },
{ ...f.draft(), config: { ...common.config, lookback: 9 } },
{ ...f.draft(), strategyParameters: { unknown: 1 } },
{ ...f.draft(), strategyParameters: { lookback: 0 } },
{ ...f.draft(), strategyParameters: { enabled: 'false' } },
{ ...f.draft(), strategyParameters: { budget: 100.25 } },
{ ...f.draft(), strategyParameters: { label: 'bad\u0000text' } },
{ ...f.draft(), strategyParameters: { label: '\ud800' } },
{ ...f.draft(), strategyParameters: JSON.parse('{"__proto__":1}') },
];
for (const input of invalidInputs) {
await expect(f.api.createBacktest(input, { autoStart: false })).rejects.toThrow();
}
await expect(
f.api.createBacktest({ ...f.draft(), strategyVersionId: randomUUID() }, { autoStart: false })
).rejects.toMatchObject({ status: 404 });
const corrupt = pkg();
corrupt.artifact.content += 'changed';
const invalidVersionId = randomUUID();
await f.pool.query(
"INSERT INTO strategy_versions(id,strategy_id,ordinal,envelope,created_by,origin,submission_key,submission_fingerprint) VALUES($1,$2,3,$3,'operator','candidate','imported-corrupt',$4)",
[invalidVersionId, f.family.id, JSON.stringify(corrupt), 'f'.repeat(64)]
);
await expect(
f.api.createBacktest(
{ ...f.draft(), strategyVersionId: invalidVersionId },
{ autoStart: false }
)
).rejects.toThrow('hash mismatch');
expect((await f.pool.query('SELECT * FROM backtests')).rows).toHaveLength(0);
});
test('partial edits retain selection, explicit changes require parameters, and neither mode silently converts', async () => {
const f = await fixture();
const saved = await f.api.createBacktest(f.draft(), { autoStart: false });
await expect(
f.api.updateBacktest(saved.id, { strategyVersionId: f.second.id })
).rejects.toThrow('explicit strategyParameters');
await expect(
f.api.updateBacktest(saved.id, { strategyParameters: JSON.parse('{"__proto__":1}') })
).rejects.toThrow('Unsupported strategy metadata key');
expect((await f.api.getBacktest(saved.id))?.strategyParameters?.lookback).toBe(3);
expect(
(
await f.api.updateBacktest(saved.id, {
strategyVersionId: f.second.id,
strategyParameters: { lookback: 8 },
})
)?.strategyParameters?.lookback
).toBe(8);
for (const update of [
{ strategy: 'sma-crossover' },
{ strategyVersionId: null },
{ strategyParameters: null },
{ strategyParameters: { lookback: -1 } },
]) {
await expect(f.api.updateBacktest(saved.id, update)).rejects.toThrow();
}
expect((await f.api.getBacktest(saved.id))?.strategyVersionId).toBe(f.second.id);
const legacy = await f.api.createBacktest(
{ ...common, strategy: 'sma-crossover' },
{ autoStart: false }
);
await expect(f.api.updateBacktest(legacy.id, f.draft())).rejects.toThrow(
'Retained strategy versions'
);
await expect(
f.pool.query(
"UPDATE backtests SET strategy='sma-crossover',strategy_version_id=NULL,strategy_parameters=NULL WHERE id=$1",
[saved.id]
)
).rejects.toThrow('separate template');
await expect(
f.pool.query(
"UPDATE backtests SET strategy='catalog',strategy_version_id=$2,strategy_parameters='{}' WHERE id=$1",
[legacy.id, f.version.id]
)
).rejects.toThrow('separate template');
});
test('family archive serializes new selection while existing selected draft remains editable', async () => {
const f = await fixture();
const saved = await f.api.createBacktest(f.draft(), { autoStart: false });
const blocker = await f.pool.connect();
await blocker.query('BEGIN');
await blocker.query('SELECT id FROM strategies WHERE id=$1 FOR UPDATE', [f.family.id]);
const admission = f.api.createBacktest(f.draft(), { autoStart: false }).then(
() => null,
error => error
);
let waiting = false;
for (let n = 0; n < 100; n++) {
if (
(
await f.pool.query(
"SELECT 1 FROM pg_stat_activity WHERE application_name=$1 AND wait_event_type='Lock'",
[f.schema]
)
).rows.length
) {
waiting = true;
break;
}
await new Promise(resolve => setTimeout(resolve, 10));
}
expect(waiting).toBe(true);
await blocker.query('UPDATE strategies SET archived_at=NOW() WHERE id=$1', [f.family.id]);
await blocker.query('COMMIT');
blocker.release();
expect(await admission).toMatchObject({ status: 409 });
await expect(
f.api.updateBacktest(saved.id, { strategyVersionId: f.second.id, strategyParameters: {} })
).rejects.toMatchObject({ status: 409 });
expect(
(await f.api.updateBacktest(saved.id, { strategyParameters: { lookback: 4 } }))
?.strategyParameters?.lookback
).toBe(4);
await f.api.archiveBacktest(saved.id, true);
await expect(f.api.updateBacktest(saved.id, { name: 'Blocked' })).rejects.toMatchObject({
code: 'backtest_archived',
});
});
test('all execution paths refuse catalog drafts and independent legacy receipts still replay unchanged', async () => {
const f = await fixture();
const saved = await f.api.createBacktest(f.draft(), { autoStart: false });
await expect(f.api.createRun({ backtestId: saved.id })).rejects.toMatchObject({
code: 'catalog_execution_unavailable',
});
const repository = new PostgresBacktestRunRepository(f.postgres);
const legacyConfig = parseBacktestRequest({
...common,
mode: 'backtest',
strategy: 'sma-crossover',
dataFrequency: '1d',
backtestId: saved.id,
});
await expect(repository.start(legacyConfig)).rejects.toThrow('Catalog strategy execution');
await expect(
repository.start({ ...legacyConfig, strategyVersionId: f.version.id } as typeof legacyConfig)
).rejects.toThrow('Retained strategy versions');
await expect(
f.pool.query(
"INSERT INTO runs(backtest_id,run_number,status,request_snapshot) VALUES($1,1,'pending','{}')",
[saved.id]
)
).rejects.toThrow('Catalog strategy execution');
await expect(
new BacktestService({ postgres: f.postgres, logger }).createBacktest(f.draft())
).rejects.toThrow('Retained strategy versions');
const legacy = await f.api.createBacktest(
{ ...common, strategy: 'sma-crossover' },
{ autoStart: false }
);
const receipt = { principal: 'operator' as const, key: 'legacy' };
const run = await f.api.createRun({ backtestId: legacy.id }, receipt);
const before = (await f.pool.query('SELECT request_snapshot FROM runs WHERE id=$1', [run.id]))
.rows[0].request_snapshot;
await f.api.updateBacktest(legacy.id, { name: 'Later edit' });
await f.api.archiveBacktest(legacy.id, true);
expect((await f.api.createRun({ backtestId: legacy.id }, receipt)).id).toBe(run.id);
expect(
(await f.pool.query('SELECT request_snapshot FROM runs WHERE id=$1', [run.id])).rows[0]
.request_snapshot
).toEqual(before);
expect((await f.pool.query('SELECT * FROM runs')).rows).toHaveLength(1);
expect((await f.pool.query('SELECT * FROM backtest_dispatch')).rows).toHaveLength(1);
});
test('HTTP persisted selection reopens, malformed drafts reject, and v1 cannot save or run them', async () => {
const f = await fixture();
const submit = (path: string, input: unknown) =>
f.app.request(path, { method: 'POST', body: JSON.stringify(input) });
for (const input of [
f.draft(),
{ ...f.draft(), autoStart: true },
{ ...f.draft(), autoStart: false, extra: true },
]) {
expect((await submit('/api/v2/backtests', input)).status).toBe(400);
}
expect((await submit('/api/backtests', f.draft())).status).toBe(400);
expect((await f.pool.query('SELECT * FROM backtests')).rows).toHaveLength(0);
const created = await submit('/api/v2/backtests', { ...f.draft(), autoStart: false });
expect(created.status).toBe(201);
const saved = await created.json();
expect(await (await f.app.request(`/api/v2/backtests/${saved.id}`)).json()).toMatchObject({
strategyVersionId: f.version.id,
strategyParameters: { enabled: false, budget: '100.25' },
});
const denied = await submit(`/api/v2/backtests/${saved.id}/runs`, {});
expect(denied.status).toBe(409);
expect(await denied.json()).toMatchObject({ code: 'catalog_execution_unavailable' });
expect((await f.pool.query('SELECT * FROM runs')).rows).toHaveLength(0);
await f.pool.query(sql('18-backtest-strategy-versions.sql'));
expect((await f.api.getBacktest(saved.id))?.strategyVersionId).toBe(f.version.id);
const fks = await f.pool.query(
"SELECT confdeltype FROM pg_constraint WHERE conrelid='backtests'::regclass AND conname='backtests_strategy_version_id_fkey'"
);
expect(fks.rows[0].confdeltype).toBe('r');
await expect(
f.pool.query('DELETE FROM strategy_versions WHERE id=$1', [f.version.id])
).rejects.toThrow();
});
});