import type { EmbedHealth, EmbedProvider } from '../../contracts/embed.js'; import type { OnnxEmbedConfig } from './onnx.js'; /** Minimal structural subset of `node:worker_threads`' `Worker` actually * used here — lets unit tests inject a fake in-process stand-in instead of * spawning a real OS thread + downloading a real model (mirrors * `OnnxEmbedProvider`'s `loadBackend` DI seam in onnx.ts). A real `Worker` * instance satisfies this shape unchanged. */ export interface OnnxWorkerLike { postMessage(value: unknown, transferList?: readonly ArrayBuffer[]): void; on(event: 'message', listener: (msg: unknown) => void): this; on(event: 'error', listener: (err: Error) => void): this; on(event: 'exit', listener: (code: number) => void): this; terminate(): Promise | void; } export interface OnnxWorkerHostOpts { /** Overrides the resolved worker script path — test/DI seam only. */ workerPath?: string; /** Overrides how the worker is constructed — test/DI seam only. Production * code never sets this; defaults to a real `new Worker(path, {workerData})`. */ workerFactory?: (path: string, workerData: OnnxEmbedConfig) => OnnxWorkerLike; spawnTimeoutMs?: number; embedTimeoutMs?: number; } /** * ADR-019 Decision 2(d) — transparent worker_thread offload for the ONNX * embed provider. Implements the SAME `EmbedProvider` interface * `OnnxEmbedProvider` does, so `buildEmbedProvider` (providers/index.ts) can * swap the concrete class for `provider: 'onnx'` with zero changes at any * call site (search.ts, distill's 08-embed-index.ts, doctor's embed probes) * — every one of them keeps calling `embed()`/`health()` exactly as before. * * What changes: `session.run()` (the confirmed 400-950ms/call synchronous, * never-yields native binding — see * `.claude/artifacts/crew/validations/20260715T000000Z-validation-onnx-embed-event-loop-block.md`) * now executes on a dedicated worker thread, never on the daemon's main * event loop. A side benefit ADR-019 calls out explicitly: the per-embed * timeout below is a plain `setTimeout` on the MAIN thread, which can now * actually fire while the worker computes — unlike every timer-based defense * this repo already had (ADR-019's root-cause item 4), because the thing * that used to starve the event loop no longer runs on it. */ export declare class OnnxWorkerHostProvider implements EmbedProvider { readonly name: "onnx"; readonly model: string; readonly dim: number; readonly queryPrefix: string; private readonly config; private readonly workerPath; private readonly workerFactory; private readonly spawnTimeoutMs; private readonly embedTimeoutMs; private readonly log; private worker; private readyPromise; private nextId; /** Set for the duration of a deliberate terminate() call so the 'exit' * handler below can tell "I asked it to stop" apart from a genuine crash * — otherwise a clean shutdown logs the exact same WARN a real ORT crash * does, which would train an operator to ignore the real signal. */ private terminating; private readonly pendingEmbeds; private readonly pendingHealth; constructor(config?: OnnxEmbedConfig, opts?: OnnxWorkerHostOpts); /** * ADR-018 SLICE-2's startup-preload contract, now absorbing the worker * spawn (ADR-019): public, idempotent wrapper that spawns the worker and * waits for the model to finish loading. `serve.ts`'s existing duck-typed * `typeof embedProvider.preload === 'function'` boot-time call (SLICE-2) * needs NO change — it now warms the WORKER instead of an in-process * backend, transparently. */ preload(): Promise; /** Spawns the worker (if none is currently live) and returns the promise * that resolves once it reports 'ready' (model loaded). Idempotent: a * second caller while a spawn is already in flight shares the same * promise rather than double-spawning. */ private ensureWorker; private handleWorkerMessage; /** * Worker died mid-flight (native ORT crash is a known v1 risk — ADR-018's * own risk register). Fails every in-flight request LOUDLY AND * IMMEDIATELY (never lets one hang to its own timeout), then drops the * worker reference so the very next `embed()`/`health()`/`preload()` call * transparently respawns a fresh worker — the on-demand-respawn mirrors * `OnnxEmbedProvider`'s own "failed load is not memoized, retry on next * call" posture rather than an unbounded background auto-restart loop * (which would risk crash-looping forever against a genuinely broken * model/artifact instead of surfacing the failure). */ private handleWorkerCrash; /** * `signal`: unlike `OnnxEmbedProvider`'s narrowed in-process contract * (checked only between texts within one synchronous call), the worker * boundary lets this proxy honor abort/timeout from a DIFFERENT thread — * an abort or timeout REJECTS THIS PROMISE IMMEDIATELY on the main thread * regardless of what the worker is doing, and best-effort relays a * `{type:'cancel'}` message so the worker's own between-texts checkpoint * (still the underlying mechanism) can stop early too. No pending message * is ever leaked: every branch below removes the request from * `pendingEmbeds` exactly once before settling. */ embed(texts: string[], signal?: AbortSignal): Promise; /** * Reports worker liveness (spawns one if none exists — same lazy posture * as `embed()`) PLUS a real embed round-trip (no network) — relayed * through a dedicated `{type:'health'}` message so the worker calls its * OWN `OnnxEmbedProvider.health()` directly (onnx.ts's smoke-inference + * dim-assert logic, unchanged), rather than this proxy reimplementing * that check on top of `embed()`. */ health(): Promise; /** * Graceful shutdown — mirrors serve.ts's other lifecycle handles * (`shipper.stop()`, the job-queue `worker.stop()`). Fails any in-flight * request loudly (via the same `handleWorkerCrash` path a real crash * takes) rather than leaving it to time out, then terminates the OS * thread. Safe to call even if a worker was never spawned. */ terminate(): Promise; }