feat(research): run durable backtests in a bounded worker pool

This commit is contained in:
Boki 2026-10-24 17:41:00 -04:00
parent bbf0dd4453
commit 26b97265c6
15 changed files with 1730 additions and 129 deletions

250
test/fixtures/research-pool.ts vendored Normal file
View file

@ -0,0 +1,250 @@
import { randomUUID } from 'node:crypto';
import { readFileSync } from 'node:fs';
import { Pool } from 'pg';
import { HandlerRegistry } from '@stock-bot/handler-registry';
import { PostgreSQLClient } from '@stock-bot/postgres';
import { Queue } from '@stock-bot/queue';
import type { CanonicalRunRequest } from '@stock-bot/stock-config/canonical-research';
import type { HistoricalDatasetV2 } from '@stock-bot/types';
import { BacktestRunner } from '../../apps/stock/orchestrator/src/backtest/BacktestRunner';
import { PostgresBacktestRunRepository } from '../../apps/stock/orchestrator/src/backtest/PostgresBacktestRunRepository';
import {
ResearchBacktestPool,
type ResearchConcurrency,
} from '../../apps/stock/orchestrator/src/backtest/ResearchBacktestPool';
import { RustBacktestAdapter } from '../../apps/stock/orchestrator/src/backtest/RustBacktestAdapter';
import { BacktestHandler } from '../../apps/stock/orchestrator/src/handlers/backtest/backtest.handler';
import { BacktestDispatcher } from '../../apps/stock/web-api/src/services/BacktestDispatcher';
import { ExperimentsService } from '../../apps/stock/web-api/src/services/experiments.service';
import { retainResearchDataset } from '../../scripts/import-research-dataset';
import { canonicalAdmissionFixture } from './canonical-admission';
import { logger } from './execution';
export async function untilResearch(check: () => Promise<boolean>, timeoutMs = 30000) {
const end = Date.now() + timeoutMs;
while (Date.now() < end) {
if (await check()) {
return;
}
await Bun.sleep(20);
}
throw new Error('Timed out waiting for durable research trials');
}
export function admittedTrialIds(experiment: {
trials: readonly { runId: string | null }[];
}): string[] {
return experiment.trials.map(trial => {
if (!trial.runId) {
throw new Error('Newly admitted experiment is missing a run identity');
}
return trial.runId;
});
}
/** Dedicated disposable SQL/Redis namespaces. Never flushes the shared Redis database. */
export async function researchPoolFixture(dataset?: HistoricalDatasetV2) {
const database = process.env.PIPELINE_TEST_DATABASE_URL,
redisUrl = process.env.BACKTEST_TEST_REDIS_URL;
if (
!database ||
!new URL(database).pathname.startsWith('/stock_bot_safety') ||
!redisUrl ||
new URL(redisUrl).pathname !== '/15'
) {
throw new Error('Dedicated stock_bot_safety PostgreSQL and Redis database15 required');
}
const schema = `stock_bot_safety_pool_${randomUUID().replaceAll('-', '')}`;
const admin = new Pool({ connectionString: database });
await admin.query(`CREATE SCHEMA ${schema}`);
const sql = new Pool({
connectionString: database,
max: 12,
application_name: schema,
options: `-c search_path=${schema} -c statement_timeout=30000`,
});
const postgres = new PostgreSQLClient(
{ host: 'unused', port: 5432, database: 'unused', username: 'unused', password: 'unused' },
logger
);
Object.defineProperty(postgres, 'connectionPool', { get: () => sql });
Object.defineProperty(postgres, 'query', { value: sql.query.bind(sql) });
const closers: (() => Promise<void>)[] = [];
const close = async () => {
const errors: unknown[] = [];
for (const closer of closers.splice(0).reverse()) {
try {
await closer();
} catch (error) {
errors.push(error);
}
}
await sql.end();
await admin.query(`DROP SCHEMA ${schema} CASCADE`);
await admin.end();
if (errors.length) {
throw new AggregateError(errors, 'Research fixture cleanup failed');
}
};
try {
const base = await canonicalAdmissionFixture(sql, postgres);
// A01 guards are exercised too; canonicalAdmissionFixture owns the earlier common chain.
for (const name of [
'20-research-workspace.sql',
'27-research-evidence-sources.sql',
'28-research-agents.sql',
]) {
await sql.query(
readFileSync(new URL(`../../database/postgres/init/${name}`, import.meta.url), 'utf8')
);
}
let draft = base.draft;
if (dataset) {
await retainResearchDataset(sql, dataset);
draft = await base.api.createBacktest(
{
...base.definition,
name: 'Bounded pool retained workload',
startDate: new Date(dataset.manifest.bounds.tradeStart).toISOString(),
endDate: new Date(dataset.manifest.bounds.tradeEnd).toISOString(),
symbols: dataset.manifest.executionSeries.map(series => series.instrumentId),
config: { ...base.definition.config, datasetHash: dataset.manifest.hash },
},
{ autoStart: false }
);
}
const experiments = new ExperimentsService({ postgres, logger });
const submit = async (
grid: Record<string, number[]> = { fastPeriod: [1, 2] },
principal = 'operator'
) => {
const input = { name: 'Bounded independent trials', backtestId: draft.id, grid };
const preview = await experiments.preview(input);
return experiments.submit(
{ ...input, previewHash: preview.previewHash },
{ principal, key: randomUUID() }
);
};
const endpoint = new URL(redisUrl);
const redis = {
host: endpoint.hostname,
port: Number(endpoint.port || 6379),
db: 15,
...(endpoint.password ? { password: decodeURIComponent(endpoint.password) } : {}),
};
const createWorkers = (
concurrency: ResearchConcurrency,
options: {
beforeExecute?: (request: CanonicalRunRequest, slot: number) => Promise<void>;
heartbeatMs?: number;
leaseMs?: number;
dispatcher?: { intervalMs: number; republishMs: number; maxAttempts: number };
} = {}
) => {
const repositories = Array.from(
{ length: concurrency },
() => new PostgresBacktestRunRepository(postgres, options.leaseMs ?? 30000)
);
const engines = repositories.map((_repository, slot) => {
const engine = new RustBacktestAdapter({
logger,
storage: {
async getHistoricalBars(): Promise<never> {
throw new Error('Retained trials must not read a provider');
},
},
});
if (options.beforeExecute) {
const execute = engine.runCanonical.bind(engine);
engine.runCanonical = async (request, resolve) => {
await options.beforeExecute!(request, slot);
return execute(request, resolve);
};
}
return engine;
});
const runners = engines.map(
(engine, i) =>
new BacktestRunner({
engine,
repository: repositories[i]!,
engineName: 'native',
logger,
heartbeatMs: options.heartbeatMs ?? 5000,
})
);
const runtime = new ResearchBacktestPool({ runners, logger });
const registry = new HandlerRegistry();
const handler = new BacktestHandler({ logger, custom: { BacktestRunner: runtime } });
registry.registerConfiguration({
name: 'orchestrator',
operations: { 'run-backtest': payload => handler.runBacktest(payload) },
});
const queue = new Queue(
`stock-bot-pool-${randomUUID()}`,
redis,
{},
{ workers: 1, concurrency, handlerRegistry: registry },
logger
);
const dispatcher = options.dispatcher
? new BacktestDispatcher(postgres, queue, logger, options.dispatcher)
: new BacktestDispatcher(postgres, queue, logger);
let closed = false;
const stop = async () => {
if (closed) {
return;
}
closed = true;
await dispatcher.shutdown();
try {
await runtime.shutdown();
} finally {
await queue.close();
// All worker connections are closed before deleting this queue's keys.
const cleaner = new Queue(queue.getName(), redis, {}, { workers: 0 }, logger);
try {
await cleaner.getBullQueue().obliterate({ force: true });
} finally {
await cleaner.close();
}
}
};
closers.push(stop);
return { runtime, runners, repositories, engines, dispatcher, queue, stop };
};
const rows = async (ids: readonly string[]) =>
(
await sql.query(
`SELECT r.*, (SELECT count(*)::int FROM backtest_results br WHERE br.run_id=r.id) result_count FROM runs r WHERE id=ANY($1::uuid[]) ORDER BY trial_index`,
[ids]
)
).rows;
const wait = async (ids: readonly string[], timeoutMs = 30000) => {
await untilResearch(async () => {
const current = await rows(ids);
return (
current.length === ids.length &&
current.every(row => ['completed', 'failed', 'cancelled'].includes(row.status))
);
}, timeoutMs);
return rows(ids);
};
return {
...base,
draft,
dataset: dataset ?? base.dataset,
sql,
postgres,
experiments,
submit,
createWorkers,
rows,
wait,
close,
};
} catch (error) {
await close();
throw error;
}
}

View file

@ -139,7 +139,7 @@ describe('canonical production workflow and legacy retirement', () => {
});
test('observer errors cannot relabel committed success and SSE detaches on completion', async () => {
const f = setup();
const response = await routes(f).request('/api/backtest/stream');
const response = await routes(f).request(`/api/backtest/stream?runId=${f.request.runId}`);
const reader = response.body!.getReader();
expect((await f.runner.runQueued(f.request.runId)).status).toBe('completed');
expect(new TextDecoder().decode((await reader.read()).value)).toContain('"event":"complete"');

View file

@ -0,0 +1,396 @@
import { randomUUID } from 'node:crypto';
import { afterEach, describe, expect, test } from 'bun:test';
import { Hono } from 'hono';
import { createBacktestRoutes } from '../../apps/stock/orchestrator/src/api/rest/backtest';
import {
BacktestCancelledError,
type BacktestExecutionEngine,
} from '../../apps/stock/orchestrator/src/backtest/execution-engine';
import { ResearchBacktestPool } from '../../apps/stock/orchestrator/src/backtest/ResearchBacktestPool';
import { canonicalRunnerFixture, deferred } from '../fixtures/canonical-runner';
import { logger } from '../fixtures/execution';
const cleanup: (() => Promise<unknown>)[] = [];
afterEach(async () => {
for (const close of cleanup.splice(0).reverse()) {
await close();
}
});
function fixture(count: 1 | 2 | 4 = 2) {
const slots = Array.from({ length: count }, () => {
const f = canonicalRunnerFixture();
const entered = deferred<void>(),
release = deferred<void>();
const execute = f.engine.runCanonical;
f.engine.runCanonical = async (...args) => {
entered.resolve();
await release.promise;
return execute(...args);
};
f.engine.stopBacktest = async () => release.reject(new BacktestCancelledError());
return { ...f, entered, release };
});
const pool = new ResearchBacktestPool({ runners: slots.map(f => f.runner), logger });
cleanup.push(() => pool.shutdown().catch(() => {}));
const app = new Hono().route(
'/backtest',
createBacktestRoutes({ logger, custom: { BacktestRunner: pool } })
);
return { slots, pool, app };
}
async function post(app: Hono, path: string, body: unknown = {}) {
return app.request(`/backtest/${path}`, { method: 'POST', body: JSON.stringify(body) });
}
async function started(f: ReturnType<typeof fixture>) {
const work = f.slots.map(slot =>
f.pool.runQueued(slot.request.runId).catch(error => error as Error)
);
await Promise.all(f.slots.map(slot => slot.entered.promise));
return work;
}
describe('bounded independent research runners', () => {
test.each([0, 3, 5, 8])('rejects %s slots', count => {
const runner = canonicalRunnerFixture().runner;
expect(
() =>
new ResearchBacktestPool({ runners: Array.from({ length: count }, () => runner), logger })
).toThrow('1, 2, or 4');
});
test('rejects duplicate mutable runner instances', () => {
const runner = canonicalRunnerFixture().runner;
expect(() => new ResearchBacktestPool({ runners: [runner, runner], logger })).toThrow(
'distinct'
);
});
test.each([1, 2, 4] as const)(
'reserves %s slots before the first await; overflow never loads or claims',
async count => {
const f = fixture(count);
const loads = f.slots.map(() => deferred<void>());
f.slots.forEach((slot, i) => {
const load = slot.repo.load;
slot.repo.load = async id => {
await loads[i]!.promise;
return load(id);
};
});
const work = f.slots.map(slot => f.pool.runQueued(slot.request.runId));
expect(f.slots.every(slot => slot.events.length === 0)).toBe(true);
await expect(f.pool.runQueued(randomUUID())).rejects.toThrow('occupied');
expect(f.slots.every(slot => slot.events.length === 0)).toBe(true);
loads.forEach(gate => gate.resolve());
await Promise.all(f.slots.map(slot => slot.entered.promise));
// Deliberately finish in the reverse submission order.
for (let i = count - 1; i >= 0; i--) {
f.slots[i]!.release.resolve();
expect(await work[i]).toEqual({ runId: f.slots[i]!.request.runId, status: 'completed' });
}
expect(f.slots.map(slot => slot.events.filter(event => event === 'claim').length)).toEqual(
Array(count).fill(1)
);
expect(f.pool.getStatus().isRunning).toBe(false);
}
);
test('duplicate deliveries, including UUID casing, join the original exact promise', async () => {
const f = fixture(1),
slot = f.slots[0]!;
const first = f.pool.runQueued(slot.request.runId);
expect(f.pool.runQueued(slot.request.runId.toUpperCase())).toBe(first);
await slot.entered.promise;
expect(f.pool.runQueued(slot.request.runId)).toBe(first);
slot.release.resolve();
await first;
expect(slot.events.filter(event => event === 'claim')).toHaveLength(1);
// Terminal redelivery is still read/acknowledged by the durable runner.
expect(await f.pool.runQueued(slot.request.runId)).toEqual({
runId: slot.request.runId,
status: 'completed',
});
expect(slot.events.filter(event => event === 'claim')).toHaveLength(1);
});
test('a reservation does not turn an unclaimed pending row into a local cancellation', async () => {
const f = fixture(1),
slot = f.slots[0]!,
gate = deferred<void>();
const load = slot.repo.load;
slot.repo.load = async id => {
await gate.promise;
return load(id);
};
const work = f.pool.runQueued(slot.request.runId);
await expect(f.pool.stopBacktest(slot.request.runId)).rejects.toThrow('No matching active');
expect(slot.events).toEqual([]);
gate.resolve();
await slot.entered.promise;
slot.release.resolve();
await work;
});
test('reused slot status never exposes the prior run while the new reservation loads', async () => {
const f = fixture(1),
slot = f.slots[0]!;
const previous = f.pool.runQueued(slot.request.runId);
await slot.entered.promise;
slot.release.resolve();
await previous;
slot.engine.getStatus = () => ({
isRunning: false,
isPaused: true,
progress: 100,
currentTime: 123456,
});
const nextId = randomUUID(),
gate = deferred<void>();
const nextRequest = structuredClone(slot.request);
nextRequest.runId = nextId;
nextRequest.policy.matching.risk.ledger.sessionId = nextId;
nextRequest.policy.matching.risk.ledger.accountId = `research:${nextId}`;
slot.repo.load = async () => {
await gate.promise;
return { status: 'pending', config: nextRequest };
};
const next = f.pool.runQueued(nextId).catch(error => error as Error);
expect(f.pool.getStatus(nextId)).toEqual({
isRunning: false,
isPaused: false,
progress: 0,
currentTime: 0,
runId: nextId,
});
const closed = f.pool.shutdown();
gate.resolve();
expect(String(await next)).toContain('shutting down');
await expect(closed).resolves.toBeUndefined();
});
test('targeted cancellation leaves the other run active and commits only its own outcome', async () => {
const f = fixture(),
work = await started(f),
[a, b] = f.slots;
await f.pool.stopBacktest(a!.request.runId);
expect(await work[0]).toBeInstanceOf(BacktestCancelledError);
expect(a!.events).toContain('cancel');
expect(b!.events).not.toContain('cancel');
expect(f.pool.getStatus().runId).toBe(b!.request.runId);
b!.release.resolve();
expect(await work[1]).toEqual({ runId: b!.request.runId, status: 'completed' });
});
test('failure publishes the captured ID once, releases just that slot, and preserves the other run', async () => {
const f = fixture(),
errors: unknown[] = [];
f.pool.on('error', event => errors.push(event));
const work = await started(f),
[a, b] = f.slots;
const error = new Error('isolated worker failure');
a!.release.reject(error);
expect(await work[0]).toBe(error);
expect(errors).toEqual([{ runId: a!.request.runId, error }]);
expect(b!.events).not.toContain('fail');
expect(f.pool.getStatus().runId).toBe(b!.request.runId);
b!.release.resolve();
await work[1];
});
test('load failure is routed without leaving a reservation or listener behind', async () => {
const f = fixture(1),
slot = f.slots[0]!,
errors: unknown[] = [];
slot.repo.load = async () => {
throw new Error('unavailable database');
};
f.pool.on('error', event => errors.push(event));
await expect(f.pool.runQueued(slot.request.runId)).rejects.toThrow('unavailable database');
expect(errors).toHaveLength(1);
expect(errors[0]).toHaveProperty('runId', slot.request.runId);
expect(f.pool.getStatus().isRunning).toBe(false);
for (const event of ['progress', 'complete', 'cancelled']) {
expect(slot.runner.listenerCount(event)).toBe(0);
}
});
test('observer failure cannot change committed success', async () => {
const f = fixture(1),
slot = f.slots[0]!;
f.pool.on('complete', () => {
throw new Error('observer');
});
const work = await started(f);
slot.release.resolve();
expect(await work[0]).toEqual({ runId: slot.request.runId, status: 'completed' });
expect(slot.events).not.toContain('fail');
});
test('shutdown closes admission synchronously, drains all slots and is idempotent', async () => {
const f = fixture(),
work = await started(f);
const shutdown = f.pool.shutdown();
expect(f.pool.shutdown()).toBe(shutdown);
await expect(f.pool.runQueued(randomUUID())).rejects.toThrow('shutting down');
await shutdown;
for (const result of await Promise.all(work)) {
expect(result).toBeInstanceOf(BacktestCancelledError);
}
expect(f.slots.every(slot => slot.events.includes('cancel'))).toBe(true);
});
test('shutdown waits for a pending load and never claims after closure', async () => {
const f = fixture(1),
slot = f.slots[0]!,
gate = deferred<void>();
const load = slot.repo.load;
slot.repo.load = async id => {
await gate.promise;
return load(id);
};
const work = f.pool.runQueued(slot.request.runId).catch(error => error as Error);
const shutdown = f.pool.shutdown();
gate.resolve();
expect(String(await work)).toContain('shutting down');
await expect(shutdown).resolves.toBeUndefined();
expect(slot.events).not.toContain('claim');
});
test('one failing shutdown cannot skip any other runner shutdown', async () => {
const f = fixture(),
closed: number[] = [];
f.slots.forEach((slot, index) => {
slot.runner.shutdown = async () => {
closed.push(index);
if (index === 0) {
throw new Error('close failed');
}
};
});
await expect(f.pool.shutdown()).rejects.toThrow('drain');
expect(closed).toEqual([0, 1]);
});
});
describe('run-scoped controls and event streams', () => {
test('unknown explicit ID never reads or controls another run; empty status stays idle', async () => {
const f = fixture(1);
expect((await f.app.request('/backtest/progress')).status).toBe(200);
expect((await f.app.request(`/backtest/progress?runId=${randomUUID()}`)).status).toBe(409);
const work = await started(f);
expect((await f.app.request(`/backtest/progress?runId=${randomUUID()}`)).status).toBe(409);
expect((await post(f.app, 'stop', { runId: randomUUID() })).status).toBe(409);
expect((await post(f.app, 'stop')).status).toBe(200);
await work[0];
});
test('multiple active runs require a run ID on all legacy controls/progress/stream', async () => {
const f = fixture(),
work = await started(f);
for (const action of ['stop', 'pause', 'resume', 'speed']) {
expect((await post(f.app, action)).status).toBe(409);
}
for (const action of ['progress', 'stream']) {
expect((await f.app.request(`/backtest/${action}`)).status).toBe(409);
}
expect(
(await f.app.request(`/backtest/progress?runId=${f.slots[1]!.request.runId}`)).status
).toBe(200);
f.slots.forEach(slot => slot.release.resolve());
await Promise.all(work);
});
test('malformed explicit IDs and JSON fail closed, never become an omitted target', async () => {
const f = fixture(1),
work = await started(f);
for (const action of ['stop', 'pause', 'resume', 'speed']) {
expect((await post(f.app, action, { runId: 'bad' })).status).toBe(400);
expect(
(await f.app.request(`/backtest/${action}`, { method: 'POST', body: '{' })).status
).toBe(400);
}
expect((await f.app.request('/backtest/progress?runId=bad')).status).toBe(400);
expect((await f.app.request('/backtest/stream?runId=bad')).status).toBe(400);
f.slots[0]!.release.resolve();
await work[0];
});
test('exactly one active run retains no-ID pause/resume/speed controls', async () => {
const f = fixture(1),
work = await started(f),
controls: unknown[] = [],
slot = f.slots[0]!;
slot.engine.pauseBacktest = async () => {
controls.push('pause');
};
slot.engine.resumeBacktest = async () => {
controls.push('resume');
};
(slot.engine as BacktestExecutionEngine).setSpeedMultiplier = speed => {
controls.push(speed);
};
for (const action of ['pause', 'resume']) {
expect((await post(f.app, action)).status).toBe(200);
}
expect((await post(f.app, 'speed', { speed: null })).status).toBe(200);
expect(controls).toEqual(['pause', 'resume', null]);
slot.release.resolve();
await work[0];
});
test('SSE captures one ID, ignores unrelated completion, and detaches on its own completion', async () => {
const f = fixture(),
[a, b] = f.slots;
// An explicit ID can subscribe before admission is claimed; no global idle subscription.
expect((await f.app.request('/backtest/stream')).status).toBe(409);
const response = await f.app.request(`/backtest/stream?runId=${b!.request.runId}`);
const reader = response.body!.getReader(),
work = await started(f);
a!.release.resolve();
await work[0];
b!.engine.emit('progress', { progress: 25 });
const progress = new TextDecoder().decode((await reader.read()).value);
expect(progress).toContain(b!.request.runId);
expect(progress).toContain('25');
expect(progress).not.toContain(a!.request.runId);
b!.release.resolve();
await work[1];
expect(new TextDecoder().decode((await reader.read()).value)).toContain('"event":"complete"');
expect((await reader.read()).done).toBe(true);
for (const event of ['progress', 'complete', 'error', 'cancelled']) {
expect(f.pool.listenerCount(event)).toBe(0);
}
});
test('no-ID stream freezes sole active identity even after another slot starts', async () => {
const f = fixture(),
[a, b] = f.slots;
const first = f.pool.runQueued(a!.request.runId);
await a!.entered.promise;
const response = await f.app.request('/backtest/stream'),
reader = response.body!.getReader();
const second = f.pool.runQueued(b!.request.runId);
await b!.entered.promise;
b!.release.resolve();
await second;
a!.release.resolve();
await first;
const body = new TextDecoder().decode((await reader.read()).value);
expect(body).toContain(a!.request.runId);
expect(body).not.toContain(b!.request.runId);
expect((await reader.read()).done).toBe(true);
});
test('SSE error and cancellation belong to their captured run; abort removes all listeners', async () => {
const f = fixture(),
[a, b] = f.slots;
const reader = (
await f.app.request(`/backtest/stream?runId=${a!.request.runId}`)
).body!.getReader();
const cancelled = (
await f.app.request(`/backtest/stream?runId=${b!.request.runId}`)
).body!.getReader();
const work = await started(f);
a!.release.reject(new Error('isolated failure'));
await work[0];
const message = new TextDecoder().decode((await reader.read()).value);
expect(message).toContain('isolated failure');
expect(message).toContain(a!.request.runId);
expect((await reader.read()).done).toBe(true);
await f.pool.stopBacktest(b!.request.runId);
await work[1];
expect(new TextDecoder().decode((await cancelled.read()).value)).toContain(
'"event":"cancelled"'
);
expect((await cancelled.read()).done).toBe(true);
const abort = new AbortController();
const response = await f.app.request(`/backtest/stream?runId=${randomUUID()}`, {
signal: abort.signal,
});
abort.abort();
expect((await response.body!.getReader().read()).done).toBe(true);
expect(f.pool.listenerCount('progress')).toBe(0);
});
});

View file

@ -2,7 +2,8 @@ import { asFunction, asValue, createContainer as createDiContainer } from 'awili
import { afterEach, describe, expect, test } from 'bun:test';
import { ServiceContainerBuilder, type ServiceCradle } from '@stock-bot/di';
import type { StockAppConfig } from '@stock-bot/stock-config';
import { RustBacktestAdapter } from '../../apps/stock/orchestrator/src/backtest/RustBacktestAdapter';
import { stockAppSchema } from '../../apps/stock/config/src/schemas/stock-app.schema';
import { ResearchBacktestPool } from '../../apps/stock/orchestrator/src/backtest/ResearchBacktestPool';
import { registerOrchestratorServices } from '../../apps/stock/orchestrator/src/container';
import { createRoutes } from '../../apps/stock/orchestrator/src/routes/create-routes';
import { createContainer } from '../../apps/stock/orchestrator/src/simple-container';
@ -15,7 +16,10 @@ afterEach(async () => {
await close();
}
});
async function compose(options: Parameters<typeof registerOrchestratorServices>[1] = {}) {
async function compose(
options: Parameters<typeof registerOrchestratorServices>[1] = {},
queues?: unknown[]
) {
const container = await new ServiceContainerBuilder()
.withOptions({
enableCache: false,
@ -28,6 +32,11 @@ async function compose(options: Parameters<typeof registerOrchestratorServices>[
})
.build();
const services: OrchestratorServices = { logger };
if (queues) {
Object.defineProperty(services, 'queueManager', {
value: { getQueue: (name: string, options: unknown) => queues.push({ name, options }) },
});
}
container.register({ serviceContainer: asValue(services) });
await registerOrchestratorServices(container, options);
cleanup.push(async () => {
@ -88,8 +97,9 @@ describe('canonical research-only default composition', () => {
'default and explicit research compose one canonical engine without any account/feed/mode gateway',
async options => {
const { services, container } = await compose(options);
expect(services.custom!.BacktestEngine).toBeInstanceOf(RustBacktestAdapter);
expect(services.custom!.BacktestRunner).toBeInstanceOf(ResearchBacktestPool);
for (const key of [
'BacktestEngine',
'ModeManager',
'ExecutionService',
'MarketDataService',
@ -118,6 +128,37 @@ describe('canonical research-only default composition', () => {
});
}
);
test.each([1, 2, 4] as const)(
'composition uses one BullMQ consumer with concurrency %s',
async maxConcurrent => {
const calls: unknown[] = [];
const { services } = await compose({ maxConcurrent }, calls);
expect(calls).toEqual([
{ name: 'orchestrator', options: { workers: 1, concurrency: maxConcurrent } },
]);
expect(services.custom!.BacktestRunner!.getStatus().isRunning).toBe(false);
}
);
test('default composition and schema select one slot; invalid values fail before resolving services/connections', async () => {
const calls: unknown[] = [];
await compose({}, calls);
expect(calls).toEqual([{ name: 'orchestrator', options: { workers: 1, concurrency: 1 } }]);
const schema = stockAppSchema.shape.services
.unwrap()
.shape.orchestrator.unwrap()
.shape.backtesting.unwrap();
expect(schema.parse({}).maxConcurrent).toBe(1);
for (const maxConcurrent of [null, 0, 3, 5, 1.5, '2', NaN, Infinity]) {
expect(schema.safeParse({ maxConcurrent }).success).toBe(false);
const container = createDiContainer<ServiceCradle>();
await expect(
registerOrchestratorServices(container, { maxConcurrent } as never)
).rejects.toThrow('1, 2, or 4');
await expect(
createContainer({ services: { orchestrator: { backtesting: { maxConcurrent } } } } as never)
).rejects.toThrow('1, 2, or 4');
}
});
test('cannot overlay the canonical graph on a legacy account runtime', async () => {
const container = createDiContainer<ServiceCradle>();
container.register({ serviceContainer: asValue({ logger, custom: { ExecutionService: {} } }) });

View file

@ -0,0 +1,233 @@
import { randomUUID } from 'node:crypto';
import { readdirSync, readFileSync } from 'node:fs';
import { afterEach, describe, expect, test } from 'bun:test';
import type { CanonicalRunResult } from '@stock-bot/stock-config/canonical-research';
import { PostgresBacktestRunRepository } from '../../apps/stock/orchestrator/src/backtest/PostgresBacktestRunRepository';
import { BacktestLeaseLostError } from '../../apps/stock/orchestrator/src/backtest/run-repository';
import { canonicalReproductionHash } from '../../apps/stock/web-api/src/services/reproduction-comparison';
import { ResearchAgentsService } from '../../apps/stock/web-api/src/services/research-agents.service';
import { ResearchService } from '../../apps/stock/web-api/src/services/research.service';
import { deferred } from '../fixtures/canonical-runner';
import { logger } from '../fixtures/execution';
import { nativeReplayFixture } from '../fixtures/native-replay';
import { admittedTrialIds, researchPoolFixture, untilResearch } from '../fixtures/research-pool';
const cleanup: (() => Promise<void>)[] = [];
afterEach(async () => {
for (const close of cleanup.splice(0).reverse()) {
await close();
}
});
async function fixture(dataset?: ReturnType<typeof nativeReplayFixture>['dataset']) {
const f = await researchPoolFixture(dataset);
cleanup.push(f.close);
return f;
}
function nativeChildren(): number[] {
const ids = new Set<number>();
for (const task of readdirSync(`/proc/${process.pid}/task`)) {
try {
for (const value of readFileSync(`/proc/${process.pid}/task/${task}/children`, 'utf8')
.trim()
.split(/\s+/)) {
const pid = Number(value);
if (pid && readFileSync(`/proc/${pid}/cmdline`, 'utf8').includes('/native-worker.js')) {
ids.add(pid);
}
}
} catch {
/* A thread/child can exit between procfs reads. */
}
}
return [...ids];
}
const grid4 = { fastPeriod: [1, 2], slowPeriod: [3, 4] };
describe.skipIf(!process.env.PIPELINE_TEST_DATABASE_URL || !process.env.BACKTEST_TEST_REDIS_URL)(
'bounded durable research pool on real PostgreSQL, Redis and Rust',
() => {
test('parallel_hash_parity: 1/2/4 slots retain candidate order and identical validated economic hashes', async () => {
const f = await fixture();
let baseline: string[] | undefined;
for (const concurrency of [1, 2, 4] as const) {
const experiment = await f.submit(grid4),
ids = admittedTrialIds(experiment);
const workers = f.createWorkers(concurrency);
await workers.queue.getBullQueue().waitUntilReady();
await workers.dispatcher.tick();
const rows = await f.wait(ids);
expect(rows.map(row => row.trial_index)).toEqual([0, 1, 2, 3]);
expect(rows.map(row => row.status)).toEqual(Array(4).fill('completed'));
expect(rows.map(row => row.attempt_number)).toEqual(Array(4).fill(1));
expect(rows.map(row => row.result_count)).toEqual(Array(4).fill(1));
const hashes: string[] = [];
for (const id of ids) {
const result = await f.api.getRunResults(id);
if (!result || !('kind' in result) || result.kind !== 'canonical-result/v1') {
throw new Error('Missing canonical result');
}
hashes.push(canonicalReproductionHash(result));
// Redelivery cannot claim or write a second outcome.
expect(await workers.runtime.runQueued(id)).toEqual({ runId: id, status: 'completed' });
}
if (baseline) {
expect(hashes).toEqual(baseline);
} else {
baseline = hashes;
}
await workers.stop();
}
}, 60000);
test('cancellation_under_load: pending and running cancellations leave unrelated native trials intact', async () => {
const f = await fixture(nativeReplayFixture(1000).dataset);
const experiment = await f.submit(grid4),
ids = admittedTrialIds(experiment);
await f.api.cancelRun(ids[3]!);
const workers = f.createWorkers(2, { heartbeatMs: 20 });
await workers.dispatcher.tick();
await untilResearch(
async () => (await f.rows(ids)).filter(row => row.status === 'running').length === 2
);
const running = (await f.rows(ids)).find(row => row.status === 'running')!;
await f.api.cancelRun(running.id);
const rows = await f.wait(ids);
expect(
rows
.filter(row => row.status === 'cancelled')
.map(row => row.id)
.sort()
).toEqual([running.id, ids[3]!].sort());
expect(rows.filter(row => row.status === 'cancelled').map(row => row.result_count)).toEqual([
0, 0,
]);
expect(rows.filter(row => row.status === 'completed')).toHaveLength(2);
expect(rows.find(row => row.id === ids[3])!.attempt_number).toBe(0);
expect(rows.every(row => row.attempt_number <= 1)).toBe(true);
await workers.stop();
}, 60000);
test('worker_crash_retry: one real native child exit fails only its trial; explicit same-run retry recovers', async () => {
const f = await fixture(nativeReplayFixture(1000).dataset);
const experiment = await f.submit(),
ids = admittedTrialIds(experiment);
const holdOther = deferred<void>();
const workers = f.createWorkers(2, {
beforeExecute: async (_request, slot) => {
if (slot === 1) {
await holdOther.promise;
}
},
});
const baseline = new Set(nativeChildren());
await workers.dispatcher.tick();
let child: number | undefined;
await untilResearch(async () => {
child = nativeChildren().find(pid => !baseline.has(pid));
return child !== undefined;
});
process.kill(child!, 'SIGKILL');
holdOther.resolve();
const rows = await f.wait(ids);
const failed = rows.find(row => row.status === 'failed')!;
expect(failed).toBeDefined();
expect(failed.result_count).toBe(0);
expect(rows.filter(row => row.status === 'completed')).toHaveLength(1);
expect(rows.every(row => row.attempt_number === 1)).toBe(true);
const before = await f.sql.query('SELECT request_snapshot FROM runs WHERE id=$1', [
failed.id,
]);
const retry = await f.experiments.retryTrial(
experiment.id,
failed.id,
{ expectedAttemptNumber: 1, expectedRetryCount: 0 },
{ principal: 'operator', key: randomUUID() }
);
expect(retry.retry.previousAttemptId).toBe(failed.attempt_id);
await workers.dispatcher.tick();
const after = await f.wait(ids);
expect(after.every(row => row.status === 'completed' && row.result_count === 1)).toBe(true);
expect(after.find(row => row.id === failed.id)!.attempt_number).toBe(2);
expect(after.find(row => row.id !== failed.id)!.attempt_number).toBe(1);
expect(after.find(row => row.id === failed.id)!.request_snapshot).toEqual(
before.rows[0].request_snapshot
);
await workers.stop();
}, 60000);
test('lease_fencing_pool: recovery replaces only an expired owner and rejects all its late writes', async () => {
const f = await fixture();
const experiment = await f.submit(),
ids = admittedTrialIds(experiment);
const repo = new PostgresBacktestRunRepository(f.postgres);
const original = (await f.rows(ids))[0]!;
const abandoned = await repo.startCanonical(original.request_snapshot);
const otherEntered = deferred<void>(),
otherRelease = deferred<void>();
const workers = f.createWorkers(2, {
beforeExecute: async request => {
if (request.runId === ids[1]) {
otherEntered.resolve();
await otherRelease.promise;
}
},
});
const unaffected = workers.runtime.runQueued(ids[1]!);
await otherEntered.promise;
const otherAttempt = (await f.rows(ids))[1]!.attempt_id;
await f.sql.query("UPDATE runs SET lease_expires_at=NOW()-INTERVAL '1 second' WHERE id=$1", [
ids[0],
]);
await workers.dispatcher.tick();
await untilResearch(async () => (await f.rows(ids))[0]!.status === 'completed');
otherRelease.resolve();
await unaffected;
const rows = await f.rows(ids);
expect(rows[0]!.attempt_number).toBe(2);
expect(rows[1]!.attempt_number).toBe(1);
expect(rows[1]!.attempt_id).toBe(otherAttempt);
const result = (await f.api.getRunResults(ids[0]!)) as CanonicalRunResult;
for (const late of [
() => repo.completeCanonical(result, abandoned.attemptId),
() => repo.cancel(ids[0]!, abandoned.attemptId),
() => repo.updateProgress(ids[0]!, 1, undefined, abandoned.attemptId),
]) {
await expect(late()).rejects.toBeInstanceOf(BacktestLeaseLostError);
}
const beforeLateFailure = await f.rows(ids);
await repo.fail(ids[0]!, 'late owner failure', abandoned.attemptId); // Deliberate no-op for abandoned failures.
expect(await f.rows(ids)).toEqual(beforeLateFailure);
expect(
(await f.rows(ids)).every(row => row.status === 'completed' && row.result_count === 1)
).toBe(true);
await workers.stop();
}, 60000);
test('four slots cannot bypass agent admission capacity or per-attempt absolute deadlines', async () => {
const f = await fixture();
const research = new ResearchService({ postgres: f.postgres, logger });
const project = await research.createProject({ title: 'Pool budget gate' }, 'operator');
const agents = new ResearchAgentsService({ postgres: f.postgres, logger });
const agent = await agents.create({
name: 'Pool researcher',
allowedProjectIds: [project.id],
allowedBacktestIds: [f.draft.id],
limits: {
maxActiveTrials: 2,
maxTrialsPerExperiment: 4,
maxBarEvaluationsPerExperiment: 1000,
maxAttemptWallMs: 1,
maxAttempts: 1,
},
});
const principal = agent.agent.id;
const experiment = await f.submit({ fastPeriod: [1, 2] }, principal),
ids = admittedTrialIds(experiment);
await expect(f.submit({ fastPeriod: [1] }, principal)).rejects.toThrow();
const workers = f.createWorkers(4);
await workers.dispatcher.tick();
const rows = await f.wait(ids);
expect(rows.map(row => row.status)).toEqual(['failed', 'failed']);
expect(rows.map(row => row.result_count)).toEqual([0, 0]);
expect(rows.every(row => row.attempt_number === 1)).toBe(true);
expect(rows.every(row => /deadline|wall time/i.test(row.error))).toBe(true);
await workers.stop();
}, 60000);
}
);