openai.js 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852
  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; local fallback is forbidden
  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. * Callers (e.g. fallback wrapper) can catch this to switch to local provider.
  318. */
  319. export class CircuitOpenError extends Error {
  320. constructor(message = "OpenAIEmbeddingsProvider circuit is OPEN") {
  321. super(message);
  322. this.name = "CircuitOpenError";
  323. }
  324. }
  325. /**
  326. * Persistent (non-retryable) HTTP error from upstream. Includes status code.
  327. */
  328. export class HttpError extends Error {
  329. status;
  330. bodyPreview;
  331. /** Server-advertised cooldown for 429s, when the response stated one. */
  332. retryAfterMs;
  333. constructor(status, bodyPreview, retryAfterMs) {
  334. super(`HTTP ${status}: ${bodyPreview.slice(0, 200)}`);
  335. this.name = "HttpError";
  336. this.status = status;
  337. this.bodyPreview = bodyPreview.slice(0, 1024);
  338. this.retryAfterMs = retryAfterMs;
  339. }
  340. }
  341. // ─────────────────────────── Bulk lane ───────────────────────────────────────
  342. /**
  343. * Client-side bulk lane for reindex traffic (i-yghj098h).
  344. *
  345. * qmd's bulk embedding shares the interactive ai.mm.mk token bucket. Without a
  346. * server-side per-caller budget, the only way bulk traffic can stop contending
  347. * head-on with interactive callers is to police itself:
  348. *
  349. * - a 429 on ANY worker pauses the ENTIRE pool for the advertised cooldown
  350. * (one shared promise — concurrent 429s coalesce instead of stacking N
  351. * cooldowns), so the bucket refills for interactive callers rather than
  352. * being re-drained by the remaining workers;
  353. * - the in-flight cap halves on each cooldown (floor 1) and recovers one unit
  354. * per `LANE_RECOVERY_STREAK` successes — classic AIMD, so a run settles at
  355. * whatever share the bucket actually has spare.
  356. *
  357. * Deliberately clock-free: cooldowns are modelled as a promise produced by the
  358. * injected `sleep`, so tests drive them with a fake sleep and no fake clock.
  359. */
  360. export class BulkLaneGate {
  361. maxPermits;
  362. sleep;
  363. permits;
  364. inFlight = 0;
  365. okStreak = 0;
  366. cooldown = null;
  367. waiters = [];
  368. constructor(maxPermits, sleep) {
  369. this.maxPermits = Math.max(1, maxPermits);
  370. this.permits = this.maxPermits;
  371. this.sleep = sleep;
  372. }
  373. /** Current in-flight cap — exported state for tests/diagnostics. */
  374. get permitCount() {
  375. return this.permits;
  376. }
  377. /** True while the lane is serving a rate-limit cooldown. */
  378. get isCoolingDown() {
  379. return this.cooldown !== null;
  380. }
  381. /** Take a slot, waiting out any cooldown and respecting the current cap. */
  382. async acquire() {
  383. while (this.cooldown !== null || this.inFlight >= this.permits) {
  384. if (this.cooldown !== null) {
  385. await this.cooldown;
  386. continue;
  387. }
  388. await new Promise((resolve) => this.waiters.push(resolve));
  389. }
  390. this.inFlight++;
  391. }
  392. /** Return a slot. Always call from a `finally`. */
  393. release() {
  394. if (this.inFlight > 0)
  395. this.inFlight--;
  396. this.wakeOne();
  397. }
  398. /**
  399. * Enter (or join) a cooldown of `waitMs` and halve the in-flight cap.
  400. * Returns the shared cooldown promise — the caller awaits it INSTEAD of
  401. * sleeping itself, so a burst of 429s costs one cooldown, not one each.
  402. */
  403. penalize(waitMs) {
  404. if (this.cooldown !== null)
  405. return this.cooldown;
  406. this.okStreak = 0;
  407. this.permits = Math.max(1, Math.floor(this.permits / 2));
  408. const cooldown = this.sleep(waitMs).then(() => {
  409. if (this.cooldown === cooldown)
  410. this.cooldown = null;
  411. this.wakeAll();
  412. });
  413. this.cooldown = cooldown;
  414. return cooldown;
  415. }
  416. /** Record a successful bulk request; recovers one permit per success streak. */
  417. noteSuccess() {
  418. if (this.permits >= this.maxPermits)
  419. return;
  420. if (++this.okStreak >= LANE_RECOVERY_STREAK) {
  421. this.okStreak = 0;
  422. this.permits++;
  423. this.wakeOne();
  424. }
  425. }
  426. wakeOne() {
  427. this.waiters.shift()?.();
  428. }
  429. wakeAll() {
  430. const pending = this.waiters;
  431. this.waiters = [];
  432. for (const resolve of pending)
  433. resolve();
  434. }
  435. }
  436. // ─────────────────────────── Provider ────────────────────────────────────────
  437. export class OpenAIEmbeddingsProvider {
  438. kind = "openai";
  439. endpoint;
  440. apiKey;
  441. modelId;
  442. upstreamModel;
  443. batchSize;
  444. concurrency;
  445. timeoutMs;
  446. fetchImpl;
  447. retryBackoffsMs;
  448. rateLimitRetries;
  449. sleep;
  450. now;
  451. dimensions = undefined;
  452. lastError = undefined;
  453. breaker;
  454. /** Shared bulk-traffic lane — see `BulkLaneGate`. */
  455. lane;
  456. constructor(config) {
  457. if (!config.endpoint) {
  458. throw new Error("OpenAIEmbeddingsProvider: endpoint is required");
  459. }
  460. this.endpoint = config.endpoint.replace(/\/+$/, "");
  461. this.apiKey = config.apiKey;
  462. this.modelId = config.modelId ?? "embeddinggemma";
  463. this.upstreamModel = config.upstreamModel ?? this.modelId;
  464. this.batchSize = config.batchSize ?? DEFAULT_BATCH_SIZE;
  465. this.concurrency = config.concurrency ?? DEFAULT_CONCURRENCY;
  466. this.timeoutMs = config.timeoutMs ?? DEFAULT_TIMEOUT_MS;
  467. this.fetchImpl = config.fetchImpl ?? globalThis.fetch;
  468. this.retryBackoffsMs = config.retryBackoffsMs ?? RETRY_BACKOFFS_MS;
  469. this.rateLimitRetries =
  470. config.rateLimitRetries ??
  471. parseNonNegativeInt(process.env.QMD_EMBED_RATE_LIMIT_RETRIES) ??
  472. DEFAULT_RATE_LIMIT_RETRIES;
  473. this.sleep = config.sleep ?? defaultSleep;
  474. this.now = config.now ?? Date.now;
  475. this.breaker = new CircuitBreaker({ now: this.now });
  476. this.lane = new BulkLaneGate(this.concurrency, this.sleep);
  477. if (!this.fetchImpl) {
  478. throw new Error("OpenAIEmbeddingsProvider: global fetch is unavailable. " +
  479. "Provide a `fetchImpl` config option (Node ≥18 ships fetch by default).");
  480. }
  481. if (this.batchSize < 1) {
  482. throw new Error(`OpenAIEmbeddingsProvider: batchSize must be ≥ 1, got ${this.batchSize}`);
  483. }
  484. if (this.concurrency < 1) {
  485. throw new Error(`OpenAIEmbeddingsProvider: concurrency must be ≥ 1, got ${this.concurrency}`);
  486. }
  487. }
  488. getModelId() {
  489. return this.modelId;
  490. }
  491. getDimensions() {
  492. return this.dimensions;
  493. }
  494. /**
  495. * Most recent per-chunk failure message (HTTP status + body preview, malformed
  496. * JSON, timeout, abort reason). Returns `undefined` after a successful call
  497. * or before the first call. See `EmbeddingProvider.getLastError`.
  498. */
  499. getLastError() {
  500. return this.lastError;
  501. }
  502. /** Endpoint URL configured at construction time — used by callers when
  503. * building error messages for failed first-chunk probes. */
  504. getEndpoint() {
  505. return this.endpoint;
  506. }
  507. async healthcheck(signal) {
  508. // Try GET /health first (worker exposes it). Fall back to probe embed.
  509. try {
  510. const { signal: attemptSig, cleanup } = buildAttemptSignal(signal, this.timeoutMs);
  511. try {
  512. const resp = await this.fetchImpl(`${this.endpoint}/health`, {
  513. method: "GET",
  514. headers: this.buildHeaders(),
  515. signal: attemptSig,
  516. });
  517. if (resp.ok) {
  518. return {
  519. ok: true,
  520. model: this.modelId,
  521. dimensions: this.dimensions,
  522. detail: `GET /health → ${resp.status}`,
  523. };
  524. }
  525. return {
  526. ok: false,
  527. model: this.modelId,
  528. detail: `GET /health → HTTP ${resp.status}`,
  529. };
  530. }
  531. finally {
  532. cleanup();
  533. }
  534. }
  535. catch (err) {
  536. // Endpoint may not implement /health — try a single embed probe instead.
  537. try {
  538. const probe = await this.embed("healthcheck", { signal });
  539. if (probe) {
  540. return {
  541. ok: true,
  542. model: this.modelId,
  543. dimensions: probe.embedding.length,
  544. detail: "embed probe ok",
  545. };
  546. }
  547. return {
  548. ok: false,
  549. model: this.modelId,
  550. detail: "embed probe returned null",
  551. };
  552. }
  553. catch (probeErr) {
  554. return {
  555. ok: false,
  556. model: this.modelId,
  557. detail: (err instanceof Error ? err.message : String(err)) +
  558. " | probe: " +
  559. (probeErr instanceof Error ? probeErr.message : String(probeErr)),
  560. };
  561. }
  562. }
  563. }
  564. async embed(text, options = {}) {
  565. const batch = await this.embedBatch([text], options);
  566. return batch[0] ?? null;
  567. }
  568. async embedBatch(texts, options = {}) {
  569. if (texts.length === 0)
  570. return [];
  571. if (this.breaker.shouldFailFast()) {
  572. throw new CircuitOpenError();
  573. }
  574. // Bulk = anything that isn't a single query-time embed. Reindex runs go
  575. // through the self-throttling lane and are attributed as `embeddings-bulk`;
  576. // `embed()` (search path) stays interactive and is never parked behind a
  577. // bulk cooldown (i-yghj098h).
  578. const lane = texts.length > 1 ? "bulk" : "interactive";
  579. const chunks = chunkArray(texts, this.batchSize);
  580. const results = new Array(texts.length).fill(null);
  581. // Pre-compute the input-array starting position for each chunk so each
  582. // worker can write its slice of `results` independently — input order is
  583. // preserved end-to-end without a final re-sort step.
  584. const chunkStarts = new Array(chunks.length);
  585. {
  586. let cursor = 0;
  587. for (let i = 0; i < chunks.length; i++) {
  588. chunkStarts[i] = cursor;
  589. cursor += chunks[i].length;
  590. }
  591. }
  592. // Shared state across the worker pool. Each transition is final-write,
  593. // so plain JS scalars are safe — no atomics or locks needed since
  594. // workers only contend on these via cooperative-scheduled awaits.
  595. let nextChunkIdx = 0;
  596. let anySucceeded = false;
  597. let aborted = false;
  598. let circuitTrippedDuringRun = null;
  599. // Workers run as parallel async tasks pulling chunks off `nextChunkIdx`
  600. // until the queue is drained or one of the early-exit flags is set.
  601. // Concurrency is capped at min(this.concurrency, chunks.length) so we
  602. // don't spin up idle workers for tiny inputs.
  603. const workerCount = Math.min(this.concurrency, chunks.length);
  604. const dispatchOne = async () => {
  605. while (true) {
  606. if (aborted || circuitTrippedDuringRun)
  607. return;
  608. const idx = nextChunkIdx++;
  609. if (idx >= chunks.length)
  610. return;
  611. const chunk = chunks[idx];
  612. const start = chunkStarts[idx];
  613. // Honor abort/breaker BEFORE issuing the request so we don't waste
  614. // network for a dispatch we know will be discarded.
  615. if (options.signal?.aborted) {
  616. aborted = true;
  617. this.lastError = `aborted by caller${options.signal.reason ? `: ${String(options.signal.reason)}` : ""}`;
  618. return;
  619. }
  620. if (this.breaker.shouldFailFast()) {
  621. // Capture the breaker-open intent so we throw it AFTER all
  622. // currently in-flight workers settle, instead of leaking
  623. // half-completed results. The thrown error is a fresh instance
  624. // (matching legacy behavior).
  625. circuitTrippedDuringRun = new CircuitOpenError();
  626. return;
  627. }
  628. try {
  629. if (lane === "bulk")
  630. await this.lane.acquire();
  631. let embeddings;
  632. try {
  633. embeddings = await this.requestWithRetry(chunk, options, lane);
  634. }
  635. finally {
  636. if (lane === "bulk")
  637. this.lane.release();
  638. }
  639. if (lane === "bulk")
  640. this.lane.noteSuccess();
  641. for (let i = 0; i < chunk.length; i++) {
  642. const embedding = embeddings[i];
  643. if (embedding) {
  644. results[start + i] = {
  645. embedding,
  646. model: this.modelId,
  647. };
  648. anySucceeded = true;
  649. // Record dimensions on first success. Concurrent workers may
  650. // race on this assignment, but they all observe the same
  651. // length so the race is benign.
  652. if (this.dimensions === undefined) {
  653. this.dimensions = embedding.length;
  654. }
  655. }
  656. }
  657. this.breaker.recordSuccess();
  658. }
  659. catch (err) {
  660. // A rate limit is backpressure, not a fault. Counting 429s toward the
  661. // breaker turns "the bucket is empty for 30s" into a 5-minute hard
  662. // OPEN, which is the outage the retry budget above exists to avoid.
  663. // The lane cooldown is already the correct control response.
  664. const rateLimited = err instanceof HttpError && err.status === 429;
  665. if (!rateLimited)
  666. this.breaker.recordFailure();
  667. if (err instanceof CircuitOpenError) {
  668. circuitTrippedDuringRun = err;
  669. return;
  670. }
  671. // Last-write-wins on lastError matches the legacy semantics — under
  672. // concurrency multiple workers may fail in the same call, but the
  673. // lastError just needs to surface "the most recent cause."
  674. this.lastError = this.formatErrorContext(err);
  675. if (process.env.QMD_EMBED_DEBUG) {
  676. process.stderr.write(`OpenAIEmbeddingsProvider: chunk failed (${err instanceof Error ? err.message : String(err)})\n`);
  677. }
  678. }
  679. }
  680. };
  681. await Promise.all(Array.from({ length: workerCount }, () => dispatchOne()));
  682. // If a worker observed `shouldFailFast()` mid-run, surface the error
  683. // after all in-flight workers have settled.
  684. if (circuitTrippedDuringRun)
  685. throw circuitTrippedDuringRun;
  686. // Clear lastError on a fully-successful sweep (every input got an embedding).
  687. if (anySucceeded && results.every((r) => r !== null)) {
  688. this.lastError = undefined;
  689. }
  690. return results;
  691. }
  692. async dispose() {
  693. // Nothing to release — fetch handles its own connection pooling.
  694. // Reset the breaker so a re-instantiation starts fresh.
  695. this.breaker.reset();
  696. }
  697. // ────────────────────── Internals ──────────────────────
  698. /**
  699. * Format a request-failure context string for `lastError`. Includes endpoint
  700. * + HTTP status + body preview when the error was an `HttpError`, otherwise
  701. * falls back to the message of the underlying error (or the value itself
  702. * when not an Error). Kept short — body preview is already capped at 1024
  703. * chars by `HttpError`, but we trim further here for the dimension-probe
  704. * thrown error which surfaces directly to users.
  705. */
  706. formatErrorContext(err) {
  707. if (err instanceof HttpError) {
  708. const preview = err.bodyPreview.replace(/\s+/g, " ").trim().slice(0, 240);
  709. return `endpoint=${this.endpoint}/v1/embeddings status=${err.status}${preview ? ` body="${preview}"` : ""}`;
  710. }
  711. if (err instanceof Error) {
  712. return `endpoint=${this.endpoint}/v1/embeddings error="${err.message}"`;
  713. }
  714. return `endpoint=${this.endpoint}/v1/embeddings error="${String(err)}"`;
  715. }
  716. buildHeaders(lane = "interactive") {
  717. const headers = {
  718. "Content-Type": "application/json",
  719. "Accept": "application/json",
  720. // Advisory caller attribution for the ai.mm.mk gateway (NULL-safe, never
  721. // auth). Single chokepoint for both /health and /v1/embeddings.
  722. // `via` distinguishes bulk reindex traffic from query-time embeds so the
  723. // gateway can budget the two separately (i-yghj098h part 1b) — the
  724. // gateway-side per-caller bucket keys off this label.
  725. "X-AI-Caller": aiCallerHeaderValue(lane === "bulk" ? "embeddings-bulk" : "embeddings"),
  726. };
  727. if (this.apiKey) {
  728. headers["Authorization"] = `Bearer ${this.apiKey}`;
  729. }
  730. return headers;
  731. }
  732. /**
  733. * Single HTTP request with retry on 429/503. Returns embeddings indexed
  734. * the same as `texts`. Throws on non-retryable failure or all attempts
  735. * exhausted.
  736. */
  737. async requestWithRetry(texts, options, lane = "interactive") {
  738. let lastErr = null;
  739. // 429s draw on their own budget: a token bucket that refills in 30s must
  740. // not be able to exhaust a schedule whose total wait is 21s (i-yghj098h).
  741. let backoffAttempt = 0;
  742. let rateLimitAttempt = 0;
  743. for (;;) {
  744. // Honor user abort BEFORE issuing the call (avoids wasted network)
  745. if (options.signal?.aborted) {
  746. throw new Error("aborted by caller");
  747. }
  748. try {
  749. return await this.requestOnce(texts, options, lane);
  750. }
  751. catch (err) {
  752. lastErr = err;
  753. const status = err instanceof HttpError ? err.status : 0;
  754. if (!isRetryableStatus(status))
  755. throw err;
  756. if (status === 429) {
  757. if (rateLimitAttempt >= this.rateLimitRetries)
  758. throw err;
  759. const waitMs = this.rateLimitWaitMs(err, rateLimitAttempt);
  760. rateLimitAttempt++;
  761. if (lane === "bulk") {
  762. // Pause the whole pool, not just this worker: the other workers
  763. // hammering the same empty bucket is exactly what turns one 429
  764. // into a cascade, and what starves interactive callers.
  765. await this.lane.penalize(waitMs);
  766. }
  767. else {
  768. await this.sleep(waitMs);
  769. }
  770. continue;
  771. }
  772. if (backoffAttempt >= this.retryBackoffsMs.length)
  773. break;
  774. await this.sleep(this.retryBackoffsMs[backoffAttempt]);
  775. backoffAttempt++;
  776. }
  777. }
  778. // Exhausted retries → throw the last error so caller marks the chunk null
  779. throw lastErr ?? new Error("requestWithRetry exhausted");
  780. }
  781. /**
  782. * How long to wait after a 429. The server's own `Retry-After` wins when it
  783. * gave one; otherwise fall back to the configured schedule (so injected test
  784. * schedules stay authoritative) and then to an exponential 5s/10s/20s… ramp.
  785. * Always clamped to `RATE_LIMIT_MAX_BACKOFF_MS`.
  786. */
  787. rateLimitWaitMs(err, rateLimitAttempt) {
  788. const scheduled = this.retryBackoffsMs[Math.min(rateLimitAttempt, this.retryBackoffsMs.length - 1)];
  789. const fallback = scheduled ?? RATE_LIMIT_BASE_BACKOFF_MS * Math.pow(2, rateLimitAttempt);
  790. return Math.min(Math.max(err.retryAfterMs ?? 0, fallback), RATE_LIMIT_MAX_BACKOFF_MS);
  791. }
  792. /**
  793. * Issue one HTTP attempt to `POST /v1/embeddings`. Does NOT retry.
  794. */
  795. async requestOnce(texts, options, lane = "interactive") {
  796. const { signal: attemptSig, cleanup } = buildAttemptSignal(options.signal, this.timeoutMs);
  797. try {
  798. const body = JSON.stringify({
  799. model: options.model ?? this.upstreamModel,
  800. input: texts,
  801. });
  802. const resp = await this.fetchImpl(`${this.endpoint}/v1/embeddings`, {
  803. method: "POST",
  804. headers: this.buildHeaders(lane),
  805. body,
  806. signal: attemptSig,
  807. });
  808. if (!resp.ok) {
  809. const text = await resp.text().catch(() => "");
  810. // ai.mm.mk states the cooldown in the JSON body, not always in a
  811. // Retry-After header — read both (i-yghj098h).
  812. const retryAfterMs = resp.status === 429
  813. ? parseRetryAfterMs(resp.headers?.get?.("retry-after"), text, this.now)
  814. : undefined;
  815. throw new HttpError(resp.status, text, retryAfterMs);
  816. }
  817. let parsed;
  818. try {
  819. parsed = (await resp.json());
  820. }
  821. catch (err) {
  822. throw new Error(`OpenAIEmbeddingsProvider: malformed JSON from ${this.endpoint}/v1/embeddings: ${err instanceof Error ? err.message : String(err)}`);
  823. }
  824. if (!parsed || !Array.isArray(parsed.data)) {
  825. throw new Error(`OpenAIEmbeddingsProvider: response missing "data" array (got ${typeof parsed})`);
  826. }
  827. // Sort by index to match input order (in case server returns out-of-order).
  828. const out = new Array(texts.length);
  829. for (const item of parsed.data) {
  830. if (typeof item.index !== "number" ||
  831. item.index < 0 ||
  832. item.index >= texts.length) {
  833. throw new Error(`OpenAIEmbeddingsProvider: data item index out of range (${item.index}, expected 0..${texts.length - 1})`);
  834. }
  835. if (!Array.isArray(item.embedding)) {
  836. throw new Error(`OpenAIEmbeddingsProvider: data[${item.index}].embedding is not an array`);
  837. }
  838. out[item.index] = item.embedding;
  839. }
  840. // Sanity check — every slot must be filled
  841. for (let i = 0; i < texts.length; i++) {
  842. if (!out[i]) {
  843. throw new Error(`OpenAIEmbeddingsProvider: response missing embedding for index ${i}`);
  844. }
  845. }
  846. return out;
  847. }
  848. finally {
  849. cleanup();
  850. }
  851. }
  852. }