Spaces:
Build error

File size: 10,518 Bytes
0cc259a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
09feb6f
0cc259a
 
 
09feb6f
 
 
0cc259a
 
 
09feb6f
 
0cc259a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
09feb6f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
# -*- 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