Spaces:
Build error

trackademi / app /services /embed.py
anwarKXC
feat: implement remote batch retry logic with per-group fallback for transient errors
6a0e581
Raw History Blame Contribute Delete
41.9 kB
import asyncio
import logging
from dataclasses import dataclass
import httpx
from app.config import get_settings
logger = logging.getLogger(__name__)
# Statuses worth retrying on the remote embeddings endpoint: transient
# congestion or a momentary gateway failure, not anything a different request
# would fix. 429 is the one that matters in practice β€” providers relay upstream
# overload through it, which is explicitly "try again later".
_RETRYABLE_STATUS = frozenset({408, 409, 425, 429, 500, 502, 503, 504})
@dataclass
class EmbedResult:
embedding: list[float]
model: str
duration_ms: int
class _NativeBatchUnavailable(Exception):
"""Raised internally when Ollama's /api/embed batch endpoint 404s β€”
signals embed_batch() to fall back to per-text calls."""
class EmbedService:
def __init__(self) -> None:
settings = get_settings()
self._ollama_url = settings.OLLAMA_BASE_URL
# Which server backs the LOCAL half of the router. `self._model` is the
# label persisted for locally-produced vectors, so it has to follow the
# backend actually in use β€” see config.TEI_EMBED_MODEL for why the TEI
# label deliberately matches the remote provider's string.
self._local_backend = (settings.EMBED_LOCAL_BACKEND or "ollama").strip().lower()
if self._local_backend not in ("ollama", "tei"):
raise RuntimeError(
f"EMBED_LOCAL_BACKEND must be 'ollama' or 'tei', got "
f"{settings.EMBED_LOCAL_BACKEND!r}"
)
self._tei_url = settings.TEI_BASE_URL.rstrip("/")
self._tei_max_chars = max(1, settings.EMBED_TEI_MAX_CHARS)
self._model = (
settings.TEI_EMBED_MODEL if self._local_backend == "tei"
else settings.OLLAMA_EMBED_MODEL
)
self._timeout = settings.EMBED_REQUEST_TIMEOUT
self._chars_per_token = settings.CHARS_PER_TOKEN
self._batch_max_bytes = settings.EMBED_BATCH_MAX_BYTES
self._batch_max_tokens = settings.EMBED_BATCH_MAX_TOKENS
self._fallback_concurrency = settings.EMBED_BATCH_FALLBACK_CONCURRENCY
self._retry_attempts = max(1, settings.EMBED_RETRY_ATTEMPTS)
self._retry_backoff = settings.EMBED_RETRY_BACKOFF_SECONDS
self._expected_dims = settings.EMBED_DIMENSIONS
# Set to False the first time /api/embed 404s so we stop retrying it
# for the rest of this process's lifetime and go straight to the
# semaphore fallback (avoids paying a failed-request round trip per
# batch on an Ollama version that doesn't have the batch endpoint).
self._native_batch_supported: bool | None = None
# ── Query-path overflow state ────────────────────────────────────
# NOTE: _query_overflow depends on _remote_enabled, which is assigned
# further down β€” it is set there, not here, so the two cannot drift.
self._local_slots = max(1, settings.EMBED_LOCAL_SLOTS)
self._local_deadline = settings.EMBED_LOCAL_DEADLINE_MS / 1000
self._breaker_threshold = settings.EMBED_LOCAL_BREAKER_FAILURES
self._breaker_cooldown = settings.EMBED_LOCAL_BREAKER_COOLDOWN_S
self._local_inflight = 0
self._local_failures = 0
self._breaker_open_until = 0.0
self._half_open_probes = max(0, settings.EMBED_BREAKER_HALF_OPEN_PROBES)
self._half_open_used = 0
# Runaway-spend guard (see config: this is a circuit breaker on bugs,
# not a cost optimisation β€” normal traffic is orders of magnitude below).
self._daily_budget = settings.EMBED_CLOUD_DAILY_BUDGET_USD
self._usd_per_1k = settings.EMBED_CLOUD_USD_PER_1K_TOKENS
self._spend_today = 0.0
self._spend_day = None
# Observability: how the query path actually resolved, so the
# local/cloud split (and therefore spend) is visible without guessing.
self.query_routing = {"local": 0, "overflow_busy": 0,
"overflow_slow": 0, "overflow_breaker": 0,
"remote_failed_to_local": 0,
"budget_capped_to_local": 0,
"cloud_only": 0}
# Remote provider β€” same model, hosted. See config for why "same
# model" is a correctness requirement and not a preference.
self._remote_enabled = (
settings.EMBED_PROVIDER == "openai_compatible"
and bool(settings.EMBED_REMOTE_URL)
)
self._remote_url = settings.EMBED_REMOTE_URL.rstrip("/")
self._remote_key = settings.EMBED_REMOTE_API_KEY
self._remote_model = settings.EMBED_REMOTE_MODEL
self._remote_timeout = settings.EMBED_REMOTE_TIMEOUT
self._remote_fallback = settings.EMBED_REMOTE_FALLBACK_TO_LOCAL
# Set False after the remote endpoint fails in a way that won't fix
# itself, so we stop paying a failed round trip per group.
self._remote_healthy = True
# Query-path overflow needs a remote to overflow *to*.
self._query_overflow = settings.EMBED_QUERY_OVERFLOW and self._remote_enabled
# Ingestion (embed_batch) prefers the remote GPU when this is on.
self._ingestion_cloud = settings.EMBED_INGESTION_CLOUD and self._remote_enabled
# Cloud-only mode: no local backend exists to route to or fall back on.
self._local_enabled = settings.EMBED_LOCAL_ENABLED
if not self._local_enabled:
self._remote_fallback = False
self._ingestion_cloud = self._remote_enabled
if not self._remote_enabled:
raise RuntimeError(
"EMBED_LOCAL_ENABLED is false but no remote embedding "
"provider is configured β€” there is no way to embed "
"anything. Set EMBED_PROVIDER=openai_compatible and "
"EMBED_REMOTE_URL, or re-enable the local backend."
)
logger.info(
"Embeddings: CLOUD-ONLY (%s, %d dims) β€” local backend disabled",
self._remote_model, self._expected_dims,
)
self._batch_max_items = (
settings.EMBED_REMOTE_BATCH_MAX_ITEMS
if self._remote_enabled
else settings.EMBED_BATCH_MAX_ITEMS
)
# The local fallback needs its OWN bound. _batch_max_items above is
# sized for the remote GPU (96) whenever a remote is configured, and
# TEI rejects anything over its --max-client-batch-size outright β€” so
# reusing that number would turn "cloud is down" into "nothing embeds".
self._local_batch_max_items = (
settings.EMBED_TEI_BATCH_MAX_ITEMS
if self._local_backend == "tei"
else settings.EMBED_BATCH_MAX_ITEMS
)
if self._local_enabled:
logger.info(
"Embeddings: local backend=%s at %s (model=%s, %d dims, "
"%d slot(s), batch<=%d)",
self._local_backend,
self._tei_url if self._local_backend == "tei" else self._ollama_url,
self._model, self._expected_dims,
self._local_slots, self._local_batch_max_items,
)
if self._remote_enabled:
logger.info(
"Embeddings: remote provider at %s (model=%s, %d dims expected); "
"local fallback %s",
self._remote_url, self._remote_model, self._expected_dims,
"enabled" if self._remote_fallback else "disabled",
)
# ── Query-path routing ───────────────────────────────────────────────────
def _breaker_open(self) -> bool:
"""True while local is being bypassed.
After the cooldown expires the breaker goes HALF-OPEN: a limited
number of probes are allowed back onto local. A success closes it, a
failure restarts the cooldown β€” so a still-sick backend doesn't get
the full traffic back the instant the timer runs out.
"""
import time
if time.monotonic() < self._breaker_open_until:
return True
if self._breaker_open_until and self._half_open_used < self._half_open_probes:
self._half_open_used += 1
logger.info("Local embedding breaker HALF-OPEN β€” probing local")
return False # let this one through as a probe
return False
def _budget_exhausted(self) -> bool:
"""True when today's cloud spend has hit the runaway ceiling."""
if not self._daily_budget:
return False
import datetime
today = datetime.date.today()
if self._spend_day != today:
self._spend_day, self._spend_today = today, 0.0
return self._spend_today >= self._daily_budget
def _record_spend(self, tokens: int) -> None:
import datetime
today = datetime.date.today()
if self._spend_day != today:
self._spend_day, self._spend_today = today, 0.0
before = self._spend_today
self._spend_today += (tokens / 1000.0) * self._usd_per_1k
if self._daily_budget and before < self._daily_budget <= self._spend_today:
logger.error(
"Cloud embedding daily budget of $%.2f reached β€” overflow "
"disabled until tomorrow. This ceiling allows millions of "
"normal queries, so treat it as a bug signal (retry loop or "
"stuck ingest), not as organic growth.",
self._daily_budget,
)
def _note_local_failure(self) -> None:
"""Trip the breaker after repeated local failures.
Without this every query keeps paying the full local deadline before
overflowing, turning a local outage into a latency tax on every user.
"""
import time
self._local_failures += 1
if self._local_failures >= self._breaker_threshold:
self._breaker_open_until = time.monotonic() + self._breaker_cooldown
self._local_failures = 0
logger.warning(
"Local embedding breaker OPEN for %.0fs β€” routing queries to "
"the remote endpoint", self._breaker_cooldown,
)
def routing_snapshot(self) -> dict:
"""Current routing tallies β€” the aggregate view of the per-request log.
Answers the questions that decide infrastructure spend: how often does
local cope on its own, how much is actually going to the cloud, and is
anything failing over.
"""
total = sum(self.query_routing.values()) or 1
cloud = (self.query_routing["overflow_busy"]
+ self.query_routing["overflow_slow"]
+ self.query_routing["overflow_breaker"])
return {
"counts": dict(self.query_routing),
"total_queries": sum(self.query_routing.values()),
"cloud_share_pct": round(100 * cloud / total, 1),
"spend_today_usd": round(self._spend_today, 6),
"daily_budget_usd": self._daily_budget,
"breaker_open": self._breaker_open_until > 0,
"local_inflight": self._local_inflight,
"overflow_enabled": self._query_overflow,
"local_model": self._model,
"remote_model": self._remote_model if self._remote_enabled else None,
"expected_dims": self._expected_dims,
}
def _note_local_success(self) -> None:
self._local_failures = 0
if self._breaker_open_until:
logger.info("Local embedding recovered β€” breaker CLOSED")
self._breaker_open_until = 0.0
self._half_open_used = 0
# ── Dimension guard ──────────────────────────────────────────────────────
def _check_dims(self, embedding: list[float], source: str) -> list[float]:
"""Reject vectors that can't belong in the pgvector column.
A wrong width means a wrong model, and a wrong model means vectors
that are not comparable to everything already indexed. Failing here
turns a silent retrieval-quality collapse into a loud ingest error.
"""
if self._expected_dims and len(embedding) != self._expected_dims:
raise ValueError(
f"{source} returned a {len(embedding)}-dim embedding but "
f"rag_chunks.embedding is vector({self._expected_dims}). "
f"Check that the remote model matches OLLAMA_EMBED_MODEL β€” "
f"vectors from different models are not interchangeable."
)
return embedding
async def embed(self, text: str, *, client: httpx.AsyncClient) -> EmbedResult:
"""Embed one text β€” the QUERY path. Local-first, cloud on contention.
Ingestion goes through embed_batch and always prefers the remote GPU.
Queries are latency-critical and arrive one at a time, so local wins
while it is free: no network hop, no external dependency, no marginal
cost. But Ollama serves embeddings from a single slot, so a query that
arrives while another is in flight waits out the first one before it
even starts β€” and the remote endpoint answers in ~287ms flat. The
instant local is busy, slow, or failing, the cloud is the better
answer, and at ~$0.02 per 100k queries the cost does not register.
Falls back to local if the remote call fails, so an outage at either
end degrades latency rather than breaking retrieval.
"""
import time as _t
started = _t.monotonic()
queue_depth = self._local_inflight
route = {"provider": "local", "reason": "local"}
try:
result = await self._route_query_embed(text, client=client, route=route)
self._emit_query_metric(text, route, queue_depth, started, ok=True)
return result
except Exception:
self._emit_query_metric(text, route, queue_depth, started, ok=False)
raise
def _emit_query_metric(self, text, route, queue_depth, started, *, ok) -> None:
"""One structured line per query embed.
Deliberately a log line rather than a metrics table: it survives
restarts, needs no schema, and can be aggregated with grep/jq. The
fields are the ones that actually drive decisions β€” whether overflow
is rare or constant tells you if the box needs upgrading, and whether
TEI is worth swapping in for Ollama.
"""
import time as _t
tokens = max(1, len(text) // self._chars_per_token)
local = route["provider"] == "local"
logger.info(
"embed_query provider=%s reason=%s model=%s dims=%d latency_ms=%d "
"queue_depth=%d tokens=%d ok=%s cost_usd=%.8f",
route["provider"], route["reason"],
# Which weights actually produced this vector. Logged because a
# line six months from now must be self-describing: comparing
# latency across a model migration is impossible if you have to
# remember when the cutover happened.
self._model if local else self._remote_model,
self._expected_dims,
int((_t.monotonic() - started) * 1000), queue_depth, tokens, ok,
0.0 if local else (tokens / 1000.0) * self._usd_per_1k,
)
async def _route_query_embed(self, text: str, *, client, route: dict) -> EmbedResult:
"""Pick a backend and run the embed; `route` records what happened."""
if not self._local_enabled:
# Cloud-only: no slot to check, no deadline to wait out, no
# breaker to trip. Straight to the remote endpoint.
result = (await self._embed_remote_batch([text], client=client))[0]
self.query_routing["cloud_only"] += 1
route.update(provider="cloud", reason="cloud_only")
return result
if not self._query_overflow:
return await self._embed_local(text, client=client)
reason = None
if self._breaker_open():
reason = "overflow_breaker"
elif self._local_inflight >= self._local_slots:
reason = "overflow_busy"
# Budget ceiling wins over the busy signal: waiting on a queued local
# request is worse than a surprise bill, but a runaway loop billing all
# night is worse than either. Breaker overflow still goes through β€”
# if local is genuinely down, queueing on it returns nothing at all.
if reason == "overflow_busy" and self._budget_exhausted():
self.query_routing["budget_capped_to_local"] += 1
route.update(provider="local", reason="budget_capped_to_local")
return await self._embed_local(text, client=client)
if reason:
try:
result = (await self._embed_remote_batch([text], client=client))[0]
self.query_routing[reason] += 1
route.update(provider="cloud", reason=reason)
return result
except ValueError:
raise # dimension/contract violation β€” never paper over
except Exception as err:
logger.warning(
"Remote query embed failed (%s) β€” falling back to local",
type(err).__name__,
)
self.query_routing["remote_failed_to_local"] += 1
route.update(provider="local", reason="remote_failed_to_local")
return await self._embed_local(text, client=client)
# Local looks free: use it, but do not wait forever.
self._local_inflight += 1
try:
result = await asyncio.wait_for(
self._embed_local(text, client=client), timeout=self._local_deadline,
)
self._note_local_success()
self.query_routing["local"] += 1
route.update(provider="local", reason="local")
return result
except Exception as err:
self._note_local_failure()
logger.warning(
"Local query embed %s after %.1fs β€” overflowing to remote",
"timed out" if isinstance(err, asyncio.TimeoutError) else
f"failed ({type(err).__name__})",
self._local_deadline,
)
result = (await self._embed_remote_batch([text], client=client))[0]
self.query_routing["overflow_slow"] += 1
route.update(provider="cloud", reason="overflow_slow")
return result
finally:
self._local_inflight -= 1
async def _embed_local(self, text: str, *, client: httpx.AsyncClient) -> EmbedResult:
"""Single-text embedding against whichever local backend is configured.
A thin dispatcher on purpose: everything above it (slots, deadline,
breaker, overflow accounting) is backend-agnostic and must stay that
way, so swapping Ollama for TEI changes only what happens below here.
"""
if self._local_backend == "tei":
results = await self._embed_tei_batch([text], client=client)
return results[0]
return await self._embed_local_ollama(text, client=client)
def _cap_for_tei(self, texts: list[str]) -> list[str]:
"""Clamp inputs to a length TEI can actually schedule.
An input longer than the server's --max-batch-tokens window never gets
batched and the request hangs indefinitely rather than failing, so this
is a liveness guard, not an optimisation. Truncation is logged because
a silently shortened chunk produces a subtly wrong vector, which is far
harder to notice than a loud error.
"""
capped: list[str] = []
for text in texts:
if len(text) > self._tei_max_chars:
logger.warning(
"Truncating %d-char input to %d chars for TEI (EMBED_TEI_MAX_CHARS) "
"β€” it exceeds what the batch window can schedule",
len(text), self._tei_max_chars,
)
text = text[: self._tei_max_chars]
capped.append(text)
return capped
async def _embed_tei_batch(
self, texts: list[str], *, client: httpx.AsyncClient
) -> list[EmbedResult]:
"""OpenAI-compatible /v1/embeddings call against the local TEI server.
Same wire format as _embed_remote_batch, but pointed at the local
container and tagged with the LOCAL model label, and with no spend
recording β€” these vectors are free. Results are re-ordered by the
response `index` rather than trusting array order, for the same reason
as the remote path: a mismatched pairing attaches embeddings to the
wrong chunks silently.
"""
import time
start = time.monotonic()
payload_texts = self._cap_for_tei(texts)
resp = await client.post(
f"{self._tei_url}/v1/embeddings",
json={"model": self._model, "input": payload_texts},
timeout=self._timeout,
)
if resp.status_code != 200:
logger.error("TEI embed error %d: %s", resp.status_code, resp.text[:500])
resp.raise_for_status()
payload = resp.json()
rows = payload.get("data") or []
if len(rows) != len(payload_texts):
raise ValueError(
f"TEI returned {len(rows)} vectors for {len(payload_texts)} inputs"
)
ordered: list[list[float] | None] = [None] * len(payload_texts)
for position, row in enumerate(rows):
index = row.get("index")
target = (
index if isinstance(index, int) and 0 <= index < len(payload_texts)
else position
)
ordered[target] = row.get("embedding") or []
duration_ms = int((time.monotonic() - start) * 1000)
per_item_ms = duration_ms // max(1, len(payload_texts))
results: list[EmbedResult] = []
for vector in ordered:
if not vector:
raise ValueError("TEI returned an empty vector")
results.append(EmbedResult(
embedding=self._check_dims(vector, "Local TEI"),
model=self._model,
duration_ms=per_item_ms,
))
return results
async def _embed_local_ollama(self, text: str, *, client: httpx.AsyncClient) -> EmbedResult:
"""Single-text embedding against the local Ollama runner."""
import time
start = time.monotonic()
resp = await client.post(
f"{self._ollama_url}/api/embeddings",
# keep_alive=-1 pins the model in memory. Belt-and-braces with
# ENV OLLAMA_KEEP_ALIVE in the Dockerfile: this one also covers
# local/dev runs and any deployment that doesn't set that env,
# where an evicted model means a cold load on the next request that
# overshoots the retrieval timeout and silently drops context.
json={"model": self._model, "prompt": text, "keep_alive": -1},
timeout=self._timeout,
)
if resp.status_code != 200:
body = resp.text
logger.error("Ollama embed error %d: %s", resp.status_code, body[:500])
resp.raise_for_status()
data = resp.json()
embedding = data.get("embedding", [])
if not embedding:
raise ValueError("Ollama returned empty embedding")
duration_ms = int((time.monotonic() - start) * 1000)
logger.debug(
"Embedded %d chars β†’ %d dims in %dms",
len(text), len(embedding), duration_ms,
)
return EmbedResult(
embedding=self._check_dims(embedding, "Local Ollama"),
model=self._model,
duration_ms=duration_ms,
)
def _group_for_batching(
self, texts: list[str], *, max_items: int | None = None
) -> list[list[int]]:
"""Split text indices into groups bounded by item count, estimated
JSON payload size, and estimated token count β€” whichever hits first.
A single unusually large OCR'd chunk gets its own group rather than
blowing up the latency of a whole batch it's lumped into.
`max_items` overrides the item bound so the local and remote paths can
use different group sizes against the same texts.
"""
item_cap = self._batch_max_items if max_items is None else max_items
groups: list[list[int]] = []
current: list[int] = []
current_bytes = 0
current_tokens = 0
for i, text in enumerate(texts):
text_bytes = len(text.encode("utf-8")) + 8 # rough JSON overhead per item
text_tokens = max(1, len(text) // self._chars_per_token)
would_exceed = current and (
len(current) >= item_cap
or current_bytes + text_bytes > self._batch_max_bytes
or current_tokens + text_tokens > self._batch_max_tokens
)
if would_exceed:
groups.append(current)
current, current_bytes, current_tokens = [], 0, 0
current.append(i)
current_bytes += text_bytes
current_tokens += text_tokens
if current:
groups.append(current)
return groups
async def _embed_native_batch(
self, texts: list[str], *, client: httpx.AsyncClient
) -> list[EmbedResult]:
"""One batched call against the local backend.
TEI batches natively over its OpenAI-compatible endpoint, so it needs
none of the /api/embed probing below and can never raise
_NativeBatchUnavailable.
"""
if self._local_backend == "tei":
return await self._embed_tei_batch(texts, client=client)
return await self._embed_ollama_native_batch(texts, client=client)
async def _embed_ollama_native_batch(
self, texts: list[str], *, client: httpx.AsyncClient
) -> list[EmbedResult]:
"""One /api/embed call for a group of texts β€” Ollama's batch endpoint
(input: [...]) returns one embedding array per input in one real
batched forward pass, avoiding N separate HTTP round trips.
Response order is assumed to match input order (Ollama's documented
/api/embed contract). If that assumption breaks on some deployed
version, mismatched embeddings would silently attach to the wrong
chunk β€” this is flagged here rather than silently trusted; verify
against the deployed Ollama version before relying on this path in
production, e.g. with a small ordered smoke test.
"""
import time
start = time.monotonic()
resp = await client.post(
f"{self._ollama_url}/api/embed",
json={"model": self._model, "input": texts, "keep_alive": -1},
timeout=self._timeout,
)
if resp.status_code == 404:
# Older Ollama without the batch endpoint β€” let caller fall back.
raise _NativeBatchUnavailable()
if resp.status_code != 200:
logger.error("Ollama batch embed error %d: %s", resp.status_code, resp.text[:500])
resp.raise_for_status()
data = resp.json()
embeddings = data.get("embeddings")
if not embeddings or len(embeddings) != len(texts):
raise ValueError(
f"Ollama /api/embed returned {len(embeddings) if embeddings else 0} "
f"embeddings for {len(texts)} inputs"
)
duration_ms = int((time.monotonic() - start) * 1000)
per_item_ms = duration_ms // max(1, len(texts))
return [
EmbedResult(embedding=emb, model=self._model, duration_ms=per_item_ms)
for emb in embeddings
]
async def _embed_remote_batch(
self, texts: list[str], *, client: httpx.AsyncClient
) -> list[EmbedResult]:
"""One OpenAI-compatible /v1/embeddings call for a group of texts.
Works with any provider exposing that shape (DeepInfra, Together,
HuggingFace TEI, vLLM, ...) as long as it serves the *same* model as
the local Ollama. Results are re-ordered by the response's `index`
field rather than trusting array order, since a mismatched pairing
would attach embeddings to the wrong chunks silently.
"""
import time
start = time.monotonic()
headers = {"Content-Type": "application/json"}
if self._remote_key:
headers["Authorization"] = f"Bearer {self._remote_key}"
resp = await client.post(
self._remote_url,
json={"model": self._remote_model, "input": texts},
headers=headers,
timeout=self._remote_timeout,
)
if resp.status_code != 200:
logger.error(
"Remote embed error %d: %s", resp.status_code, resp.text[:500]
)
resp.raise_for_status()
payload = resp.json()
usage = payload.get("usage") or {}
if usage.get("prompt_tokens"):
self._record_spend(int(usage["prompt_tokens"]))
rows = payload.get("data") or []
if len(rows) != len(texts):
raise ValueError(
f"Remote embeddings endpoint returned {len(rows)} vectors "
f"for {len(texts)} inputs"
)
ordered: list[list[float] | None] = [None] * len(texts)
for position, row in enumerate(rows):
index = row.get("index")
target = index if isinstance(index, int) and 0 <= index < len(texts) else position
ordered[target] = row.get("embedding") or []
duration_ms = int((time.monotonic() - start) * 1000)
per_item_ms = duration_ms // max(1, len(texts))
results: list[EmbedResult] = []
for vector in ordered:
if not vector:
raise ValueError("Remote embeddings endpoint returned an empty vector")
results.append(EmbedResult(
embedding=self._check_dims(vector, "Remote embeddings endpoint"),
model=self._remote_model,
duration_ms=per_item_ms,
))
return results
@staticmethod
def _retry_after_seconds(response) -> float | None:
"""`Retry-After` in seconds, when the provider tells us how long to wait.
Only the delta-seconds form is honoured. The HTTP-date form is rare on
embedding APIs and parsing it wrong would be worse than falling back to
our own backoff.
"""
raw = (response.headers.get("Retry-After") or "").strip()
if not raw:
return None
try:
seconds = float(raw)
except ValueError:
return None
# Never let a provider park an ingest for minutes; local is right there.
return seconds if 0 < seconds <= 30 else None
async def _embed_remote_batch_with_retry(
self, texts: list[str], *, client: httpx.AsyncClient
) -> list[EmbedResult]:
"""_embed_remote_batch, retried on failures that are worth retrying.
The batch path had no retry at all, while EMBED_RETRY_ATTEMPTS was
wired only into the single-text path β€” so the most retryable error
there is silently downgraded a whole document to the local CPU
backend. On 2026-08-07 the provider returned exactly that: HTTP 429
"The engine is currently overloaded. Please try again later" β€” upstream
congestion relayed through OpenRouter, not a quota on our key.
ValueError is never retried: a dimension or vector-count mismatch is a
misconfiguration, and repeating the call only wastes money before the
caller fails loudly (which it must β€” see embed_batch).
"""
last_error: Exception | None = None
for attempt in range(1, self._retry_attempts + 1):
try:
return await self._embed_remote_batch(texts, client=client)
except ValueError:
raise
except httpx.HTTPStatusError as err:
status = err.response.status_code
if status not in _RETRYABLE_STATUS or attempt == self._retry_attempts:
raise
delay = (self._retry_after_seconds(err.response)
or self._retry_backoff * attempt)
last_error = err
logger.warning(
"Remote embed HTTP %d on attempt %d/%d β€” retrying in %.1fs",
status, attempt, self._retry_attempts, delay,
)
except (httpx.TimeoutException, httpx.TransportError) as err:
if attempt == self._retry_attempts:
raise
delay = self._retry_backoff * attempt
last_error = err
logger.warning(
"Remote embed %s on attempt %d/%d β€” retrying in %.1fs",
type(err).__name__, attempt, self._retry_attempts, delay,
)
await asyncio.sleep(delay)
# Unreachable: the final attempt either returns or raises above.
raise last_error or RuntimeError("remote embed retry loop exhausted")
async def _embed_one_with_retry(
self, text: str, *, client: httpx.AsyncClient
) -> EmbedResult | None:
"""Single-text embed with bounded retries.
The per-chunk path is the last line of defence: whatever it returns
None for is dropped from the index entirely, so a lone transient
timeout must not be enough to lose a chunk.
"""
for attempt in range(1, self._retry_attempts + 1):
try:
return await self.embed(text, client=client)
except Exception as err:
if attempt == self._retry_attempts:
logger.warning(
"Embed failed after %d attempts (%s) β€” chunk will be skipped",
self._retry_attempts, type(err).__name__,
)
return None
await asyncio.sleep(self._retry_backoff * attempt)
return None
async def embed_batch(
self, texts: list[str], *, client: httpx.AsyncClient, concurrency: int | None = None
) -> list[EmbedResult | None]:
"""Embed multiple texts, preferring one batched /api/embed call per
group (see _group_for_batching) over N sequential/concurrent
single-text calls. Falls back to semaphore-bounded concurrent
single-text calls if the deployed Ollama doesn't support /api/embed.
Order of the returned list matches the order of `texts`. An entry is
`None` where that specific text's embedding failed (transient error
within an otherwise-successful batch) β€” callers must skip those
rather than assume every entry is populated.
"""
if not texts:
return []
# Remote GPU provider first when configured β€” same model, far faster.
if self._ingestion_cloud and self._remote_healthy:
results: list[EmbedResult | None] = [None] * len(texts)
pending_idx: list[int] = []
for group_idx in self._group_for_batching(texts):
group_texts = [texts[i] for i in group_idx]
try:
for i, result in zip(group_idx, await self._embed_remote_batch_with_retry(
group_texts, client=client,
)):
results[i] = result
except ValueError:
# Dimension/contract violation β€” a misconfiguration that
# retrying cannot fix, and one we must never paper over by
# quietly falling back. Fail the whole call loudly.
self._remote_healthy = False
raise
except Exception as err:
# This group only. `break` here used to abandon every
# remaining group and discard the ones already embedded
# remotely, so one transient 429 re-ran the entire document
# on local CPU and threw away cloud calls already paid for.
# The local path has always degraded per-group; so does
# this one now.
logger.warning(
"Remote embed failed for group of %d (%s) β€” that group "
"falls back to local",
len(group_texts), type(err).__name__,
)
pending_idx.extend(group_idx)
if not pending_idx:
return results
if not self._remote_fallback:
logger.error("Remote embeddings failed and local fallback is disabled")
return results
logger.warning(
"Falling back to local %s embeddings for %d of %d text(s)",
self._local_backend, len(pending_idx), len(texts),
)
for i, result in zip(pending_idx, await self._embed_batch_local(
[texts[i] for i in pending_idx], client=client, concurrency=concurrency,
)):
results[i] = result
return results
return await self._embed_batch_local(
texts, client=client, concurrency=concurrency,
)
async def _embed_batch_local(
self, texts: list[str], *, client: httpx.AsyncClient,
concurrency: int | None = None,
) -> list[EmbedResult | None]:
"""The local-backend half of embed_batch, callable for a subset.
Split out so a partial remote failure re-embeds only the groups that
actually failed, instead of starting the whole batch over.
"""
if not texts:
return []
if self._native_batch_supported is not False:
# Regroup for the LOCAL backend β€” the groups the remote path would
# have used are sized for a GPU and TEI would reject them.
groups = self._group_for_batching(
texts, max_items=self._local_batch_max_items,
)
try:
results: list[EmbedResult | None] = [None] * len(texts)
for group_idx in groups:
group_texts = [texts[i] for i in group_idx]
try:
group_results = await self._embed_native_batch(group_texts, client=client)
except _NativeBatchUnavailable:
raise # endpoint doesn't exist β€” abandon native path entirely
except Exception as group_err:
# Transient failure (timeout, 5xx, count mismatch) on
# this one group only β€” don't lose every other
# already-batched group over it. Fall back to
# per-text calls for just this group's texts, same
# as the old sequential behaviour, so one bad batch
# degrades to per-chunk skips instead of failing the
# whole document.
logger.warning(
"Batch embed failed for group of %d texts (%s) β€” "
"retrying individually",
len(group_texts), type(group_err).__name__,
)
group_results = await asyncio.gather(
*(self._embed_one_with_retry(t, client=client)
for t in group_texts),
return_exceptions=True,
)
group_results = [
r if isinstance(r, EmbedResult) else None
for r in group_results
]
for i, result in zip(group_idx, group_results):
results[i] = result
self._native_batch_supported = True
return results
except _NativeBatchUnavailable:
logger.warning(
"Ollama /api/embed batch endpoint unavailable (404) β€” "
"falling back to bounded concurrent single-text calls for "
"the rest of this process's lifetime."
)
self._native_batch_supported = False
# Fallback: OLLAMA_NUM_PARALLEL=1 in production serializes requests
# server-side regardless, so keep this concurrency low by default β€”
# it mainly overlaps HTTP/network latency, not real parallel compute.
semaphore = asyncio.Semaphore(concurrency or self._fallback_concurrency)
async def _embed_one(text: str) -> EmbedResult | None:
async with semaphore:
return await self._embed_one_with_retry(text, client=client)
return list(await asyncio.gather(*(_embed_one(t) for t in texts)))
@staticmethod
def to_vector_literal(embedding: list[float]) -> str:
"""Format float list as pgvector literal: '[0.1,0.2,...]'"""
return "[" + ",".join(str(v) for v in embedding) + "]"