feat(research): run durable backtests in a bounded worker pool
This commit is contained in:
parent
bbf0dd4453
commit
26b97265c6
15 changed files with 1730 additions and 129 deletions
|
|
@ -220,7 +220,7 @@
|
|||
"paperTradingCapital": 100000,
|
||||
"enableWebSocket": true,
|
||||
"backtesting": {
|
||||
"maxConcurrent": 5,
|
||||
"maxConcurrent": 1,
|
||||
"defaultSpeed": "max",
|
||||
"dataResolutions": ["1m", "5m", "15m", "1h", "1d"]
|
||||
},
|
||||
|
|
|
|||
|
|
@ -92,7 +92,7 @@ export const stockAppSchema = baseAppSchema.extend({
|
|||
enableWebSocket: z.boolean().default(true),
|
||||
backtesting: z
|
||||
.object({
|
||||
maxConcurrent: z.number().default(5),
|
||||
maxConcurrent: z.union([z.literal(1), z.literal(2), z.literal(4)]).default(1),
|
||||
useRustEngine: z.boolean().default(true),
|
||||
executionTimeoutMs: z.number().int().positive().max(2_147_483_647).default(300_000),
|
||||
allowSyntheticData: z.boolean().default(false),
|
||||
|
|
|
|||
|
|
@ -7,9 +7,11 @@ import { BacktestCancelledError, LEGACY_EXECUTION_RETIRED } from '../../backtest
|
|||
import { BacktestConflictError } from '../../backtest/run-repository';
|
||||
import type { OrchestratorServices as IServiceContainer } from '../../types';
|
||||
|
||||
const _BacktestIdSchema = z.object({
|
||||
backtestId: z.string(),
|
||||
});
|
||||
const runIdSchema = z
|
||||
.string()
|
||||
.uuid()
|
||||
.transform(value => value.toLowerCase());
|
||||
const controlSchema = z.object({ runId: runIdSchema.optional() }).strict();
|
||||
|
||||
export function createBacktestRoutes(container: IServiceContainer): Hono {
|
||||
const app = new Hono();
|
||||
|
|
@ -60,103 +62,60 @@ export function createBacktestRoutes(container: IServiceContainer): Hono {
|
|||
app.post('/', runBacktest);
|
||||
app.post('/run', runBacktest);
|
||||
|
||||
// Stop running backtest
|
||||
app.post('/stop', async c => {
|
||||
try {
|
||||
const { runId } = await c.req.json().catch(() => ({}));
|
||||
await backtestEngine.stopBacktest(runId);
|
||||
|
||||
return c.json({
|
||||
message: 'Backtest stop requested',
|
||||
timestamp: new Date().toISOString(),
|
||||
});
|
||||
} catch (error) {
|
||||
container.logger.error('Error stopping backtest:', error);
|
||||
return c.json(
|
||||
{
|
||||
error: error instanceof Error ? error.message : 'Failed to stop backtest',
|
||||
},
|
||||
500
|
||||
);
|
||||
}
|
||||
const controlError = (error: unknown) => ({
|
||||
body: { error: error instanceof Error ? error.message : 'Backtest control failed' },
|
||||
status:
|
||||
error instanceof BacktestConflictError
|
||||
? (409 as const)
|
||||
: error instanceof z.ZodError || error instanceof SyntaxError
|
||||
? (400 as const)
|
||||
: (500 as const),
|
||||
});
|
||||
|
||||
// Pause running backtest
|
||||
app.post('/pause', async c => {
|
||||
try {
|
||||
const { runId } = await c.req.json().catch(() => ({}));
|
||||
await backtestEngine.pauseBacktest(runId);
|
||||
|
||||
return c.json({
|
||||
message: 'Backtest paused',
|
||||
timestamp: new Date().toISOString(),
|
||||
});
|
||||
} catch (error) {
|
||||
container.logger.error('Error pausing backtest:', error);
|
||||
return c.json(
|
||||
{
|
||||
error: error instanceof Error ? error.message : 'Failed to pause backtest',
|
||||
},
|
||||
500
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
// Resume paused backtest
|
||||
app.post('/resume', async c => {
|
||||
try {
|
||||
const { runId } = await c.req.json().catch(() => ({}));
|
||||
await backtestEngine.resumeBacktest(runId);
|
||||
|
||||
return c.json({
|
||||
message: 'Backtest resumed',
|
||||
timestamp: new Date().toISOString(),
|
||||
});
|
||||
} catch (error) {
|
||||
container.logger.error('Error resuming backtest:', error);
|
||||
return c.json(
|
||||
{
|
||||
error: error instanceof Error ? error.message : 'Failed to resume backtest',
|
||||
},
|
||||
500
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
// Set backtest speed
|
||||
// Empty legacy bodies still target the sole active run. Invalid JSON never becomes an untargeted control.
|
||||
for (const [path, operation, message] of [
|
||||
['/stop', 'stopBacktest', 'Backtest stop requested'],
|
||||
['/pause', 'pauseBacktest', 'Backtest paused'],
|
||||
['/resume', 'resumeBacktest', 'Backtest resumed'],
|
||||
] as const) {
|
||||
app.post(path, async c => {
|
||||
try {
|
||||
const text = await c.req.text();
|
||||
const { runId } = controlSchema.parse(text.trim() ? JSON.parse(text) : {});
|
||||
await backtestEngine[operation](runId);
|
||||
return c.json({ message, timestamp: new Date().toISOString() });
|
||||
} catch (error) {
|
||||
const failure = controlError(error);
|
||||
return c.json(failure.body, failure.status);
|
||||
}
|
||||
});
|
||||
}
|
||||
app.post('/speed', async c => {
|
||||
try {
|
||||
const body = await c.req.json();
|
||||
const { speed, runId } = z
|
||||
.object({
|
||||
speed: z.number().finite().positive().nullable().default(1),
|
||||
runId: z.string().uuid().optional(),
|
||||
runId: runIdSchema.optional(),
|
||||
})
|
||||
.parse(body);
|
||||
|
||||
.strict()
|
||||
.parse(await c.req.json());
|
||||
await backtestEngine.setSpeedMultiplier(speed, runId);
|
||||
|
||||
return c.json({
|
||||
message: 'Backtest speed updated',
|
||||
speed: speed === null ? 'unlimited' : speed,
|
||||
timestamp: new Date().toISOString(),
|
||||
});
|
||||
} catch (error) {
|
||||
container.logger.error('Error setting backtest speed:', error);
|
||||
return c.json(
|
||||
{
|
||||
error: error instanceof Error ? error.message : 'Failed to set speed',
|
||||
},
|
||||
500
|
||||
);
|
||||
const failure = controlError(error);
|
||||
return c.json(failure.body, failure.status);
|
||||
}
|
||||
});
|
||||
|
||||
// Get backtest progress
|
||||
app.get('/progress', async c => {
|
||||
app.get('/progress', c => {
|
||||
try {
|
||||
const status = backtestEngine.getStatus();
|
||||
|
||||
const runId = runIdSchema.optional().parse(c.req.query('runId'));
|
||||
const status = backtestEngine.getStatus(runId);
|
||||
if (runId !== undefined && status.runId !== runId) {
|
||||
throw new BacktestConflictError('No matching active backtest');
|
||||
}
|
||||
return c.json({
|
||||
status: status.isPaused ? 'paused' : status.isRunning ? 'running' : 'idle',
|
||||
progress: status.progress,
|
||||
|
|
@ -166,18 +125,25 @@ export function createBacktestRoutes(container: IServiceContainer): Hono {
|
|||
runId: status.runId,
|
||||
});
|
||||
} catch (error) {
|
||||
container.logger.error('Error getting backtest progress:', error);
|
||||
return c.json(
|
||||
{
|
||||
error: error instanceof Error ? error.message : 'Failed to get progress',
|
||||
},
|
||||
500
|
||||
);
|
||||
const failure = controlError(error);
|
||||
return c.json(failure.body, failure.status);
|
||||
}
|
||||
});
|
||||
|
||||
// Stream backtest events (Server-Sent Events)
|
||||
app.get('/stream', async c => {
|
||||
app.get('/stream', c => {
|
||||
let runId: string;
|
||||
try {
|
||||
const requested = runIdSchema.optional().parse(c.req.query('runId'));
|
||||
const target = requested ?? backtestEngine.getStatus().runId;
|
||||
if (!target) {
|
||||
throw new BacktestConflictError('An exact runId is required when no backtest is active');
|
||||
}
|
||||
runId = target;
|
||||
} catch (error) {
|
||||
const failure = controlError(error);
|
||||
return c.json(failure.body, failure.status);
|
||||
}
|
||||
c.header('Content-Type', 'text/event-stream');
|
||||
c.header('Cache-Control', 'no-cache');
|
||||
c.header('Connection', 'keep-alive');
|
||||
|
|
@ -194,25 +160,40 @@ export function createBacktestRoutes(container: IServiceContainer): Hono {
|
|||
dispose();
|
||||
controller.close();
|
||||
};
|
||||
const onProgress = (data: unknown) => {
|
||||
const matches = (data: unknown) =>
|
||||
data !== null && typeof data === 'object' && 'runId' in data && data.runId === runId;
|
||||
const send = (data: unknown) => {
|
||||
if (!closed) {
|
||||
controller.enqueue(encoder.encode(`data: ${JSON.stringify(data)}\n\n`));
|
||||
}
|
||||
};
|
||||
const onComplete = (data: unknown) => {
|
||||
onProgress({ event: 'complete', data });
|
||||
finish();
|
||||
const onProgress = (data: unknown) => {
|
||||
if (matches(data)) {
|
||||
send(data);
|
||||
}
|
||||
};
|
||||
const onError = (error: unknown) => {
|
||||
onProgress({
|
||||
event: 'error',
|
||||
error: error instanceof Error ? error.message : String(error),
|
||||
});
|
||||
finish();
|
||||
const onComplete = (data: unknown) => {
|
||||
if (matches(data)) {
|
||||
send({ event: 'complete', runId, data });
|
||||
finish();
|
||||
}
|
||||
};
|
||||
const onError = (data: unknown) => {
|
||||
if (matches(data)) {
|
||||
const error = (data as { error: unknown }).error;
|
||||
send({
|
||||
event: 'error',
|
||||
runId,
|
||||
error: error instanceof Error ? error.message : String(error),
|
||||
});
|
||||
finish();
|
||||
}
|
||||
};
|
||||
const onCancelled = (data: unknown) => {
|
||||
onProgress({ event: 'cancelled', data });
|
||||
finish();
|
||||
if (matches(data)) {
|
||||
send({ event: 'cancelled', runId, data });
|
||||
finish();
|
||||
}
|
||||
};
|
||||
dispose = () => {
|
||||
closed = true;
|
||||
|
|
|
|||
197
apps/stock/orchestrator/src/backtest/ResearchBacktestPool.ts
Normal file
197
apps/stock/orchestrator/src/backtest/ResearchBacktestPool.ts
Normal file
|
|
@ -0,0 +1,197 @@
|
|||
import { EventEmitter } from 'node:events';
|
||||
import { z } from 'zod';
|
||||
import type { Logger } from '@stock-bot/services';
|
||||
import { parseBacktestRequest } from '@stock-bot/stock-config/backtest';
|
||||
import type { BacktestRunResult } from '@stock-bot/types';
|
||||
import type { BacktestRunner } from './BacktestRunner';
|
||||
import { BacktestCancelledError, LEGACY_EXECUTION_RETIRED } from './execution-engine';
|
||||
import { BacktestConflictError } from './run-repository';
|
||||
|
||||
export type ResearchConcurrency = 1 | 2 | 4;
|
||||
export function assertResearchConcurrency(value: unknown): asserts value is ResearchConcurrency {
|
||||
if (value !== 1 && value !== 2 && value !== 4) {
|
||||
throw new Error('Research concurrency must be 1, 2, or 4');
|
||||
}
|
||||
}
|
||||
|
||||
/** The existing runner surface, shared by production pool and single-runner fixtures. */
|
||||
export type ResearchBacktestRuntime = Pick<
|
||||
BacktestRunner,
|
||||
| 'runQueued'
|
||||
| 'runBacktest'
|
||||
| 'stopBacktest'
|
||||
| 'pauseBacktest'
|
||||
| 'resumeBacktest'
|
||||
| 'setSpeedMultiplier'
|
||||
| 'shutdown'
|
||||
> &
|
||||
Pick<EventEmitter, 'on' | 'off'> & {
|
||||
getStatus(runId?: string): ReturnType<BacktestRunner['getStatus']>;
|
||||
};
|
||||
|
||||
type Reservation = {
|
||||
runner: BacktestRunner;
|
||||
execution: ReturnType<BacktestRunner['runQueued']>;
|
||||
};
|
||||
const runIdSchema = z
|
||||
.string()
|
||||
.uuid()
|
||||
.transform(value => value.toLowerCase());
|
||||
|
||||
/** Independent portfolios only. BullMQ remains the sole waiting queue; SQL owns attempts. */
|
||||
export class ResearchBacktestPool extends EventEmitter implements ResearchBacktestRuntime {
|
||||
private readonly runners: readonly BacktestRunner[];
|
||||
private readonly reservations = new Map<string, Reservation>();
|
||||
private closing = false;
|
||||
private shutdownWork: Promise<void> | undefined;
|
||||
|
||||
constructor(
|
||||
private readonly dependencies: {
|
||||
runners: readonly BacktestRunner[];
|
||||
logger: Pick<Logger, 'error'>;
|
||||
}
|
||||
) {
|
||||
super();
|
||||
assertResearchConcurrency(dependencies.runners.length);
|
||||
if (new Set(dependencies.runners).size !== dependencies.runners.length) {
|
||||
throw new Error('Research slots require distinct runner instances');
|
||||
}
|
||||
this.runners = [...dependencies.runners];
|
||||
}
|
||||
|
||||
async runBacktest(input: unknown): Promise<BacktestRunResult> {
|
||||
parseBacktestRequest(input);
|
||||
throw new BacktestConflictError(LEGACY_EXECUTION_RETIRED);
|
||||
}
|
||||
|
||||
// Intentionally not async: reserve before any load/claim and return the exact shared promise.
|
||||
runQueued(input: string): ReturnType<BacktestRunner['runQueued']> {
|
||||
const runId = runIdSchema.parse(input);
|
||||
if (this.closing) {
|
||||
return Promise.reject(new BacktestConflictError('Backtest pool is shutting down'));
|
||||
}
|
||||
const existing = this.reservations.get(runId);
|
||||
if (existing) {
|
||||
return existing.execution;
|
||||
}
|
||||
const occupied = new Set([...this.reservations.values()].map(value => value.runner));
|
||||
const runner = this.runners.find(candidate => !occupied.has(candidate));
|
||||
if (!runner) {
|
||||
return Promise.reject(new BacktestConflictError('All research slots are occupied'));
|
||||
}
|
||||
const forward = (event: string) => (data: unknown) => {
|
||||
if (data && typeof data === 'object') {
|
||||
this.publish(event, { ...data, runId });
|
||||
}
|
||||
};
|
||||
const progress = forward('progress');
|
||||
const complete = forward('complete');
|
||||
const cancelled = forward('cancelled');
|
||||
runner.on('progress', progress);
|
||||
runner.on('complete', complete);
|
||||
runner.on('cancelled', cancelled);
|
||||
const execution = Promise.resolve()
|
||||
.then(() => runner.runQueued(runId))
|
||||
.catch((error: unknown) => {
|
||||
if (!(error instanceof BacktestCancelledError)) {
|
||||
this.publish('error', { runId, error });
|
||||
}
|
||||
throw error;
|
||||
})
|
||||
.finally(() => {
|
||||
runner.off('progress', progress);
|
||||
runner.off('complete', complete);
|
||||
runner.off('cancelled', cancelled);
|
||||
this.reservations.delete(runId);
|
||||
});
|
||||
this.reservations.set(runId, { runner, execution });
|
||||
return execution;
|
||||
}
|
||||
|
||||
private publish(event: string, value: unknown) {
|
||||
if (event === 'error' && !this.listenerCount('error')) {
|
||||
return;
|
||||
}
|
||||
try {
|
||||
this.emit(event, value);
|
||||
} catch (error) {
|
||||
this.dependencies.logger.error('Research pool observer failed', { event, error });
|
||||
}
|
||||
}
|
||||
|
||||
private resolve(input?: string): [string, Reservation] {
|
||||
if (input !== undefined) {
|
||||
const runId = runIdSchema.parse(input);
|
||||
const reservation = this.reservations.get(runId);
|
||||
if (!reservation) {
|
||||
throw new BacktestConflictError('No matching active backtest');
|
||||
}
|
||||
return [runId, reservation];
|
||||
}
|
||||
if (this.reservations.size > 1) {
|
||||
throw new BacktestConflictError('Multiple backtests are active; an exact runId is required');
|
||||
}
|
||||
const only = this.reservations.entries().next().value;
|
||||
if (!only) {
|
||||
throw new BacktestConflictError('No matching active backtest');
|
||||
}
|
||||
return only;
|
||||
}
|
||||
|
||||
async stopBacktest(input?: string) {
|
||||
const [runId, { runner }] = this.resolve(input);
|
||||
// A reservation is not a SQL claim. The runner retains its pending/committing refusal rules.
|
||||
await runner.stopBacktest(runId);
|
||||
}
|
||||
async pauseBacktest(input?: string) {
|
||||
const [runId, { runner }] = this.resolve(input);
|
||||
await runner.pauseBacktest(runId);
|
||||
}
|
||||
async resumeBacktest(input?: string) {
|
||||
const [runId, { runner }] = this.resolve(input);
|
||||
await runner.resumeBacktest(runId);
|
||||
}
|
||||
async setSpeedMultiplier(speed: number | null, input?: string) {
|
||||
const [runId, { runner }] = this.resolve(input);
|
||||
await runner.setSpeedMultiplier(speed, runId);
|
||||
}
|
||||
getStatus(input?: string): ReturnType<BacktestRunner['getStatus']> {
|
||||
if (input === undefined && this.reservations.size === 0) {
|
||||
return { isRunning: false, isPaused: false, progress: 0, currentTime: 0, runId: undefined };
|
||||
}
|
||||
const [runId, { runner }] = this.resolve(input);
|
||||
const status = runner.getStatus();
|
||||
if (status.runId !== runId) {
|
||||
return { isRunning: false, isPaused: false, progress: 0, currentTime: 0, runId };
|
||||
}
|
||||
return { ...status, runId };
|
||||
}
|
||||
|
||||
shutdown(): Promise<void> {
|
||||
if (!this.shutdownWork) {
|
||||
this.closing = true;
|
||||
const executions = [...this.reservations.values()].map(value => value.execution);
|
||||
this.shutdownWork = (async () => {
|
||||
const [results] = await Promise.all([
|
||||
Promise.allSettled(
|
||||
this.runners.map(runner => Promise.resolve().then(() => runner.shutdown()))
|
||||
),
|
||||
// Each job already reports its outcome to its caller/queue. An unclaimed
|
||||
// load deferred by closure is not a failure to drain the worker itself.
|
||||
Promise.allSettled(executions),
|
||||
]);
|
||||
const errors = new Set(
|
||||
results.flatMap(result =>
|
||||
result.status === 'rejected' && !(result.reason instanceof BacktestCancelledError)
|
||||
? [result.reason as unknown]
|
||||
: []
|
||||
)
|
||||
);
|
||||
if (errors.size) {
|
||||
throw new AggregateError([...errors], 'Could not cleanly drain the research pool');
|
||||
}
|
||||
})();
|
||||
}
|
||||
return this.shutdownWork;
|
||||
}
|
||||
}
|
||||
|
|
@ -1,8 +1,8 @@
|
|||
import { asValue, type AwilixContainer } from 'awilix';
|
||||
import type { ServiceCradle as ServiceDefinitions } from '@stock-bot/di';
|
||||
import { BacktestRunner } from './backtest/BacktestRunner';
|
||||
import type { BacktestExecutionEngine } from './backtest/execution-engine';
|
||||
import { PostgresBacktestRunRepository } from './backtest/PostgresBacktestRunRepository';
|
||||
import { assertResearchConcurrency, ResearchBacktestPool } from './backtest/ResearchBacktestPool';
|
||||
import { UnavailableBacktestRunRepository } from './backtest/run-repository';
|
||||
import { RustBacktestAdapter } from './backtest/RustBacktestAdapter';
|
||||
import type { PaperConfigurationInput, PaperRuntime } from './contracts/paper-runtime';
|
||||
|
|
@ -41,12 +41,15 @@ export async function registerOrchestratorServices(
|
|||
allowSyntheticData?: boolean;
|
||||
syntheticSeed?: number;
|
||||
nativeExecutionTimeoutMs?: number;
|
||||
maxConcurrent?: number;
|
||||
canonicalPaper?: PaperConfigurationInput;
|
||||
} = {}
|
||||
): Promise<void> {
|
||||
const role = options.role === undefined ? 'research-only' : options.role;
|
||||
const useRustEngine = options.useRustEngine === undefined ? true : options.useRustEngine;
|
||||
assertSupportedComposition(role, useRustEngine);
|
||||
const maxConcurrent = options.maxConcurrent === undefined ? 1 : options.maxConcurrent;
|
||||
assertResearchConcurrency(maxConcurrent);
|
||||
if (options.canonicalPaper !== undefined && role !== 'paper') {
|
||||
throw new Error('Canonical paper configuration requires a paper composition');
|
||||
}
|
||||
|
|
@ -100,16 +103,22 @@ export async function registerOrchestratorServices(
|
|||
programs: canonicalPaper.strategies.map(createBuiltinStrategy),
|
||||
})
|
||||
: undefined;
|
||||
const engine = new RustBacktestAdapter(
|
||||
{ logger: services.logger, storage: storageService },
|
||||
{ timeoutMs: options.nativeExecutionTimeoutMs }
|
||||
);
|
||||
const runner = new BacktestRunner({
|
||||
engine,
|
||||
engineName: 'native',
|
||||
repository: services.postgres
|
||||
? new PostgresBacktestRunRepository(services.postgres)
|
||||
: new UnavailableBacktestRunRepository(),
|
||||
const runner = new ResearchBacktestPool({
|
||||
runners: Array.from(
|
||||
{ length: maxConcurrent },
|
||||
() =>
|
||||
new BacktestRunner({
|
||||
engine: new RustBacktestAdapter(
|
||||
{ logger: services.logger, storage: storageService },
|
||||
{ timeoutMs: options.nativeExecutionTimeoutMs }
|
||||
),
|
||||
engineName: 'native',
|
||||
repository: services.postgres
|
||||
? new PostgresBacktestRunRepository(services.postgres)
|
||||
: new UnavailableBacktestRunRepository(),
|
||||
logger: services.logger,
|
||||
})
|
||||
),
|
||||
logger: services.logger,
|
||||
});
|
||||
const analytics = new AnalyticsService(services);
|
||||
|
|
@ -118,7 +127,6 @@ export async function registerOrchestratorServices(
|
|||
Object.assign(custom, {
|
||||
StorageService: storageService,
|
||||
AnalyticsService: analytics,
|
||||
BacktestEngine: engine,
|
||||
BacktestRunner: runner,
|
||||
...(paper ? { CanonicalPaperRuntime: paper } : {}),
|
||||
});
|
||||
|
|
@ -127,15 +135,13 @@ export async function registerOrchestratorServices(
|
|||
StorageService: StorageService;
|
||||
AnalyticsService: AnalyticsService;
|
||||
CanonicalPaperRuntime: PaperRuntime;
|
||||
BacktestEngine: BacktestExecutionEngine;
|
||||
BacktestRunner: BacktestRunner;
|
||||
BacktestRunner: ResearchBacktestPool;
|
||||
orchestratorServices: IServiceContainer;
|
||||
}
|
||||
>;
|
||||
canonicalContainer.register({
|
||||
StorageService: asValue(storageService),
|
||||
AnalyticsService: asValue(analytics),
|
||||
BacktestEngine: asValue(engine),
|
||||
BacktestRunner: asValue(runner),
|
||||
orchestratorServices: asValue(services),
|
||||
...(paper ? { CanonicalPaperRuntime: asValue(paper) } : {}),
|
||||
|
|
@ -147,8 +153,9 @@ export async function registerOrchestratorServices(
|
|||
if (paper && canonicalPaper && options.initializeMode !== false) {
|
||||
await paper.initialize(canonicalPaper);
|
||||
}
|
||||
services.queueManager?.getQueue('orchestrator', { workers: 1, concurrency: 1 });
|
||||
services.queueManager?.getQueue('orchestrator', { workers: 1, concurrency: maxConcurrent });
|
||||
} catch (error) {
|
||||
await runner.shutdown().catch(() => {});
|
||||
await paper?.shutdown().catch(() => {});
|
||||
throw error;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,13 +1,13 @@
|
|||
import { z } from 'zod';
|
||||
import { BaseHandler, Handler, Operation } from '@stock-bot/handlers';
|
||||
import { defined } from '@stock-bot/invariants';
|
||||
import type { BacktestRunner } from '../../backtest/BacktestRunner';
|
||||
import { LEGACY_EXECUTION_RETIRED } from '../../backtest/execution-engine';
|
||||
import type { ResearchBacktestRuntime } from '../../backtest/ResearchBacktestPool';
|
||||
import type { OrchestratorServices } from '../../types';
|
||||
|
||||
@Handler('orchestrator')
|
||||
export class BacktestHandler extends BaseHandler<OrchestratorServices> {
|
||||
private readonly runner: BacktestRunner;
|
||||
private readonly runner: ResearchBacktestRuntime;
|
||||
constructor(services: OrchestratorServices) {
|
||||
super(services);
|
||||
this.runner = defined(services.custom?.BacktestRunner, 'Backtest runner is unavailable');
|
||||
|
|
|
|||
|
|
@ -1,5 +1,6 @@
|
|||
import { ServiceContainerBuilder } from '@stock-bot/di';
|
||||
import type { StockAppConfig } from '@stock-bot/stock-config';
|
||||
import { assertResearchConcurrency } from './backtest/ResearchBacktestPool';
|
||||
import { paperConfigurationSchema } from './contracts/paper-runtime';
|
||||
import { validatePaperConfiguration } from './paper/feed';
|
||||
import {
|
||||
|
|
@ -28,6 +29,9 @@ export async function createContainer(
|
|||
const useRustEngine = configuredEngine === undefined ? true : configuredEngine;
|
||||
// Fail before opening connections as well as before registering runtime services.
|
||||
assertSupportedComposition(role, useRustEngine);
|
||||
const maxConcurrent =
|
||||
settings?.backtesting?.maxConcurrent === undefined ? 1 : settings.backtesting.maxConcurrent;
|
||||
assertResearchConcurrency(maxConcurrent);
|
||||
if (settings?.canonicalPaper !== undefined && role !== 'paper') {
|
||||
throw new Error('Canonical paper configuration requires a paper composition');
|
||||
}
|
||||
|
|
@ -58,6 +62,7 @@ export async function createContainer(
|
|||
await registerOrchestratorServices(container, {
|
||||
role,
|
||||
useRustEngine,
|
||||
maxConcurrent,
|
||||
allowSyntheticData: config.services?.orchestrator?.backtesting?.allowSyntheticData ?? false,
|
||||
syntheticSeed: config.services?.orchestrator?.backtesting?.syntheticSeed ?? 42,
|
||||
nativeExecutionTimeoutMs: config.services?.orchestrator?.backtesting?.executionTimeoutMs,
|
||||
|
|
|
|||
|
|
@ -47,13 +47,12 @@ export const ModeConfigSchema = z.discriminatedUnion('mode', [
|
|||
|
||||
export type OrchestratorServices = import('@stock-bot/services').IServiceContainer & {
|
||||
custom?: Partial<{
|
||||
BacktestRunner: import('./backtest/BacktestRunner').BacktestRunner;
|
||||
BacktestRunner: import('./backtest/ResearchBacktestPool').ResearchBacktestRuntime;
|
||||
StorageService: import('./services/StorageService').StorageService;
|
||||
MarketDataService: import('./services/MarketDataService').MarketDataService;
|
||||
ExecutionService: import('./services/ExecutionService').ExecutionService;
|
||||
AnalyticsService: import('./services/AnalyticsService').AnalyticsService;
|
||||
StrategyManager: import('./strategies/StrategyManager').StrategyManager;
|
||||
BacktestEngine: import('./backtest/execution-engine').BacktestExecutionEngine;
|
||||
PaperTradingManager: import('./paper/PaperTradingManager').PaperTradingManager;
|
||||
ModeManager: import('./core/ModeManager').ModeManager;
|
||||
CanonicalPaperRuntime: import('./contracts/paper-runtime').PaperRuntime;
|
||||
|
|
|
|||
430
scripts/benchmark-research-pool.ts
Normal file
430
scripts/benchmark-research-pool.ts
Normal file
|
|
@ -0,0 +1,430 @@
|
|||
/** Disposable PG/Redis + actual one-shot Rust workers. No financial simulator or timing pass/fail threshold. */
|
||||
import { execFileSync } from 'node:child_process';
|
||||
import { createHash, randomUUID } from 'node:crypto';
|
||||
import { readdirSync, readFileSync, writeFileSync } from 'node:fs';
|
||||
import { cpus, freemem, platform, release, totalmem } from 'node:os';
|
||||
import { resolve } from 'node:path';
|
||||
import { defined } from '@stock-bot/invariants';
|
||||
import type { CanonicalRunResult } from '@stock-bot/stock-config/canonical-research';
|
||||
import { readCanonicalBuildIdentity } from '../apps/stock/orchestrator/src/backtest/canonical-build';
|
||||
import type { ResearchConcurrency } from '../apps/stock/orchestrator/src/backtest/ResearchBacktestPool';
|
||||
import { canonicalReproductionHash } from '../apps/stock/web-api/src/services/reproduction-comparison';
|
||||
import { nativeReplayFixture } from '../test/fixtures/native-replay';
|
||||
import {
|
||||
admittedTrialIds,
|
||||
researchPoolFixture,
|
||||
untilResearch,
|
||||
} from '../test/fixtures/research-pool';
|
||||
|
||||
export function percentile(samples: readonly number[], quantile: number) {
|
||||
if (
|
||||
!samples.length ||
|
||||
samples.some(value => !Number.isFinite(value) || value < 0) ||
|
||||
quantile <= 0 ||
|
||||
quantile > 1
|
||||
) {
|
||||
throw new Error('Invalid latency samples');
|
||||
}
|
||||
const sorted = [...samples].sort((a, b) => a - b);
|
||||
return defined(
|
||||
sorted[Math.max(0, Math.ceil(quantile * sorted.length) - 1)],
|
||||
'Missing percentile'
|
||||
);
|
||||
}
|
||||
export function efficiency(serialMs: number, parallelMs: number, slots: ResearchConcurrency) {
|
||||
if (serialMs <= 0 || parallelMs <= 0 || !Number.isFinite(serialMs + parallelMs)) {
|
||||
throw new Error('Invalid batch duration');
|
||||
}
|
||||
return serialMs / (slots * parallelMs);
|
||||
}
|
||||
export function verifyHashParity(
|
||||
expected: readonly string[] | undefined,
|
||||
actual: readonly string[]
|
||||
) {
|
||||
if (
|
||||
!actual.length ||
|
||||
actual.some(hash => !/^[a-f0-9]{64}$/.test(hash)) ||
|
||||
(expected &&
|
||||
(expected.length !== actual.length || expected.some((hash, index) => hash !== actual[index])))
|
||||
) {
|
||||
throw new Error('Per-candidate economic hash parity failed');
|
||||
}
|
||||
}
|
||||
export function sampleProcessTree(root = process.pid) {
|
||||
const pending = [root],
|
||||
seen = new Set<number>(),
|
||||
processes: { pid: number; rssBytes: number }[] = [];
|
||||
while (pending.length) {
|
||||
const pid = defined(pending.pop(), 'Missing sampled process');
|
||||
if (seen.has(pid)) {
|
||||
continue;
|
||||
}
|
||||
seen.add(pid);
|
||||
try {
|
||||
const match = /^VmRSS:\s+(\d+)\s+kB$/m.exec(readFileSync(`/proc/${pid}/status`, 'utf8'));
|
||||
if (match) {
|
||||
processes.push({ pid, rssBytes: Number(match[1]) * 1024 });
|
||||
}
|
||||
for (const tid of readdirSync(`/proc/${pid}/task`)) {
|
||||
try {
|
||||
for (const child of readFileSync(`/proc/${pid}/task/${tid}/children`, 'utf8')
|
||||
.trim()
|
||||
.split(/\s+/)) {
|
||||
if (Number(child) > 0) {
|
||||
pending.push(Number(child));
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
/* Threads can exit while sampling. */
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
/* Children can exit while sampling. */
|
||||
}
|
||||
}
|
||||
return { rssBytes: processes.reduce((sum, child) => sum + child.rssBytes, 0), processes };
|
||||
}
|
||||
|
||||
export async function measurePool(options: { output?: string; smoke?: boolean }) {
|
||||
const startedAt = new Date().toISOString(),
|
||||
start = performance.now();
|
||||
const bars = options.smoke ? 100 : 10000,
|
||||
repetitions = options.smoke ? 1 : 5;
|
||||
const grid = options.smoke
|
||||
? { fastPeriod: [2, 3], slowPeriod: [12, 16] }
|
||||
: { fastPeriod: [2, 3, 4, 5, 6, 7], slowPeriod: [12, 16, 20, 24] };
|
||||
const report: Record<string, unknown> = {
|
||||
version: 'research-pool-measurement/v1',
|
||||
status: 'running',
|
||||
startedAt,
|
||||
smoke: options.smoke ?? false,
|
||||
workload: {
|
||||
assetsPerTrial: 1,
|
||||
barsPerTrial: bars,
|
||||
candidates: grid.fastPeriod.length * grid.slowPeriod.length,
|
||||
grid,
|
||||
seed: 42,
|
||||
repetitions,
|
||||
slots: [1, 2, 4],
|
||||
},
|
||||
host: {
|
||||
platform: platform(),
|
||||
release: release(),
|
||||
cpuModel: cpus()[0]?.model,
|
||||
logicalCpus: cpus().length,
|
||||
totalMemoryBytes: totalmem(),
|
||||
freeMemoryBytesAtStart: freemem(),
|
||||
runtime: Bun.version,
|
||||
pid: process.pid,
|
||||
},
|
||||
definitions: {
|
||||
throughput:
|
||||
'Successful trials / (first submission request start to last durable completion event). Includes admission, SQL/Redis dispatch, data loading, native one-shot startup, replay, and result commit.',
|
||||
serviceLatency:
|
||||
'Claim transaction resolved to durable completion event, measured in one parent monotonic clock.',
|
||||
endToEndLatency:
|
||||
'First submission request start to each durable completion event; shared batch admission start, including queue wait.',
|
||||
queueWait:
|
||||
'Submission response resolved to claim transaction resolved; dispatcher starts after admission.',
|
||||
aggregation:
|
||||
'Validated result reads, canonical economic hashes and row inspection measured separately after completion.',
|
||||
rss: '100ms procfs sum of benchmark driver and all descendants; approximate sampled peak, shared pages counted per process, short peaks can be missed. External PostgreSQL/Redis RSS excluded.',
|
||||
cold: 'Initial fixture/catalog packaging, SQL migration/dataset retention, and first one-trial native run reported separately. OS/DB page caches are not flushed.',
|
||||
warm: 'Same retained SQL dataset and executable build reused; every trial still forks a fresh native process. No resident worker/dataset cache.',
|
||||
dispatcher:
|
||||
'Unmodified production batch20, interval5000ms, republish30000ms, maxAttempts3. One BullMQ worker with concurrency1/2/4.',
|
||||
claims:
|
||||
'Single asset independent retained builtin strategies only; synthetic deterministic price history, not market alpha evidence or candidate sandbox throughput.',
|
||||
},
|
||||
};
|
||||
const persist = () => {
|
||||
if (options.output) {
|
||||
writeFileSync(resolve(options.output), JSON.stringify(report, null, 2) + '\n');
|
||||
}
|
||||
};
|
||||
persist();
|
||||
let fixture: Awaited<ReturnType<typeof researchPoolFixture>> | undefined;
|
||||
const samples: unknown[] = [];
|
||||
report.samples = samples;
|
||||
let failure: unknown;
|
||||
try {
|
||||
const sourceFiles = [
|
||||
'apps/stock/orchestrator/src/backtest/ResearchBacktestPool.ts',
|
||||
'apps/stock/orchestrator/src/container.ts',
|
||||
'apps/stock/orchestrator/src/backtest/BacktestRunner.ts',
|
||||
'apps/stock/orchestrator/src/backtest/RustBacktestAdapter.ts',
|
||||
'apps/stock/web-api/src/services/BacktestDispatcher.ts',
|
||||
'scripts/benchmark-research-pool.ts',
|
||||
'test/fixtures/research-pool.ts',
|
||||
];
|
||||
report.source = {
|
||||
revision: execFileSync('git', ['rev-parse', 'HEAD'], { encoding: 'utf8' }).trim(),
|
||||
dirty: execFileSync('git', ['status', '--porcelain'], { encoding: 'utf8' }).trim().length > 0,
|
||||
files: Object.fromEntries(
|
||||
sourceFiles.map(path => [
|
||||
path,
|
||||
createHash('sha256').update(readFileSync(path)).digest('hex'),
|
||||
])
|
||||
),
|
||||
};
|
||||
report.build = await readCanonicalBuildIdentity();
|
||||
const dataset = nativeReplayFixture(bars).dataset;
|
||||
fixture = await researchPoolFixture(dataset);
|
||||
const f = fixture;
|
||||
report.dataset = dataset.manifest;
|
||||
report.setupMs = performance.now() - start;
|
||||
let baseline: string[] | undefined;
|
||||
async function batch(slots: ResearchConcurrency, repetition: number, cold = false) {
|
||||
const workers = f.createWorkers(slots);
|
||||
await workers.queue.getBullQueue().waitUntilReady();
|
||||
const input = {
|
||||
backtestId: f.draft.id,
|
||||
name: 'Paired bounded pool workload',
|
||||
grid: cold ? { fastPeriod: [2], slowPeriod: [12] } : grid,
|
||||
};
|
||||
const previewStart = performance.now();
|
||||
const preview = await f.experiments.preview(input);
|
||||
const previewMs = performance.now() - previewStart;
|
||||
const claims = new Map<string, number>(),
|
||||
completed = new Map<string, number>();
|
||||
workers.repositories.forEach(repository => {
|
||||
const claim = repository.startCanonical.bind(repository);
|
||||
repository.startCanonical = async request => {
|
||||
const result = await claim(request);
|
||||
claims.set(result.runId, performance.now());
|
||||
return result;
|
||||
};
|
||||
});
|
||||
workers.runtime.on('complete', (result: CanonicalRunResult) => {
|
||||
completed.set(result.runId, performance.now());
|
||||
});
|
||||
const rss: {
|
||||
elapsedMs: number;
|
||||
rssBytes: number;
|
||||
processes: { pid: number; rssBytes: number }[];
|
||||
}[] = [];
|
||||
const batchStart = performance.now();
|
||||
const sample = () =>
|
||||
rss.push({ elapsedMs: performance.now() - batchStart, ...sampleProcessTree() });
|
||||
sample();
|
||||
const timer = setInterval(sample, 100);
|
||||
try {
|
||||
const experiment = await f.experiments.submit(
|
||||
{ ...input, previewHash: preview.previewHash },
|
||||
{ principal: 'operator', key: randomUUID() }
|
||||
);
|
||||
const admittedAt = performance.now();
|
||||
const ids = admittedTrialIds(experiment);
|
||||
workers.dispatcher.start();
|
||||
const rows = await f.wait(ids, 180000);
|
||||
if (rows.every(row => row.status === 'completed')) {
|
||||
await untilResearch(async () => completed.size === ids.length, 5000);
|
||||
}
|
||||
sample();
|
||||
const observations = rows.map(row => ({
|
||||
runId: row.id,
|
||||
candidateIndex: row.trial_index,
|
||||
trialKey: row.trial_key,
|
||||
status: row.status,
|
||||
attemptNumber: row.attempt_number,
|
||||
error: row.error,
|
||||
resultCount: row.result_count,
|
||||
createdAt: row.created_at,
|
||||
startedAt: row.started_at,
|
||||
completedAt: row.completed_at,
|
||||
claimElapsedMs: claims.has(row.id)
|
||||
? defined(claims.get(row.id), 'Missing claim timestamp') - batchStart
|
||||
: null,
|
||||
commitElapsedMs: completed.has(row.id)
|
||||
? defined(completed.get(row.id), 'Missing completion timestamp') - batchStart
|
||||
: null,
|
||||
}));
|
||||
if (
|
||||
rows.some(
|
||||
row => row.status !== 'completed' || row.attempt_number !== 1 || row.result_count !== 1
|
||||
) ||
|
||||
completed.size !== ids.length ||
|
||||
claims.size !== ids.length
|
||||
) {
|
||||
samples.push({
|
||||
slots,
|
||||
repetition,
|
||||
cold,
|
||||
observations,
|
||||
rss,
|
||||
error: 'Incomplete, failed, retried, or unobserved trial',
|
||||
});
|
||||
throw new Error('Every measured trial must complete exactly once');
|
||||
}
|
||||
const elapsedMs = Math.max(...completed.values()) - batchStart;
|
||||
const aggregateStart = performance.now(),
|
||||
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 validated canonical result');
|
||||
}
|
||||
hashes.push(canonicalReproductionHash(result));
|
||||
}
|
||||
if (!cold) {
|
||||
verifyHashParity(baseline, hashes);
|
||||
baseline ??= hashes;
|
||||
}
|
||||
const aggregationMs = performance.now() - aggregateStart;
|
||||
const service = ids.map(
|
||||
id =>
|
||||
defined(completed.get(id), 'Missing completion timestamp') -
|
||||
defined(claims.get(id), 'Missing claim timestamp')
|
||||
);
|
||||
const endToEnd = ids.map(
|
||||
id => defined(completed.get(id), 'Missing completion timestamp') - batchStart
|
||||
);
|
||||
const queueWait = ids.map(
|
||||
id => defined(claims.get(id), 'Missing claim timestamp') - admittedAt
|
||||
);
|
||||
const measurement = {
|
||||
slots,
|
||||
repetition,
|
||||
cold,
|
||||
experimentId: experiment.id,
|
||||
previewHash: preview.previewHash,
|
||||
parameters: experiment.preview.candidates.map(candidate => candidate.parameters),
|
||||
previewMs,
|
||||
admissionMs: admittedAt - batchStart,
|
||||
elapsedMs,
|
||||
trialsPerSecond: (ids.length * 1000) / elapsedMs,
|
||||
aggregationMs,
|
||||
hashes,
|
||||
serviceMs: {
|
||||
p50: percentile(service, 0.5),
|
||||
p95: percentile(service, 0.95),
|
||||
raw: service,
|
||||
},
|
||||
endToEndMs: {
|
||||
p50: percentile(endToEnd, 0.5),
|
||||
p95: percentile(endToEnd, 0.95),
|
||||
raw: endToEnd,
|
||||
},
|
||||
queueWaitMs: {
|
||||
p50: percentile(queueWait, 0.5),
|
||||
p95: percentile(queueWait, 0.95),
|
||||
raw: queueWait,
|
||||
},
|
||||
peakAggregateRssBytes: Math.max(...rss.map(sample => sample.rssBytes)),
|
||||
rss,
|
||||
observations,
|
||||
};
|
||||
console.error(
|
||||
`pool slots=${slots} repetition=${repetition} cold=${cold} trials=${ids.length} ms=${elapsedMs.toFixed(1)} trials/s=${measurement.trialsPerSecond.toFixed(3)}`
|
||||
);
|
||||
return measurement;
|
||||
} finally {
|
||||
clearInterval(timer);
|
||||
await workers.stop();
|
||||
}
|
||||
}
|
||||
report.firstNativeTrial = await batch(1, -1, true);
|
||||
persist();
|
||||
const batches: Awaited<ReturnType<typeof batch>>[] = [];
|
||||
for (let repetition = 0; repetition < repetitions; repetition++) {
|
||||
const order: ResearchConcurrency[] =
|
||||
repetition % 3 === 0 ? [1, 2, 4] : repetition % 3 === 1 ? [2, 4, 1] : [4, 1, 2];
|
||||
for (const slots of order) {
|
||||
const sample = await batch(slots, repetition);
|
||||
batches.push(sample);
|
||||
samples.push(sample);
|
||||
persist();
|
||||
}
|
||||
}
|
||||
report.summary = [1, 2, 4].map(slots => {
|
||||
const selected = batches.filter(batch => batch.slots === slots);
|
||||
return {
|
||||
slots,
|
||||
medianTrialsPerSecond: percentile(
|
||||
selected.map(batch => batch.trialsPerSecond),
|
||||
0.5
|
||||
),
|
||||
medianBatchMs: percentile(
|
||||
selected.map(batch => batch.elapsedMs),
|
||||
0.5
|
||||
),
|
||||
pairedEfficiency: selected.map(batch => ({
|
||||
repetition: batch.repetition,
|
||||
value: efficiency(
|
||||
defined(
|
||||
batches.find(serial => serial.repetition === batch.repetition && serial.slots === 1),
|
||||
'Missing paired serial batch'
|
||||
).elapsedMs,
|
||||
batch.elapsedMs,
|
||||
batch.slots
|
||||
),
|
||||
})),
|
||||
peakAggregateRssBytes: Math.max(...selected.map(batch => batch.peakAggregateRssBytes)),
|
||||
serviceP95Ms: percentile(
|
||||
selected.flatMap(batch => batch.serviceMs.raw),
|
||||
0.95
|
||||
),
|
||||
endToEndP95Ms: percentile(
|
||||
selected.flatMap(batch => batch.endToEndMs.raw),
|
||||
0.95
|
||||
),
|
||||
};
|
||||
});
|
||||
report.status = 'passed';
|
||||
} catch (error) {
|
||||
report.status = 'failed';
|
||||
report.error = error instanceof Error ? error.message : String(error);
|
||||
failure = error;
|
||||
} finally {
|
||||
try {
|
||||
await fixture?.close();
|
||||
} catch (error) {
|
||||
report.status = 'failed';
|
||||
report.cleanupError = String(error);
|
||||
failure =
|
||||
failure === undefined
|
||||
? error
|
||||
: new AggregateError([failure, error], 'Measurement and cleanup failed');
|
||||
} finally {
|
||||
report.finishedAt = new Date().toISOString();
|
||||
report.totalMs = performance.now() - start;
|
||||
persist();
|
||||
}
|
||||
}
|
||||
if (failure !== undefined) {
|
||||
throw failure;
|
||||
}
|
||||
return report;
|
||||
}
|
||||
|
||||
export function parsePoolArguments(args: string[]): { output?: string; smoke: boolean } {
|
||||
let measure = false,
|
||||
smoke = false,
|
||||
output: string | undefined;
|
||||
for (let i = 0; i < args.length; i++) {
|
||||
const argument = args[i];
|
||||
if (argument === '--measure' && !measure) {
|
||||
measure = true;
|
||||
} else if (argument === '--smoke' && !smoke) {
|
||||
smoke = true;
|
||||
} else if (
|
||||
argument === '--output' &&
|
||||
output === undefined &&
|
||||
args[i + 1] &&
|
||||
!args[i + 1]?.startsWith('--')
|
||||
) {
|
||||
output = args[++i];
|
||||
} else {
|
||||
throw new Error('Invalid pool benchmark arguments');
|
||||
}
|
||||
}
|
||||
if (!measure) {
|
||||
throw new Error('Pass --measure to run disposable PostgreSQL/Redis/native measurements');
|
||||
}
|
||||
return { output, smoke };
|
||||
}
|
||||
if (import.meta.main) {
|
||||
console.log(
|
||||
JSON.stringify(await measurePool(parsePoolArguments(process.argv.slice(2))), null, 2)
|
||||
);
|
||||
}
|
||||
62
scripts/test/benchmark-research-pool.test.ts
Normal file
62
scripts/test/benchmark-research-pool.test.ts
Normal file
|
|
@ -0,0 +1,62 @@
|
|||
import { describe, expect, test } from 'bun:test';
|
||||
import {
|
||||
efficiency,
|
||||
parsePoolArguments,
|
||||
percentile,
|
||||
sampleProcessTree,
|
||||
verifyHashParity,
|
||||
} from '../benchmark-research-pool';
|
||||
|
||||
describe('bounded pool measurement integrity', () => {
|
||||
test('nearest-rank tails preserve zero and reject incomplete/nonfinite samples', () => {
|
||||
expect(percentile([0, 4, 2, 1, 3], 0.5)).toBe(2);
|
||||
expect(
|
||||
percentile(
|
||||
Array.from({ length: 24 }, (_, i) => i),
|
||||
0.95
|
||||
)
|
||||
).toBe(22);
|
||||
for (const values of [[], [NaN], [Infinity], [-1]]) {
|
||||
expect(() => percentile(values, 0.95)).toThrow();
|
||||
}
|
||||
});
|
||||
test('paired efficiency uses full serial duration divided by slots times parallel duration', () => {
|
||||
expect(efficiency(100, 60, 2)).toBeCloseTo(0.83333333);
|
||||
expect(efficiency(100, 100, 1)).toBe(1);
|
||||
expect(efficiency(100, 120, 4)).toBeCloseTo(0.20833333);
|
||||
expect(() => efficiency(100, 0, 2)).toThrow();
|
||||
});
|
||||
test('parity is per candidate index, never sorted by result or completion order', () => {
|
||||
const a = 'a'.repeat(64),
|
||||
b = 'b'.repeat(64);
|
||||
verifyHashParity(undefined, [a, b]);
|
||||
verifyHashParity([a, b], [a, b]);
|
||||
for (const hashes of [[b, a], [a], [], [a, 'invalid']]) {
|
||||
expect(() => verifyHashParity([a, b], hashes)).toThrow();
|
||||
}
|
||||
});
|
||||
test('measurement execution is explicit and malformed options cannot silently run', () => {
|
||||
expect(parsePoolArguments(['--measure', '--smoke', '--output', '/tmp/report.json'])).toEqual({
|
||||
smoke: true,
|
||||
output: '/tmp/report.json',
|
||||
});
|
||||
for (const args of [
|
||||
[],
|
||||
['--smoke'],
|
||||
['unknown', '--measure'],
|
||||
['--measure', '--output'],
|
||||
['--measure', '--output', '--smoke'],
|
||||
['--measure', '--measure'],
|
||||
]) {
|
||||
expect(() => parsePoolArguments(args)).toThrow();
|
||||
}
|
||||
});
|
||||
test('RSS includes the actual driver and records process identities', () => {
|
||||
const sample = sampleProcessTree();
|
||||
expect(sample.processes.some(processInfo => processInfo.pid === process.pid)).toBe(true);
|
||||
expect(sample.rssBytes).toBeGreaterThan(0);
|
||||
expect(sample.rssBytes).toBe(
|
||||
sample.processes.reduce((total, processInfo) => total + processInfo.rssBytes, 0)
|
||||
);
|
||||
});
|
||||
});
|
||||
250
test/fixtures/research-pool.ts
vendored
Normal file
250
test/fixtures/research-pool.ts
vendored
Normal 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;
|
||||
}
|
||||
}
|
||||
|
|
@ -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"');
|
||||
|
|
|
|||
396
test/integration/research-pool.test.ts
Normal file
396
test/integration/research-pool.test.ts
Normal 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);
|
||||
});
|
||||
});
|
||||
|
|
@ -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: {} } }) });
|
||||
|
|
|
|||
233
test/postgres/research-pool.test.ts
Normal file
233
test/postgres/research-pool.test.ts
Normal 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);
|
||||
}
|
||||
);
|
||||
Loading…
Add table
Add a link
Reference in a new issue