fix(orchestrator): own startup and shutdown resources (CL16)

This commit is contained in:
Boki 2026-10-26 19:28:43 -04:00
parent 21666242f4
commit 8546fce4a9
8 changed files with 384 additions and 117 deletions

View file

@ -15,6 +15,7 @@ import { PaperDeploymentHost } from './paper/PaperDeploymentHost';
import { AnalyticsService } from './services/AnalyticsService';
import { StorageService } from './services/StorageService';
import { createBuiltinStrategy } from './strategies/canonical-builtins';
import { stopOrchestratorWork } from './runtime';
import type { OrchestratorServices as IServiceContainer } from './types';
export type OrchestratorRole = 'paper' | 'research-only';
@ -203,9 +204,9 @@ export async function registerOrchestratorServices(
}
services.queueManager?.getQueue('orchestrator', { workers: 1, concurrency: maxConcurrent });
} catch (error) {
await runner.shutdown().catch(() => {});
await paper?.shutdown().catch(() => {});
await deploymentHost?.shutdown().catch(() => {});
await stopOrchestratorWork(services).catch(cleanupError => {
services.logger.error('Orchestrator registration cleanup failed', { cleanupError });
});
throw error;
}
}

View file

@ -9,6 +9,7 @@ import { createHttpSecurity, httpSecurityOptions } from '@stock-bot/di';
import { getLogger } from '@stock-bot/logger';
import { initializeStockConfig } from '@stock-bot/stock-config';
import { createRoutes } from './routes/create-routes';
import { startOrchestratorServer, type OrchestratorRuntime } from './runtime';
import { createContainer } from './simple-container';
// Initialize configuration with service-specific overrides
@ -40,85 +41,70 @@ logger.info('Service configuration:', {
});
async function main() {
let server: ReturnType<typeof Bun.serve> | undefined; // Declare server in outer scope for shutdown
let server: ReturnType<typeof Bun.serve> | undefined;
let runtime: OrchestratorRuntime | undefined;
try {
// Initialize container with all services using configuration
const services = await createContainer(config);
const started = await startOrchestratorServer(
() => createContainer(config),
services => {
// Initialize Hono app
const app = new Hono();
// Initialize Hono app
const app = new Hono();
// CORS middleware - use config for origins
app.use(
'*',
cors({
origin: config.services?.webApi?.cors?.origins || [
'http://localhost:4200',
'http://localhost:3000',
'http://localhost:5173',
'http://localhost:5174',
],
allowMethods: ['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS'],
allowHeaders: ['Content-Type', 'Authorization'],
credentials: config.services?.webApi?.cors?.credentials ?? true,
})
);
security.mount(app);
// CORS middleware - use config for origins
app.use(
'*',
cors({
origin: config.services?.webApi?.cors?.origins || [
'http://localhost:4200',
'http://localhost:3000',
'http://localhost:5173',
'http://localhost:5174',
],
allowMethods: ['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS'],
allowHeaders: ['Content-Type', 'Authorization'],
credentials: config.services?.webApi?.cors?.credentials ?? true,
})
);
security.mount(app);
// Logging middleware
app.use('*', async (c, next) => {
const start = Date.now();
await next();
const ms = Date.now() - start;
services.logger.debug(`${c.req.method} ${c.req.url} - ${ms}ms`);
});
// Logging middleware
app.use('*', async (c, next) => {
const start = Date.now();
await next();
const ms = Date.now() - start;
services.logger.debug(`${c.req.method} ${c.req.url} - ${ms}ms`);
});
// Create and mount routes (without Socket.IO for now)
const routes = createRoutes(services, undefined, security.allowedOrigins);
app.route('/', routes);
// Create and mount routes (without Socket.IO for now)
const routes = createRoutes(services, undefined, security.allowedOrigins);
app.route('/', routes);
// Start Bun server
try {
server = Bun.serve({
port: PORT,
hostname: security.hostname,
maxRequestBodySize: 1_048_576,
fetch: async req => {
services.logger.debug(`Incoming request: ${req.method} ${req.url}`);
try {
const response = await app.fetch(req);
return response;
} catch (error) {
services.logger.error('Request handling error:', error);
return Bun.serve({
port: PORT,
hostname: security.hostname,
maxRequestBodySize: 1_048_576,
fetch: async req => {
services.logger.debug(`Incoming request: ${req.method} ${req.url}`);
try {
const response = await app.fetch(req);
return response;
} catch (error) {
services.logger.error('Request handling error:', error);
return new Response('Internal Server Error', { status: 500 });
}
},
error: error => {
services.logger.error('Server error:', error);
return new Response('Internal Server Error', { status: 500 });
}
},
error: error => {
services.logger.error('Server error:', error);
return new Response('Internal Server Error', { status: 500 });
},
});
services.logger.info(`Orchestrator service started on port ${server?.port ?? PORT}`);
services.logger.info(`Server hostname: ${server.hostname}`);
services.logger.info(`Server URL: http://${server.hostname}:${server.port}`);
// Test that server is actually listening
setTimeout(async () => {
try {
const testResponse = await fetch(`http://localhost:${server?.port ?? PORT}/health`);
services.logger.info(
`Server self-test: ${testResponse.status} ${testResponse.statusText}`
);
} catch (error) {
services.logger.error('Server self-test failed:', error);
}
}, 1000);
} catch (error) {
services.logger.error('Failed to start Bun server:', error);
throw error;
}
},
});
}
);
server = started.server;
runtime = started.runtime;
const services = runtime.services;
services.logger.info(`Orchestrator service started on port ${server.port}`);
services.logger.info('Service metadata:', {
version: '1.0.0',
description: 'Trading System Orchestrator',
@ -151,19 +137,11 @@ async function main() {
services.logger.info('Orchestrator service shutting down...', { signal });
const deadline = setTimeout(() => process.exit(1), 10_000);
deadline.unref();
// Stop accepting connections, but let the active run persist its terminal state.
const stopped = server?.stop();
let exitCode = 0;
try {
const failures: unknown[] = [];
for (const close of [
() => services.custom?.PaperDeploymentHost?.shutdown(),
() => services.custom?.CanonicalPaperRuntime?.shutdown(),
() => services.custom?.BacktestRunner?.shutdown(),
() => services.queueManager?.shutdown(),
() => services.custom?.ModeManager?.shutdown(),
() => stopped,
]) {
// Finish accepted HTTP requests, drain durable work, then close shared clients.
for (const close of [() => server?.stop(), () => runtime?.shutdown()]) {
try {
await close();
} catch (error) {
@ -185,6 +163,12 @@ async function main() {
process.on('SIGINT', () => void shutdown('SIGINT'));
process.on('SIGTERM', () => void shutdown('SIGTERM'));
} catch (error) {
server?.stop(true);
try {
await runtime?.shutdown();
} catch (cleanupError) {
logger.error('Orchestrator startup cleanup failed', { cleanupError });
}
logger.error('Failed to start orchestrator service:', error);
process.exit(1);
}

View file

@ -0,0 +1,77 @@
import type { OrchestratorServices } from './types';
export interface OrchestratorRuntime {
services: OrchestratorServices;
shutdown(): Promise<void>;
}
const workShutdown = new WeakMap<OrchestratorServices, Promise<void>>();
/** Registration rollback and application shutdown share the same work lifetime. */
export function stopOrchestratorWork(services: OrchestratorServices): Promise<void> {
let pending = workShutdown.get(services);
if (!pending) {
pending = (async () => {
const failures: unknown[] = [];
for (const close of [
() => services.custom?.PaperDeploymentHost?.shutdown(),
() => services.custom?.CanonicalPaperRuntime?.shutdown(),
() => services.custom?.BacktestRunner?.shutdown(),
]) {
try {
await close();
} catch (error) {
failures.push(error);
}
}
if (failures.length) {
throw new AggregateError(failures, 'Orchestrator work shutdown failed');
}
})();
workShutdown.set(services, pending);
}
return pending;
}
/** Shared clients stay open until work has drained or reported its cleanup failure. */
export function ownOrchestratorRuntime(
services: OrchestratorServices,
closeSharedServices: () => Promise<void>
): OrchestratorRuntime {
let shutdown: Promise<void> | undefined;
return {
services,
shutdown: () =>
(shutdown ??= (async () => {
const failures: unknown[] = [];
for (const close of [() => stopOrchestratorWork(services), closeSharedServices]) {
try {
await close();
} catch (error) {
failures.push(error);
}
}
if (failures.length) {
throw new AggregateError(failures, 'Orchestrator shutdown failed');
}
})()),
};
}
/** Route setup and HTTP bind failure release the already initialized runtime. */
export async function startOrchestratorServer<Server>(
create: () => Promise<OrchestratorRuntime>,
listen: (services: OrchestratorServices) => Server
): Promise<{ runtime: OrchestratorRuntime; server: Server }> {
const runtime = await create();
try {
return { runtime, server: listen(runtime.services) };
} catch (error) {
try {
await runtime.shutdown();
} catch (cleanupError) {
runtime.services.logger.error('Orchestrator startup cleanup failed', { cleanupError });
}
throw error;
}
}

View file

@ -8,12 +8,31 @@ import {
resolvePaperComposition,
type OrchestratorRole,
} from './container';
import { ownOrchestratorRuntime } from './runtime';
import type { OrchestratorServices } from './types';
type OwnedServices = Awaited<ReturnType<ServiceContainerBuilder['buildOwned']>>;
function buildSharedServices(config: StockAppConfig): Promise<OwnedServices> {
return new ServiceContainerBuilder()
.withConfig(config)
.withOptions({
enableMongoDB: config.database?.mongodb?.enabled ?? false,
enablePostgres: config.database?.postgres?.enabled ?? false,
enableCache: config.database?.dragonfly?.enabled ?? false,
enableQueue: config.queue?.enabled ?? false,
enableQuestDB: config.database?.questdb?.enabled ?? false,
enableBrowser: false,
enableProxy: false,
})
.buildOwned();
}
/** Use the shared builder for connection setup and adapter ownership. */
export async function createContainer(
config: StockAppConfig,
options: { role?: OrchestratorRole } = {}
options: { role?: OrchestratorRole } = {},
build: (config: StockAppConfig) => Promise<OwnedServices> = buildSharedServices
) {
const settings = config.services?.orchestrator;
if (settings?.defaultMode === 'live') {
@ -43,27 +62,28 @@ export async function createContainer(
throw new Error('Canonical paper requires durable PostgreSQL custody');
}
const container = await new ServiceContainerBuilder()
.withConfig(config)
.withOptions({
enableMongoDB: config.database?.mongodb?.enabled ?? false,
enablePostgres: config.database?.postgres?.enabled ?? false,
enableCache: config.database?.dragonfly?.enabled ?? false,
enableQueue: config.queue?.enabled ?? false,
enableQuestDB: config.database?.questdb?.enabled ?? false,
enableBrowser: false,
enableProxy: false,
})
.build();
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,
canonicalPaper,
paperDeploymentHost,
});
return container.resolve('serviceContainer') as OrchestratorServices;
const owned = await build(config);
let runtime: ReturnType<typeof ownOrchestratorRuntime> | undefined;
try {
const services = owned.container.resolve('serviceContainer') as OrchestratorServices;
runtime = ownOrchestratorRuntime(services, owned.shutdown);
await registerOrchestratorServices(owned.container, {
role,
useRustEngine,
maxConcurrent,
allowSyntheticData: config.services?.orchestrator?.backtesting?.allowSyntheticData ?? false,
syntheticSeed: config.services?.orchestrator?.backtesting?.syntheticSeed ?? 42,
nativeExecutionTimeoutMs: config.services?.orchestrator?.backtesting?.executionTimeoutMs,
canonicalPaper,
paperDeploymentHost,
});
return runtime;
} catch (error) {
try {
await (runtime ? runtime.shutdown() : owned.shutdown());
} catch (cleanupError) {
runtime?.services.logger.error('Orchestrator composition cleanup failed', { cleanupError });
}
throw error;
}
}

View file

@ -2731,10 +2731,10 @@
],
"assignment": "/root/implement_cl14",
"branch": "cleanup/cl14-canonical-contracts",
"completed_commit": null,
"completed_commit": "21666242",
"blocker": null,
"release_gates": [],
"integration_state": "validated_pending_commit",
"integration_state": "validated_committed",
"integration_base": "700ee09c",
"completion_evidence": "orchestrator-engine-cleanup.md",
"worktree": "/tmp/stock-bot-engine-cleanup-20261026/cl14",
@ -2744,7 +2744,8 @@
"focused": "91 pass,6888 assertions across6 files",
"postgres": "33 pass,181 assertions across canonical-durable-backtest and durable-backtest; disposable stock_bot_safety database/Redis15",
"static": "Orchestrator build, application typecheck, negative contract fixtures and diff checks pass"
}
},
"implementation_commit": "21666242"
},
{
"id": "CL15",
@ -2805,7 +2806,7 @@
"epic": "E11",
"priority": "P1",
"severity": "High",
"status": "in_progress",
"status": "done",
"dependencies": [],
"decision_dependencies": [],
"task_file": "backlog/tasks/CL16.md",
@ -2833,10 +2834,18 @@
"completed_commit": null,
"blocker": null,
"release_gates": [],
"integration_state": "not_started",
"integration_state": "validated_pending_commit",
"integration_base": "700ee09c",
"completion_evidence": "orchestrator-engine-cleanup.md",
"worktree": "/tmp/stock-bot-engine-cleanup-20261026/cl16"
"worktree": "/tmp/stock-bot-engine-cleanup-20261026/cl16",
"reviewed_by": "/root/review_cl16",
"review_notes": "Independent source review accepted;39 lifecycle/composition cases and17 architecture checks passed independently. Root completed native-worker10/33 and explicit authored-test types/lint, then full combined repository gate.",
"validation": {
"focused": "39 pass,166 assertions across lifecycle/composition tests; worker lifecycle10 pass,33 assertions",
"review": "Independent source/scope acceptance by review_cl16; no blocking findings",
"static": "Application typecheck, explicit new-test typecheck, scoped lint, formatting and diff pass",
"combined": "CARGO_BUILD_JOBS=2 bun run check: tooling132, utilities43, calculations44, integration1231, Rust150 passed;14 integration conditional skips and4 Rust ignored retained"
}
},
{
"id": "CL17",

View file

@ -38,3 +38,13 @@ The durable runner now requires canonical engine/repository capabilities. Legacy
Implemented by `/root/implement_cl14`; independently reviewed/integrated by `/root`. Root rebuilt the orchestrator and passed application typecheck/contract tests. Focused runner/workflow/worker/pool/isolation/architecture suite: 91 passed, 6,888 assertions. Disposable PostgreSQL canonical and retained durable-run suites: 33 passed, 181 assertions. No SQL/native/economic policy changes. Worker tests required execution outside the sandbox; two transient worktree Bun dependency-reading failures passed on separate reruns and root integration. Legacy-only provider-spy assertions were removed with the unused injection, not replaced with fabricated coverage. Full combined repository gate follows CL16 integration.
CL15 implementation commit: `bc2b8a89`.
### CL16 — accepted
`ServiceContainerBuilder.buildOwned()` adds an explicit shared-resource lifetime while preserving `build()` for existing callers. Orchestrator composition returns `{services, shutdown}`; registration rollback and normal shutdown share idempotent application cleanup. Startup route/bind failures release the runtime. Shutdown finishes accepted HTTP requests and durable work before closing queue/database/cache adapters. The obsolete ModeManager closer and unowned delayed self-test timer are removed from the canonical entrypoint.
Implemented by `/root`; independently reviewed by `/root/review_cl16` with no blocking findings. Focused lifecycle/composition tests: 39 passed, 166 assertions. Independent architecture rerun: 17 passed. Native worker lifecycle outside sandbox: 10 passed, 33 assertions. The new test was explicitly typechecked and linted because the default application tsconfig excludes tests; controlled fixture adapters have an explicit test-only container widening. Tests cover registration/resolution/bind failure, original-error retention, repeated stop, continued cleanup and a delayed terminal write before PostgreSQL closes.
Combined `CARGO_BUILD_JOBS=2 bun run check` passed on CL14+CL15+CL16: 132 tooling, 43 utility, 44 calculation, 1,231 integration and 150 Rust tests. Fourteen existing integration conditional skips and four Rust ignored tests remain. Builds, application/contract typechecks, lint and secret audit passed. Scoped disposable PostgreSQL gate remains the CL14 33-case result; no UI or financial schema/transition changed, so browser/full database suites were not rerun. Logs are under `/tmp/stock-bot-engine-cleanup-20261026/` (`combined-check.log`, `cl14-root-postgres.log`, `cl16-worker-accepted.log`). No performance profiling or activation was performed.
CL14 implementation commit: `21666242`. First wave completes CL14, CL15 and CL16; CL17–CL20 are the next ready tasks and CL21 remains conditional. Prior 68 task records retain their pre-wave state.

View file

@ -59,6 +59,11 @@ export class ServiceContainerBuilder {
}
async build(): Promise<AwilixContainer<ServiceDefinitions>> {
return (await this.buildOwned()).container;
}
/** Keep initialization and shutdown in one resource lifetime when the caller owns an app. */
async buildOwned() {
// Validate and prepare config
const validatedConfig = this.prepareConfig();
@ -71,13 +76,24 @@ export class ServiceContainerBuilder {
// Register services
this.registerServices(container, validatedConfig);
const lifecycleManager = new ServiceLifecycleManager();
// Initialize services if not skipped
if (!this.options.skipInitialization) {
const lifecycleManager = new ServiceLifecycleManager();
await lifecycleManager.initializeServices(container, this.options.initializationTimeout);
}
return container;
let shutdown: Promise<void> | undefined;
return {
container,
shutdown: () =>
(shutdown ??= (async () => {
try {
await lifecycleManager.shutdownServices(container);
} finally {
await container.dispose();
}
})()),
};
}
private prepareConfig(): AppConfig {

View file

@ -0,0 +1,150 @@
import { asValue, type AwilixContainer } from 'awilix';
import { expect, mock, test } from 'bun:test';
import { ServiceContainerBuilder } from '@stock-bot/di';
import type { StockAppConfig } from '@stock-bot/stock-config';
import { startOrchestratorServer } from '../../apps/stock/orchestrator/src/runtime';
import { createContainer } from '../../apps/stock/orchestrator/src/simple-container';
import type { OrchestratorServices } from '../../apps/stock/orchestrator/src/types';
import { logger } from '../fixtures/execution';
const config = { services: { orchestrator: { defaultMode: 'backtest' } } } as StockAppConfig;
async function resources(options: { registrationFailure?: Error; cleanupFailure?: Error } = {}) {
// Real owned builder/lifecycle; replace disabled adapters with controlled acquired resources.
// No client opens a socket and no global module mocking affects other tests.
const owned = await new ServiceContainerBuilder()
.withOptions({
enableCache: false,
enableQueue: false,
enableMongoDB: false,
enablePostgres: false,
enableQuestDB: false,
enableBrowser: false,
enableProxy: false,
})
.buildOwned();
const events: string[] = [];
const closed = new Map<string, number>();
const adapter = (name: string) => ({
async disconnect() {
events.push(name);
closed.set(name, (closed.get(name) ?? 0) + 1);
if (name === 'questdb' && options.cleanupFailure) {
throw options.cleanupFailure;
}
},
});
const postgres = adapter('postgres');
const queue = {
getQueue() {
if (options.registrationFailure) {
const runner = services.custom!.BacktestRunner!;
const shutdown = runner.shutdown.bind(runner);
runner.shutdown = mock(async () => {
events.push('runner');
await shutdown();
});
throw options.registrationFailure;
}
},
shutdown: mock(async () => {
events.push('queue');
}),
};
const services = { logger, postgres, queueManager: queue } as unknown as OrchestratorServices;
// The fixture supplies lifecycle-only adapters, not production database/query APIs.
(owned.container as AwilixContainer).register({
serviceContainer: asValue(services),
cache: asValue(adapter('cache')),
mongoClient: asValue(adapter('mongo')),
postgresClient: asValue(postgres),
questdbClient: asValue(adapter('questdb')),
queueManager: asValue(queue),
});
return { owned, events, closed, services, queue };
}
test('registration failure closes app work once then every shared resource, retaining original error', async () => {
const failure = new Error('queue registration failed');
const f = await resources({
registrationFailure: failure,
cleanupFailure: new Error('close failed'),
});
await expect(createContainer(config, {}, async () => f.owned)).rejects.toBe(failure);
expect(f.events).toEqual(['runner', 'queue', 'questdb', 'postgres', 'mongo', 'cache']);
expect(f.services.custom!.BacktestRunner!.shutdown).toHaveBeenCalledTimes(1);
await f.owned.shutdown();
expect([...f.closed.values()]).toEqual([1, 1, 1, 1]);
expect(f.queue.shutdown).toHaveBeenCalledTimes(1);
});
test('HTTP bind failure releases initialized runtime and preserves the bind error', async () => {
const failure = new Error('address already in use');
const f = await resources();
await expect(
startOrchestratorServer(
() => createContainer(config, {}, async () => f.owned),
() => {
throw failure;
}
)
).rejects.toBe(failure);
expect(f.events).toEqual(['queue', 'questdb', 'postgres', 'mongo', 'cache']);
expect(f.queue.shutdown).toHaveBeenCalledTimes(1);
});
test('normal repeated shutdown waits for durable work before closing PostgreSQL', async () => {
const f = await resources();
const { runtime, server } = await startOrchestratorServer(
() => createContainer(config, {}, async () => f.owned),
services => ({ services })
);
expect(server.services).toBe(runtime.services);
expect(f.events).toEqual([]);
let finish!: () => void;
const drain = new Promise<void>(resolve => {
finish = resolve;
});
runtime.services.custom!.BacktestRunner!.shutdown = mock(async () => {
await drain;
expect(f.closed.has('postgres')).toBe(false);
f.events.push('terminal-write');
});
const first = runtime.shutdown();
expect(runtime.shutdown()).toBe(first);
await Promise.resolve();
expect(f.events).toEqual([]);
finish();
await first;
await runtime.shutdown();
expect(f.events).toEqual(['terminal-write', 'queue', 'questdb', 'postgres', 'mongo', 'cache']);
expect(f.queue.shutdown).toHaveBeenCalledTimes(1);
expect([...f.closed.values()]).toEqual([1, 1, 1, 1]);
});
test('app cleanup failure still closes shared resources and is reported', async () => {
const f = await resources();
const runtime = await createContainer(config, {}, async () => f.owned);
runtime.services.custom!.BacktestRunner!.shutdown = mock(async () => {
throw new Error('runner close failed');
});
await expect(runtime.shutdown()).rejects.toThrow('Orchestrator shutdown failed');
expect(f.events).toEqual(['queue', 'questdb', 'postgres', 'mongo', 'cache']);
await expect(runtime.shutdown()).rejects.toThrow('Orchestrator shutdown failed');
expect(f.queue.shutdown).toHaveBeenCalledTimes(1);
});
test('service aggregate resolution failure releases the acquired shared owner', async () => {
const f = await resources();
const failure = new Error('service aggregate failed');
const resolve = f.owned.container.resolve.bind(f.owned.container);
f.owned.container.resolve = ((key: string, options?: object) => {
if (key === 'serviceContainer') {
throw failure;
}
return resolve(key, options);
}) as typeof f.owned.container.resolve;
await expect(createContainer(config, {}, async () => f.owned)).rejects.toBe(failure);
expect(f.queue.shutdown).toHaveBeenCalledTimes(1);
expect([...f.closed.values()]).toEqual([1, 1, 1, 1]);
});