openai.js 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851
  1. /**
  2. * openai.ts - OpenAI-compatible HTTP embedding provider
  3. *
  4. * Talks to any endpoint that implements `POST /v1/embeddings` with the OpenAI
  5. * shape: request `{model, input: string|string[]}`, response
  6. * `{data: [{embedding: number[], index: number}, ...]}`.
  7. *
  8. * Used by qmd to delegate embeddings to an approved commercial HTTPS API.
  9. *
  10. * Features:
  11. * - Batches input in groups of ≤64 (configurable via QMD_EMBED_BATCH_SIZE)
  12. * - Retries 429 / 503 with exponential backoff (1s, 4s, 16s)
  13. * - 429 gets its own, larger retry budget and honours `Retry-After`
  14. * (header or `"Retry after 29s"` body text) — a shared gateway bucket
  15. * refilling in 30s must not exhaust a 1s/4s/16s schedule (i-yghj098h)
  16. * - Bulk lane (`embedBatch` with >1 input): a 429 pauses the WHOLE worker
  17. * pool for the advertised cooldown and halves in-flight concurrency
  18. * (AIMD), so reindex traffic yields the bucket to interactive callers
  19. * instead of contending head-on with them
  20. * - 4xx (non-429) → no retry, count as failure
  21. * - Circuit breaker: >50% failures in a 60s window → OPEN for 5 min;
  22. * callers receive failures and no model fallback is selected
  23. * - Per-call timeout via AbortSignal (default QMD_EMBED_TIMEOUT_MS=30000)
  24. * - Healthcheck via `GET /health` if available, else a probe embed call
  25. */
  26. import os from "node:os";
  27. // ─────────────────────────── Configuration ───────────────────────────────────
  28. /**
  29. * Default batch size — most OpenAI-compatible embedding endpoints accept up to
  30. * 2048 inputs per call but for memory and latency we cap at 64.
  31. */
  32. export const DEFAULT_BATCH_SIZE = 64;
  33. /**
  34. * Default in-flight concurrency cap for `embedBatch`. The qmd-embed-worker
  35. * exposes a 4-way semaphore (`MAX_CONCURRENT_REQUESTS=4`) and idles at
  36. * queue-depth 1.0 under sequential clients (i-fkpnar9i baseline). Defaulting
  37. * to 4 matches the worker's advertised concurrency without overshooting the
  38. * GPU. Override per-deploy via `QMD_EMBED_CONCURRENCY`. Setting to 1 reverts
  39. * to the legacy sequential dispatch.
  40. */
  41. export const DEFAULT_CONCURRENCY = 4;
  42. /**
  43. * Default per-request timeout (30 s). embeddinggemma-300M on RTX 4090 takes
  44. * <500ms per batch of 64 in practice; 30s is a safe upper bound.
  45. */
  46. export const DEFAULT_TIMEOUT_MS = 30_000;
  47. /**
  48. * Retry backoff schedule (ms) for 429/503 responses. 3 attempts total
  49. * (initial + 2 retries) — aligns with issue spec "1s/4s/16s".
  50. */
  51. export const RETRY_BACKOFFS_MS = [1_000, 4_000, 16_000];
  52. /**
  53. * Rate-limit (429) retry budget, separate from `RETRY_BACKOFFS_MS`.
  54. *
  55. * A 429 is backpressure, not a fault: the shared ai.mm.mk gateway answers
  56. * `{"detail":"Rate limit exceeded (tokens). Retry after 29s."}` with observed
  57. * retry-after values of 7s/29s/30s, while the generic schedule waits at most
  58. * 1+4+16 = 21s in total. Bulk reindex runs therefore burned all three attempts
  59. * inside one bucket refill and reported the chunk as failed (i-yghj098h).
  60. * 429s get their own attempt count and always wait at least as long as the
  61. * server asked for, capped by `RATE_LIMIT_MAX_BACKOFF_MS`.
  62. */
  63. export const DEFAULT_RATE_LIMIT_RETRIES = 5;
  64. /** Upper bound on a single rate-limit wait, so a bogus Retry-After can't hang a run. */
  65. export const RATE_LIMIT_MAX_BACKOFF_MS = 60_000;
  66. /** Fallback wait when a 429 carries no parseable Retry-After (doubles per attempt). */
  67. export const RATE_LIMIT_BASE_BACKOFF_MS = 5_000;
  68. /**
  69. * Consecutive successful bulk requests before the lane additively recovers one
  70. * unit of concurrency after a 429-triggered halving (AIMD).
  71. */
  72. export const LANE_RECOVERY_STREAK = 8;
  73. /**
  74. * Circuit breaker — flips OPEN when error rate exceeds threshold within
  75. * window. While OPEN, every call fails fast so the caller can fall back.
  76. */
  77. export const CIRCUIT_WINDOW_MS = 60_000;
  78. export const CIRCUIT_OPEN_DURATION_MS = 5 * 60_000;
  79. export const CIRCUIT_FAILURE_RATE_THRESHOLD = 0.5;
  80. export const CIRCUIT_MIN_SAMPLES = 4;
  81. // ─────────────────────────── Helpers ─────────────────────────────────────────
  82. function defaultSleep(ms) {
  83. return new Promise((resolve) => setTimeout(resolve, ms));
  84. }
  85. /** Parse a non-negative integer env value; `undefined` when unset/invalid. */
  86. function parseNonNegativeInt(raw) {
  87. if (raw == null || raw.trim() === "")
  88. return undefined;
  89. const n = Number.parseInt(raw, 10);
  90. return Number.isFinite(n) && n >= 0 ? n : undefined;
  91. }
  92. /**
  93. * Build the advisory `X-AI-Caller` attribution header value (Oivo ai.mm.mk
  94. * "Observability-Driven Fleet Self-Improvement" rollout, Thread 1). Format
  95. * mirrors Oivo's `cli/src/shared/aiCallerHeader.ts` EXACTLY:
  96. * site=<file:line | tool file>; mc=<machine>; sid=<session-8char>;
  97. * comp=<component>; via=<logical-label>
  98. *
  99. * Advisory metadata ONLY — never an auth/authorization input. `mc`/`sid` come
  100. * from the Oivo fleet env when qmd runs as a delegated embedder; both degrade
  101. * to `-`/short-hostname safely when qmd runs standalone. Values are sanitized
  102. * (`;` + control chars stripped, capped at 120) so a pathological env value can
  103. * never break the header grammar.
  104. */
  105. function aiCallerHeaderValue(via) {
  106. const clean = (raw, fallback) => {
  107. if (raw == null)
  108. return fallback;
  109. let out = "";
  110. for (const ch of String(raw)) {
  111. const code = ch.charCodeAt(0);
  112. out += code < 32 || code === 127 || ch === ";" ? " " : ch;
  113. }
  114. const collapsed = out.replace(/\s+/g, " ").trim();
  115. return (collapsed || fallback).slice(0, 120);
  116. };
  117. let mc = (process.env.OIVO_MACHINE_NAME ?? "").trim();
  118. if (!mc) {
  119. try {
  120. mc = os.hostname().split(".")[0] || "unknown";
  121. }
  122. catch {
  123. mc = "unknown";
  124. }
  125. }
  126. const sid = (process.env.OIVO_SESSION_ID || process.env.CLAUDE_CODE_SESSION_ID || "-").slice(0, 8);
  127. return `site=src/embedding/openai.ts; mc=${clean(mc, "unknown")}; sid=${clean(sid, "-")}; comp=qmd; via=${clean(via, "-")}`;
  128. }
  129. /**
  130. * Build the merged AbortSignal for a single HTTP attempt: combines an
  131. * external `userSignal` (from caller / withLLMSession) with a per-attempt
  132. * timeout signal. Returns the merged signal AND the timeout id so the
  133. * caller can `clearTimeout` after the attempt completes (avoids leaks).
  134. */
  135. function buildAttemptSignal(userSignal, timeoutMs) {
  136. const ctrl = new AbortController();
  137. const timeoutId = setTimeout(() => {
  138. ctrl.abort(new Error(`Request timed out after ${timeoutMs}ms`));
  139. }, timeoutMs);
  140. // Don't keep process alive just for this timer
  141. if (typeof timeoutId === "object" && timeoutId !== null && "unref" in timeoutId) {
  142. timeoutId.unref();
  143. }
  144. const onUserAbort = () => ctrl.abort(userSignal?.reason);
  145. if (userSignal) {
  146. if (userSignal.aborted) {
  147. ctrl.abort(userSignal.reason);
  148. }
  149. else {
  150. userSignal.addEventListener("abort", onUserAbort, { once: true });
  151. }
  152. }
  153. const cleanup = () => {
  154. clearTimeout(timeoutId);
  155. if (userSignal)
  156. userSignal.removeEventListener("abort", onUserAbort);
  157. };
  158. return { signal: ctrl.signal, cleanup };
  159. }
  160. /**
  161. * Determine whether an HTTP status is retryable. 429 (Too Many Requests)
  162. * and 503 (Service Unavailable) are retried; 4xx (other than 429) are not.
  163. */
  164. export function isRetryableStatus(status) {
  165. return status === 429 || status === 503;
  166. }
  167. /**
  168. * Extract the server-advertised cooldown from a rate-limited response.
  169. *
  170. * Two sources, in priority order:
  171. * 1. the standard `Retry-After` header — delta-seconds or an HTTP-date;
  172. * 2. the ai.mm.mk body text, which states the cooldown in prose only:
  173. * `{"detail":"Rate limit exceeded (tokens). Retry after 29s.", ...}`.
  174. *
  175. * Returns `undefined` when neither source yields a sane positive duration, so
  176. * the caller falls back to its own schedule. Values are clamped to
  177. * `RATE_LIMIT_MAX_BACKOFF_MS`.
  178. */
  179. export function parseRetryAfterMs(headerValue, bodyPreview, now = Date.now) {
  180. const clamp = (ms) => Number.isFinite(ms) && ms > 0 ? Math.min(ms, RATE_LIMIT_MAX_BACKOFF_MS) : undefined;
  181. const header = headerValue?.trim();
  182. if (header) {
  183. if (/^\d+(\.\d+)?$/.test(header)) {
  184. const fromSeconds = clamp(Number(header) * 1000);
  185. if (fromSeconds !== undefined)
  186. return fromSeconds;
  187. }
  188. const asDate = Date.parse(header);
  189. if (!Number.isNaN(asDate)) {
  190. const fromDate = clamp(asDate - now());
  191. if (fromDate !== undefined)
  192. return fromDate;
  193. }
  194. }
  195. if (bodyPreview) {
  196. const m = /retry\s+after\s+(\d+(?:\.\d+)?)\s*(ms|s|seconds?)?/i.exec(bodyPreview);
  197. if (m) {
  198. const value = Number(m[1]);
  199. const unit = (m[2] ?? "s").toLowerCase();
  200. return clamp(unit === "ms" ? value : value * 1000);
  201. }
  202. }
  203. return undefined;
  204. }
  205. /**
  206. * Chunk an array into pieces of ≤ size each. `size` MUST be ≥ 1.
  207. */
  208. export function chunkArray(items, size) {
  209. if (size < 1)
  210. throw new Error(`chunkArray: size must be ≥ 1, got ${size}`);
  211. if (items.length <= size)
  212. return items.length === 0 ? [] : [items];
  213. const out = [];
  214. for (let i = 0; i < items.length; i += size) {
  215. out.push(items.slice(i, i + size));
  216. }
  217. return out;
  218. }
  219. // ─────────────────────────── Circuit Breaker ─────────────────────────────────
  220. /**
  221. * Sliding-window circuit breaker. Tracks the last N samples (min 4) over a
  222. * 60-second window; flips OPEN when failure rate exceeds 50%, then auto-
  223. * resets to HALF-OPEN after 5 minutes — at which point the next probe
  224. * decides whether to close (success) or re-open (failure).
  225. */
  226. export class CircuitBreaker {
  227. samples = [];
  228. state = "closed";
  229. openedAt = null;
  230. windowMs;
  231. openDurationMs;
  232. threshold;
  233. minSamples;
  234. now;
  235. constructor(opts = {}) {
  236. this.windowMs = opts.windowMs ?? CIRCUIT_WINDOW_MS;
  237. this.openDurationMs = opts.openDurationMs ?? CIRCUIT_OPEN_DURATION_MS;
  238. this.threshold = opts.threshold ?? CIRCUIT_FAILURE_RATE_THRESHOLD;
  239. this.minSamples = opts.minSamples ?? CIRCUIT_MIN_SAMPLES;
  240. this.now = opts.now ?? Date.now;
  241. }
  242. getState() {
  243. this.tickAutoReset();
  244. return this.state;
  245. }
  246. /**
  247. * Returns true when calls should be short-circuited (skip HTTP, fall back).
  248. * Side-effects: may transition OPEN → HALF-OPEN if the open window expired.
  249. */
  250. shouldFailFast() {
  251. return this.getState() === "open";
  252. }
  253. /** Record a successful call. */
  254. recordSuccess() {
  255. // Honor the time-based OPEN→HALF-OPEN transition before deciding what
  256. // to do with this sample. Without this, a success that lands AFTER the
  257. // open window expired would still see state==="open" and never close
  258. // the breaker (a probe call could only flip it via getState()).
  259. this.tickAutoReset();
  260. this.pushSample(true);
  261. if (this.state === "half-open") {
  262. this.state = "closed";
  263. this.openedAt = null;
  264. }
  265. }
  266. /** Record a failed call. May trigger OPEN. */
  267. recordFailure() {
  268. // Same reasoning as recordSuccess — apply lazy auto-reset before
  269. // classifying the sample.
  270. this.tickAutoReset();
  271. this.pushSample(false);
  272. if (this.state === "half-open") {
  273. // Probe failed — re-open
  274. this.state = "open";
  275. this.openedAt = this.now();
  276. return;
  277. }
  278. if (this.state === "closed")
  279. this.evaluate();
  280. }
  281. /** Force-reset the breaker (used by tests / admin) */
  282. reset() {
  283. this.samples = [];
  284. this.state = "closed";
  285. this.openedAt = null;
  286. }
  287. pushSample(ok) {
  288. const ts = this.now();
  289. this.samples.push({ ts, ok });
  290. // Drop samples outside the window
  291. const cutoff = ts - this.windowMs;
  292. while (this.samples.length > 0 && this.samples[0].ts < cutoff) {
  293. this.samples.shift();
  294. }
  295. }
  296. evaluate() {
  297. if (this.samples.length < this.minSamples)
  298. return;
  299. const failures = this.samples.filter((s) => !s.ok).length;
  300. const rate = failures / this.samples.length;
  301. if (rate > this.threshold) {
  302. this.state = "open";
  303. this.openedAt = this.now();
  304. }
  305. }
  306. tickAutoReset() {
  307. if (this.state === "open" && this.openedAt !== null) {
  308. if (this.now() - this.openedAt >= this.openDurationMs) {
  309. this.state = "half-open";
  310. }
  311. }
  312. }
  313. }
  314. // ─────────────────────────── Errors ──────────────────────────────────────────
  315. /**
  316. * Raised when the circuit breaker is OPEN and a call is short-circuited.
  317. */
  318. export class CircuitOpenError extends Error {
  319. constructor(message = "OpenAIEmbeddingsProvider circuit is OPEN") {
  320. super(message);
  321. this.name = "CircuitOpenError";
  322. }
  323. }
  324. /**
  325. * Persistent (non-retryable) HTTP error from upstream. Includes status code.
  326. */
  327. export class HttpError extends Error {
  328. status;
  329. bodyPreview;
  330. /** Server-advertised cooldown for 429s, when the response stated one. */
  331. retryAfterMs;
  332. constructor(status, bodyPreview, retryAfterMs) {
  333. super(`HTTP ${status}: ${bodyPreview.slice(0, 200)}`);
  334. this.name = "HttpError";
  335. this.status = status;
  336. this.bodyPreview = bodyPreview.slice(0, 1024);
  337. this.retryAfterMs = retryAfterMs;
  338. }
  339. }
  340. // ─────────────────────────── Bulk lane ───────────────────────────────────────
  341. /**
  342. * Client-side bulk lane for reindex traffic (i-yghj098h).
  343. *
  344. * qmd's bulk embedding shares the interactive ai.mm.mk token bucket. Without a
  345. * server-side per-caller budget, the only way bulk traffic can stop contending
  346. * head-on with interactive callers is to police itself:
  347. *
  348. * - a 429 on ANY worker pauses the ENTIRE pool for the advertised cooldown
  349. * (one shared promise — concurrent 429s coalesce instead of stacking N
  350. * cooldowns), so the bucket refills for interactive callers rather than
  351. * being re-drained by the remaining workers;
  352. * - the in-flight cap halves on each cooldown (floor 1) and recovers one unit
  353. * per `LANE_RECOVERY_STREAK` successes — classic AIMD, so a run settles at
  354. * whatever share the bucket actually has spare.
  355. *
  356. * Deliberately clock-free: cooldowns are modelled as a promise produced by the
  357. * injected `sleep`, so tests drive them with a fake sleep and no fake clock.
  358. */
  359. export class BulkLaneGate {
  360. maxPermits;
  361. sleep;
  362. permits;
  363. inFlight = 0;
  364. okStreak = 0;
  365. cooldown = null;
  366. waiters = [];
  367. constructor(maxPermits, sleep) {
  368. this.maxPermits = Math.max(1, maxPermits);
  369. this.permits = this.maxPermits;
  370. this.sleep = sleep;
  371. }
  372. /** Current in-flight cap — exported state for tests/diagnostics. */
  373. get permitCount() {
  374. return this.permits;
  375. }
  376. /** True while the lane is serving a rate-limit cooldown. */
  377. get isCoolingDown() {
  378. return this.cooldown !== null;
  379. }
  380. /** Take a slot, waiting out any cooldown and respecting the current cap. */
  381. async acquire() {
  382. while (this.cooldown !== null || this.inFlight >= this.permits) {
  383. if (this.cooldown !== null) {
  384. await this.cooldown;
  385. continue;
  386. }
  387. await new Promise((resolve) => this.waiters.push(resolve));
  388. }
  389. this.inFlight++;
  390. }
  391. /** Return a slot. Always call from a `finally`. */
  392. release() {
  393. if (this.inFlight > 0)
  394. this.inFlight--;
  395. this.wakeOne();
  396. }
  397. /**
  398. * Enter (or join) a cooldown of `waitMs` and halve the in-flight cap.
  399. * Returns the shared cooldown promise — the caller awaits it INSTEAD of
  400. * sleeping itself, so a burst of 429s costs one cooldown, not one each.
  401. */
  402. penalize(waitMs) {
  403. if (this.cooldown !== null)
  404. return this.cooldown;
  405. this.okStreak = 0;
  406. this.permits = Math.max(1, Math.floor(this.permits / 2));
  407. const cooldown = this.sleep(waitMs).then(() => {
  408. if (this.cooldown === cooldown)
  409. this.cooldown = null;
  410. this.wakeAll();
  411. });
  412. this.cooldown = cooldown;
  413. return cooldown;
  414. }
  415. /** Record a successful bulk request; recovers one permit per success streak. */
  416. noteSuccess() {
  417. if (this.permits >= this.maxPermits)
  418. return;
  419. if (++this.okStreak >= LANE_RECOVERY_STREAK) {
  420. this.okStreak = 0;
  421. this.permits++;
  422. this.wakeOne();
  423. }
  424. }
  425. wakeOne() {
  426. this.waiters.shift()?.();
  427. }
  428. wakeAll() {
  429. const pending = this.waiters;
  430. this.waiters = [];
  431. for (const resolve of pending)
  432. resolve();
  433. }
  434. }
  435. // ─────────────────────────── Provider ────────────────────────────────────────
  436. export class OpenAIEmbeddingsProvider {
  437. kind = "openai";
  438. endpoint;
  439. apiKey;
  440. modelId;
  441. upstreamModel;
  442. batchSize;
  443. concurrency;
  444. timeoutMs;
  445. fetchImpl;
  446. retryBackoffsMs;
  447. rateLimitRetries;
  448. sleep;
  449. now;
  450. dimensions = undefined;
  451. lastError = undefined;
  452. breaker;
  453. /** Shared bulk-traffic lane — see `BulkLaneGate`. */
  454. lane;
  455. constructor(config) {
  456. if (!config.endpoint) {
  457. throw new Error("OpenAIEmbeddingsProvider: endpoint is required");
  458. }
  459. this.endpoint = config.endpoint.replace(/\/+$/, "");
  460. this.apiKey = config.apiKey;
  461. this.modelId = config.modelId ?? "embeddinggemma";
  462. this.upstreamModel = config.upstreamModel ?? this.modelId;
  463. this.batchSize = config.batchSize ?? DEFAULT_BATCH_SIZE;
  464. this.concurrency = config.concurrency ?? DEFAULT_CONCURRENCY;
  465. this.timeoutMs = config.timeoutMs ?? DEFAULT_TIMEOUT_MS;
  466. this.fetchImpl = config.fetchImpl ?? globalThis.fetch;
  467. this.retryBackoffsMs = config.retryBackoffsMs ?? RETRY_BACKOFFS_MS;
  468. this.rateLimitRetries =
  469. config.rateLimitRetries ??
  470. parseNonNegativeInt(process.env.QMD_EMBED_RATE_LIMIT_RETRIES) ??
  471. DEFAULT_RATE_LIMIT_RETRIES;
  472. this.sleep = config.sleep ?? defaultSleep;
  473. this.now = config.now ?? Date.now;
  474. this.breaker = new CircuitBreaker({ now: this.now });
  475. this.lane = new BulkLaneGate(this.concurrency, this.sleep);
  476. if (!this.fetchImpl) {
  477. throw new Error("OpenAIEmbeddingsProvider: global fetch is unavailable. " +
  478. "Provide a `fetchImpl` config option (Node ≥18 ships fetch by default).");
  479. }
  480. if (this.batchSize < 1) {
  481. throw new Error(`OpenAIEmbeddingsProvider: batchSize must be ≥ 1, got ${this.batchSize}`);
  482. }
  483. if (this.concurrency < 1) {
  484. throw new Error(`OpenAIEmbeddingsProvider: concurrency must be ≥ 1, got ${this.concurrency}`);
  485. }
  486. }
  487. getModelId() {
  488. return this.modelId;
  489. }
  490. getDimensions() {
  491. return this.dimensions;
  492. }
  493. /**
  494. * Most recent per-chunk failure message (HTTP status + body preview, malformed
  495. * JSON, timeout, abort reason). Returns `undefined` after a successful call
  496. * or before the first call. See `EmbeddingProvider.getLastError`.
  497. */
  498. getLastError() {
  499. return this.lastError;
  500. }
  501. /** Endpoint URL configured at construction time — used by callers when
  502. * building error messages for failed first-chunk probes. */
  503. getEndpoint() {
  504. return this.endpoint;
  505. }
  506. async healthcheck(signal) {
  507. // Try GET /health first (worker exposes it). Fall back to probe embed.
  508. try {
  509. const { signal: attemptSig, cleanup } = buildAttemptSignal(signal, this.timeoutMs);
  510. try {
  511. const resp = await this.fetchImpl(`${this.endpoint}/health`, {
  512. method: "GET",
  513. headers: this.buildHeaders(),
  514. signal: attemptSig,
  515. });
  516. if (resp.ok) {
  517. return {
  518. ok: true,
  519. model: this.modelId,
  520. dimensions: this.dimensions,
  521. detail: `GET /health → ${resp.status}`,
  522. };
  523. }
  524. return {
  525. ok: false,
  526. model: this.modelId,
  527. detail: `GET /health → HTTP ${resp.status}`,
  528. };
  529. }
  530. finally {
  531. cleanup();
  532. }
  533. }
  534. catch (err) {
  535. // Endpoint may not implement /health — try a single embed probe instead.
  536. try {
  537. const probe = await this.embed("healthcheck", { signal });
  538. if (probe) {
  539. return {
  540. ok: true,
  541. model: this.modelId,
  542. dimensions: probe.embedding.length,
  543. detail: "embed probe ok",
  544. };
  545. }
  546. return {
  547. ok: false,
  548. model: this.modelId,
  549. detail: "embed probe returned null",
  550. };
  551. }
  552. catch (probeErr) {
  553. return {
  554. ok: false,
  555. model: this.modelId,
  556. detail: (err instanceof Error ? err.message : String(err)) +
  557. " | probe: " +
  558. (probeErr instanceof Error ? probeErr.message : String(probeErr)),
  559. };
  560. }
  561. }
  562. }
  563. async embed(text, options = {}) {
  564. const batch = await this.embedBatch([text], options);
  565. return batch[0] ?? null;
  566. }
  567. async embedBatch(texts, options = {}) {
  568. if (texts.length === 0)
  569. return [];
  570. if (this.breaker.shouldFailFast()) {
  571. throw new CircuitOpenError();
  572. }
  573. // Bulk = anything that isn't a single query-time embed. Reindex runs go
  574. // through the self-throttling lane and are attributed as `embeddings-bulk`;
  575. // `embed()` (search path) stays interactive and is never parked behind a
  576. // bulk cooldown (i-yghj098h).
  577. const lane = texts.length > 1 ? "bulk" : "interactive";
  578. const chunks = chunkArray(texts, this.batchSize);
  579. const results = new Array(texts.length).fill(null);
  580. // Pre-compute the input-array starting position for each chunk so each
  581. // worker can write its slice of `results` independently — input order is
  582. // preserved end-to-end without a final re-sort step.
  583. const chunkStarts = new Array(chunks.length);
  584. {
  585. let cursor = 0;
  586. for (let i = 0; i < chunks.length; i++) {
  587. chunkStarts[i] = cursor;
  588. cursor += chunks[i].length;
  589. }
  590. }
  591. // Shared state across the worker pool. Each transition is final-write,
  592. // so plain JS scalars are safe — no atomics or locks needed since
  593. // workers only contend on these via cooperative-scheduled awaits.
  594. let nextChunkIdx = 0;
  595. let anySucceeded = false;
  596. let aborted = false;
  597. let circuitTrippedDuringRun = null;
  598. // Workers run as parallel async tasks pulling chunks off `nextChunkIdx`
  599. // until the queue is drained or one of the early-exit flags is set.
  600. // Concurrency is capped at min(this.concurrency, chunks.length) so we
  601. // don't spin up idle workers for tiny inputs.
  602. const workerCount = Math.min(this.concurrency, chunks.length);
  603. const dispatchOne = async () => {
  604. while (true) {
  605. if (aborted || circuitTrippedDuringRun)
  606. return;
  607. const idx = nextChunkIdx++;
  608. if (idx >= chunks.length)
  609. return;
  610. const chunk = chunks[idx];
  611. const start = chunkStarts[idx];
  612. // Honor abort/breaker BEFORE issuing the request so we don't waste
  613. // network for a dispatch we know will be discarded.
  614. if (options.signal?.aborted) {
  615. aborted = true;
  616. this.lastError = `aborted by caller${options.signal.reason ? `: ${String(options.signal.reason)}` : ""}`;
  617. return;
  618. }
  619. if (this.breaker.shouldFailFast()) {
  620. // Capture the breaker-open intent so we throw it AFTER all
  621. // currently in-flight workers settle, instead of leaking
  622. // half-completed results. The thrown error is a fresh instance
  623. // (matching legacy behavior).
  624. circuitTrippedDuringRun = new CircuitOpenError();
  625. return;
  626. }
  627. try {
  628. if (lane === "bulk")
  629. await this.lane.acquire();
  630. let embeddings;
  631. try {
  632. embeddings = await this.requestWithRetry(chunk, options, lane);
  633. }
  634. finally {
  635. if (lane === "bulk")
  636. this.lane.release();
  637. }
  638. if (lane === "bulk")
  639. this.lane.noteSuccess();
  640. for (let i = 0; i < chunk.length; i++) {
  641. const embedding = embeddings[i];
  642. if (embedding) {
  643. results[start + i] = {
  644. embedding,
  645. model: this.modelId,
  646. };
  647. anySucceeded = true;
  648. // Record dimensions on first success. Concurrent workers may
  649. // race on this assignment, but they all observe the same
  650. // length so the race is benign.
  651. if (this.dimensions === undefined) {
  652. this.dimensions = embedding.length;
  653. }
  654. }
  655. }
  656. this.breaker.recordSuccess();
  657. }
  658. catch (err) {
  659. // A rate limit is backpressure, not a fault. Counting 429s toward the
  660. // breaker turns "the bucket is empty for 30s" into a 5-minute hard
  661. // OPEN, which is the outage the retry budget above exists to avoid.
  662. // The lane cooldown is already the correct control response.
  663. const rateLimited = err instanceof HttpError && err.status === 429;
  664. if (!rateLimited)
  665. this.breaker.recordFailure();
  666. if (err instanceof CircuitOpenError) {
  667. circuitTrippedDuringRun = err;
  668. return;
  669. }
  670. // Last-write-wins on lastError matches the legacy semantics — under
  671. // concurrency multiple workers may fail in the same call, but the
  672. // lastError just needs to surface "the most recent cause."
  673. this.lastError = this.formatErrorContext(err);
  674. if (process.env.QMD_EMBED_DEBUG) {
  675. process.stderr.write(`OpenAIEmbeddingsProvider: chunk failed (${err instanceof Error ? err.message : String(err)})\n`);
  676. }
  677. }
  678. }
  679. };
  680. await Promise.all(Array.from({ length: workerCount }, () => dispatchOne()));
  681. // If a worker observed `shouldFailFast()` mid-run, surface the error
  682. // after all in-flight workers have settled.
  683. if (circuitTrippedDuringRun)
  684. throw circuitTrippedDuringRun;
  685. // Clear lastError on a fully-successful sweep (every input got an embedding).
  686. if (anySucceeded && results.every((r) => r !== null)) {
  687. this.lastError = undefined;
  688. }
  689. return results;
  690. }
  691. async dispose() {
  692. // Nothing to release — fetch handles its own connection pooling.
  693. // Reset the breaker so a re-instantiation starts fresh.
  694. this.breaker.reset();
  695. }
  696. // ────────────────────── Internals ──────────────────────
  697. /**
  698. * Format a request-failure context string for `lastError`. Includes endpoint
  699. * + HTTP status + body preview when the error was an `HttpError`, otherwise
  700. * falls back to the message of the underlying error (or the value itself
  701. * when not an Error). Kept short — body preview is already capped at 1024
  702. * chars by `HttpError`, but we trim further here for the dimension-probe
  703. * thrown error which surfaces directly to users.
  704. */
  705. formatErrorContext(err) {
  706. if (err instanceof HttpError) {
  707. const preview = err.bodyPreview.replace(/\s+/g, " ").trim().slice(0, 240);
  708. return `endpoint=${this.endpoint}/v1/embeddings status=${err.status}${preview ? ` body="${preview}"` : ""}`;
  709. }
  710. if (err instanceof Error) {
  711. return `endpoint=${this.endpoint}/v1/embeddings error="${err.message}"`;
  712. }
  713. return `endpoint=${this.endpoint}/v1/embeddings error="${String(err)}"`;
  714. }
  715. buildHeaders(lane = "interactive") {
  716. const headers = {
  717. "Content-Type": "application/json",
  718. "Accept": "application/json",
  719. // Advisory caller attribution for the ai.mm.mk gateway (NULL-safe, never
  720. // auth). Single chokepoint for both /health and /v1/embeddings.
  721. // `via` distinguishes bulk reindex traffic from query-time embeds so the
  722. // gateway can budget the two separately (i-yghj098h part 1b) — the
  723. // gateway-side per-caller bucket keys off this label.
  724. "X-AI-Caller": aiCallerHeaderValue(lane === "bulk" ? "embeddings-bulk" : "embeddings"),
  725. };
  726. if (this.apiKey) {
  727. headers["Authorization"] = `Bearer ${this.apiKey}`;
  728. }
  729. return headers;
  730. }
  731. /**
  732. * Single HTTP request with retry on 429/503. Returns embeddings indexed
  733. * the same as `texts`. Throws on non-retryable failure or all attempts
  734. * exhausted.
  735. */
  736. async requestWithRetry(texts, options, lane = "interactive") {
  737. let lastErr = null;
  738. // 429s draw on their own budget: a token bucket that refills in 30s must
  739. // not be able to exhaust a schedule whose total wait is 21s (i-yghj098h).
  740. let backoffAttempt = 0;
  741. let rateLimitAttempt = 0;
  742. for (;;) {
  743. // Honor user abort BEFORE issuing the call (avoids wasted network)
  744. if (options.signal?.aborted) {
  745. throw new Error("aborted by caller");
  746. }
  747. try {
  748. return await this.requestOnce(texts, options, lane);
  749. }
  750. catch (err) {
  751. lastErr = err;
  752. const status = err instanceof HttpError ? err.status : 0;
  753. if (!isRetryableStatus(status))
  754. throw err;
  755. if (status === 429) {
  756. if (rateLimitAttempt >= this.rateLimitRetries)
  757. throw err;
  758. const waitMs = this.rateLimitWaitMs(err, rateLimitAttempt);
  759. rateLimitAttempt++;
  760. if (lane === "bulk") {
  761. // Pause the whole pool, not just this worker: the other workers
  762. // hammering the same empty bucket is exactly what turns one 429
  763. // into a cascade, and what starves interactive callers.
  764. await this.lane.penalize(waitMs);
  765. }
  766. else {
  767. await this.sleep(waitMs);
  768. }
  769. continue;
  770. }
  771. if (backoffAttempt >= this.retryBackoffsMs.length)
  772. break;
  773. await this.sleep(this.retryBackoffsMs[backoffAttempt]);
  774. backoffAttempt++;
  775. }
  776. }
  777. // Exhausted retries → throw the last error so caller marks the chunk null
  778. throw lastErr ?? new Error("requestWithRetry exhausted");
  779. }
  780. /**
  781. * How long to wait after a 429. The server's own `Retry-After` wins when it
  782. * gave one; otherwise fall back to the configured schedule (so injected test
  783. * schedules stay authoritative) and then to an exponential 5s/10s/20s… ramp.
  784. * Always clamped to `RATE_LIMIT_MAX_BACKOFF_MS`.
  785. */
  786. rateLimitWaitMs(err, rateLimitAttempt) {
  787. const scheduled = this.retryBackoffsMs[Math.min(rateLimitAttempt, this.retryBackoffsMs.length - 1)];
  788. const fallback = scheduled ?? RATE_LIMIT_BASE_BACKOFF_MS * Math.pow(2, rateLimitAttempt);
  789. return Math.min(Math.max(err.retryAfterMs ?? 0, fallback), RATE_LIMIT_MAX_BACKOFF_MS);
  790. }
  791. /**
  792. * Issue one HTTP attempt to `POST /v1/embeddings`. Does NOT retry.
  793. */
  794. async requestOnce(texts, options, lane = "interactive") {
  795. const { signal: attemptSig, cleanup } = buildAttemptSignal(options.signal, this.timeoutMs);
  796. try {
  797. const body = JSON.stringify({
  798. model: options.model ?? this.upstreamModel,
  799. input: texts,
  800. });
  801. const resp = await this.fetchImpl(`${this.endpoint}/v1/embeddings`, {
  802. method: "POST",
  803. headers: this.buildHeaders(lane),
  804. body,
  805. signal: attemptSig,
  806. });
  807. if (!resp.ok) {
  808. const text = await resp.text().catch(() => "");
  809. // ai.mm.mk states the cooldown in the JSON body, not always in a
  810. // Retry-After header — read both (i-yghj098h).
  811. const retryAfterMs = resp.status === 429
  812. ? parseRetryAfterMs(resp.headers?.get?.("retry-after"), text, this.now)
  813. : undefined;
  814. throw new HttpError(resp.status, text, retryAfterMs);
  815. }
  816. let parsed;
  817. try {
  818. parsed = (await resp.json());
  819. }
  820. catch (err) {
  821. throw new Error(`OpenAIEmbeddingsProvider: malformed JSON from ${this.endpoint}/v1/embeddings: ${err instanceof Error ? err.message : String(err)}`);
  822. }
  823. if (!parsed || !Array.isArray(parsed.data)) {
  824. throw new Error(`OpenAIEmbeddingsProvider: response missing "data" array (got ${typeof parsed})`);
  825. }
  826. // Sort by index to match input order (in case server returns out-of-order).
  827. const out = new Array(texts.length);
  828. for (const item of parsed.data) {
  829. if (typeof item.index !== "number" ||
  830. item.index < 0 ||
  831. item.index >= texts.length) {
  832. throw new Error(`OpenAIEmbeddingsProvider: data item index out of range (${item.index}, expected 0..${texts.length - 1})`);
  833. }
  834. if (!Array.isArray(item.embedding)) {
  835. throw new Error(`OpenAIEmbeddingsProvider: data[${item.index}].embedding is not an array`);
  836. }
  837. out[item.index] = item.embedding;
  838. }
  839. // Sanity check — every slot must be filled
  840. for (let i = 0; i < texts.length; i++) {
  841. if (!out[i]) {
  842. throw new Error(`OpenAIEmbeddingsProvider: response missing embedding for index ${i}`);
  843. }
  844. }
  845. return out;
  846. }
  847. finally {
  848. cleanup();
  849. }
  850. }
  851. }