import { parentPort, workerData } from 'node:worker_threads'; import { performance } from 'node:perf_hooks'; import { PERCEPTION_PLUGIN_API_VERSION, type PerceptionApi, } from '../../../../sdk/perception-plugin/index.js'; import { createSpatialApi, type SpatialFacts } from '../../spatial-api.js'; import type { PerceptionAnalysisFailure, PerceptionAnalysisJob, PerceptionAnalysisResult, } from './perception-analysis-thread-pool.js'; import type { PerceptionThreadModuleSpec } from './perception-module-loader.js'; import { assertRuntimeModuleOutputSize } from '../../../framework/modules/runtime-module-output.js'; interface PerceptionAnalysisWorkerData { readonly poolId: string; readonly spatialFacts: SpatialFacts; readonly modules: readonly PerceptionThreadModuleSpec[]; readonly diagnosticsEnabled?: boolean; } interface PerceptionAnalysisRequest { readonly type: 'analyze'; readonly poolId: string; readonly requestId: string; readonly jobs: readonly PerceptionAnalysisJob[]; } interface PerceptionAnalysisResponse { readonly type: 'analysis'; readonly poolId: string; readonly requestId: string; readonly results: readonly PerceptionAnalysisResult[]; readonly heapUsedBytes?: number; } interface PerceptionAnalysisWorkerReady { readonly type: 'ready'; readonly poolId: string; readonly heapUsedBytes?: number; } interface PerceptionAnalysisWorkerError { readonly type: 'error'; readonly poolId: string; readonly requestId?: string; readonly code: string; /** Present only when Worker initialization can attribute the failure. */ readonly moduleId?: string; readonly heapUsedBytes?: number; } function roundedElapsed(startedAt: number): number { return Math.round(Math.max(0, performance.now() - startedAt) * 1_000) / 1_000; } function diagnosticMemory(): Readonly> { return data?.diagnosticsEnabled === true ? { heapUsedBytes: process.memoryUsage().heapUsed } : {}; } function deepFreeze(value: T, seen = new WeakSet()): T { if (!value || typeof value !== 'object' || Object.isFrozen(value)) return value; const object = value as object; if (seen.has(object)) return value; seen.add(object); for (const child of Object.values(object)) deepFreeze(child, seen); return Object.freeze(value); } function failureDetails(reason: unknown): PerceptionAnalysisFailure { const code = reason && typeof reason === 'object' && typeof (reason as any).code === 'string' ? (reason as any).code.trim() : ''; const message = reason instanceof Error ? reason.message : typeof reason === 'string' ? reason : ''; const prefix = /^([A-Za-z][A-Za-z0-9_.-]{0,119})(?::|$)/.exec(message.trim())?.[1]; return { errorCode: /^[A-Za-z][A-Za-z0-9_.-]{0,119}$/.test(code) ? code : prefix ?? 'PERCEPTION_MODULE_FAILED', messagePresent: message.length > 0, ...(message ? { messageLength: message.length } : {}), }; } async function analyzeJob( job: PerceptionAnalysisJob, api: PerceptionApi, modules: ReadonlyMap { analyze(input: PerceptionAnalysisJob['input'], api: PerceptionApi): unknown | Promise; }>, ): Promise { const startedAt = performance.now(); try { const ModuleClass = modules.get(job.moduleId); if (!ModuleClass) throw new Error('perception_analysis_module_unknown'); const analyzer = new ModuleClass(); if (typeof analyzer.analyze !== 'function') { throw new Error('perception_analysis_module_not_parallel'); } // postMessage already cloned the full batch away from Runtime. Freezing the // Worker-owned graph gives every parallel module the same immutable frame // without cloning the ten-frame history once again per module. const isolatedInput = deepFreeze(job.input); const analysis = structuredClone(await analyzer.analyze(isolatedInput, api)); assertRuntimeModuleOutputSize(analysis, 'perception_analysis_output'); return { moduleId: job.moduleId, outcome: 'fulfilled', durationMs: roundedElapsed(startedAt), analysis, }; } catch (error) { return { moduleId: job.moduleId, outcome: 'rejected', durationMs: roundedElapsed(startedAt), failure: failureDetails(error), }; } } const port = parentPort; if (!port) throw new Error('perception_analysis_worker_parent_missing'); const data = workerData as Partial | undefined; if ( !data || typeof data.poolId !== 'string' || !data.poolId || !data.spatialFacts || typeof data.spatialFacts !== 'object' || !Array.isArray(data.modules) ) throw new Error('perception_analysis_worker_data_invalid'); function send(value: PerceptionAnalysisResponse | PerceptionAnalysisWorkerReady | PerceptionAnalysisWorkerError): void { port!.postMessage(value); } const api: PerceptionApi = Object.freeze({ spatial: createSpatialApi(data.spatialFacts), }); const moduleClasses = new Map { analyze(input: PerceptionAnalysisJob['input'], api: PerceptionApi): unknown | Promise; }>(); let startupFailed = false; for (const spec of data.modules) { const moduleId = typeof spec?.moduleId === 'string' && spec.moduleId ? spec.moduleId : undefined; try { if ( !moduleId || typeof spec.sourceUrl !== 'string' || !spec.sourceUrl || moduleClasses.has(moduleId) ) throw new Error('perception_analysis_worker_module_invalid'); const loaded = await import(spec.sourceUrl) as Record; const ModuleClass = loaded.default; if (typeof ModuleClass !== 'function') throw new Error('perception_analysis_worker_class_missing'); const manifest = (ModuleClass as any).manifest; if ( manifest?.apiVersion !== PERCEPTION_PLUGIN_API_VERSION || manifest.id !== (spec.declaredId ?? moduleId) || manifest.execution !== 'parallel_analysis' ) { throw new Error('perception_analysis_worker_manifest_mismatch'); } moduleClasses.set(moduleId, ModuleClass as any); } catch { send({ type: 'error', poolId: data.poolId, code: 'perception_analysis_worker_module_load_failed', ...(moduleId ? { moduleId } : {}), ...diagnosticMemory(), }); startupFailed = true; break; } } let operationTail = Promise.resolve(); async function handle(value: unknown): Promise { if ( !value || typeof value !== 'object' || Array.isArray(value) || (value as Partial).type !== 'analyze' ) { send({ type: 'error', poolId: data!.poolId!, code: 'perception_analysis_worker_request_invalid', ...diagnosticMemory(), }); return; } const request = value as Partial; if ( request.poolId !== data!.poolId || typeof request.requestId !== 'string' || !request.requestId || !Array.isArray(request.jobs) ) { send({ type: 'error', poolId: data!.poolId!, ...(typeof request.requestId === 'string' ? { requestId: request.requestId } : {}), code: 'perception_analysis_worker_request_invalid', ...diagnosticMemory(), }); return; } const results = await Promise.all(request.jobs.map((job) => analyzeJob(job, api, moduleClasses))); send({ type: 'analysis', poolId: data!.poolId!, requestId: request.requestId, results, ...diagnosticMemory(), }); } if (!startupFailed) { port.on('message', (value: unknown) => { // A pool slot submits only one frame at a time. Keep this guard in the host // so a parent-side protocol regression still cannot overlap two batches in // one isolate. operationTail = operationTail.then(() => handle(value)).catch(() => { send({ type: 'error', poolId: data!.poolId!, code: 'perception_analysis_worker_failed', ...diagnosticMemory(), }); }); }); send({ type: 'ready', poolId: data.poolId, ...diagnosticMemory(), }); } else { // Keep the port alive until the parent retires this failed startup slot. // This prevents an exit event from racing ahead of the attributed error. port.on('message', () => {}); }