Spaces:
Build error

trackademi / tests /test_embed_resilience.py
anwarKXC
feat: implement remote batch retry logic with per-group fallback for transient errors
6a0e581
Raw History Blame Contribute Delete
14.2 kB
# -*- coding: utf-8 -*-
"""Embedding loss prevention and remote-provider safety.
Regression origin (2026-08-05): a 252-page textbook generated 154 chunks but
indexed only 78. Two 64-item groups exceeded EMBED_REQUEST_TIMEOUT on the
CPU-only VPS, fell back to per-text calls with no retries, and 76 of those
also timed out. The document was still marked INDEXED, so half the book was
silently unsearchable.
"""
import asyncio
import pytest
from app.config import get_settings
from app.services.embed import EmbedResult, EmbedService
from app.services.ingest import _MIN_INDEX_COMPLETENESS
_DIMS = get_settings().EMBED_DIMENSIONS
class _FlakyClient:
"""Fails the first `fail_times` calls, then succeeds."""
def __init__(self, fail_times: int, dims: int = None):
dims = dims or _DIMS
self.fail_times = fail_times
self.calls = 0
self.dims = dims
async def post(self, url, **kwargs):
self.calls += 1
if self.calls <= self.fail_times:
raise TimeoutError("simulated read timeout")
return _Response(200, {"embedding": [0.1] * self.dims})
class _Response:
def __init__(self, status_code, payload):
self.status_code = status_code
self._payload = payload
self.text = str(payload)
def json(self):
return self._payload
def raise_for_status(self):
if self.status_code != 200:
raise RuntimeError(f"HTTP {self.status_code}")
def _service(**overrides) -> EmbedService:
svc = EmbedService()
svc._retry_backoff = 0.0 # keep tests fast
for key, value in overrides.items():
setattr(svc, key, value)
return svc
# ── Retry behaviour ─────────────────────────────────────────────────────────
def test_transient_failure_is_retried_not_dropped():
"""One timeout must not cost a chunk β€” that is how the 76 were lost."""
svc = _service()
client = _FlakyClient(fail_times=2)
result = asyncio.run(svc._embed_one_with_retry("Ω†Ψ΅", client=client))
assert result is not None
assert len(result.embedding) == _DIMS
assert client.calls == 3 # two failures, then success
def test_retry_gives_up_and_reports_none():
svc = _service()
client = _FlakyClient(fail_times=99)
assert asyncio.run(svc._embed_one_with_retry("Ω†Ψ΅", client=client)) is None
assert client.calls == svc._retry_attempts # bounded, not infinite
def test_batches_are_small_enough_for_a_slow_backend():
"""64 items at ~0.3 chunks/sec overran the 120s timeout."""
svc = _service()
assert svc._batch_max_items <= 32
# ── Dimension guard ─────────────────────────────────────────────────────────
def test_wrong_dimension_is_rejected():
"""A 768-wide column plus a different model equals meaningless similarity."""
svc = _service()
with pytest.raises(ValueError, match="not interchangeable"):
svc._check_dims([0.0] * 1536, "some provider")
def test_correct_dimension_passes_through():
svc = _service()
assert len(svc._check_dims([0.0] * _DIMS, "ollama")) == _DIMS
# ── Remote provider ─────────────────────────────────────────────────────────
class _RemoteClient:
"""OpenAI-compatible endpoint returning vectors out of order."""
def __init__(self, dims=None, shuffle=True):
dims = dims or _DIMS
self.dims = dims
self.shuffle = shuffle
async def post(self, url, **kwargs):
texts = kwargs["json"]["input"]
rows = [
{"index": i, "embedding": [float(i)] * self.dims}
for i in range(len(texts))
]
if self.shuffle:
rows = list(reversed(rows))
return _Response(200, {"data": rows})
def test_remote_results_are_reordered_by_index():
"""Trusting array order would attach vectors to the wrong chunks."""
svc = _service(_remote_enabled=True, _remote_url="http://x/v1/embeddings")
results = asyncio.run(
svc._embed_remote_batch(["a", "b", "c"], client=_RemoteClient())
)
# Vector i is filled with float(i); after reordering position i must hold i.
assert [r.embedding[0] for r in results] == [0.0, 1.0, 2.0]
def test_remote_model_with_wrong_dimensions_raises():
"""Misconfiguration must fail loudly rather than poison the index."""
svc = _service(_remote_enabled=True, _remote_url="http://x/v1/embeddings")
with pytest.raises(ValueError):
asyncio.run(
svc._embed_remote_batch(["a"], client=_RemoteClient(dims=_DIMS + 256))
)
def test_remote_batch_size_is_larger_than_local():
"""A hosted GPU should not be throttled to the CPU box's group size."""
from app.config import get_settings
settings = get_settings()
assert settings.EMBED_REMOTE_BATCH_MAX_ITEMS > settings.EMBED_BATCH_MAX_ITEMS
# ── Completeness floor ──────────────────────────────────────────────────────
def test_completeness_floor_would_have_failed_the_biology_run():
"""78/154 must not be reportable as a successful import."""
assert (78 / 154) < _MIN_INDEX_COMPLETENESS
def test_completeness_floor_tolerates_a_few_stragglers():
assert (152 / 154) >= _MIN_INDEX_COMPLETENESS
# ── Head-of-line blocking (2026-08-06) ──────────────────────────────────────
#
# Ollama forces its embedding runner to a single slot, so one batched request
# holds that slot for the whole group and a user's query embedding queues
# behind it. Measured on the VPS: a batch of 8 made a concurrent query wait
# 21.9s versus 2.6s for the same 8 sent individually β€” and at the previous
# group size of 16 the wait exceeded ROUTING_MAX_TIMEOUT_MS, so retrieval
# timed out and the gateway answered with no context at all.
#
# Batching also bought no throughput (speedup 1.06x), so grouping locally is
# pure downside.
def test_local_batching_is_disabled():
"""Group size >1 blocks live queries and buys nothing on this backend."""
from app.config import get_settings
assert get_settings().EMBED_BATCH_MAX_ITEMS == 1
def test_local_grouping_never_exceeds_the_retrieval_timeout():
"""A group must not be able to out-wait ROUTING_MAX_TIMEOUT_MS.
Worst case, a query arrives just as a group starts and waits for all of
it. At ~2.8s per chunk on the CPU-only VPS, a group of 8 already exceeds
the 20s ceiling and guarantees an ungrounded answer.
"""
from app.config import get_settings
settings = get_settings()
seconds_per_chunk = 2.8 # measured
worst_case_ms = settings.EMBED_BATCH_MAX_ITEMS * seconds_per_chunk * 1000
assert worst_case_ms < settings.ROUTING_MAX_TIMEOUT_MS
def test_remote_batching_stays_enabled():
"""The reasoning is backend-specific β€” a real batching backend still wants groups."""
from app.config import get_settings
assert get_settings().EMBED_REMOTE_BATCH_MAX_ITEMS > 1
# ── Constructor completeness (2026-08-06) ───────────────────────────────────
#
# A refactor left `self._native_batch_supported = None` stranded after a
# `return` inside another method, so it was never assigned and every
# embed_batch() call died with AttributeError β€” breaking all ingestion while
# queries (which use embed(), not embed_batch()) kept working, so nothing
# looked wrong. The suite missed it because no test called embed_batch on a
# real, unmocked instance.
def test_embed_batch_works_on_a_freshly_constructed_service():
"""The end-to-end path a real ingest takes, with nothing patched in."""
svc = EmbedService()
svc._retry_backoff = 0.0
results = asyncio.run(svc.embed_batch(["Ω†Ψ΅ Ψ£ΩˆΩ„", "Ω†Ψ΅ ثانٍ"], client=_FlakyClient(0)))
assert len(results) == 2
assert all(r is not None and len(r.embedding) == _DIMS for r in results)
def test_embed_batch_on_empty_input_is_a_noop():
assert asyncio.run(EmbedService().embed_batch([], client=_FlakyClient(0))) == []
def test_every_attribute_embed_batch_touches_is_initialised():
"""Guards against another assignment drifting out of __init__."""
svc = EmbedService()
for attr in (
"_native_batch_supported", "_batch_max_items", "_batch_max_bytes",
"_batch_max_tokens", "_fallback_concurrency", "_retry_attempts",
"_retry_backoff", "_expected_dims", "_remote_enabled", "_remote_healthy",
):
assert hasattr(svc, attr), f"EmbedService.__init__ never sets {attr}"
# ── Remote batch retry + per-group fallback (2026-08-07) ───────────────
import httpx
import pytest
from app.services.embed import _RETRYABLE_STATUS
def _http_error(status: int, retry_after: str | None = None):
headers = {"Retry-After": retry_after} if retry_after else {}
response = httpx.Response(status, headers=headers, request=httpx.Request("POST", "http://x"))
return httpx.HTTPStatusError("boom", request=response.request, response=response)
def test_a_429_is_retried_before_falling_back(monkeypatch):
"""The provider said "the engine is currently overloaded, try again later"
β€” the single most retryable error there is β€” and the batch path had no
retry at all, so one blip downgraded a whole document to local CPU."""
from app.services.embed import EmbedService
svc = EmbedService.__new__(EmbedService)
svc._retry_attempts = 3
svc._retry_backoff = 0.0
calls = {"n": 0}
async def _flaky(texts, *, client):
calls["n"] += 1
if calls["n"] < 3:
raise _http_error(429)
return ["ok"]
svc._embed_remote_batch = _flaky
out = asyncio.run(svc._embed_remote_batch_with_retry(["t"], client=None))
assert out == ["ok"]
assert calls["n"] == 3
def test_a_dimension_mismatch_is_never_retried():
"""Repeating a misconfigured call only spends money before the caller
fails loudly, which it must β€” a half-and-half vector space is worse than
an error."""
from app.services.embed import EmbedService
svc = EmbedService.__new__(EmbedService)
svc._retry_attempts = 3
svc._retry_backoff = 0.0
calls = {"n": 0}
async def _bad(texts, *, client):
calls["n"] += 1
raise ValueError("returned 512-dim vectors")
svc._embed_remote_batch = _bad
with pytest.raises(ValueError):
asyncio.run(svc._embed_remote_batch_with_retry(["t"], client=None))
assert calls["n"] == 1
def test_a_404_is_not_retried():
from app.services.embed import EmbedService
svc = EmbedService.__new__(EmbedService)
svc._retry_attempts = 3
svc._retry_backoff = 0.0
calls = {"n": 0}
async def _gone(texts, *, client):
calls["n"] += 1
raise _http_error(404)
svc._embed_remote_batch = _gone
with pytest.raises(httpx.HTTPStatusError):
asyncio.run(svc._embed_remote_batch_with_retry(["t"], client=None))
assert calls["n"] == 1
assert 404 not in _RETRYABLE_STATUS
def test_retry_after_is_honoured_but_capped():
from app.services.embed import EmbedService
assert EmbedService._retry_after_seconds(
httpx.Response(429, headers={"Retry-After": "5"}, request=httpx.Request("POST", "http://x"))
) == 5.0
# A provider must not park an ingest for minutes when local is right there.
assert EmbedService._retry_after_seconds(
httpx.Response(429, headers={"Retry-After": "600"}, request=httpx.Request("POST", "http://x"))
) is None
assert EmbedService._retry_after_seconds(
httpx.Response(429, request=httpx.Request("POST", "http://x"))
) is None
def test_only_the_failed_group_falls_back_to_local():
"""A `break` 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 β€” throwing away cloud calls already paid for."""
from app.services.embed import EmbedResult, EmbedService
svc = EmbedService.__new__(EmbedService)
svc._ingestion_cloud = True
svc._remote_healthy = True
svc._remote_fallback = True
svc._local_backend = "tei"
svc._retry_attempts = 1
svc._retry_backoff = 0.0
texts = ["a", "b", "c", "d"]
svc._group_for_batching = lambda t, **kw: [[0, 1], [2, 3]]
async def _remote(group, *, client):
if group == ["c", "d"]:
raise _http_error(429)
return [EmbedResult(embedding=[0.1], model="cloud", duration_ms=1) for _ in group]
svc._embed_remote_batch_with_retry = _remote
local_seen: list[list[str]] = []
async def _local(subset, *, client, concurrency=None):
local_seen.append(list(subset))
return [EmbedResult(embedding=[0.2], model="tei", duration_ms=1) for _ in subset]
svc._embed_batch_local = _local
out = asyncio.run(svc.embed_batch(texts, client=None))
# Only the failed group is recomputed β€” the cloud work is kept.
assert local_seen == [["c", "d"]]
assert [r.model for r in out] == ["cloud", "cloud", "tei", "tei"]
def test_a_dimension_mismatch_still_fails_the_whole_call():
"""Never paper over a contract violation with a local fallback."""
from app.services.embed import EmbedService
svc = EmbedService.__new__(EmbedService)
svc._ingestion_cloud = True
svc._remote_healthy = True
svc._remote_fallback = True
svc._local_backend = "tei"
svc._group_for_batching = lambda t, **kw: [[0]]
async def _remote(group, *, client):
raise ValueError("512-dim vectors")
svc._embed_remote_batch_with_retry = _remote
with pytest.raises(ValueError):
asyncio.run(svc.embed_batch(["a"], client=None))
assert svc._remote_healthy is False