# -*- coding: utf-8 -*- """Query-path overflow routing: local-first, cloud under contention. Ollama serves embeddings from a single slot, so a query arriving while another is in flight waits out the first before it even starts. Measured 2026-08-06: remote bge-m3 answers a single query in ~287ms at ~$0.02 per 100k queries, so the moment local is busy the cloud is both faster and effectively free. Ingestion (embed_batch) always prefers remote; queries only overflow under contention. """ import asyncio import pytest from app.config import get_settings from app.services.embed import EmbedResult, EmbedService _DIMS = get_settings().EMBED_DIMENSIONS class _Recorder: """Counts which endpoint was hit; local can be made slow or broken.""" def __init__(self, local_delay=0.0, local_fails=False, dims=None): dims = dims or _DIMS self.local_calls = 0 self.remote_calls = 0 self.local_delay = local_delay self.local_fails = local_fails self.dims = dims async def post(self, url, **kwargs): if "openrouter" in url or "/v1/embeddings" in url: self.remote_calls += 1 texts = kwargs["json"]["input"] return _Resp(200, {"data": [{"index": i, "embedding": [0.2] * self.dims} for i in range(len(texts))]}) self.local_calls += 1 if self.local_delay: await asyncio.sleep(self.local_delay) if self.local_fails: raise RuntimeError("local down") return _Resp(200, {"embedding": [0.1] * self.dims}) class _Resp: def __init__(self, status_code, payload): self.status_code, self._p = status_code, payload self.text = str(payload) def json(self): return self._p def raise_for_status(self): pass def _svc(**kw) -> EmbedService: s = EmbedService() s._remote_enabled = True s._remote_url = "http://remote/v1/embeddings" s._query_overflow = True s._retry_backoff = 0.0 for k, v in kw.items(): setattr(s, k, v) return s def test_idle_local_is_preferred(): """No contention means no spend.""" svc, rec = _svc(), _Recorder() asyncio.run(svc.embed("سؤال", client=rec)) assert rec.local_calls == 1 and rec.remote_calls == 0 assert svc.query_routing["local"] == 1 def test_busy_local_overflows_to_remote(): """The second concurrent query must not queue behind the first.""" svc, rec = _svc(), _Recorder(local_delay=0.05) async def go(): return await asyncio.gather(*(svc.embed("سؤال", client=rec) for _ in range(3))) results = asyncio.run(go()) assert len(results) == 3 assert rec.local_calls == 1, "only one query should occupy the single local slot" assert rec.remote_calls == 2 assert svc.query_routing["overflow_busy"] == 2 def test_slow_local_overflows_after_the_deadline(): svc = _svc(_local_deadline=0.05) rec = _Recorder(local_delay=5.0) result = asyncio.run(svc.embed("سؤال", client=rec)) assert result is not None assert rec.remote_calls == 1 assert svc.query_routing["overflow_slow"] == 1 def test_breaker_opens_after_repeated_local_failures(): """A local outage must stop costing every request the full deadline.""" svc = _svc(_breaker_threshold=2) rec = _Recorder(local_fails=True) for _ in range(2): asyncio.run(svc.embed("سؤال", client=rec)) local_after_failures = rec.local_calls asyncio.run(svc.embed("سؤال", client=rec)) # breaker should be open now assert svc._breaker_open() assert rec.local_calls == local_after_failures, "local retried while breaker open" assert svc.query_routing["overflow_breaker"] == 1 def test_remote_failure_falls_back_to_local(): """An outage at either end degrades latency, never breaks retrieval.""" svc = _svc() rec = _Recorder() async def failing_remote(url, **kwargs): if "/v1/embeddings" in url: raise RuntimeError("remote down") return await _Recorder.post(rec, url, **kwargs) class _C: post = staticmethod(failing_remote) svc._local_inflight = 1 # force the overflow decision result = asyncio.run(svc.embed("سؤال", client=_C())) assert result is not None assert svc.query_routing["remote_failed_to_local"] == 1 def test_wrong_dimensions_still_raise_through_the_overflow_path(): """Overflow must never smuggle in an incompatible model.""" svc = _svc() svc._local_inflight = 1 rec = _Recorder(dims=1536) with pytest.raises(ValueError, match="not interchangeable"): asyncio.run(svc.embed("سؤال", client=rec)) def test_overflow_disabled_keeps_everything_local(): svc = _svc(_query_overflow=False) rec = _Recorder() asyncio.run(svc.embed("سؤال", client=rec)) assert rec.remote_calls == 0 # ── Half-open recovery & runaway-spend guard ──────────────────────────────── def test_breaker_probes_local_before_restoring_full_traffic(): """Half-open: one probe tests local, success closes the breaker.""" svc = _svc(_breaker_threshold=1, _breaker_cooldown=0.0) rec = _Recorder(local_fails=True) asyncio.run(svc.embed("سؤال", client=rec)) # trips the breaker assert svc._breaker_open_until != 0.0 healthy = _Recorder() asyncio.run(svc.embed("سؤال", client=healthy)) # probe goes to local assert healthy.local_calls == 1, "probe did not reach local" assert svc._breaker_open_until == 0.0, "breaker did not close after success" def test_daily_budget_stops_overflow(): """A runaway loop must not bill all night.""" svc = _svc(_daily_budget=0.0000001, _usd_per_1k=1.0) svc._record_spend(1000) # blow the tiny ceiling rec = _Recorder() svc._local_inflight = 1 # would normally overflow asyncio.run(svc.embed("سؤال", client=rec)) assert rec.remote_calls == 0, "spent past the budget ceiling" assert svc.query_routing["budget_capped_to_local"] == 1 def test_budget_does_not_block_failover_when_local_is_down(): """Cost control must never turn a local outage into a total outage.""" svc = _svc(_daily_budget=0.0000001, _usd_per_1k=1.0, _breaker_threshold=1) svc._record_spend(1000) svc._breaker_open_until = float("inf") # local considered down rec = _Recorder() asyncio.run(svc.embed("سؤال", client=rec)) assert rec.remote_calls == 1, "failover blocked by budget — outage" def test_spend_resets_on_a_new_day(): svc = _svc(_daily_budget=1.0, _usd_per_1k=1.0) svc._record_spend(1000) assert svc._budget_exhausted() import datetime svc._spend_day = datetime.date.today() - datetime.timedelta(days=1) assert not svc._budget_exhausted() # ── Self-describing telemetry ─────────────────────────────────────────────── def test_query_log_names_the_model_and_dimensions(caplog): """A log line must stay interpretable across a model migration. Without model/dims recorded, comparing latency before and after a cutover depends on remembering when the cutover happened. """ import logging svc, rec = _svc(), _Recorder() with caplog.at_level(logging.INFO, logger="app.services.embed"): asyncio.run(svc.embed("سؤال", client=rec)) line = next(r.getMessage() for r in caplog.records if "embed_query" in r.getMessage()) assert "model=" in line and "dims=" in line assert "provider=local" in line and "cost_usd=0.00000000" in line def test_cloud_route_logs_the_remote_model_not_the_local_one(): """The vector came from the remote weights — log those.""" svc, rec = _svc(), _Recorder() svc._local_inflight = 1 route = {"provider": "local", "reason": "local"} asyncio.run(svc._route_query_embed("سؤال", client=rec, route=route)) assert route["provider"] == "cloud" # ── Ingestion routing ─────────────────────────────────────────────────────── def test_ingestion_prefers_cloud_when_enabled(): """Books must not monopolise the single local slot.""" svc, rec = _svc(), _Recorder() svc._ingestion_cloud = True asyncio.run(svc.embed_batch(["نص ١", "نص ٢"], client=rec)) assert rec.remote_calls >= 1 and rec.local_calls == 0 def test_ingestion_stays_local_when_cloud_disabled(): svc, rec = _svc(), _Recorder() svc._ingestion_cloud = False asyncio.run(svc.embed_batch(["نص ١"], client=rec)) assert rec.remote_calls == 0 and rec.local_calls >= 1 # ── Cloud-only mode (2026-08-06 bge-m3 cutover) ───────────────────────────── # # OpenRouter serves only baai/bge-m3 (1024 dims); the old local model was # nomic-embed-text (768). Mixing them is meaningless, and the container's 2GB # cap cannot hold bge-m3 (1.2GB) alongside the app — so until the VPS is # upgraded, every embedding goes to the cloud and the local backend is off. def test_cloud_only_sends_queries_straight_to_the_remote(): """No slot check, no deadline, no breaker — there is no local backend.""" svc, rec = _svc(), _Recorder() svc._local_enabled = False asyncio.run(svc.embed("سؤال", client=rec)) assert rec.local_calls == 0 and rec.remote_calls == 1 assert svc.query_routing["cloud_only"] == 1 def test_cloud_only_still_enforces_dimensions(): svc = _svc() svc._local_enabled = False rec = _Recorder(dims=_DIMS + 256) with pytest.raises(ValueError, match="not interchangeable"): asyncio.run(svc.embed("سؤال", client=rec)) def test_cloud_only_without_a_provider_refuses_to_start(): """Silently embedding nothing would be far worse than failing loudly.""" import app.services.embed as E original = E.get_settings class _S: def __getattr__(self, name): return getattr(original(), name) EMBED_LOCAL_ENABLED = False EMBED_PROVIDER = "ollama" # no remote configured EMBED_REMOTE_URL = "" E.get_settings = lambda: _S() try: with pytest.raises(RuntimeError, match="no way to embed"): EmbedService() finally: E.get_settings = original