feat(research): add strategy catalog and versioned backtest setup
This commit is contained in:
parent
8cca0ee588
commit
d929db707a
44 changed files with 4198 additions and 209 deletions
373
test/postgres/catalog-backtest-drafts.test.ts
Normal file
373
test/postgres/catalog-backtest-drafts.test.ts
Normal file
|
|
@ -0,0 +1,373 @@
|
|||
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',
|
||||
]) {
|
||||
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();
|
||||
});
|
||||
});
|
||||
|
|
@ -69,7 +69,9 @@ async function fixture() {
|
|||
'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',
|
||||
]) {
|
||||
await pool.query(
|
||||
readFileSync(new URL(`../../database/postgres/init/${name}`, import.meta.url), 'utf8')
|
||||
|
|
|
|||
|
|
@ -80,7 +80,9 @@ async function fixture() {
|
|||
'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',
|
||||
]) {
|
||||
await pool.query(
|
||||
readFileSync(new URL(`../../database/postgres/init/${filename}`, import.meta.url), 'utf8')
|
||||
|
|
@ -127,6 +129,16 @@ async function fixture() {
|
|||
},
|
||||
{ autoStart: false }
|
||||
);
|
||||
// A response DTO includes nullable catalog markers; legacy input deliberately omits them.
|
||||
const definitionInput = {
|
||||
name: definition.name,
|
||||
strategy: definition.strategy,
|
||||
symbols: definition.symbols,
|
||||
startDate: definition.startDate.toISOString(),
|
||||
endDate: definition.endDate.toISOString(),
|
||||
initialCapital: definition.initialCapital,
|
||||
config: definition.config,
|
||||
};
|
||||
const repository = new PostgresBacktestRunRepository(postgres, 2_000);
|
||||
const history = { reads: 0, unavailable: false };
|
||||
const storage = {
|
||||
|
|
@ -197,6 +209,7 @@ async function fixture() {
|
|||
postgres,
|
||||
api,
|
||||
definition,
|
||||
definitionInput,
|
||||
repository,
|
||||
runner,
|
||||
engine,
|
||||
|
|
@ -243,7 +256,7 @@ describe.skipIf(!url || !redisUrl)('durable backtests on real PostgreSQL and Red
|
|||
const f = await fixture();
|
||||
const second = await f.api.createBacktest(
|
||||
{
|
||||
...f.definition,
|
||||
...f.definitionInput,
|
||||
startDate: f.definition.startDate.toISOString(),
|
||||
endDate: f.definition.endDate.toISOString(),
|
||||
name: 'Second',
|
||||
|
|
@ -339,7 +352,7 @@ describe.skipIf(!url || !redisUrl)('durable backtests on real PostgreSQL and Red
|
|||
const app = new Hono();
|
||||
createHttpSecurity({ disabled: true, environment: 'test' }).mount(app);
|
||||
app.route('/', createBacktestV2Routes({ postgres: f.postgres, logger }));
|
||||
const body = { ...f.definition, autoStart: false };
|
||||
const body = { ...f.definitionInput, autoStart: false };
|
||||
expect(
|
||||
(
|
||||
await app.request('/api/v2/backtests', {
|
||||
|
|
@ -585,7 +598,7 @@ describe.skipIf(!url || !redisUrl)('durable backtests on real PostgreSQL and Red
|
|||
const f = await fixture();
|
||||
const runId = randomUUID();
|
||||
const snapshot = backtestRequestFromDefinition(
|
||||
{ ...f.definition, config: { ...f.definition.config, datasetHash: 'f'.repeat(64) } },
|
||||
{ ...f.definitionInput, config: { ...f.definition.config, datasetHash: 'f'.repeat(64) } },
|
||||
{ runId, backtestId: f.definition.id }
|
||||
);
|
||||
// Imported history can reference unavailable storage; retain its request and report the loss.
|
||||
|
|
@ -637,7 +650,7 @@ describe.skipIf(!url || !redisUrl)('durable backtests on real PostgreSQL and Red
|
|||
const snapshot = (
|
||||
await f.pool.query('SELECT request_snapshot FROM runs WHERE id = $1', [run.id])
|
||||
).rows[0].request_snapshot;
|
||||
const expected = backtestRequestFromDefinition(f.definition, {
|
||||
const expected = backtestRequestFromDefinition(f.definitionInput, {
|
||||
runId: run.id,
|
||||
backtestId: f.definition.id,
|
||||
speedMultiplier: 7,
|
||||
|
|
|
|||
|
|
@ -20,6 +20,7 @@ const migrations = [
|
|||
'15-canonical-paper-intents.sql',
|
||||
'16-strategy-catalog.sql',
|
||||
'17-research-retention.sql',
|
||||
'18-backtest-strategy-versions.sql',
|
||||
];
|
||||
const cleanup: (() => Promise<void>)[] = [];
|
||||
afterEach(async () => {
|
||||
|
|
|
|||
|
|
@ -19,7 +19,8 @@ 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 retention = sql('17-research-retention.sql');
|
||||
const retention =
|
||||
sql('17-research-retention.sql') + '\n' + sql('18-backtest-strategy-versions.sql');
|
||||
const request = {
|
||||
name: 'Retained evidence',
|
||||
strategy: 'sma-crossover',
|
||||
|
|
@ -34,7 +35,7 @@ afterEach(async () => {
|
|||
await close();
|
||||
}
|
||||
});
|
||||
async function fixture(install = true) {
|
||||
async function fixture() {
|
||||
if (!url || !new URL(url).pathname.startsWith('/stock_bot_safety')) {
|
||||
throw new Error('Dedicated stock_bot_safety database required');
|
||||
}
|
||||
|
|
@ -58,14 +59,11 @@ async function fixture(install = true) {
|
|||
'10-durable-backtest-dispatch.sql',
|
||||
'12-historical-datasets.sql',
|
||||
'14-backtest-submission.sql',
|
||||
'16-strategy-catalog.sql',
|
||||
]) {
|
||||
await pool.query(sql(name));
|
||||
}
|
||||
// The pre17 setup mode is only for constructing historical/corrupt imported rows.
|
||||
await pool.query('ALTER TABLE backtests ADD COLUMN archived_at timestamptz');
|
||||
if (install) {
|
||||
await pool.query(retention);
|
||||
}
|
||||
await pool.query(retention);
|
||||
const postgres = new PostgreSQLClient(
|
||||
{ host: 'unused', port: 5432, database: 'unused', username: 'unused', password: 'unused' },
|
||||
logger
|
||||
|
|
@ -391,18 +389,20 @@ describe.skipIf(!url)('research evidence retention on real PostgreSQL', () => {
|
|||
});
|
||||
|
||||
test('preexisting corrupted datasets remain immutable and fail checksum verification on retrieval', async () => {
|
||||
const f = await fixture(false);
|
||||
const f = await fixture();
|
||||
const run = await f.api.createRun({ backtestId: f.definition.id });
|
||||
const claim = await f.repository.start(await f.snapshot(run.id));
|
||||
const dataset = await f.repository.freezeDataset(
|
||||
const dataset = await f.dataset(run.id);
|
||||
const corrupt = structuredClone(dataset);
|
||||
corrupt.bars[0]!.volume = 0;
|
||||
await f.pool.query('INSERT INTO backtest_datasets(hash,payload) VALUES($1,$2)', [
|
||||
dataset.manifest.hash,
|
||||
corrupt,
|
||||
]);
|
||||
await f.pool.query('UPDATE runs SET dataset_hash=$2 WHERE id=$1', [
|
||||
run.id,
|
||||
claim.attemptId,
|
||||
await f.dataset(run.id)
|
||||
);
|
||||
await f.pool.query(
|
||||
"UPDATE backtest_datasets SET payload=jsonb_set(payload,'{bars,0,volume}','0') WHERE hash=$1",
|
||||
[dataset.manifest.hash]
|
||||
);
|
||||
dataset.manifest.hash,
|
||||
]);
|
||||
await f.pool.query(retention);
|
||||
await expect(f.repository.loadDataset(run.id, claim.attemptId)).rejects.toThrow('hash/content');
|
||||
await expect(
|
||||
|
|
|
|||
|
|
@ -65,7 +65,9 @@ async function fixture() {
|
|||
'12-historical-datasets.sql',
|
||||
'13-strategy-recovery.sql',
|
||||
'14-backtest-submission.sql',
|
||||
'16-strategy-catalog.sql',
|
||||
'17-research-retention.sql',
|
||||
'18-backtest-strategy-versions.sql',
|
||||
]) {
|
||||
await pool.query(
|
||||
readFileSync(new URL(`../../database/postgres/init/${filename}`, import.meta.url), 'utf8')
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue