feat(research): cut over canonical runtime and enforce agent budgets

This commit is contained in:
Boki 2026-10-24 16:47:19 -04:00
parent ab08db82fd
commit bbf0dd4453
103 changed files with 6138 additions and 3112 deletions

View file

@ -16,6 +16,7 @@ import {
} 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';
import { seedHistoricalRun } from '../fixtures/historical-run';
setLoggerConfig({ logLevel: 'fatal', logConsole: false });
const logger = getLogger('catalog-draft-test');
@ -329,7 +330,10 @@ describe.skipIf(!url)('saved catalog backtest drafts on PostgreSQL', () => {
{ autoStart: false }
);
const receipt = { principal: 'operator' as const, key: 'legacy' };
const run = await f.api.createRun({ backtestId: legacy.id }, receipt);
await expect(f.api.createRun({ backtestId: legacy.id }, receipt)).rejects.toThrow(
'Legacy backtest execution is retired'
);
const run = await seedHistoricalRun(f.pool, f.api, { 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' });

View file

@ -12,6 +12,7 @@ import {
type BacktestRequest,
} from '../../apps/stock/web-api/src/services/backtest-v2.service';
import { DatasetCatalogService } from '../../apps/stock/web-api/src/services/dataset-catalog.service';
import { seedHistoricalRun } from '../fixtures/historical-run';
setLoggerConfig({ logLevel: 'fatal', logConsole: false });
const logger = getLogger('dataset-catalog-test');
@ -200,7 +201,7 @@ describe.skipIf(!url)('dataset catalog and selected-run submission on real Postg
}
});
test('missing, inconsistent, malformed and unsupported selected snapshots reject before any run/outbox is inserted', async () => {
test('legacy admission refuses missing, inconsistent, malformed and unsupported snapshots before any run/outbox is inserted', async () => {
const f = await fixture();
const saved = await f.api.createBacktest(
{ ...request(), config: { fastPeriod: 2, slowPeriod: 3 } },
@ -230,7 +231,9 @@ describe.skipIf(!url)('dataset catalog and selected-run submission on real Postg
saved.id,
{ ...request().config, datasetHash: 'e'.repeat(64) },
]);
await expect(f.api.createRun({ backtestId: saved.id })).rejects.toThrow('not found');
await expect(f.api.createRun({ backtestId: saved.id })).rejects.toThrow(
'Legacy backtest execution is retired'
);
expect((await f.pool.query('SELECT count(*)::int AS n FROM runs')).rows[0].n).toBe(0);
expect((await f.pool.query('SELECT count(*)::int AS n FROM backtest_dispatch')).rows[0].n).toBe(
0
@ -288,23 +291,20 @@ describe.skipIf(!url)('dataset catalog and selected-run submission on real Postg
const retained = await f.api.getBacktest(saved.id);
expect(retained!.endDate.toISOString()).toBe(manifest().endDate);
expect(retained!.config.datasetHash).toBe(hash);
expect((await f.api.createRun({ backtestId: saved.id })).dataset.requestedHash).toBe(hash);
expect(
(await seedHistoricalRun(f.pool, f.api, { backtestId: saved.id })).dataset.requestedHash
).toBe(hash);
await expect(f.api.createRun({ backtestId: saved.id })).rejects.toThrow(
'Legacy backtest execution is retired'
);
});
test('selected run snapshots commit atomically and same-key retry returns its original receipt before mutable definition validation', async () => {
test('historical selected snapshots and original receipts survive retired admission and later definition edits', async () => {
const f = await fixture();
await f.insert(hash, { manifest: manifest(), bars: [{}] });
const saved = await f.api.createBacktest(request(), { autoStart: false });
await f.pool.query(
`CREATE FUNCTION reject_dataset_outbox() RETURNS trigger LANGUAGE plpgsql AS $$ BEGIN RAISE EXCEPTION 'injected outbox failure'; END $$; CREATE TRIGGER reject_dataset_outbox BEFORE INSERT ON backtest_dispatch FOR EACH ROW EXECUTE FUNCTION reject_dataset_outbox()`
);
await expect(f.api.createRun({ backtestId: saved.id })).rejects.toThrow(
'injected outbox failure'
);
expect((await f.pool.query('SELECT count(*)::int AS n FROM runs')).rows[0].n).toBe(0);
await f.pool.query('DROP TRIGGER reject_dataset_outbox ON backtest_dispatch');
const submission = { principal: 'operator' as const, key: 'dataset-retry' };
const first = await f.api.createRun({ backtestId: saved.id }, submission);
const first = await seedHistoricalRun(f.pool, f.api, { backtestId: saved.id }, submission);
expect(first.dataset).toEqual({
requestedHash: hash,
pinnedHash: null,
@ -334,7 +334,7 @@ describe.skipIf(!url)('dataset catalog and selected-run submission on real Postg
{ ...request(), config: { dataSource: 'eod' } },
{ autoStart: false }
);
const run = await f.api.createRun({ backtestId: saved.id });
const run = await seedHistoricalRun(f.pool, f.api, { backtestId: saved.id });
expect(run.dataset).toEqual({
requestedHash: null,
pinnedHash: null,

View file

@ -10,10 +10,12 @@ import { HandlerRegistry } from '@stock-bot/handler-registry';
import { getLogger, setLoggerConfig } from '@stock-bot/logger';
import { PostgreSQLClient } from '@stock-bot/postgres';
import { Queue } from '@stock-bot/queue';
import { backtestRequestFromDefinition } from '@stock-bot/stock-config/backtest';
import {
backtestRequestFromDefinition,
parseBacktestRequest,
} from '@stock-bot/stock-config/backtest';
canonicalRunRequestSchema,
type CanonicalRunRequest,
type CanonicalRunResult,
} from '@stock-bot/stock-config/canonical-research';
import { BacktestRunner } from '../../apps/stock/orchestrator/src/backtest/BacktestRunner';
import { BacktestCancelledError } from '../../apps/stock/orchestrator/src/backtest/execution-engine';
import { PostgresBacktestRunRepository } from '../../apps/stock/orchestrator/src/backtest/PostgresBacktestRunRepository';
@ -28,6 +30,8 @@ import {
RunSubmissionConflictError,
} from '../../apps/stock/web-api/src/services/backtest-v2.service';
import { BacktestDispatcher } from '../../apps/stock/web-api/src/services/BacktestDispatcher';
import { canonicalAdmissionFixture } from '../fixtures/canonical-admission';
import { canonicalSettings } from '../fixtures/canonical-research';
setLoggerConfig({ logLevel: 'fatal', logConsole: false });
const logger = getLogger('durable-backtest-test');
@ -35,19 +39,23 @@ const url = process.env.PIPELINE_TEST_DATABASE_URL;
const redisUrl = process.env.BACKTEST_TEST_REDIS_URL;
const cleanup: (() => Promise<void>)[] = [];
afterEach(async () => {
for (const close of cleanup.splice(0).reverse()) await close();
for (const close of cleanup.splice(0).reverse()) {
await close();
}
});
const sleep = (ms: number) => new Promise(resolve => setTimeout(resolve, ms));
async function until(check: () => Promise<boolean>, timeoutMs = 3_000) {
const deadline = Date.now() + timeoutMs;
while (Date.now() < deadline) {
if (await check()) return;
if (await check()) {
return;
}
await sleep(20);
}
throw new Error('Timed out waiting for durable workflow');
}
async function fixture() {
async function fixture(historical = false) {
if (
!url ||
!new URL(url).pathname.startsWith('/stock_bot_safety') ||
@ -59,7 +67,11 @@ async function fixture() {
const schema = `stock_bot_safety_${randomUUID().replaceAll('-', '')}`;
const admin = new Pool({ connectionString: url });
await admin.query(`CREATE SCHEMA ${schema}`);
const pool = new Pool({ connectionString: url, options: `-c search_path=${schema}` });
const pool = new Pool({
connectionString: url,
application_name: schema,
options: `-c search_path=${schema}`,
});
cleanup.push(async () => {
await pool.end();
await admin.query(`DROP SCHEMA ${schema} CASCADE`);
@ -96,7 +108,7 @@ async function fixture() {
);
}
const postgres = new PostgreSQLClient(
{ host: 'unused', port: 5432, database: 'unused', user: 'unused', password: 'unused' },
{ host: 'unused', port: 5432, database: 'unused', username: 'unused', password: 'unused' },
logger
);
Object.defineProperty(postgres, 'connectionPool', { get: () => pool });
@ -124,20 +136,23 @@ async function fixture() {
const api = new BacktestServiceV2({ postgres, logger }, async () => {
throw new Error('No HTTP execution dispatch allowed');
});
const definition = await api.createBacktest(
{
name: 'Durable fixture',
strategy: 'sma-crossover',
symbols: ['FIXTURE.TEST'],
startDate: '2024-01-01T00:00:00.000Z',
endDate: '2024-03-15T00:00:00.000Z',
initialCapital: 100000,
config: { fastPeriod: 3, slowPeriod: 7, commission: 0, slippage: 0 },
},
{ autoStart: false }
);
// A response DTO includes nullable catalog markers; legacy input deliberately omits them.
const definitionInput = {
const legacyDefinition = historical
? await api.createBacktest(
{
name: 'Durable fixture',
strategy: 'sma-crossover',
symbols: ['FIXTURE.TEST'],
startDate: '2024-01-01T00:00:00.000Z',
endDate: '2024-03-15T00:00:00.000Z',
initialCapital: 100000,
config: { fastPeriod: 3, slowPeriod: 7, commission: 0, slippage: 0 },
},
{ autoStart: false }
)
: undefined;
const canonical = historical ? undefined : await canonicalAdmissionFixture(pool, postgres, false);
const definition = canonical?.draft ?? legacyDefinition!;
const definitionInput = canonical?.definition ?? {
name: definition.name,
strategy: definition.strategy,
symbols: definition.symbols,
@ -146,6 +161,25 @@ async function fixture() {
initialCapital: definition.initialCapital,
config: definition.config,
};
// This raw insertion represents already accepted pre-cutover history. It is
// deliberately not exposed through a service or production admission switch.
const historicalRun = async (_request: { backtestId: string }) => {
if (!historical) {
throw new Error('Historical fixture only');
}
const runId = randomUUID();
const snapshot = backtestRequestFromDefinition(definitionInput, {
runId,
backtestId: definition.id,
});
await pool.query(
`INSERT INTO runs(id,backtest_id,run_number,request_snapshot)
SELECT $1,$2,COALESCE(MAX(run_number),0)+1,$3 FROM runs WHERE backtest_id=$2`,
[runId, definition.id, snapshot]
);
await pool.query('INSERT INTO backtest_dispatch(run_id) VALUES($1)', [runId]);
return { id: runId };
};
const repository = new PostgresBacktestRunRepository(postgres, 2_000);
const history = { reads: 0, unavailable: false };
const storage = {
@ -200,10 +234,27 @@ async function fixture() {
return worker;
};
const snapshot = async (runId: string) =>
BacktestConfigSchema.parse(
canonicalRunRequestSchema.parse(
(await pool.query('SELECT request_snapshot FROM runs WHERE id = $1', [runId])).rows[0]
.request_snapshot
);
const legacySnapshot = async (runId: string) =>
BacktestConfigSchema.parse(
(await pool.query('SELECT request_snapshot FROM runs WHERE id=$1', [runId])).rows[0]
.request_snapshot
);
const report = async (request: CanonicalRunRequest): Promise<CanonicalRunResult> => ({
kind: 'canonical-result/v1',
runId: request.runId,
backtestId: request.backtestId,
status: 'completed',
completedAt: new Date().toISOString(),
executionTime: 1,
financialEngine: 'rust',
strategyExecution: 'typescript-retained-builtin/v1',
request,
...(await engine.runCanonical(request, async () => canonical!.dataset)),
});
const expire = async (runId: string) => {
await pool.query(
"UPDATE runs SET lease_expires_at = NOW() - INTERVAL '1 second' WHERE id = $1",
@ -224,6 +275,10 @@ async function fixture() {
dispatcher,
enqueueWorker,
snapshot,
legacySnapshot,
historicalRun,
report,
canonical,
expire,
history,
storage,
@ -246,7 +301,7 @@ describe.skipIf(!url || !redisUrl)('durable backtests on real PostgreSQL and Red
const original = await f.snapshot(runs[0]!.id);
await f.api.updateBacktest(f.definition.id, {
initialCapital: 12345,
config: { fastPeriod: 4, slowPeriod: 9 },
strategyParameters: { fastPeriod: 3, slowPeriod: 4 },
});
expect((await f.api.createRun({ backtestId: f.definition.id }, submission)).id).toBe(
runs[0]!.id
@ -282,17 +337,27 @@ describe.skipIf(!url || !redisUrl)('durable backtests on real PostgreSQL and Red
[f.definition.id, second.id].map(backtestId => f.api.createRun({ backtestId }, submission))
);
try {
// Both parent-row locks are held, neither run exists yet, and both transactions
// are inside their INSERT. Releasing shared waiters forces the unique-index race.
// Both requests passed their initial receipt lookup and hold distinct parent
// locks. One waits inside INSERT; the other waits on the shared strategy
// family lock. The stale second receipt lookup must still conflict after
// the first transaction commits, rather than returning its unrelated run.
await until(
async () =>
(
await f.pool.query(
"SELECT count(*)::int AS count FROM pg_locks WHERE locktype = 'advisory' AND classid = 40303 AND objid = $1 AND NOT granted",
[barrierKey]
"SELECT count(*)::int AS count FROM pg_stat_activity WHERE application_name=$1 AND wait_event_type='Lock'",
[f.schema]
)
).rows[0].count === 2
);
expect(
(
await f.pool.query(
"SELECT count(*)::int AS count FROM pg_locks WHERE locktype='advisory' AND classid=40303 AND objid=$1 AND NOT granted",
[barrierKey]
)
).rows[0].count
).toBe(1);
expect((await f.pool.query('SELECT * FROM runs')).rows).toHaveLength(0);
} finally {
await barrier.query('SELECT pg_advisory_unlock(40303, $1)', [barrierKey]);
@ -313,7 +378,7 @@ describe.skipIf(!url || !redisUrl)('durable backtests on real PostgreSQL and Red
);
});
test('different principals can reuse keys; concurrent distinct and legacy submissions preserve run numbering', async () => {
test('different principals can reuse keys; concurrent distinct and unkeyed submissions preserve run numbering', async () => {
const f = await fixture();
const runs = await Promise.all([
f.api.createRun({ backtestId: f.definition.id }, { principal: 'operator', key: 'shared' }),
@ -354,7 +419,7 @@ describe.skipIf(!url || !redisUrl)('durable backtests on real PostgreSQL and Red
expect((await f.pool.query('SELECT * FROM backtest_dispatch')).rows).toHaveLength(1);
});
test('save_only route honors autoStart; authenticated keyed submissions return202/Location or409', async () => {
test('save_only catalog route requires explicit false; authenticated keyed submissions return202/Location or409', async () => {
const f = await fixture();
const app = new Hono();
createHttpSecurity({ disabled: true, environment: 'test' }).mount(app);
@ -387,11 +452,14 @@ describe.skipIf(!url || !redisUrl)('durable backtests on real PostgreSQL and Red
expect(response.headers.get('Location')).toBe(`/api/v2/runs/${run.id}`);
expect((await (await post({ speedMultiplier: null })).json()).id).toBe(run.id);
expect((await post({ speedMultiplier: 2 })).status).toBe(409);
const legacy = await app.request('/api/v2/backtests', {
const saveOnly = await app.request('/api/v2/backtests', {
method: 'POST',
body: JSON.stringify({ ...body, autoStart: undefined }),
});
expect(await f.api.listRuns((await legacy.json()).id)).toHaveLength(1);
expect(saveOnly.status).toBe(400);
expect((await f.pool.query('SELECT count(*)::int AS count FROM backtests')).rows[0].count).toBe(
2
);
});
test('cookie renewal and admin bearer replay the same operator submission while service keys are separate', async () => {
@ -442,9 +510,9 @@ describe.skipIf(!url || !redisUrl)('durable backtests on real PostgreSQL and Red
});
test('a lease expiring during snapshot insertion cannot pin or leave an orphan snapshot', async () => {
const f = await fixture();
const run = await f.api.createRun({ backtestId: f.definition.id });
const config = await f.snapshot(run.id);
const f = await fixture(true);
const run = await f.historicalRun({ backtestId: f.definition.id });
const config = await f.legacySnapshot(run.id);
const dataset = await loadDataset(f.storage, config);
await f.pool
.query(`CREATE FUNCTION delay_snapshot() RETURNS trigger LANGUAGE plpgsql AS $$ BEGIN
@ -461,51 +529,40 @@ describe.skipIf(!url || !redisUrl)('durable backtests on real PostgreSQL and Red
.dataset_hash
).toBeNull();
});
test('prepared snapshots survive owner loss and replay through JSONB without provider reads', async () => {
test('retained canonical inputs survive owner loss and replay without provider reads', async () => {
const f = await fixture();
const parameters = {
...f.definition.config,
dataFrequency: '1d',
dataPolicy: { adjustment: 'raw', timestamp: 'utc-session-date' },
};
await f.api.updateBacktest(f.definition.id, { config: parameters });
const first = await f.runner.runQueued(
(await f.api.createRun({ backtestId: f.definition.id })).id
);
const baseline = (await f.api.getRunResults(first.runId))!;
expect(baseline.config.parameters).toEqual(parameters);
const first = await f.api.createRun({ backtestId: f.definition.id });
await f.runner.runQueued(first.id);
const baseline = await f.api.getRunResults(first.id);
const run = await f.api.createRun({ backtestId: f.definition.id });
const old = await f.repository.start(await f.snapshot(run.id));
const frozen = await f.repository.loadDataset(
const old = await f.repository.startCanonical(await f.snapshot(run.id));
const frozen = await f.repository.loadCanonicalDataset(
run.id,
old.attemptId,
baseline.config.dataset!.hash
f.canonical!.dataset.manifest.hash
);
expect(frozen?.bars).toHaveLength(70);
await f.expire(run.id);
await expect(f.repository.loadDataset(run.id, old.attemptId)).rejects.toBeInstanceOf(
BacktestLeaseLostError
);
await expect(f.repository.freezeDataset(run.id, old.attemptId, frozen!)).rejects.toBeInstanceOf(
BacktestLeaseLostError
);
const reads = f.history.reads;
await expect(
f.repository.loadCanonicalDataset(run.id, old.attemptId, frozen.manifest.hash)
).rejects.toBeInstanceOf(BacktestLeaseLostError);
f.history.unavailable = true;
await f.dispatcher.tick();
await f.runner.runQueued(run.id);
const replay = (await f.api.getRunResults(run.id))!;
expect(f.history.reads).toBe(reads);
expect(replay.config.dataset).toEqual(baseline.config.dataset);
expect(replay.config.parameters).toEqual(parameters);
expect(replay.trades).toEqual(baseline.trades);
expect(replay.metrics).toEqual(baseline.metrics);
const replay = await f.api.getRunResults(run.id);
if (!baseline || !replay || !('financial' in baseline) || !('financial' in replay)) {
throw new Error('Canonical results required');
}
expect(f.history.reads).toBe(0);
expect(replay.financial.projection.valuation).toEqual(baseline.financial.projection.valuation);
expect(replay.financial.projection.fills).toEqual(baseline.financial.projection.fills);
expect(replay.analytics).toEqual(baseline.analytics);
expect((await f.pool.query('SELECT * FROM backtest_datasets')).rows).toHaveLength(1);
});
test('snapshot insertion and the run pointer roll back together; frozen inputs cannot be replaced', async () => {
const f = await fixture();
const run = await f.api.createRun({ backtestId: f.definition.id });
const config = await f.snapshot(run.id);
const f = await fixture(true);
const run = await f.historicalRun({ backtestId: f.definition.id });
const config = await f.legacySnapshot(run.id);
const claim = await f.repository.start(config);
const dataset = await loadDataset(f.storage, config);
await f.pool
@ -536,9 +593,9 @@ describe.skipIf(!url || !redisUrl)('durable backtests on real PostgreSQL and Red
});
test('cancellation after snapshot insertion aborts preparation and rolls back the run pointer and payload', async () => {
const f = await fixture();
const run = await f.api.createRun({ backtestId: f.definition.id });
const config = await f.snapshot(run.id);
const f = await fixture(true);
const run = await f.historicalRun({ backtestId: f.definition.id });
const config = await f.legacySnapshot(run.id);
const claim = await f.repository.start(config);
const dataset = await loadDataset(f.storage, config);
const controller = new AbortController();
@ -549,10 +606,14 @@ describe.skipIf(!url || !redisUrl)('durable backtests on real PostgreSQL and Red
work(
new Proxy(client, {
get(target, key) {
if (key !== 'query') return Reflect.get(target, key);
if (key !== 'query') {
return Reflect.get(target, key);
}
return async (sql: string, params?: unknown[]) => {
const result = await target.query(sql, params);
if (sql.startsWith('INSERT INTO backtest_datasets')) controller.abort(reason);
if (sql.startsWith('INSERT INTO backtest_datasets')) {
controller.abort(reason);
}
return result;
};
},
@ -574,9 +635,9 @@ describe.skipIf(!url || !redisUrl)('durable backtests on real PostgreSQL and Red
});
test('restored snapshots are revalidated rather than trusted by their content-addressed key', async () => {
const f = await fixture();
const run = await f.api.createRun({ backtestId: f.definition.id });
const config = await f.snapshot(run.id);
const f = await fixture(true);
const run = await f.historicalRun({ backtestId: f.definition.id });
const config = await f.legacySnapshot(run.id);
const claim = await f.repository.start(config);
const dataset = await loadDataset(f.storage, config);
// Model corrupt historical storage at initial insertion; retained evidence cannot be edited.
@ -595,14 +656,15 @@ describe.skipIf(!url || !redisUrl)('durable backtests on real PostgreSQL and Red
await expect(f.repository.loadDataset(run.id, claim.attemptId)).rejects.toThrow('hash/content');
await f.expire(run.id);
await f.dispatcher.tick();
await expect(f.runner.runQueued(run.id)).rejects.toThrow('hash/content');
expect((await f.runner.runQueued(run.id)).status).toBe('failed');
expect((await f.api.getRun(run.id))?.error).toContain('Legacy backtest execution is retired');
expect((await f.api.getRun(run.id))?.status).toBe('failed');
expect(await f.api.getRunResults(run.id)).toBeNull();
expect(f.history.reads).toBe(reads);
});
test('a missing retained dataset fails a historical request without provider fallback', async () => {
const f = await fixture();
const f = await fixture(true);
const runId = randomUUID();
const snapshot = backtestRequestFromDefinition(
{ ...f.definitionInput, config: { ...f.definition.config, datasetHash: 'f'.repeat(64) } },
@ -615,56 +677,38 @@ describe.skipIf(!url || !redisUrl)('durable backtests on real PostgreSQL and Red
);
await f.pool.query('INSERT INTO backtest_dispatch(run_id) VALUES ($1)', [runId]);
f.history.unavailable = true;
await expect(f.runner.runQueued(runId)).rejects.toThrow('Frozen dataset not found');
expect((await f.runner.runQueued(runId)).status).toBe('failed');
expect((await f.api.getRun(runId))?.error).toContain('Legacy backtest execution is retired');
expect(f.history.reads).toBe(0);
expect((await f.api.getRun(runId))?.status).toBe('failed');
expect(await f.api.getRunResults(runId)).toBeNull();
});
test('an explicit dataset replay rejects a different listing or date range', async () => {
const f = await fixture();
const run = await f.api.createRun({ backtestId: f.definition.id });
await f.runner.runQueued(run.id);
const result = (await f.api.getRunResults(run.id))!;
await expect(
f.runner.runBacktest({
...(await f.snapshot(run.id)),
runId: undefined,
endDate: '2024-03-16T00:00:00.000Z',
datasetHash: result.config.dataset!.hash,
})
).rejects.toThrow('does not match');
});
test('API acceptance uses the runner contract before writing a run or dispatch intent', async () => {
test('canonical admission rejects template ranges inconsistent with its retained dataset', async () => {
const f = await fixture();
await expect(
f.api.updateBacktest(f.definition.id, { config: { commission: -1 } })
).rejects.toThrow('commission');
expect((await f.api.getBacktest(f.definition.id))?.config).toEqual(f.definition.config);
// Model malformed historical configuration that bypassed today's API validator.
await f.pool.query('UPDATE backtests SET config = $2::jsonb WHERE id = $1', [
f.api.updateBacktest(f.definition.id, { endDate: '2025-01-01T00:00:00.000Z' })
).rejects.toThrow('trade bounds');
await f.pool.query('UPDATE backtests SET end_date=$2 WHERE id=$1', [
f.definition.id,
JSON.stringify({ ...f.definition.config, slippage: 0.2 }),
'2025-01-01T00:00:00.000Z',
]);
await expect(f.api.createRun({ backtestId: f.definition.id })).rejects.toThrow('slippage');
await expect(f.api.createRun({ backtestId: f.definition.id })).rejects.toThrow();
expect((await f.pool.query('SELECT * FROM runs')).rowCount).toBe(0);
expect((await f.pool.query('SELECT * FROM backtest_dispatch')).rowCount).toBe(0);
});
test('canonical admission rejects malformed policy and legacy pacing before run/outbox writes', async () => {
const f = await fixture();
await expect(
f.api.createRun({ backtestId: f.definition.id, speedMultiplier: 7 })
).rejects.toThrow('maximum speed');
await f.pool.query('UPDATE backtests SET config=$2 WHERE id=$1', [
f.definition.id,
{ ...f.definition.config, canonical: { ...canonicalSettings, feeRate: '-1' } },
]);
await expect(f.api.createRun({ backtestId: f.definition.id })).rejects.toThrow();
expect((await f.pool.query('SELECT * FROM runs')).rows).toHaveLength(0);
expect((await f.pool.query('SELECT * FROM backtest_dispatch')).rows).toHaveLength(0);
await f.pool.query('UPDATE backtests SET config = $2::jsonb WHERE id = $1', [
f.definition.id,
JSON.stringify(f.definition.config),
]);
const run = await f.api.createRun({ backtestId: f.definition.id, speedMultiplier: 7 });
const snapshot = (
await f.pool.query('SELECT request_snapshot FROM runs WHERE id = $1', [run.id])
).rows[0].request_snapshot;
const expected = backtestRequestFromDefinition(f.definitionInput, {
runId: run.id,
backtestId: f.definition.id,
speedMultiplier: 7,
});
expect(parseBacktestRequest(snapshot)).toEqual(expected);
expect(snapshot.speed).toBe('5x');
expect((await f.pool.query('SELECT * FROM backtest_dispatch')).rows).toHaveLength(1);
});
test('acceptance commits run + immutable snapshot + intent atomically, with no Redis/HTTP dependency', async () => {
@ -691,8 +735,8 @@ describe.skipIf(!url || !redisUrl)('durable backtests on real PostgreSQL and Red
(await f.pool.query('SELECT * FROM backtest_dispatch WHERE run_id = $1', [run.id])).rows
).toHaveLength(1);
await f.api.updateBacktest(f.definition.id, {
config: { fastPeriod: 999 },
symbols: ['MUTATED.TEST'],
strategyParameters: { fastPeriod: 3, slowPeriod: 4 },
name: 'Mutated after admission',
});
// A fresh dispatcher models an API restart after SQL commit but before the first publish.
const restarted = new BacktestDispatcher(f.postgres, f.queue, logger);
@ -701,8 +745,12 @@ describe.skipIf(!url || !redisUrl)('durable backtests on real PostgreSQL and Red
f.enqueueWorker();
await until(async () => (await f.api.getRun(run.id))?.status === 'completed');
const result = await f.api.getRunResults(run.id);
expect(result?.config.symbols).toEqual(['FIXTURE.TEST']);
expect(result?.config.parameters.fastPeriod).toBe(3);
expect(result).toHaveProperty('kind', 'canonical-result/v1');
if (!result || !('request' in result)) {
throw new Error('Canonical result required');
}
expect(result.request.strategy.selection.instrumentId).toBe(f.definition.symbols[0]!);
expect(result.request.strategy.selection.parameters).toMatchObject({ fastPeriod: 2 });
expect((await f.api.getRun(run.id))?.attemptNumber).toBe(1);
});
@ -711,8 +759,8 @@ describe.skipIf(!url || !redisUrl)('durable backtests on real PostgreSQL and Red
const run = await f.api.createRun({ backtestId: f.definition.id });
const config = await f.snapshot(run.id);
const claims = await Promise.allSettled([
f.repository.start(config),
f.repository.start(config),
f.repository.startCanonical(config),
f.repository.startCanonical(config),
]);
expect(claims.filter(result => result.status === 'fulfilled')).toHaveLength(1);
expect(claims.filter(result => result.status === 'rejected')).toHaveLength(1);
@ -736,14 +784,13 @@ describe.skipIf(!url || !redisUrl)('durable backtests on real PostgreSQL and Red
test('expired owners cannot heartbeat, write progress/control/failure/cancellation, or commit a stale result', async () => {
const f = await fixture();
const baseline = await f.runner.runBacktest({
...(await f.snapshot((await f.api.createRun({ backtestId: f.definition.id })).id)),
});
const run = await f.api.createRun({ backtestId: f.definition.id });
const old = await f.repository.start(await f.snapshot(run.id));
const request = await f.snapshot(run.id);
const old = await f.repository.startCanonical(request);
const result = await f.report(request);
await f.expire(run.id);
await f.dispatcher.tick();
const replacement = await f.repository.start(await f.snapshot(run.id));
const replacement = await f.repository.startCanonical(await f.snapshot(run.id));
await expect(f.repository.heartbeat(run.id, old.attemptId)).rejects.toBeInstanceOf(
BacktestLeaseLostError
);
@ -757,13 +804,12 @@ describe.skipIf(!url || !redisUrl)('durable backtests on real PostgreSQL and Red
BacktestLeaseLostError
);
await f.repository.fail(run.id, 'stale failure', old.attemptId);
const result = { ...baseline, runId: run.id };
await expect(f.repository.complete(result, old.attemptId)).rejects.toBeInstanceOf(
await expect(f.repository.completeCanonical(result, old.attemptId)).rejects.toBeInstanceOf(
BacktestLeaseLostError
);
expect((await f.api.getRun(run.id))?.status).toBe('running');
await f.repository.loadDataset(run.id, replacement.attemptId, baseline.config.dataset!.hash);
await f.repository.complete(result, replacement.attemptId);
await f.repository.loadCanonicalDataset(run.id, replacement.attemptId, request.datasetHash);
await f.repository.completeCanonical(result, replacement.attemptId);
expect(
(await f.pool.query('SELECT * FROM backtest_results WHERE run_id = $1', [run.id])).rows
).toHaveLength(1);
@ -773,7 +819,7 @@ describe.skipIf(!url || !redisUrl)('durable backtests on real PostgreSQL and Red
const f = await fixture();
const run = await f.api.createRun({ backtestId: f.definition.id });
const shortLease = new PostgresBacktestRunRepository(f.postgres, 300);
const claim = await shortLease.start(await f.snapshot(run.id));
const claim = await shortLease.startCanonical(await f.snapshot(run.id));
await sleep(200);
await shortLease.heartbeat(run.id, claim.attemptId);
await sleep(150);
@ -792,7 +838,7 @@ describe.skipIf(!url || !redisUrl)('durable backtests on real PostgreSQL and Red
const f = await fixture();
const run = await f.api.createRun({ backtestId: f.definition.id });
const shortLease = new PostgresBacktestRunRepository(f.postgres, 300);
const claim = await shortLease.start(await f.snapshot(run.id));
const claim = await shortLease.startCanonical(await f.snapshot(run.id));
const lock = await f.pool.connect();
let renewal: Promise<unknown> | undefined;
try {
@ -813,20 +859,13 @@ describe.skipIf(!url || !redisUrl)('durable backtests on real PostgreSQL and Red
test('cancellation wins against late completion and expires an abandoned cancelled owner truthfully', async () => {
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 claim = await f.repository.startCanonical(await f.snapshot(run.id));
const result = await f.report(await f.snapshot(run.id));
await f.api.cancelRun(run.id);
expect((await f.repository.heartbeat(run.id, claim.attemptId)).cancelRequested).toBe(true);
await expect(
f.repository.complete(
{
runId: run.id,
backtestId: f.definition.id,
status: 'completed',
completedAt: new Date().toISOString(),
} as never,
claim.attemptId
)
).rejects.toBeInstanceOf(BacktestCancelledError);
await expect(f.repository.completeCanonical(result, claim.attemptId)).rejects.toBeInstanceOf(
BacktestCancelledError
);
await f.expire(run.id);
await f.dispatcher.tick();
expect((await f.api.getRun(run.id))?.status).toBe('cancelled');
@ -837,7 +876,7 @@ describe.skipIf(!url || !redisUrl)('durable backtests on real PostgreSQL and Red
const f = await fixture();
const run = await f.api.createRun({ backtestId: f.definition.id });
for (let attempt = 1; attempt <= 3; attempt++) {
await f.repository.start(await f.snapshot(run.id));
await f.repository.startCanonical(await f.snapshot(run.id));
await f.expire(run.id);
await f.dispatcher.tick();
expect((await f.api.getRun(run.id))?.status).toBe(attempt === 3 ? 'failed' : 'pending');
@ -874,7 +913,9 @@ describe.skipIf(!url || !redisUrl)('durable backtests on real PostgreSQL and Red
child.once('error', reject);
child.once('exit', code => {
clearTimeout(timeout);
if (code) reject(new Error(`Crash owner exited: ${code}`));
if (code) {
reject(new Error(`Crash owner exited: ${code}`));
}
});
});
expect((await f.api.getRun(run.id))?.status).toBe('running');
@ -934,7 +975,7 @@ describe.skipIf(!url || !redisUrl)('durable backtests on real PostgreSQL and Red
});
test('invalid persisted snapshots become failed instead of remaining stranded pending', async () => {
const f = await fixture();
const f = await fixture(true);
const run = { id: randomUUID() };
// A legacy malformed snapshot is inserted as found, not fabricated by editing retained evidence.
await f.pool.query(
@ -948,15 +989,15 @@ describe.skipIf(!url || !redisUrl)('durable backtests on real PostgreSQL and Red
});
test('migration replay preserves leased owners, backfills legacy pending snapshots, and fails ownerless legacy runs', async () => {
const f = await fixture();
const f = await fixture(true);
const pending = { id: randomUUID() };
await f.pool.query('INSERT INTO runs(id,backtest_id,run_number) VALUES ($1,$2,1)', [
pending.id,
f.definition.id,
]);
const active = await f.api.createRun({ backtestId: f.definition.id });
const oldActive = await f.api.createRun({ backtestId: f.definition.id });
const claim = await f.repository.start(await f.snapshot(active.id));
const active = await f.historicalRun({ backtestId: f.definition.id });
const oldActive = await f.historicalRun({ backtestId: f.definition.id });
const claim = await f.repository.start(await f.legacySnapshot(active.id));
await f.pool.query("UPDATE runs SET status = 'running' WHERE id = $1", [oldActive.id]);
const migration = readFileSync(
new URL('../../database/postgres/init/10-durable-backtest-dispatch.sql', import.meta.url),
@ -964,13 +1005,16 @@ describe.skipIf(!url || !redisUrl)('durable backtests on real PostgreSQL and Red
);
await f.pool.query(migration);
await f.pool.query(migration);
expect((await f.snapshot(pending.id)).startDate).toBe('2024-01-01T00:00:00.000Z');
expect((await f.legacySnapshot(pending.id)).startDate).toBe('2024-01-01T00:00:00.000Z');
expect(
(await f.pool.query('SELECT * FROM backtest_dispatch WHERE run_id = $1', [pending.id])).rows
).toHaveLength(1);
expect((await f.api.getRun(oldActive.id))?.status).toBe('failed');
expect((await f.repository.heartbeat(active.id, claim.attemptId)).cancelRequested).toBe(false);
await f.runner.runQueued(pending.id);
expect((await f.api.getRun(pending.id))?.status).toBe('completed');
expect((await f.api.getRun(pending.id))?.status).toBe('failed');
expect((await f.api.getRun(pending.id))?.error).toContain(
'Legacy backtest execution is retired'
);
});
});

View file

@ -30,6 +30,7 @@ const migrations = [
'25-walk-forward.sql',
'26-cost-sensitivity.sql',
'27-research-evidence-sources.sql',
'28-research-agents.sql',
];
const cleanup: (() => Promise<void>)[] = [];
afterEach(async () => {

View file

@ -8,10 +8,8 @@ import { registerOrchestratorServices } from '../../apps/stock/orchestrator/src/
import { builtinStrategySelectionSchema } from '../../apps/stock/orchestrator/src/contracts/builtin-strategy';
import type { PaperRuntime } from '../../apps/stock/orchestrator/src/contracts/paper-runtime';
import { createBuiltinStrategy } from '../../apps/stock/orchestrator/src/strategies/canonical-builtins';
import {
BacktestConfigSchema,
type OrchestratorServices,
} from '../../apps/stock/orchestrator/src/types';
import type { OrchestratorServices } from '../../apps/stock/orchestrator/src/types';
import { canonicalAdmissionFixture } from '../fixtures/canonical-admission';
import { logger } from '../fixtures/execution';
import { paperConfig, paperFixture, paperFrame } from '../fixtures/paper-runtime';
@ -131,6 +129,7 @@ describe.skipIf(!process.env.PIPELINE_TEST_DATABASE_URL)(
const services: OrchestratorServices = { logger, postgres: f.postgres };
container.register({ serviceContainer: asValue(services) });
await registerOrchestratorServices(container, {
role: 'paper',
canonicalPaper: config,
nativeExecutionTimeoutMs: 10000,
});
@ -153,36 +152,15 @@ describe.skipIf(!process.env.PIPELINE_TEST_DATABASE_URL)(
}
expect((await custom.CanonicalPaperRuntime!.status()).active).toBe(false);
const before = await f.snapshot();
const research = BacktestConfigSchema.parse({
mode: 'backtest',
strategy: 'sma-crossover',
symbols: ['RESEARCH.TEST'],
startDate: '2024-01-01T00:00:00.000Z',
endDate: '2024-01-21T00:00:00.000Z',
initialCapital: 100000,
dataFrequency: '1d',
commission: 0,
slippage: 0,
config: { fastPeriod: 2, slowPeriod: 3 },
});
custom.StorageService!.getHistoricalBars = async () =>
Array.from({ length: 20 }, (_, i) => {
const close = 100 + Math.sin(i) * 5;
return {
symbol: 'RESEARCH.TEST',
source: 'eod' as const,
timestamp: new Date(Date.parse(research.startDate) + i * 86400000),
open: close,
high: close + 1,
low: close - 1,
close,
volume: 1000000,
};
});
expect((await custom.BacktestEngine!.runBacktest(research)).status).toBe('completed');
const research = await canonicalAdmissionFixture(f.pool, f.postgres);
custom.StorageService!.getHistoricalBars = async () => {
throw new Error('Canonical execution cannot query providers');
};
const run = await research.api.createRun({ backtestId: research.draft.id });
expect((await custom.BacktestRunner!.runQueued(run.id)).status).toBe('completed');
expect(await f.snapshot()).toEqual(before);
await expect(
registerOrchestratorServices(container, { canonicalPaper: config })
registerOrchestratorServices(container, { role: 'paper', canonicalPaper: config })
).rejects.toThrow('fresh runtime composition');
await expect(registerOrchestratorServices(container)).rejects.toThrow(
'fresh runtime composition'

View file

@ -0,0 +1,959 @@
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 { createHttpSecurity } from '@stock-bot/di';
import { getLogger, setLoggerConfig } from '@stock-bot/logger';
import { PostgreSQLClient } from '@stock-bot/postgres';
import type {
CanonicalRunRequest,
CanonicalRunResult,
} from '@stock-bot/stock-config/canonical-research';
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 { createResearchAgentRoutes } from '../../apps/stock/web-api/src/routes/research-agents.routes';
import { createResearchRoutes } from '../../apps/stock/web-api/src/routes/research.routes';
import { BacktestServiceV2 } from '../../apps/stock/web-api/src/services/backtest-v2.service';
import { BacktestDispatcher } from '../../apps/stock/web-api/src/services/BacktestDispatcher';
import { ChronologicalValidationService } from '../../apps/stock/web-api/src/services/chronological-validation.service';
import { ExperimentsService } from '../../apps/stock/web-api/src/services/experiments.service';
import { researchGrantPolicy } from '../../apps/stock/web-api/src/services/research-agent-budget';
import { ResearchAgentsService } from '../../apps/stock/web-api/src/services/research-agents.service';
import { ResearchService } from '../../apps/stock/web-api/src/services/research.service';
import { StrategyCatalogService } from '../../apps/stock/web-api/src/services/strategy-catalog.service';
import { WalkForwardService } from '../../apps/stock/web-api/src/services/walk-forward.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 { walkForwardDataset } from '../fixtures/walk-forward';
setLoggerConfig({ logLevel: 'fatal', logConsole: false });
const logger = getLogger('experiments');
const url = process.env.PIPELINE_TEST_DATABASE_URL;
const cleanup: (() => Promise<void>)[] = [];
let packages: ReturnType<typeof packageBuiltinStrategies> | undefined;
afterEach(async () => {
for (const close of cleanup.splice(0).reverse()) {
await close();
}
});
async function fixture(poolMax = 4, withAgents = true, dataset = canonicalSmaFixture().dataset) {
if (!url || !new URL(url).pathname.startsWith('/stock_bot_safety')) {
throw new Error('Disposable safety database required');
}
const schema = 'stock_bot_safety_agents_' + randomUUID().replaceAll('-', '');
const admin = new Pool({ connectionString: url });
await admin.query(`CREATE SCHEMA ${schema}`);
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',
'20-research-workspace.sql',
'21-run-reproduction.sql',
'22-experiments.sql',
'23-experiment-retries.sql',
'24-chronological-validation.sql',
'25-walk-forward.sql',
'26-cost-sensitivity.sql',
'27-research-evidence-sources.sql',
...(withAgents ? ['28-research-agents.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 };
const api = new BacktestServiceV2(container);
const experiments = new ExperimentsService(container);
const repository = new PostgresBacktestRunRepository(postgres);
const catalog = new StrategyCatalogService(container);
const pkg = (await (packages ??= packageBuiltinStrategies()))[0]!;
const version = await catalog.seedBuiltin('Retained SMA', pkg, 'seed');
await retainResearchDataset(pool, dataset);
const definition = {
name: 'Canonical API',
strategy: 'catalog',
strategyVersionId: version.id,
strategyParameters: { fastPeriod: 2, slowPeriod: 3 },
symbols: dataset.manifest.executionSeries.map(s => s.instrumentId),
startDate: new Date(dataset.manifest.bounds.tradeStart).toISOString(),
endDate: new Date(dataset.manifest.bounds.tradeEnd).toISOString(),
initialCapital: 10000,
config: {
datasetHash: dataset.manifest.hash,
dataFrequency: dataset.manifest.series[0]!.interval,
canonical: canonicalSettings,
},
};
const draft = await api.createBacktest(definition, { autoStart: false });
const approve = async () => {
await catalog.reviewVersion(
version.id,
{ decision: 'approve', reason: 'Reviewed retained builtin' },
'operator'
);
return (await catalog.getVersionReviews(version.id)).at(-1)!;
};
const execute = async (id: string) => {
const engine = new RustBacktestAdapter({
logger,
storage: {
async getHistoricalBars() {
throw new Error('Canonical execution must never load provider data');
},
},
});
const runner = new BacktestRunner({
engine,
engineName: 'native',
repository: new PostgresBacktestRunRepository(postgres),
logger,
});
try {
await runner.runQueued(id);
} finally {
await runner.shutdown();
}
};
return {
pool,
postgres,
container,
agents: new ResearchAgentsService(container),
research: new ResearchService(container),
schema,
api,
experiments,
repository,
catalog,
pkg,
version,
draft,
definition,
dataset,
approve,
execute,
app: new Hono().route('/', createExperimentRoutes(container)),
};
}
const limits = {
maxActiveTrials: 2,
maxTrialsPerExperiment: 10,
maxBarEvaluationsPerExperiment: 10000,
maxAttemptWallMs: 60000,
maxAttempts: 2,
};
function required<T>(value: T | null | undefined): T {
if (value === null || value === undefined) {
throw new Error('Required fixture value is missing');
}
return value;
}
type Fixture = Awaited<ReturnType<typeof fixture>>;
const receipt = (principal: string = 'operator', key = randomUUID()) => ({ principal, key });
async function provision(f: Fixture, overrides: Partial<typeof limits> = {}) {
await f.approve();
const project = await f.research.createProject({ title: 'Agent research' }, 'operator');
const created = await f.agents.create({
name: 'Bounded researcher',
allowedProjectIds: [project.id],
allowedBacktestIds: [f.draft.id],
limits: { ...limits, ...overrides },
});
return { ...created, project };
}
async function preparation(
f: Fixture,
name = 'Agent search',
backtestId = f.draft.id,
grid = { fastPeriod: [1, 2] }
) {
const input = { backtestId, name, grid };
const preview = await f.experiments.preview(input);
return { ...input, previewHash: preview.previewHash };
}
async function requestFor(f: Fixture, id: string): Promise<CanonicalRunRequest> {
return (await f.pool.query('SELECT request_snapshot FROM runs WHERE id=$1', [id])).rows[0]
.request_snapshot;
}
async function totals(f: Fixture) {
return (
await f.pool.query(
'SELECT (SELECT count(*)::int FROM runs) runs,(SELECT count(*)::int FROM research_experiments) experiments,(SELECT count(*)::int FROM backtest_dispatch) dispatch'
)
).rows[0];
}
function http(f: Fixture) {
const app = new Hono();
const security = createHttpSecurity({
adminToken: 'operator-test-secret-12345678901234567890',
serviceToken: 'service-test-secret-123456789012345678901',
environment: 'test',
resolveResearchCredential: request => f.agents.authenticate(request),
});
security.mount(app);
app.route('/', createResearchAgentRoutes(f.container, security.researchEnabled));
app.route('/', createExperimentRoutes(f.container));
app.route('/', createResearchRoutes(f.container));
return (path: string, token: string, body?: unknown, key?: string) =>
app.request(path, {
method: body === undefined ? 'GET' : 'POST',
headers: {
Authorization: `Bearer ${token}`,
'Content-Type': 'application/json',
...(key ? { 'Idempotency-Key': key } : {}),
},
...(body === undefined ? {} : { body: JSON.stringify(body) }),
});
}
describe.skipIf(!url)('authoritative research principals and budgets', () => {
test('operator provisioning stores only a hash; real mounted authentication, AI authorship and scoped writes', async () => {
const f = await fixture(1),
p = await provision(f);
const request = http(f);
expect(p.token.startsWith('sb-research.')).toBe(true);
const stored = (await f.pool.query('SELECT * FROM research_agents WHERE id=$1', [p.agent.id]))
.rows[0];
expect(JSON.stringify(stored)).not.toContain(p.token);
expect(stored.token_hash).toHaveLength(64);
const info = await request('/api/v2/research-agent/budget', p.token);
expect(info.status).toBe(200);
expect((await info.json()).activeTrials).toBe(0);
const submitted = await request(
`/api/v2/research-projects/${p.project.id}/hypotheses`,
p.token,
{ title: 'AI hypothesis', proposition: 'Test a bounded signal' }
);
expect(submitted.status).toBe(201);
const hypothesis = await submitted.json();
expect(JSON.stringify(hypothesis)).toContain(p.agent.id);
expect(JSON.stringify(hypothesis)).toContain('"contentOrigin":"ai"');
for (const contentOrigin of ['human', 'unknown']) {
const bad = await request(`/api/v2/research-projects/${p.project.id}/hypotheses`, p.token, {
title: 'False provenance',
proposition: 'not human',
contentOrigin,
});
expect(bad.status).toBe(403);
}
const denied = await request('/api/v2/research-projects', p.token, { title: 'unauthorized' });
expect(denied.status).toBe(403);
const foreign = await f.research.createProject({ title: 'Other project' }, 'operator');
expect(
(
await request(`/api/v2/research-projects/${foreign.id}/hypotheses`, p.token, {
title: 'Wrong',
proposition: 'Wrong project',
})
).status
).toBe(403);
expect((await request('/api/v2/research-agents', p.token)).status).toBe(403);
expect(
(
await f.pool.query('SELECT count(*)::int n FROM research_agent_audit WHERE agent_id=$1', [
p.agent.id,
])
).rows[0].n
).toBeGreaterThan(2);
const clone = await f.catalog.cloneVersion(
f.version.id,
{ name: 'Agent candidate' },
p.agent.id as `agent:${string}`,
randomUUID()
);
expect(String(clone.strategy.ownerPrincipal)).toBe(p.agent.id);
expect(clone.version.origin).toBe('candidate');
const candidate = await f.api.createBacktest(
{ ...f.definition, strategyVersionId: clone.version.id, name: 'Candidate cannot execute' },
{ autoStart: false }
);
await expect(
f.agents.update(p.agent.id, { expectedRevision: 1, allowedBacktestIds: [candidate.id] })
).rejects.toThrow('approved canonical templates');
expect((await totals(f)).runs).toBe(0);
await f.agents.update(p.agent.id, { expectedRevision: 1, enabled: false });
expect((await request('/api/v2/research-agent/budget', p.token)).status).toBe(401);
expect((await f.agents.budget(p.agent.id, true)).agent.enabled).toBe(false);
});
test('same receipt is exact after quota changes; capacity and grant errors are typed and atomic', async () => {
const f = await fixture(1),
p = await provision(f);
const submission = await preparation(f),
key = randomUUID();
const run = await f.experiments.submit(submission, receipt(p.agent.id, key));
expect(run.trials).toHaveLength(2);
expect((await f.agents.budget(p.agent.id)).activeTrials).toBe(2);
const policies = (
await f.pool.query(
'SELECT request_snapshot,research_limits,research_agent_id FROM runs ORDER BY run_number'
)
).rows;
for (const row of policies) {
expect(row.research_agent_id).toBe(p.agent.id);
expect(row.research_limits).toEqual(limits);
expect(
await f.pool
.query('SELECT research_grant_policy($1::jsonb) AS p', [row.request_snapshot])
.then(r => r.rows[0].p)
).toEqual(researchGrantPolicy(row.request_snapshot));
}
await f.agents.update(p.agent.id, {
expectedRevision: 1,
limits: { ...limits, maxActiveTrials: 1 },
allowedBacktestIds: [],
});
expect((await f.experiments.submit(submission, receipt(p.agent.id, key))).id).toBe(run.id);
const before = await totals(f);
const denied = await http(f)('/api/v2/experiments', p.token, submission, randomUUID());
expect(denied.status).toBe(403);
expect(await totals(f)).toEqual(before);
await f.agents.update(p.agent.id, { expectedRevision: 2, allowedBacktestIds: [f.draft.id] });
expect((await http(f)('/api/v2/experiments', p.token, submission, randomUUID())).status).toBe(
429
);
expect(await totals(f)).toEqual(before);
await f.agents.update(p.agent.id, { expectedRevision: 3, enabled: false });
expect((await http(f)('/api/v2/experiments', p.token, submission, key)).status).toBe(401);
await expect(f.experiments.submit(submission, receipt(p.agent.id, key))).rejects.toThrow(
'disabled'
);
});
test('concurrent different-parent grids cannot oversubscribe; failure releases durable capacity and ownership is immutable', async () => {
const f = await fixture(),
p = await provision(f);
const other = await f.api.createBacktest(
{ ...f.definition, name: 'Second template' },
{ autoStart: false }
);
await f.agents.update(p.agent.id, {
expectedRevision: 1,
allowedBacktestIds: [f.draft.id, other.id],
});
const [a, b] = await Promise.all([preparation(f), preparation(f, 'Other', other.id)]);
const race = await Promise.allSettled([
f.experiments.submit(a, receipt(p.agent.id)),
f.experiments.submit(b, receipt(p.agent.id)),
]);
expect(race.filter(r => r.status === 'fulfilled')).toHaveLength(1);
expect(race.filter(r => r.status === 'rejected')).toHaveLength(1);
const failed = race.find(r => r.status === 'rejected');
if (failed?.status !== 'rejected') {
throw new Error('Missing failure');
}
expect(failed.reason.message).toContain('research_budget:');
expect(await totals(f)).toEqual({ runs: 2, experiments: 1, dispatch: 2 });
const winner = race.find(r => r.status === 'fulfilled');
if (winner?.status !== 'fulfilled') {
throw new Error('Missing winner');
}
const first = winner.value.trials[0]!;
const claim = await f.repository.startCanonical(await requestFor(f, required(first.runId)));
expect(claim.executionDeadlineAt).toBeGreaterThan(Date.now());
await expect(
f.pool.query('UPDATE runs SET research_agent_id=NULL WHERE id=$1', [required(first.runId)])
).rejects.toThrow('immutable');
await expect(
f.pool.query(
"UPDATE runs SET research_limits=jsonb_set(research_limits,'{maxAttempts}','3') WHERE id=$1",
[required(first.runId)]
)
).rejects.toThrow('immutable');
await expect(
f.pool.query('UPDATE runs SET attempt_number=0 WHERE id=$1', [required(first.runId)])
).rejects.toThrow('cannot be reset');
await f.repository.fail(required(first.runId), 'controlled failure', claim.attemptId);
expect((await f.agents.budget(p.agent.id)).activeTrials).toBe(1);
const single = await preparation(f, 'Replacement', f.draft.id, { fastPeriod: [1] });
await f.experiments.submit(single, receipt(p.agent.id));
expect((await f.agents.budget(p.agent.id)).activeTrials).toBe(2);
await f.experiments.cancel(winner.value.id);
expect((await f.agents.budget(p.agent.id)).activeTrials).toBe(1);
});
test('deadline and attempts survive lease renewal/recovery and revocation; no expired completion', async () => {
const f = await fixture(),
p = await provision(f, { maxAttemptWallMs: 100, maxAttempts: 1 });
const run = await f.experiments.submit(
await preparation(f, 'Deadline', f.draft.id, { fastPeriod: [1] }),
receipt(p.agent.id)
);
const id = required(run.trials[0]!.runId);
await expect(
f.pool.query("UPDATE runs SET status='running' WHERE id=$1", [id])
).rejects.toThrow('complete bounded claim');
const claim = await f.repository.startCanonical(await requestFor(f, id));
const frozen = (await f.pool.query('SELECT research_deadline_at FROM runs WHERE id=$1', [id]))
.rows[0].research_deadline_at;
await f.pool.query(
"UPDATE runs SET lease_expires_at=clock_timestamp()+interval '1 hour' WHERE id=$1",
[id]
);
await expect(
f.pool.query(
"UPDATE runs SET research_deadline_at=clock_timestamp()+interval '1 hour' WHERE id=$1",
[id]
)
).rejects.toThrow('server-owned');
await f.agents.update(p.agent.id, { expectedRevision: 1, enabled: false });
await f.pool.query('SELECT pg_sleep(0.12)');
await expect(
f.pool.query("UPDATE runs SET status='completed',completed_at=NOW() WHERE id=$1", [id])
).rejects.toThrow('wall time');
const dispatcher = new BacktestDispatcher(
f.postgres,
{ add: async () => ({}) as never },
logger
);
await dispatcher.tick();
await dispatcher.shutdown();
const saved = (await f.pool.query('SELECT * FROM runs WHERE id=$1', [id])).rows[0];
expect(saved.status).toBe('failed');
expect(saved.error).toContain('wall time');
expect(saved.research_deadline_at).toEqual(frozen);
expect(saved.attempt_number).toBe(1);
expect((await f.agents.budget(p.agent.id, true)).activeTrials).toBe(0);
await f.agents.update(p.agent.id, { expectedRevision: 2, enabled: true });
await expect(
f.experiments.retryTrial(
run.id,
id,
{ expectedAttemptNumber: 1, expectedRetryCount: 0 },
receipt(p.agent.id)
)
).rejects.toThrow('attempt budget exhausted');
expect(
(await f.pool.query('SELECT count(*)::int n FROM experiment_trial_retries')).rows[0].n
).toBe(0);
expect(claim.executionDeadlineAt).toBeDefined();
});
test('ordinary native accounting is unchanged; first migration and reapply preserve saved economic evidence and leases', async () => {
const f = await fixture(4, false);
await f.approve();
const input = await preparation(f);
const before = await f.experiments.submit(input, receipt());
await f.execute(required(before.trials[0]!.runId));
const pending = required(before.trials[1]!.runId);
const claim = await f.repository.startCanonical(await requestFor(f, pending));
const snapshot = async () => ({
runs: (
await f.pool.query(
"SELECT to_jsonb(r)-ARRAY['research_agent_id','research_limits','research_deadline_at'] AS r FROM runs r ORDER BY id"
)
).rows,
results: (await f.pool.query('SELECT * FROM backtest_results ORDER BY run_id')).rows,
experiments: (await f.pool.query('SELECT * FROM research_experiments ORDER BY id')).rows,
dispatch: (await f.pool.query('SELECT * FROM backtest_dispatch ORDER BY run_id')).rows,
});
const original = await snapshot();
const sql = readFileSync(
new URL('../../database/postgres/init/28-research-agents.sql', import.meta.url),
'utf8'
);
await f.pool.query(sql);
expect(await snapshot()).toEqual(original);
await f.pool.query(sql);
expect(await snapshot()).toEqual(original);
expect(
(await f.pool.query('SELECT attempt_id FROM runs WHERE id=$1', [pending])).rows[0].attempt_id
).toBe(claim.attemptId);
const p = await provision(f);
const agentRun = await f.experiments.submit(
await preparation(f, 'Native agent', f.draft.id, { fastPeriod: [1] }),
receipt(p.agent.id)
);
await f.execute(required(agentRun.trials[0]!.runId));
const result = await f.api.getRunResults(required(agentRun.trials[0]!.runId));
expect(result && 'kind' in result ? result.kind : null).toBe('canonical-result/v1');
expect(result?.status).toBe('completed');
expect((await f.agents.budget(p.agent.id)).activeTrials).toBe(0);
const audit = (await f.pool.query('SELECT * FROM research_agent_audit ORDER BY id')).rows;
await f.pool.query(sql);
expect((await f.pool.query('SELECT * FROM research_agent_audit ORDER BY id')).rows).toEqual(
audit
);
await expect(f.pool.query('DELETE FROM research_agent_audit')).rejects.toThrow(
'cannot be rewritten'
);
});
test('manual retry reacquires capacity once and lifetime attempts remain bounded across recovery', async () => {
const f = await fixture(),
p = await provision(f, { maxActiveTrials: 1, maxAttempts: 2 });
const submitted = await f.experiments.submit(
await preparation(f, 'Retry', f.draft.id, { fastPeriod: [1] }),
receipt(p.agent.id)
);
const id = required(submitted.trials[0]!.runId),
request = await requestFor(f, id),
first = await f.repository.startCanonical(request);
await f.pool.query(
"UPDATE runs SET lease_expires_at=clock_timestamp()-interval '1 second' WHERE id=$1",
[id]
);
const dispatcher = new BacktestDispatcher(
f.postgres,
{ add: async () => ({}) as never },
logger
);
await dispatcher.tick();
expect((await f.agents.budget(p.agent.id)).activeTrials).toBe(1);
const second = await f.repository.startCanonical(request);
expect(second.executionDeadlineAt).toBeGreaterThanOrEqual(first.executionDeadlineAt!);
await f.repository.fail(id, 'Second attempt failed', second.attemptId);
const before = await totals(f);
await expect(
f.experiments.retryTrial(
submitted.id,
id,
{ expectedAttemptNumber: 2, expectedRetryCount: 0 },
receipt(p.agent.id)
)
).rejects.toThrow('attempt budget exhausted');
expect(await totals(f)).toEqual(before);
expect(
(await f.pool.query('SELECT count(*)::int n FROM experiment_trial_retries')).rows[0].n
).toBe(0);
const next = await f.experiments.submit(
await preparation(f, 'Manual', f.draft.id, { fastPeriod: [1] }),
receipt(p.agent.id)
);
const nextId = required(next.trials[0]!.runId);
const claim = await f.repository.startCanonical(await requestFor(f, nextId));
await f.repository.fail(nextId, 'Retryable failure', claim.attemptId);
const key = randomUUID(),
intent = { expectedAttemptNumber: 1, expectedRetryCount: 0 };
await f.agents.update(p.agent.id, { expectedRevision: 1, allowedBacktestIds: [] });
await expect(
f.experiments.retryTrial(next.id, nextId, intent, receipt(p.agent.id, key))
).rejects.toThrow('Operator approval');
await f.agents.update(p.agent.id, { expectedRevision: 2, allowedBacktestIds: [f.draft.id] });
const retry = await f.experiments.retryTrial(next.id, nextId, intent, receipt(p.agent.id, key));
expect(String(retry.retry.principal)).toBe(p.agent.id);
expect((await f.agents.budget(p.agent.id)).activeTrials).toBe(1);
await f.agents.update(p.agent.id, { expectedRevision: 3, allowedBacktestIds: [] });
expect(
(await f.experiments.retryTrial(next.id, nextId, intent, receipt(p.agent.id, key))).retry.id
).toBe(retry.retry.id);
await f.agents.update(p.agent.id, { expectedRevision: 4, enabled: false });
const resumed = await f.repository.startCanonical(await requestFor(f, nextId));
expect(resumed.executionDeadlineAt).toBeDefined();
await f.repository.fail(
nextId,
'Accepted bounded work still runs after token revocation',
resumed.attemptId
);
await dispatcher.shutdown();
});
test('cost scenarios and chronological/walk-forward phases retain exact baseline grants and bounded planned work', async () => {
const data = walkForwardDataset(),
f = await fixture(4, true, data.dataset),
p = await provision(f, { maxActiveTrials: 4 });
const costs = {
backtestId: f.draft.id,
name: 'Fees',
scenarios: [{ feeRate: '0.002', slippageRate: '0.001' }],
};
const preview = await f.experiments.previewCosts(costs);
const cost = await f.experiments.submitCosts(
{ ...costs, previewHash: preview.previewHash },
receipt(p.agent.id)
);
expect(cost.trials).toHaveLength(2);
await f.experiments.cancel(cost.id);
const validation = new ChronologicalValidationService(f.container),
walk = new WalkForwardService(f.container);
const input = {
backtestId: f.draft.id,
name: 'Validation',
grid: { fastPeriod: [1, 2] },
recipe: data.windows[0]!,
};
const prepared = await f.experiments.previewValidation(input);
const train = await validation.submit(
{ ...input, previewHash: prepared.previewHash },
receipt(p.agent.id)
);
await expect(
validation.select(train.id, { previewHash: prepared.previewHash }, receipt())
).rejects.toThrow('owning research principal');
for (const trial of train.phases[0].experiment!.trials) {
await f.execute(required(trial.runId));
}
await f.agents.update(p.agent.id, {
expectedRevision: 1,
limits: { ...limits, maxActiveTrials: 1 },
});
const selectKey = randomUUID();
await expect(
validation.select(
train.id,
{ previewHash: prepared.previewHash },
receipt(p.agent.id, selectKey)
)
).rejects.toThrow('research_budget:');
expect(
(
await f.pool.query('SELECT validation_selection FROM research_experiments WHERE id=$1', [
train.id,
])
).rows[0].validation_selection
).toBeNull();
expect(
(
await f.pool.query(
'SELECT count(*)::int n FROM research_experiments WHERE validation_parent_id=$1',
[train.id]
)
).rows[0].n
).toBe(0);
await f.agents.update(p.agent.id, {
expectedRevision: 2,
limits: { ...limits, maxActiveTrials: 4 },
});
const selected = await validation.select(
train.id,
{ previewHash: prepared.previewHash },
receipt(p.agent.id, selectKey)
);
expect(String(selected.receipt.principal)).toBe(p.agent.id);
for (const phase of selected.validation.phases.slice(1)) {
for (const trial of required(phase.experiment).trials) {
await f.execute(required(trial.runId));
}
}
const finalizeInput = {
previewHash: prepared.previewHash,
selectionHash: required(selected.validation.selection).selectionHash,
},
finalKey = randomUUID();
const sealed = await validation.finalize(
train.id,
finalizeInput,
receipt(p.agent.id, finalKey)
);
expect(String(required(sealed.validation.report).principal)).toBe(p.agent.id);
expect(
(await validation.finalize(train.id, finalizeInput, receipt(p.agent.id, finalKey))).receipt
).toEqual(sealed.receipt);
const walkInput = {
backtestId: f.draft.id,
name: 'Rolling',
grid: { fastPeriod: [1, 2] },
windows: data.windows,
};
const walkPreview = await walk.preview(walkInput);
await f.agents.update(p.agent.id, {
expectedRevision: 3,
limits: { ...limits, maxActiveTrials: 4, maxTrialsPerExperiment: 7 },
});
const before = await totals(f);
await expect(
walk.submit({ ...walkInput, previewHash: walkPreview.previewHash }, receipt(p.agent.id))
).rejects.toThrow('trial or observation budget');
expect(await totals(f)).toEqual(before);
await f.agents.update(p.agent.id, {
expectedRevision: 4,
limits: { ...limits, maxActiveTrials: 4 },
});
const series = await walk.submit(
{ ...walkInput, previewHash: walkPreview.previewHash },
receipt(p.agent.id)
);
expect(series.windows).toHaveLength(2);
expect((await f.agents.budget(p.agent.id)).activeTrials).toBe(4);
for (const window of series.windows) {
const member = required(window.validation);
for (const trial of required(member.phases[0].experiment).trials) {
await f.execute(required(trial.runId));
}
const selection = await validation.select(
member.id,
{ previewHash: member.previewHash },
receipt(p.agent.id)
);
for (const phase of selection.validation.phases.slice(1)) {
for (const trial of required(phase.experiment).trials) {
await f.execute(required(trial.runId));
}
}
await validation.finalize(
member.id,
{
previewHash: member.previewHash,
selectionHash: required(selection.validation.selection).selectionHash,
},
receipt(p.agent.id)
);
}
const reportKey = randomUUID(),
reportInput = { previewHash: walkPreview.previewHash };
const report = await walk.finalize(series.id, reportInput, receipt(p.agent.id, reportKey));
expect(String(required(report.walkForward.report).principal)).toBe(p.agent.id);
expect(
(await walk.finalize(series.id, reportInput, receipt(p.agent.id, reportKey))).receipt
).toEqual(report.receipt);
expect((await f.agents.budget(p.agent.id)).activeTrials).toBe(0);
}, 30000);
test('deadline is rechecked at result transaction commit after a valid native result and timely completed transition', async () => {
const f = await fixture(),
p = await provision(f, { maxAttemptWallMs: 1000 });
const run = await f.experiments.submit(
await preparation(f, 'Delayed commit', f.draft.id, { fastPeriod: [1] }),
receipt(p.agent.id)
);
const id = required(run.trials[0]!.runId),
request = await requestFor(f, id);
const engine = new RustBacktestAdapter({
logger,
storage: {
getHistoricalBars: async () => {
throw new Error('Provider forbidden');
},
},
});
let economic: Pick<CanonicalRunResult, 'financial' | 'analytics'>;
try {
economic = await engine.runCanonical(request, async () => f.dataset);
} finally {
await engine.shutdown();
}
const claim = await f.repository.startCanonical(request);
const result = {
kind: 'canonical-result/v1',
status: 'completed',
runId: id,
backtestId: request.backtestId,
request,
financialEngine: 'rust',
strategyExecution: 'typescript-retained-builtin/v1',
completedAt: new Date().toISOString(),
executionTime: 1,
...economic,
};
const client = await f.pool.connect();
try {
await client.query('BEGIN');
await client.query(
"UPDATE runs SET status='completed',progress=100,completed_at=NOW() WHERE id=$1 AND attempt_id=$2",
[id, claim.attemptId]
);
await client.query(
"INSERT INTO backtest_results(run_id,completed_at,execution_time,canonical_result,metrics,equity_curve,ohlc_data,trades,positions,analytics) VALUES($1,NOW(),1,$2::jsonb,'null','null','null','null','null','null')",
[id, result]
);
await client.query('SELECT pg_sleep(1.1)');
await expect(client.query('COMMIT')).rejects.toThrow(
'wall time exceeded before result commit'
);
} finally {
await client.query('ROLLBACK');
client.release();
}
expect((await f.pool.query('SELECT status FROM runs WHERE id=$1', [id])).rows[0].status).toBe(
'running'
);
expect(
(await f.pool.query('SELECT count(*)::int n FROM backtest_results WHERE run_id=$1', [id]))
.rows[0].n
).toBe(0);
await f.repository.fail(id, 'Budget expired while saving', claim.attemptId);
expect((await f.agents.budget(p.agent.id)).activeTrials).toBe(0);
});
test('foreign/disabled agent phase and retry receipts fail through service and direct SQL before any mutation', async () => {
const data = walkForwardDataset(),
f = await fixture(4, true, data.dataset),
a = await provision(f),
b = await provision(f);
const ordinary = await f.experiments.submit(
await preparation(f, 'Owned', f.draft.id, { fastPeriod: [1] }),
receipt(a.agent.id)
);
const runId = required(ordinary.trials[0]!.runId),
claim = await f.repository.startCanonical(await requestFor(f, runId));
await f.repository.fail(runId, 'controlled failure', claim.attemptId);
await expect(
f.experiments.retryTrial(
ordinary.id,
runId,
{ expectedAttemptNumber: 1, expectedRetryCount: 0 },
receipt(b.agent.id)
)
).rejects.toThrow(/owning.*principal/);
await expect(
f.pool.query(
`INSERT INTO experiment_trial_retries(id,experiment_id,run_id,trial_key,retry_number,previous_attempt_number,previous_attempt_id,error,progress,current_simulation_date,started_at,completed_at,paused_at,failure_updated_at,principal,review_id,submission_key,submission_hash)
SELECT $1,experiment_id,id,trial_key,1,attempt_number,attempt_id,error,progress,current_simulation_date,started_at,completed_at,paused_at,updated_at,$3,(SELECT id FROM strategy_review_events ORDER BY created_at DESC LIMIT 1),$4,$5 FROM runs WHERE id=$2`,
[randomUUID(), runId, b.agent.id, randomUUID(), 'a'.repeat(64)]
)
).rejects.toThrow(/owning.*principal/);
const validation = new ChronologicalValidationService(f.container),
input = {
backtestId: f.draft.id,
name: 'Owned phases',
grid: { fastPeriod: [1] },
recipe: data.windows[0]!,
};
const preview = await f.experiments.previewValidation(input),
train = await validation.submit(
{ ...input, previewHash: preview.previewHash },
receipt(a.agent.id)
);
await expect(
validation.select(train.id, { previewHash: preview.previewHash }, receipt(b.agent.id))
).rejects.toThrow(/owning.*principal/);
for (const principal of [b.agent.id, a.agent.id]) {
if (principal === a.agent.id) {
await f.agents.update(principal, { expectedRevision: 1, enabled: false });
}
for (const column of ['validation_selection', 'validation_report']) {
await expect(
f.pool.query(`UPDATE research_experiments SET ${column}=$2::jsonb WHERE id=$1`, [
train.id,
{ principal },
])
).rejects.toThrow(/owning.*principal/);
}
}
expect(
(await f.pool.query('SELECT count(*)::int n FROM experiment_trial_retries')).rows[0].n
).toBe(0);
expect(
(
await f.pool.query(
'SELECT validation_selection,validation_report FROM research_experiments WHERE id=$1',
[train.id]
)
).rows[0]
).toEqual({ validation_selection: null, validation_report: null });
});
test('operator retry reserves owning agent before parent so policy edits cannot deadlock admissions', async () => {
const f = await fixture(),
p = await provision(f),
run = await f.experiments.submit(
await preparation(f, 'Lock order', f.draft.id, { fastPeriod: [1] }),
receipt(p.agent.id)
);
const id = required(run.trials[0]!.runId),
claim = await f.repository.startCanonical(await requestFor(f, id));
await f.repository.fail(id, 'controlled', claim.attemptId);
const blocker = await f.pool.connect();
await blocker.query('BEGIN');
await blocker.query('SELECT id FROM research_agents WHERE id=$1 FOR UPDATE', [p.agent.id]);
const retry = f.experiments.retryTrial(
run.id,
id,
{ expectedAttemptNumber: 1, expectedRetryCount: 0 },
receipt()
);
try {
let waiting = false;
for (let i = 0; i < 100; i++) {
const rows = (
await f.pool.query(
"SELECT 1 FROM pg_stat_activity WHERE application_name=$1 AND wait_event_type='Lock' AND query LIKE 'SELECT id,enabled FROM research_agents%'",
[f.schema]
)
).rows;
if (rows.length) {
waiting = true;
break;
}
await blocker.query('SELECT pg_sleep(0.01)');
}
expect(waiting).toBe(true);
await blocker.query('SELECT id FROM backtests WHERE id=$1 FOR UPDATE NOWAIT', [f.draft.id]);
await blocker.query('COMMIT');
} finally {
await blocker.query('ROLLBACK');
blocker.release();
}
expect((await retry).retry.principal).toBe('operator');
expect((await f.agents.budget(p.agent.id)).activeTrials).toBe(1);
});
test('multi-template policy locks all parents before shared strategy families', async () => {
const f = await fixture(),
p = await provision(f),
other = await f.api.createBacktest(
{ ...f.definition, name: 'Shared family' },
{ autoStart: false }
);
const ids = [f.draft.id, other.id].sort(),
blocker = await f.pool.connect();
await blocker.query('BEGIN');
await blocker.query('SELECT id FROM backtests WHERE id=$1 FOR UPDATE', [ids[1]]);
const update = f.agents.update(p.agent.id, { expectedRevision: 1, allowedBacktestIds: ids });
try {
let waiting = false;
for (let i = 0; i < 100; i++) {
const rows = (
await f.pool.query(
"SELECT 1 FROM pg_stat_activity WHERE application_name=$1 AND wait_event_type='Lock' AND query LIKE 'SELECT * FROM backtests WHERE id=ANY%'",
[f.schema]
)
).rows;
if (rows.length) {
waiting = true;
break;
}
await blocker.query('SELECT pg_sleep(0.01)');
}
expect(waiting).toBe(true);
await blocker.query('SELECT id FROM strategies WHERE id=$1 FOR UPDATE NOWAIT', [
f.version.strategyId,
]);
await blocker.query('COMMIT');
} finally {
await blocker.query('ROLLBACK');
blocker.release();
}
expect((await update).grants).toHaveLength(2);
});
test('observation budgets and changed financial policy reject without partial admission', async () => {
const f = await fixture(),
p = await provision(f, { maxBarEvaluationsPerExperiment: 1 });
const input = await preparation(f),
before = await totals(f);
await expect(f.experiments.submit(input, receipt(p.agent.id))).rejects.toThrow(
'trial or observation budget'
);
expect(await totals(f)).toEqual(before);
await f.agents.update(p.agent.id, { expectedRevision: 1, limits });
await f.pool.query('UPDATE backtests SET initial_capital=20000 WHERE id=$1', [f.draft.id]);
const changed = await preparation(f);
expect(changed.previewHash).not.toBe(input.previewHash);
await expect(f.experiments.submit(changed, receipt(p.agent.id))).rejects.toThrow(
'Operator approval'
);
expect(await totals(f)).toEqual(before);
await f.agents.update(p.agent.id, { expectedRevision: 2, allowedBacktestIds: [f.draft.id] });
expect((await f.experiments.submit(changed, receipt(p.agent.id))).trials).toHaveLength(2);
});
});

View file

@ -12,6 +12,7 @@ import { loadDataset } from '../../apps/stock/orchestrator/src/data/historical-d
import { createBacktestV2Routes } from '../../apps/stock/web-api/src/routes/backtests-v2.routes';
import { BacktestServiceV2 } from '../../apps/stock/web-api/src/services/backtest-v2.service';
import { BacktestDispatcher } from '../../apps/stock/web-api/src/services/BacktestDispatcher';
import { seedHistoricalRun } from '../fixtures/historical-run';
setLoggerConfig({ logLevel: 'fatal', logConsole: false });
const logger = getLogger('research-retention-test');
@ -172,7 +173,9 @@ async function waitForBlocked(pool: Pool, schema: string) {
describe.skipIf(!url)('research evidence retention on real PostgreSQL', () => {
test('retained_run_delete_restricted_postgres blocks raw cascades, mutations and truncation while preserving runless legacy deletion', async () => {
const f = await fixture();
const run = await f.api.createRun(
const run = await seedHistoricalRun(
f.pool,
f.api,
{ backtestId: f.definition.id },
{ principal: 'operator', key: 'retained' }
);
@ -217,7 +220,7 @@ describe.skipIf(!url)('research evidence retention on real PostgreSQL', () => {
test('archive_preserves_replay hides discovery only and rejects new admission or edits until restored', async () => {
const f = await fixture();
const receipt = { principal: 'operator' as const, key: 'archive-retry' };
const run = await f.api.createRun({ backtestId: f.definition.id }, receipt);
const run = await seedHistoricalRun(f.pool, f.api, { backtestId: f.definition.id }, receipt);
const before = await f.snapshot(run.id);
const archived = await f.api.archiveBacktest(f.definition.id, true);
expect(archived?.archivedAt).toBeString();
@ -247,12 +250,15 @@ describe.skipIf(!url)('research evidence retention on real PostgreSQL', () => {
expect((await f.api.updateBacktest(f.definition.id, { name: 'Restored' }))?.name).toBe(
'Restored'
);
expect((await f.api.createRun({ backtestId: f.definition.id })).runNumber).toBe(2);
await expect(f.api.createRun({ backtestId: f.definition.id })).rejects.toThrow(
'Legacy backtest execution is retired'
);
expect(await f.api.listRuns(f.definition.id)).toHaveLength(1);
});
test('archive and admission use one parent lock, including direct repository inserts', async () => {
const f = await fixture();
const accepted = await f.api.createRun({ backtestId: f.definition.id });
const accepted = await seedHistoricalRun(f.pool, f.api, { backtestId: f.definition.id });
const blocker = await f.pool.connect();
await blocker.query('BEGIN');
await blocker.query('SELECT id FROM backtests WHERE id=$1 FOR UPDATE', [f.definition.id]);
@ -279,7 +285,7 @@ describe.skipIf(!url)('research evidence retention on real PostgreSQL', () => {
test('accepted archived work retains binding, lease recovery, controls, progress and terminal result writes', async () => {
const f = await fixture();
const run = await f.api.createRun({ backtestId: f.definition.id });
const run = await seedHistoricalRun(f.pool, f.api, { backtestId: f.definition.id });
await f.api.archiveBacktest(f.definition.id, true);
const claim = await f.repository.start(await f.snapshot(run.id));
const frozen = await f.repository.freezeDataset(
@ -319,7 +325,10 @@ describe.skipIf(!url)('research evidence retention on real PostgreSQL', () => {
await f.api.updateRunProgress(run.id, { progress: 90, attemptId: retry.attemptId });
await f.repository.complete(result(run.id, f.definition.id, frozen), retry.attemptId);
const saved = await f.api.getRunResults(run.id);
expect(saved?.config.dataset?.hash).toBe(frozen.manifest.hash);
if (!saved || !('config' in saved)) {
throw new Error('Expected preserved historical result');
}
expect(saved.config.dataset?.hash).toBe(frozen.manifest.hash);
expect((await f.api.getRun(run.id))?.attemptNumber).toBe(2);
expect((await f.api.getRun(run.id))?.status).toBe('completed');
await f.pool.query(retention);
@ -329,7 +338,9 @@ describe.skipIf(!url)('research evidence retention on real PostgreSQL', () => {
test('run identity and frozen inputs reject rewrites while legacy NULL snapshots can be populated once', async () => {
const f = await fixture();
const run = await f.api.createRun(
const run = await seedHistoricalRun(
f.pool,
f.api,
{ backtestId: f.definition.id },
{ principal: 'service', key: 'immutable' }
);
@ -381,7 +392,9 @@ describe.skipIf(!url)('research evidence retention on real PostgreSQL', () => {
test('pending and running cancellation/failure still terminate accepted archived requests', async () => {
const f = await fixture();
const runs = await Promise.all(
Array.from({ length: 4 }, () => f.api.createRun({ backtestId: f.definition.id }))
Array.from({ length: 4 }, () =>
seedHistoricalRun(f.pool, f.api, { backtestId: f.definition.id })
)
);
await f.api.archiveBacktest(f.definition.id, true);
await f.api.cancelRun(runs[0]!.id);
@ -405,7 +418,7 @@ 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();
const run = await f.api.createRun({ backtestId: f.definition.id });
const run = await seedHistoricalRun(f.pool, f.api, { backtestId: f.definition.id });
const claim = await f.repository.start(await f.snapshot(run.id));
const dataset = await f.dataset(run.id);
const corrupt = structuredClone(dataset);
@ -430,7 +443,7 @@ describe.skipIf(!url)('research evidence retention on real PostgreSQL', () => {
test('HTTP archive/list/delete errors are actionable and direct saved resources remain accessible', async () => {
const f = await fixture();
const run = await f.api.createRun({ backtestId: f.definition.id });
const run = await seedHistoricalRun(f.pool, f.api, { backtestId: f.definition.id });
const archived = await f.app.request(`/api/v2/backtests/${f.definition.id}/archive`, {
method: 'POST',
body: JSON.stringify({ archived: true }),

View file

@ -1,91 +1,28 @@
import { createHash, randomUUID } from 'node:crypto';
import { readFileSync } from 'node:fs';
import { asValue } from 'awilix';
import { afterEach, describe, expect, spyOn, test } from 'bun:test';
import { Pool } from 'pg';
import { afterEach, describe, expect, test } from 'bun:test';
import { ServiceContainerBuilder } from '@stock-bot/di';
import { PostgreSQLClient } from '@stock-bot/postgres';
import { BacktestCancelledError } from '../../apps/stock/orchestrator/src/backtest/execution-engine';
import { registerOrchestratorServices } from '../../apps/stock/orchestrator/src/container';
import { canonicalJson } from '../../apps/stock/orchestrator/src/execution/strategy-recovery';
import {
BacktestConfigSchema,
type OrchestratorServices,
} from '../../apps/stock/orchestrator/src/types';
import { logger, quote } from '../fixtures/execution';
import { CounterStrategy } from '../fixtures/strategy-recovery';
import type { OrchestratorServices } from '../../apps/stock/orchestrator/src/types';
import { canonicalAdmissionFixture } from '../fixtures/canonical-admission';
import { logger } from '../fixtures/execution';
import { paperFixture, paperFrame } from '../fixtures/paper-runtime';
const url = process.env.PIPELINE_TEST_DATABASE_URL;
const cleanup: (() => Promise<void>)[] = [];
afterEach(async () => {
for (const close of cleanup.splice(0).reverse()) await close();
for (const close of cleanup.splice(0).reverse()) {
await close();
}
});
const research = BacktestConfigSchema.parse({
mode: 'backtest',
strategy: 'sma-crossover',
symbols: ['RESEARCH.TEST'],
startDate: '2024-01-01T00:00:00.000Z',
endDate: '2024-03-15T00:00:00.000Z',
initialCapital: 100000,
dataFrequency: '1d',
commission: 0,
slippage: 0,
config: { fastPeriod: 3, slowPeriod: 7 },
});
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_' + randomUUID().replaceAll('-', '');
const admin = new Pool({ connectionString: url });
await admin.query(`CREATE SCHEMA ${schema}`);
const pool = new Pool({ connectionString: url, options: `-c search_path=${schema}` });
cleanup.push(async () => {
await pool.end();
await admin.query(`DROP SCHEMA ${schema} CASCADE`);
await admin.end();
});
await pool.query(`CREATE TYPE run_status AS ENUM ('pending','running','completed','failed','cancelled','paused');
CREATE TABLE backtests (id uuid PRIMARY KEY, name text, strategy text, symbols jsonb,
start_date timestamptz, end_date timestamptz, initial_capital numeric, config jsonb,
created_at timestamptz DEFAULT NOW(), updated_at timestamptz DEFAULT NOW());
CREATE TABLE runs (id uuid PRIMARY KEY, backtest_id uuid REFERENCES backtests(id), run_number integer,
status run_status DEFAULT 'pending', speed_multiplier numeric, progress numeric DEFAULT 0, error text,
started_at timestamptz, completed_at timestamptz, paused_at timestamptz, current_simulation_date timestamptz,
created_at timestamptz DEFAULT NOW(), updated_at timestamptz DEFAULT NOW(), UNIQUE(backtest_id, run_number));
CREATE TABLE backtest_results (run_id uuid REFERENCES runs(id), completed_at timestamptz,
metrics jsonb, equity_curve jsonb, ohlc_data jsonb, trades jsonb, positions jsonb, analytics jsonb,
execution_time numeric);`);
for (const filename of [
'09-backtest-run-contract.sql',
'10-durable-backtest-dispatch.sql',
'11-simulation-execution-ledger.sql',
'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',
'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/${filename}`, import.meta.url), 'utf8')
);
}
const postgres = new PostgreSQLClient(
{ host: 'unused', port: 5432, database: 'unused', user: 'unused', password: 'unused' },
logger
);
Object.defineProperty(postgres, 'connectionPool', { get: () => pool });
Object.defineProperty(postgres, 'query', { value: pool.query.bind(pool) });
const paper = await paperFixture();
cleanup.push(paper.close);
await paper.runtime.connect({ sourceId: 'fixture', connectionId: 'one' });
await paper.runtime.ingest(paperFrame(1));
await paper.runtime.activate({ recoverPending: false });
paper.clock(20);
await paper.runtime.ingest(paperFrame(2));
const admitted = await canonicalAdmissionFixture(paper.pool, paper.postgres);
const container = await new ServiceContainerBuilder()
.withOptions({
enableCache: false,
@ -97,187 +34,109 @@ async function fixture() {
enableProxy: false,
})
.build();
const services: OrchestratorServices = { logger, postgres };
const services: OrchestratorServices = { logger, postgres: paper.postgres };
container.register({ serviceContainer: asValue(services) });
await registerOrchestratorServices(container, {
initializeMode: false,
nativeExecutionTimeoutMs: 5000,
});
const runtime = services.custom!;
const mode = runtime.ModeManager!;
const runner = runtime.BacktestRunner!;
const market = runtime.MarketDataService!;
const storage = runtime.StorageService!;
const execution = runtime.ExecutionService!;
const strategies = runtime.StrategyManager!;
const feed = { connected: false };
// Only the external transport is offline; real admission, ledger, checkpoints and replay run.
const feedStart = spyOn(market, 'initialize').mockImplementation(async () => {
feed.connected = true;
});
const originalShutdown = market.shutdown.bind(market);
const feedStop = spyOn(market, 'shutdown').mockImplementation(async () => {
feed.connected = false;
await originalShutdown();
});
const lifecycle = [
feedStart,
feedStop,
spyOn(execution, 'initialize'),
spyOn(execution, 'shutdown'),
spyOn(storage, 'initialize'),
spyOn(storage, 'shutdown'),
spyOn(strategies, 'restoreStrategies'),
spyOn(strategies, 'shutdown'),
];
await registerOrchestratorServices(container);
const runtime = services.custom!,
runner = runtime.BacktestRunner!,
engine = runtime.BacktestEngine!;
cleanup.push(async () => {
try {
await runner.shutdown();
await mode.shutdown();
await strategies.shutdown();
await container.dispose();
} finally {
for (const method of lifecycle) method.mockRestore();
}
await runner.shutdown();
await paper.runtime.shutdown();
await container.dispose();
});
await mode.initializeMode({
mode: 'paper',
accountId: 'paper-fixture',
startingCapital: 10000,
commission: 0.001,
slippage: 0,
});
const strategy = new CounterStrategy(execution);
await strategies.attachStrategy(strategy);
await market.subscribeToSymbol('A');
market.ingest(quote('paper-one', 100, 100, Date.now()));
await market.flush();
expect(strategy.count).toBe(1);
expect((await execution.getAccount()).cash).toBe(9899.9);
let failedRead = false;
storage.getHistoricalBars = async () => {
if (failedRead) throw new Error('Injected research history failure');
return Array.from({ length: 70 }, (_, i) => {
const close = 100 + Math.sin((i * Math.PI) / 6) * 8;
return {
symbol: research.symbols[0]!,
source: 'eod' as const,
timestamp: new Date(Date.parse(research.startDate) + i * 86400000),
open: close,
high: close + 1,
low: close - 1,
close,
volume: 1000000,
};
});
};
const stateHash = async () => {
const state: unknown[] = [];
for (const [table, columns] of [
['simulation_accounts', 'id,state'],
['simulation_orders', 'id,payload'],
['simulation_fills', 'id,payload'],
['simulation_events', 'id,fingerprint'],
['simulation_market_inputs', 'id,payload'],
['simulation_strategy_journal', 'sequence,payload'],
['simulation_strategy_checkpoints', 'strategy_id,payload'],
['simulation_strategy_intents', 'client_order_id,payload'],
]) {
const rows = (await pool.query(`SELECT ${columns} FROM ${table}`)).rows;
state.push([table, rows.map(row => canonicalJson(row)).sort()]);
}
return createHash('sha256').update(canonicalJson(state)).digest('hex');
};
return {
services,
pool,
runner,
mode,
execution,
market,
strategies,
strategy,
feed,
stateHash,
lifecycleCounts: () => lifecycle.map(method => method.mock.calls.length),
failHistory: (fail: boolean) => {
failedRead = fail;
},
};
return { paper, ...admitted, container, services, runtime, runner, engine };
}
describe.skipIf(!url)('research isolation from a real paper ledger', () => {
test('legacy_paper_combination_rejected_before_prepare preserves an active paper graph', async () => {
const f = await fixture();
const engine = f.mode.getTradingEngine();
const before = await f.stateHash();
const lifecycle = f.lifecycleCounts();
await expect(f.mode.initializeMode(research)).rejects.toThrow('only permits paper');
await expect(f.mode.transitionMode('paper', 'backtest', research)).rejects.toThrow(
'only permits paper'
);
await expect(f.execution.initialize(research, engine)).rejects.toThrow('only permits paper');
expect(f.mode.getTradingEngine()).toBe(engine);
expect(f.mode.isPaperMode()).toBe(true);
expect(f.feed.connected).toBe(true);
expect(f.lifecycleCounts()).toEqual(
lifecycle.map((count, index) => count + (index === 2 ? 1 : 0))
);
expect(await f.stateHash()).toBe(before);
});
test('native_paper_isolation across successful, cancelled and failed durable jobs', async () => {
const f = await fixture();
const engine = f.mode.getTradingEngine();
const paperConfig = f.mode.getConfig();
const before = await f.stateHash();
const lifecycle = f.lifecycleCounts();
const unchanged = async () => {
expect(await f.stateHash()).toBe(before);
expect(f.mode.getTradingEngine()).toBe(engine);
expect(f.mode.getConfig()).toEqual(paperConfig);
expect(f.lifecycleCounts()).toEqual(lifecycle);
expect(f.market.listenerCount('marketDataBatch')).toBe(1);
expect(f.strategies.getActiveStrategies()).toEqual(['counter']);
expect(f.feed.connected).toBe(true);
};
expect((await f.runner.runBacktest(research)).status).toBe('completed');
await unchanged();
for (let i = 0; i < 2; i++) {
let stopped: Promise<void> | undefined;
f.runner.once('progress', () => {
stopped = f.runner.stopBacktest();
});
const outcome = await f.runner.runBacktest(research).catch(error => error);
await stopped;
expect(stopped).toBeDefined();
expect(outcome).toBeInstanceOf(BacktestCancelledError);
await unchanged();
f.failHistory(true);
await expect(f.runner.runBacktest(research)).rejects.toThrow(
'Injected research history failure'
describe.skipIf(!process.env.PIPELINE_TEST_DATABASE_URL)(
'canonical research isolation from durable paper custody',
() => {
test('default research composition cannot activate, reset or overlay the existing paper account', async () => {
const f = await fixture(),
before = await f.paper.snapshot();
for (const key of [
'ModeManager',
'ExecutionService',
'MarketDataService',
'StrategyManager',
'PaperTradingManager',
'CanonicalPaperRuntime',
]) {
expect(f.runtime).not.toHaveProperty(key);
}
await expect(registerOrchestratorServices(f.container, { role: 'paper' })).rejects.toThrow(
'explicit canonicalPaper'
);
f.failHistory(false);
await expect(
registerOrchestratorServices(f.container, { useRustEngine: false })
).rejects.toThrow('Legacy financial execution is retired');
await expect(
registerOrchestratorServices(f.container, {
role: 'paper',
canonicalPaper: f.paper.configuration,
})
).rejects.toThrow('fresh runtime composition');
expect(await f.paper.snapshot()).toEqual(before);
expect((await f.paper.runtime.status()).active).toBe(true);
});
test('real native success, cancellation and failed durable research leave paper ledger/checkpoint/decisions unchanged', async () => {
const f = await fixture(),
before = await f.paper.snapshot();
const unchanged = async () => {
expect(await f.paper.snapshot()).toEqual(before);
expect((await f.paper.runtime.status()).active).toBe(true);
};
const accept = () => f.api.createRun({ backtestId: f.draft.id });
const completed = await accept();
expect((await f.runner.runQueued(completed.id)).status).toBe('completed');
await unchanged();
}
expect((await f.runner.runBacktest(research)).status).toBe('completed');
await unchanged();
expect(
(
await f.pool.query(
'SELECT status, count(*)::int AS count FROM runs GROUP BY status ORDER BY status::text'
)
).rows
).toEqual([
{ status: 'cancelled', count: 2 },
{ status: 'completed', count: 2 },
{ status: 'failed', count: 2 },
]);
// The existing feed still makes exactly one new durable paper decision after research.
f.market.ingest(quote('paper-two', 101, 100, Date.now()));
await f.market.flush();
expect(f.strategy.count).toBe(2);
expect((await f.execution.getAccount()).strategyPositions.counter?.A).toBe(2);
}, 15000);
});
const result = await f.api.getRunResults(completed.id);
expect(result).not.toBeNull();
expect(result).toHaveProperty('kind', 'canonical-result/v1');
for (let index = 0; index < 2; index++) {
const run = await accept();
let stopped: Promise<void> | undefined;
f.runner.once('progress', () => {
stopped = f.runner.stopBacktest();
});
const cancelled = await f.runner.runQueued(run.id).catch(error => error);
await stopped;
expect(stopped).toBeDefined();
expect(cancelled).toBeInstanceOf(BacktestCancelledError);
await unchanged();
const failed = await accept(),
original = f.engine.runCanonical;
f.engine.runCanonical = async () => {
throw new Error('Injected canonical execution failure');
};
try {
await expect(f.runner.runQueued(failed.id)).rejects.toThrow(
'Injected canonical execution failure'
);
} finally {
f.engine.runCanonical = original;
}
await unchanged();
}
expect((await f.runner.runQueued((await accept()).id)).status).toBe('completed');
await unchanged();
expect(
(
await f.paper.pool.query(
'SELECT status,count(*)::int AS count FROM runs GROUP BY status ORDER BY status::text'
)
).rows
).toEqual([
{ status: 'cancelled', count: 2 },
{ status: 'completed', count: 2 },
{ status: 'failed', count: 2 },
]);
f.paper.clock(30);
await f.paper.runtime.ingest(paperFrame(3));
const continued = await f.paper.snapshot();
expect(continued.owners[0]!.diagnostic.nextDecisionSequence).toBe(
before.owners[0]!.diagnostic.nextDecisionSequence + 1
);
expect(continued.account.view.portfolio.positions).toHaveLength(1);
}, 15000);
}
);

View file

@ -15,6 +15,7 @@ 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 { seedHistoricalRun } from '../fixtures/historical-run';
setLoggerConfig({ logLevel: 'fatal', logConsole: false });
const logger = getLogger('research-workspace');
@ -96,7 +97,7 @@ async function fixture(applyWorkspace = true, maxConnections = 10) {
},
{ autoStart: false }
);
const run = await backtests.createRun({ backtestId: definition.id });
const run = await seedHistoricalRun(pool, backtests, { backtestId: definition.id });
// Fixed old-display fixtures exercise custody/conversion, not financial simulation.
await pool.query(
`INSERT INTO backtest_results(run_id,metrics,equity_curve,ohlc_data,trades,positions,analytics,execution_time,engine)
@ -326,7 +327,7 @@ describe.skipIf(!url)('research workspace retained narratives and evidence', ()
expect(revised.updatedBy).toBe('operator');
await expect(
f.service.createHypothesis(p.id, { ...hypothesisInput, contentOrigin: 'human' }, 'service')
).rejects.toThrow('cannot declare human');
).rejects.toThrow('Only operator credentials can declare human authorship');
await expect(
f.service.reviseHypothesis(
h.id,
@ -535,7 +536,9 @@ describe.skipIf(!url)('research workspace retained narratives and evidence', ()
).rejects.toThrow();
}
const { run, definition } = await f.legacy();
const missingResult = await f.backtests.createRun({ backtestId: definition.id });
const missingResult = await seedHistoricalRun(f.pool, f.backtests, {
backtestId: definition.id,
});
await f.pool.query("UPDATE runs SET status='completed' WHERE id=$1", [missingResult.id]);
for (const bad of [
reference(randomUUID()),

View file

@ -19,6 +19,7 @@ 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 { seedHistoricalRun } from '../fixtures/historical-run';
setLoggerConfig({ logLevel: 'fatal', logConsole: false });
const logger = getLogger('run-reproduction');
@ -600,7 +601,7 @@ describe.skipIf(!url)('retained original-run reproduction', () => {
},
{ autoStart: false }
);
const legacyRun = await f.api.createRun({ backtestId: legacy.id });
const legacyRun = await seedHistoricalRun(f.pool, f.api, { backtestId: legacy.id });
await f.pool.query("UPDATE runs SET status='completed' WHERE id=$1", [legacyRun.id]);
expect((await f.api.getRun(legacyRun.id))?.originalRunId).toBeNull();
expect((await f.api.getReproductionPreview(legacyRun.id)).reason).toContain(