import { randomUUID } from 'node:crypto'; import { DetailCapture } from '../../../observability/detail-capture.js'; import { performance } from 'node:perf_hooks'; import { Worker } from 'node:worker_threads'; import type { RuntimeDiagnosticSeverity } from '../../../framework/plugins/index.js'; import type { PerceptionAnalysisInput, PerceptionSpatialFacts, } from './contracts.js'; import type { PerceptionThreadLoaderConfig, PerceptionThreadModuleSpec, } from './perception-module-loader.js'; const WORKER_BOOTSTRAP_URL = new URL( '../../../framework/modules/runtime-module-worker-bootstrap.mjs', import.meta.url, ); const WORKER_HOST_URL = new URL('./perception-analysis-thread-worker.ts', import.meta.url).href; const DEFAULT_WORKERS = 10; const DEFAULT_WARM_WORKERS = 2; const MAX_WORKERS = 10; const START_TIMEOUT_MS = 20_000; const REPLACEMENT_RETRY_BASE_MS = 50; const REPLACEMENT_RETRY_MAX_MS = 2_000; export const PERCEPTION_ANALYSIS_IDLE_WORKER_TIMEOUT_MS = 30_000; type WorkerStartTrigger = 'prewarm' | 'pressure' | 'replacement'; export interface PerceptionAnalysisJob { readonly moduleId: string; readonly input: Readonly; } export interface PerceptionAnalysisFailure { readonly errorCode: string; readonly messagePresent: boolean; readonly messageLength?: number; } export type PerceptionAnalysisResult = Readonly<{ moduleId: string; durationMs: number; } & ( | { outcome: 'fulfilled'; analysis: unknown } | { outcome: 'rejected'; failure: PerceptionAnalysisFailure } )>; export interface PerceptionAnalysisBatch { readonly results: readonly PerceptionAnalysisResult[]; readonly queueDurationMs: number; readonly durationMs: number; readonly workerCount: number; readonly workerHeapUsedBytes: number; readonly workerPoolHeapUsedBytes: number; } export interface PerceptionAnalysisThreadPoolSnapshot { readonly state: 'new' | 'starting' | 'running' | 'stopping' | 'stopped'; readonly minWorkers: number; readonly maxWorkers: number; readonly workerCount: number; readonly idleWorkerCount: number; readonly busyWorkerCount: number; readonly queuedBatchCount: number; readonly queuedJobCount: number; readonly inFlightBatchCount: number; readonly startedWorkerCount: number; readonly retiredWorkerCount: number; readonly startupWorkerHeapUsedBytes: number; readonly workerHeapUsedBytes: number; readonly peakWorkerHeapUsedBytes: number; } export interface PerceptionAnalysisThreadPoolOptions { /** Accepted frame batches, independent of the number of module-analysis Workers. */ readonly maxPendingBatches?: number; /** Prewarm and retain the configured pool instead of importing Workers during overload. */ readonly fixedWorkers?: boolean; readonly modules: readonly PerceptionThreadModuleSpec[]; readonly loader: PerceptionThreadLoaderConfig; readonly spatialFacts: PerceptionSpatialFacts; readonly maxWorkers?: number; readonly maxOldGenerationSizeMb?: number; /** Samples Worker heaps only for explicit full diagnostics. */ readonly diagnosticsEnabled?: boolean; readonly diagnostic?: ( name: string, attributes?: Readonly>, severity?: RuntimeDiagnosticSeverity, ) => void; } interface PendingBatch { readonly captureRequestId?: string; readonly requestId: string; readonly jobs: readonly PerceptionAnalysisJob[]; readonly signal: AbortSignal; readonly enqueuedAt: number; readonly resolve: (value: PerceptionAnalysisBatch) => void; readonly reject: (error: Error) => void; readonly onAbort: () => void; readonly results: Array; firstAssignedAt?: number; remaining: number; peakWorkerHeapUsedBytes: number; settled: boolean; } interface PendingModuleJob { readonly requestId: string; readonly batch: PendingBatch; readonly index: number; readonly job: PerceptionAnalysisJob; assignedAt?: number; slot?: WorkerSlot; } interface WorkerSlot { readonly id: number; readonly worker: Worker; state: 'starting' | 'idle' | 'busy' | 'retiring'; current?: PendingModuleJob; readyResolve?: () => void; readyReject?: (error: Error) => void; readyHeapUsedBytes?: number; idleSince?: number; retirement?: Promise; } interface ReplacementDelay { readonly timer: ReturnType; readonly resolve: () => void; } interface WorkerReadyMessage { readonly type: 'ready'; readonly poolId: string; readonly heapUsedBytes?: number; } interface WorkerAnalysisMessage { readonly type: 'analysis'; readonly poolId: string; readonly requestId: string; readonly results: readonly PerceptionAnalysisResult[]; readonly heapUsedBytes?: number; } interface WorkerErrorMessage { readonly type: 'error'; readonly poolId: string; readonly requestId?: string; readonly code: string; readonly moduleId?: string; readonly heapUsedBytes?: number; } interface PerceptionAnalysisWorkerStartError extends Error { readonly moduleId?: string; } /** Returns the module attributed by the Worker startup handshake, when known. */ export function perceptionAnalysisWorkerStartModuleId(error: unknown): string | undefined { if (!error || typeof error !== 'object') return undefined; const moduleId = (error as Partial).moduleId; return typeof moduleId === 'string' && moduleId ? moduleId : undefined; } function roundedElapsed(startedAt: number): number { return Math.round(Math.max(0, performance.now() - startedAt) * 1_000) / 1_000; } function asError(value: unknown, fallback: string): Error { return value instanceof Error ? value : new Error(typeof value === 'string' ? value : fallback); } function abortError(signal: AbortSignal): Error { return asError(signal.reason, 'perception_analysis_aborted'); } function moduleFailure(error: unknown): PerceptionAnalysisFailure { const message = error instanceof Error ? error.message : String(error); const prefix = /^([A-Za-z][A-Za-z0-9_.-]{0,119})(?::|$)/.exec(message.trim())?.[1]; return { errorCode: prefix ?? 'PERCEPTION_MODULE_FAILED', messagePresent: message.length > 0, ...(message ? { messageLength: message.length } : {}), }; } export class PerceptionAnalysisThreadPool { private readonly poolId = randomUUID(); private readonly minWorkers: number; private readonly maxWorkers: number; private readonly maxPendingBatches: number; private readonly maxOldGenerationSizeMb: number; private state: PerceptionAnalysisThreadPoolSnapshot['state'] = 'new'; private readonly slots = new Set(); private readonly queue: PendingModuleJob[] = []; private readonly inFlight = new Set(); private readonly spawnTasks = new Set>(); private startTask?: Promise; private stopTask?: Promise; private replacementTask?: Promise; private replacementDelay?: ReplacementDelay; private idleShrinkTimer?: ReturnType; private replacementFailureCount = 0; private nextSlotId = 1; private startedWorkerCount = 0; private retiredWorkerCount = 0; private peakWorkerHeapUsedBytes = 0; constructor(private readonly options: PerceptionAnalysisThreadPoolOptions) { const maxWorkers = options.maxWorkers ?? DEFAULT_WORKERS; if (!Number.isInteger(maxWorkers) || maxWorkers <= 0 || maxWorkers > MAX_WORKERS) { throw new TypeError(`maxWorkers must be between 1 and ${MAX_WORKERS}.`); } this.maxWorkers = maxWorkers; this.maxPendingBatches = options.maxPendingBatches ?? maxWorkers; if (!Number.isInteger(this.maxPendingBatches) || this.maxPendingBatches < 1 || this.maxPendingBatches > MAX_WORKERS) { throw new Error('perception_pending_batch_limit_invalid'); } this.minWorkers = options.fixedWorkers ? maxWorkers : Math.min(DEFAULT_WARM_WORKERS, maxWorkers); this.maxOldGenerationSizeMb = Math.max(16, Math.min( 256, Math.floor(options.maxOldGenerationSizeMb ?? 64), )); const ids = options.modules.map(({ moduleId }) => moduleId); if (new Set(ids).size !== ids.length) throw new Error('perception_thread_module_duplicate'); } start(): Promise { if (this.state === 'running') return Promise.resolve(); if (this.state === 'starting') return this.startTask!; if (this.state === 'stopping' || this.state === 'stopped') { return Promise.reject(new Error('perception_analysis_pool_stopped')); } this.state = 'starting'; const startedAt = performance.now(); this.startTask = this.startInternal().then(() => { if (this.state !== 'starting') throw new Error('perception_analysis_pool_stopped'); this.state = 'running'; this.emitDiagnostic('perception.analysis_pool.started', { worker_count: this.slots.size, min_worker_count: this.minWorkers, max_worker_count: this.maxWorkers, started_worker_count: this.startedWorkerCount, retired_worker_count: this.retiredWorkerCount, module_count: this.options.modules.length, duration_ms: roundedElapsed(startedAt), worker_max_old_generation_mb: this.maxOldGenerationSizeMb, startup_worker_heap_used_bytes: this.currentWorkerHeapUsedBytes(), peak_worker_heap_used_bytes: this.peakWorkerHeapUsedBytes, }, 'info'); }).catch(async (error) => { if (this.state === 'starting') this.state = 'stopped'; await Promise.allSettled([...this.slots].map((slot) => this.retireSlot(slot, 'start_failed'))); throw error; }); return this.startTask; } async analyze( jobs: readonly PerceptionAnalysisJob[], signal: AbortSignal, ): Promise { const capture = this.detailCapture ??= new DetailCapture('perception_io', (name, attributes, severity) => this.emitDiagnostic(name, attributes, severity)); if (!capture.enabled) return this.analyzeInternal(jobs, signal); const requestId = randomUUID(); for (const job of jobs) capture.emit('input', () => ({ invocation_id: `${requestId}:${job.moduleId}`, module_id: job.moduleId, operation: 'analyze', tick: job.input.frame.tick, frame_seq: job.input.frame.frameSeq, game_id: job.input.frame.gameState.game_id, input: job.input, stage: 'requested' })); try { return await this.analyzeInternal(jobs, signal, requestId); } catch (error) { for (const job of jobs) capture.emit(signal.aborted ? 'cancelled' : 'failed', () => ({ invocation_id: `${requestId}:${job.moduleId}`, module_id: job.moduleId, operation: 'analyze', cancelled: signal.aborted, tick: job.input.frame.tick, frame_seq: job.input.frame.frameSeq, stage: 'batch_discarded', error: error instanceof Error ? error.message : String(error) })); throw error; } } private detailCapture?: DetailCapture; private async analyzeInternal(jobs: readonly PerceptionAnalysisJob[], signal: AbortSignal, captureRequestId?: string): Promise { signal.throwIfAborted(); await this.start(); signal.throwIfAborted(); if (this.state !== 'running') throw new Error('perception_analysis_pool_not_running'); if (jobs.length === 0) { return { results: [], queueDurationMs: 0, durationMs: 0, workerCount: this.slots.size, workerHeapUsedBytes: 0, workerPoolHeapUsedBytes: this.currentWorkerHeapUsedBytes(), }; } if (this.inFlight.size >= this.maxPendingBatches) { throw new Error('perception_analysis_window_full'); } const configured = new Set(this.options.modules.map(({ moduleId }) => moduleId)); const ids = jobs.map(({ moduleId }) => moduleId); if (new Set(ids).size !== ids.length || ids.some((id) => !configured.has(id))) { throw new Error('perception_analysis_jobs_invalid'); } return new Promise((resolve, reject) => { const pending: PendingBatch = { captureRequestId, requestId: randomUUID(), jobs, signal, enqueuedAt: performance.now(), resolve, reject, results: new Array(jobs.length), remaining: jobs.length, peakWorkerHeapUsedBytes: 0, settled: false, onAbort: () => this.abortBatch(pending), }; signal.addEventListener('abort', pending.onAbort, { once: true }); this.inFlight.add(pending); this.queue.push(...jobs.map((job, index): PendingModuleJob => ({ requestId: `${pending.requestId}:${index}`, batch: pending, index, job, }))); this.pump(); }); } stop(): Promise { if (this.state === 'stopped') return Promise.resolve(); if (this.state === 'stopping') return this.stopTask ?? Promise.resolve(); if (this.state === 'new') { this.state = 'stopped'; return Promise.resolve(); } this.state = 'stopping'; const task = this.stopInternal().finally(() => { this.state = 'stopped'; if (this.stopTask === task) this.stopTask = undefined; }); this.stopTask = task; return task; } private async stopInternal(): Promise { this.cancelReplacementDelay(); this.cancelIdleShrink(); const error = new Error('perception_analysis_pool_stopped'); for (const batch of [...this.inFlight]) this.rejectBatch(batch, error); await Promise.allSettled([...this.slots].map((slot) => this.retireSlot(slot, 'shutdown'))); await Promise.allSettled([...this.spawnTasks]); await this.startTask?.catch(() => {}); await Promise.allSettled([...this.slots].map((slot) => this.retireSlot(slot, 'shutdown'))); this.emitDiagnostic('perception.analysis_pool.stopped', { worker_count: this.slots.size, min_worker_count: this.minWorkers, max_worker_count: this.maxWorkers, started_worker_count: this.startedWorkerCount, retired_worker_count: this.retiredWorkerCount, worker_heap_used_bytes: this.currentWorkerHeapUsedBytes(), peak_worker_heap_used_bytes: this.peakWorkerHeapUsedBytes, }, 'info'); } snapshot(): PerceptionAnalysisThreadPoolSnapshot { const values = [...this.slots]; return { state: this.state, minWorkers: this.minWorkers, maxWorkers: this.maxWorkers, workerCount: values.length, idleWorkerCount: values.filter(({ state }) => state === 'idle').length, busyWorkerCount: values.filter(({ state }) => state === 'busy').length, queuedBatchCount: new Set(this.queue.map(({ batch }) => batch.requestId)).size, queuedJobCount: this.queue.length, inFlightBatchCount: this.inFlight.size, startedWorkerCount: this.startedWorkerCount, retiredWorkerCount: this.retiredWorkerCount, startupWorkerHeapUsedBytes: this.currentWorkerHeapUsedBytes(), workerHeapUsedBytes: this.currentWorkerHeapUsedBytes(), peakWorkerHeapUsedBytes: this.peakWorkerHeapUsedBytes, }; } private async startInternal(): Promise { // Keep the common case small while preserving the ten-frame in-flight // window. Extra slots are started one at a time only when all warm slots // are occupied and another frame is queued. await Promise.all(Array.from( { length: this.minWorkers }, () => this.spawnSlot('prewarm'), )); } private async spawnSlot(trigger: WorkerStartTrigger): Promise { const worker = new Worker(WORKER_BOOTSTRAP_URL, { execArgv: [], resourceLimits: { maxOldGenerationSizeMb: this.maxOldGenerationSizeMb }, stderr: true, stdout: true, workerData: { runtimeModuleBootstrap: { hostUrl: WORKER_HOST_URL, hooksUrl: this.options.loader.hooksUrl, sdkAliases: this.options.loader.sdkAliases, esmModuleRoots: [...new Set(this.options.modules.map((module) => ( new URL('.', module.sourceUrl).href )))], }, poolId: this.poolId, spatialFacts: this.options.spatialFacts, modules: this.options.modules, diagnosticsEnabled: this.options.diagnosticsEnabled === true, }, }); const slot: WorkerSlot = { id: this.nextSlotId++, worker, state: 'starting' }; this.slots.add(slot); worker.stdout?.on('data', (chunk: Buffer) => this.emitDiagnostic( 'perception.analysis_worker.stdout', { bytes: chunk.length, slot_id: slot.id }, )); worker.stderr?.on('data', (chunk: Buffer) => this.emitDiagnostic( 'perception.analysis_worker.stderr', { bytes: chunk.length, slot_id: slot.id }, )); worker.on('message', (message: unknown) => this.handleMessage(slot, message)); worker.once('error', (error) => this.failSlot(slot, error)); worker.once('exit', (code) => { if (slot.state !== 'retiring') { this.failSlot(slot, new Error(`perception_analysis_worker_exited:${code}`)); } }); let timer: ReturnType | undefined; try { await new Promise((resolve, reject) => { slot.readyResolve = resolve; slot.readyReject = reject; timer = setTimeout(() => reject(new Error('perception_analysis_worker_start_timeout')), START_TIMEOUT_MS); timer.unref?.(); }); if (this.state !== 'starting' && this.state !== 'running') { throw new Error('perception_analysis_pool_stopped'); } slot.state = 'idle'; slot.idleSince = performance.now(); this.startedWorkerCount += 1; this.peakWorkerHeapUsedBytes = Math.max( this.peakWorkerHeapUsedBytes, this.currentWorkerHeapUsedBytes(), ); this.emitDiagnostic('perception.analysis_worker.started', { slot_id: slot.id, worker_count: this.readyWorkerCount(), min_worker_count: this.minWorkers, max_worker_count: this.maxWorkers, trigger, worker_heap_used_bytes: slot.readyHeapUsedBytes ?? 0, }, 'info'); } catch (error) { await this.retireSlot(slot, 'start_failed'); throw error; } finally { if (timer) clearTimeout(timer); slot.readyResolve = undefined; slot.readyReject = undefined; } } private pump(): void { if (this.state !== 'running') return; while (this.queue.length > 0) { const slot = [...this.slots].find((candidate) => candidate.state === 'idle'); if (!slot) break; const moduleJob = this.queue.shift()!; const { batch } = moduleJob; if (batch.settled || batch.signal.aborted) { if (!batch.settled) this.rejectBatch(batch, abortError(batch.signal)); continue; } slot.state = 'busy'; slot.idleSince = undefined; slot.current = moduleJob; moduleJob.slot = slot; moduleJob.assignedAt = performance.now(); batch.firstAssignedAt ??= moduleJob.assignedAt; try { slot.worker.postMessage({ type: 'analyze', poolId: this.poolId, requestId: moduleJob.requestId, jobs: [moduleJob.job], }); } catch (error) { this.failModuleJob(moduleJob, asError(error, 'perception_analysis_submit_failed')); slot.current = undefined; void this.retireSlot(slot, 'submit_failed'); } } this.rebalanceCapacity(); } private handleMessage(slot: WorkerSlot, value: unknown): void { if (!value || typeof value !== 'object' || Array.isArray(value)) { this.failSlot(slot, new Error('perception_analysis_protocol_invalid')); return; } const message = value as WorkerReadyMessage | WorkerAnalysisMessage | WorkerErrorMessage; if (message.poolId !== this.poolId) { this.failSlot(slot, new Error('perception_analysis_pool_mismatch')); return; } if (message.type === 'ready') { if (slot.state !== 'starting') { this.failSlot(slot, new Error('perception_analysis_ready_unexpected')); return; } if (this.options.diagnosticsEnabled === true && ( !Number.isFinite(message.heapUsedBytes) || Number(message.heapUsedBytes) < 0 )) { this.failSlot(slot, new Error('perception_analysis_worker_memory_invalid')); return; } if (typeof message.heapUsedBytes === 'number') { slot.readyHeapUsedBytes = message.heapUsedBytes; } slot.readyResolve?.(); return; } if (message.type === 'error') { if (typeof message.heapUsedBytes === 'number' && Number.isFinite(message.heapUsedBytes)) { slot.readyHeapUsedBytes = Math.max(0, message.heapUsedBytes); this.peakWorkerHeapUsedBytes = Math.max( this.peakWorkerHeapUsedBytes, this.currentWorkerHeapUsedBytes(), ); } const error: PerceptionAnalysisWorkerStartError = new Error(typeof message.code === 'string' ? message.code : 'perception_analysis_worker_failed'); const moduleId = typeof message.moduleId === 'string' && this.options.modules.some((module) => module.moduleId === message.moduleId) ? message.moduleId : undefined; if (slot.state === 'starting') { if (moduleId) Object.defineProperty(error, 'moduleId', { value: moduleId, enumerable: true }); this.failSlot(slot, error); return; } if (slot.current && (!message.requestId || message.requestId === slot.current.requestId)) { const moduleJob = slot.current; slot.current = undefined; this.failModuleJob(moduleJob, error); } void this.retireSlot(slot, 'worker_error'); return; } if (message.type !== 'analysis' || !Array.isArray(message.results)) { this.failSlot(slot, new Error('perception_analysis_protocol_invalid')); return; } if (this.options.diagnosticsEnabled === true && ( !Number.isFinite(message.heapUsedBytes) || Number(message.heapUsedBytes) < 0 )) { this.failSlot(slot, new Error('perception_analysis_worker_memory_invalid')); return; } const moduleJob = slot.current; if (!moduleJob || message.requestId !== moduleJob.requestId) { this.failSlot(slot, new Error('perception_analysis_request_mismatch')); return; } const { batch } = moduleJob; const result = message.results[0]; if ( message.results.length !== 1 || result?.moduleId !== moduleJob.job.moduleId ) { slot.current = undefined; this.failModuleJob(moduleJob, new Error('perception_analysis_results_invalid')); void this.retireSlot(slot, 'invalid_results'); return; } slot.current = undefined; slot.state = 'idle'; slot.idleSince = performance.now(); if (typeof message.heapUsedBytes === 'number') slot.readyHeapUsedBytes = message.heapUsedBytes; this.peakWorkerHeapUsedBytes = Math.max( this.peakWorkerHeapUsedBytes, this.currentWorkerHeapUsedBytes(), ); moduleJob.slot = undefined; this.captureModuleResult(moduleJob, result); if (!batch.settled) { batch.results[moduleJob.index] = result; batch.remaining -= 1; batch.peakWorkerHeapUsedBytes = Math.max( batch.peakWorkerHeapUsedBytes, message.heapUsedBytes ?? 0, ); if (batch.remaining === 0) this.resolveBatch(batch); } this.pump(); } private abortBatch(batch: PendingBatch): void { if (batch.settled) return; const slots = [...this.slots].filter(({ current }) => current?.batch === batch); this.rejectBatch(batch, abortError(batch.signal)); // Worker threads cannot interrupt synchronous module code. Retire only // slots executing jobs from this stale frame; other frame jobs survive. for (const slot of slots) void this.retireSlot(slot, 'analysis_aborted'); this.pump(); } private resolveBatch( batch: PendingBatch, ): void { if (batch.settled) return; batch.settled = true; batch.signal.removeEventListener('abort', batch.onAbort); this.inFlight.delete(batch); const results = batch.results.filter((result): result is PerceptionAnalysisResult => !!result); if (results.length !== batch.jobs.length) { batch.reject(new Error('perception_analysis_results_incomplete')); return; } batch.resolve({ results, queueDurationMs: Math.round(Math.max( 0, (batch.firstAssignedAt ?? performance.now()) - batch.enqueuedAt, ) * 1_000) / 1_000, durationMs: roundedElapsed(batch.enqueuedAt), workerCount: this.slots.size, workerHeapUsedBytes: batch.peakWorkerHeapUsedBytes, workerPoolHeapUsedBytes: this.currentWorkerHeapUsedBytes(), }); } private rejectBatch(batch: PendingBatch, error: Error): void { if (batch.settled) return; batch.settled = true; batch.signal.removeEventListener('abort', batch.onAbort); this.inFlight.delete(batch); for (let index = this.queue.length - 1; index >= 0; index -= 1) { if (this.queue[index]!.batch === batch) this.queue.splice(index, 1); } batch.reject(error); } private failModuleJob(moduleJob: PendingModuleJob, error: Error): void { const { batch } = moduleJob; moduleJob.slot = undefined; if (batch.settled || batch.results[moduleJob.index]) return; batch.results[moduleJob.index] = { moduleId: moduleJob.job.moduleId, durationMs: roundedElapsed(moduleJob.assignedAt ?? batch.enqueuedAt), outcome: 'rejected', failure: moduleFailure(error), }; this.captureModuleResult(moduleJob, batch.results[moduleJob.index]!); batch.remaining -= 1; if (batch.remaining === 0) this.resolveBatch(batch); } private captureModuleResult(job: PendingModuleJob, result: PerceptionAnalysisResult): void { if (!job.batch.captureRequestId) return; this.detailCapture?.emit('output', () => ({ invocation_id: `${job.batch.captureRequestId}:${job.job.moduleId}`, worker_request_id: job.requestId, module_id: job.job.moduleId, operation: 'analyze', tick: job.job.input.frame.tick, frame_seq: job.job.input.frame.frameSeq, game_id: job.job.input.frame.gameState.game_id, outcome: result.outcome, stage: job.batch.settled ? 'late_result' : 'analysis_only_not_committed', output: result, })); } private failSlot(slot: WorkerSlot, error: Error): void { slot.readyReject?.(error); if (slot.current) { const moduleJob = slot.current; slot.current = undefined; this.failModuleJob(moduleJob, error); } void this.retireSlot(slot, 'failed'); } private retireSlot(slot: WorkerSlot, reason: string): Promise { if (slot.retirement) return slot.retirement; slot.state = 'retiring'; if (slot.current) { const moduleJob = slot.current; slot.current = undefined; this.failModuleJob(moduleJob, new Error(`perception_analysis_worker_retired:${reason}`)); } const retirement = Promise.resolve().then(() => slot.worker.terminate()).catch(() => -1).then(() => { this.slots.delete(slot); this.retiredWorkerCount += 1; this.emitDiagnostic('perception.analysis_worker.retired', { slot_id: slot.id, reason, worker_count: this.slots.size, min_worker_count: this.minWorkers, max_worker_count: this.maxWorkers, }, reason === 'idle' ? 'info' : 'debug'); if (this.state === 'running') { this.pump(); } }); slot.retirement = retirement; // A retiring Worker may still be waiting for its ready message. Rejecting // that wait makes stop/replacement cancellation immediate instead of // leaving start() parked on the 20-second bootstrap timeout. slot.readyReject?.(new Error(`perception_analysis_worker_retired:${reason}`)); if (this.state === 'running') this.pump(); return retirement; } private scheduleReplacement(): void { if (this.state !== 'running' || this.activeWorkerCount() >= this.desiredWorkerCount()) return; if (this.replacementTask) return; const delayMs = this.replacementRetryDelayMs(); let trigger: WorkerStartTrigger = this.activeWorkerCount() < this.minWorkers ? 'replacement' : 'pressure'; let task!: Promise; task = this.waitForReplacementDelay(delayMs).then(async () => { if (this.state !== 'running' || this.activeWorkerCount() >= this.desiredWorkerCount()) return; trigger = this.activeWorkerCount() < this.minWorkers ? 'replacement' : 'pressure'; await this.spawnSlot(trigger); this.replacementFailureCount = 0; this.pump(); }).catch((error) => { if (this.state !== 'running') return; this.replacementFailureCount += 1; this.emitDiagnostic('perception.analysis_worker.replacement_failed', { error_code: error instanceof Error ? error.message.split(':', 1)[0] : 'perception_analysis_worker_start_failed', consecutive_failures: this.replacementFailureCount, retry_delay_ms: this.replacementRetryDelayMs(), worker_count: this.activeWorkerCount(), queued_batch_count: new Set(this.queue.map(({ batch }) => batch.requestId)).size, queued_job_count: this.queue.length, trigger, }, 'error'); }).finally(() => { this.spawnTasks.delete(task); if (this.replacementTask === task) this.replacementTask = undefined; this.pump(); }); this.replacementTask = task; this.spawnTasks.add(task); } private replacementRetryDelayMs(): number { if (this.replacementFailureCount <= 0) return 0; const exponent = Math.min(8, this.replacementFailureCount - 1); return Math.min(REPLACEMENT_RETRY_MAX_MS, REPLACEMENT_RETRY_BASE_MS * (2 ** exponent)); } private waitForReplacementDelay(delayMs: number): Promise { if (delayMs <= 0) return Promise.resolve(); return new Promise((resolve) => { let settled = false; let timer!: ReturnType; const finish = () => { if (settled) return; settled = true; clearTimeout(timer); if (this.replacementDelay?.timer === timer) this.replacementDelay = undefined; resolve(); }; timer = setTimeout(finish, delayMs); this.replacementDelay = { timer, resolve: finish }; }); } private cancelReplacementDelay(): void { const delay = this.replacementDelay; this.replacementDelay = undefined; delay?.resolve(); } private desiredWorkerCount(): number { const busyWorkerCount = [...this.slots].filter(({ state }) => state === 'busy').length; return Math.max( this.minWorkers, Math.min(this.maxWorkers, this.queue.length + busyWorkerCount), ); } private rebalanceCapacity(): void { if (this.state !== 'running') return; if (this.queue.length > 0 || this.activeWorkerCount() < this.minWorkers) { this.scheduleReplacement(); } this.scheduleIdleShrink(); } private scheduleIdleShrink(): void { if (this.state !== 'running' || this.idleShrinkTimer) return; const delayMs = this.nextIdleShrinkDelayMs(); if (delayMs === undefined) return; const timer = setTimeout(() => { if (this.idleShrinkTimer === timer) this.idleShrinkTimer = undefined; this.shrinkIdleWorkers(); this.scheduleIdleShrink(); }, delayMs); timer.unref?.(); this.idleShrinkTimer = timer; } private nextIdleShrinkDelayMs(): number | undefined { const excess = this.activeWorkerCount() - this.desiredWorkerCount(); if (excess <= 0) return undefined; const oldestIdleSince = [...this.slots].reduce((oldest, slot) => { if (slot.state !== 'idle' || slot.idleSince === undefined) return oldest; return oldest === undefined ? slot.idleSince : Math.min(oldest, slot.idleSince); }, undefined); if (oldestIdleSince === undefined) return undefined; return Math.max( 0, Math.ceil(oldestIdleSince + PERCEPTION_ANALYSIS_IDLE_WORKER_TIMEOUT_MS - performance.now()), ); } private cancelIdleShrink(): void { if (!this.idleShrinkTimer) return; clearTimeout(this.idleShrinkTimer); this.idleShrinkTimer = undefined; } private shrinkIdleWorkers(): void { if (this.state !== 'running') return; // Recompute the floor at callback time. A timer scheduled under light load // must not retire capacity that a newer pressure burst already needs. const excess = this.activeWorkerCount() - this.desiredWorkerCount(); if (excess <= 0) return; const cutoff = performance.now() - PERCEPTION_ANALYSIS_IDLE_WORKER_TIMEOUT_MS; const idle = [...this.slots] .filter((slot) => ( slot.state === 'idle' && slot.idleSince !== undefined && slot.idleSince <= cutoff )) .sort((left, right) => left.idleSince! - right.idleSince!) .slice(0, excess); for (const slot of idle) void this.retireSlot(slot, 'idle'); } private activeWorkerCount(): number { return [...this.slots].filter(({ state }) => state !== 'retiring').length; } private currentWorkerHeapUsedBytes(): number { return [...this.slots].reduce( (sum, slot) => sum + (slot.state === 'retiring' ? 0 : slot.readyHeapUsedBytes ?? 0), 0, ); } private readyWorkerCount(): number { return [...this.slots].filter(({ state }) => state === 'idle' || state === 'busy').length; } private emitDiagnostic( name: string, attributes?: Readonly>, severity: RuntimeDiagnosticSeverity = 'debug', ): void { try { this.options.diagnostic?.(name, attributes, severity); } catch { // Diagnostics are observational. A user callback must never change pool // lifecycle, frame delivery, or Worker replacement behavior. } } }