From d53f68afe74bce9232c2345bece77164a1b38a02 Mon Sep 17 00:00:00 2001 From: xin Date: Fri, 27 Nov 2026 07:14:34 +0000 Subject: [PATCH] 0.8.0: integrations no longer switch the cache off during cold start While a workspace has no model of its own, /v1/verify rejects every call. The integrations send every hit, so they rejected all of them and silently dropped the notice saying why. - VerifiedCache (LangChain): cold_start="serve" (default) serves cold-start hits exactly as the wrapped cache returned them; cold_start="reject" keeps the old behavior. The first cold-start verdict is logged once. - CacheVerifierEvaluation (GPTCache): fallback= takes the evaluator it replaces; during cold start its score divided by its range width is returned, so GPTCache's similarity_threshold accepts exactly the hits it did before. Without a fallback cold-start hits stay misses, with a warning. direct_hit= serves hits whose fallback score is at least that high without a verify call. similarity_score is deliberately not sent to verify, so it can't diverge from the raw scale report_feedback documents. - VerifyResult.cold_start property. --- CHANGELOG.md | 16 ++++ README.md | 30 +++++++- cacheverifier/__init__.py | 2 +- cacheverifier/client.py | 15 ++++ cacheverifier/integrations/_cold_start.py | 52 +++++++++++++ cacheverifier/integrations/gptcache.py | 86 +++++++++++++++++++-- cacheverifier/integrations/langchain.py | 25 +++++- examples/gptcache_example.py | 8 +- pyproject.toml | 2 +- tests/test_gptcache_integration.py | 94 +++++++++++++++++++++++ tests/test_langchain_integration.py | 62 +++++++++++++++ 11 files changed, 379 insertions(+), 13 deletions(-) create mode 100644 cacheverifier/integrations/_cold_start.py diff --git a/CHANGELOG.md b/CHANGELOG.md index b2905a6..9330b98 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,21 @@ # Changelog +## 0.8.0 + +The integrations no longer switch your cache off during cold start. While a +workspace has no model of its own, `/v1/verify` rejects every call; an +integration sends every hit, so that rejected all of them, silently. + +- `VerifiedCache` (LangChain) now serves cold-start hits exactly as the + wrapped cache returned them, and logs the service's notice once. Pass + `cold_start="reject"` for the old behavior. +- `CacheVerifierEvaluation` (GPTCache) takes `fallback=`, the evaluator it + replaces (e.g. `SearchDistanceEvaluation()`): during cold start GPTCache + decides with it exactly as before. Without a fallback, cold-start hits stay + misses, now with a warning saying how to keep them. `direct_hit=` serves + hits whose fallback score is at least that high without a verify call. +- `VerifyResult.cold_start`: True when no model decided the call. + ## 0.7.1 README only, no code change, so the PyPI page matches the docs: the diff --git a/README.md b/README.md index 2bb282e..93219a7 100644 --- a/README.md +++ b/README.md @@ -100,10 +100,13 @@ cv.feedback(query, candidate, was_correct=candidate_was_right, similarity_score= | `latency_ms` | server-side inference time | | `degraded` | `True` when the call failed and this result was synthesized client-side | | `notice` | why no model decided the call (cold start); `None` otherwise | +| `cold_start` | property: `True` when no model decided the call (`model_version` is `"cold_start_..."`) | | `shadow` | cold start only: a `ShadowVerdict` with what the shared stock model would have decided. The call is still rejected, so treat it as a preview | A new account starts in cold start: every call returns `approved=False` until a -Health Check shows the shared model is accurate enough on your data. Look at +Health Check shows the shared model is accurate enough on your data. (The +LangChain and GPTCache integrations hand cold-start hits back to your cache's +own decision instead, see below.) Look at `result.shadow` to see what it would have decided in the meantime: ```python @@ -164,21 +167,44 @@ set_llm_cache( ) ``` +Until your workspace has a model of its own (cold start), the service +decides nothing and would reject every hit, which would switch your cache +off. So during cold start `VerifiedCache` serves each hit exactly as the +wrapped cache returned it, the same as without it, and logs a warning the +first time. Pass `cold_start="reject"` to fall through to your model instead, +for example if you loosened the wrapped cache's similarity threshold because +a verifier would be checking its hits. + ## GPTCache Drop the verifier into a GPTCache pipeline as its similarity evaluator — no fork required: ```python from gptcache import cache +from gptcache.similarity_evaluation import SearchDistanceEvaluation from cacheverifier.integrations.gptcache import CacheVerifierEvaluation -evaluator = CacheVerifierEvaluation(api_key="cv_...") +evaluator = CacheVerifierEvaluation( + api_key="cv_...", + fallback=SearchDistanceEvaluation(), # the evaluator you used before + direct_hit=0.95, # optional: trust hits this close without verifying +) cache.init(similarity_evaluation=evaluator, ...) # when you learn a served hit's real outcome: evaluator.report_feedback(query, answer, was_correct=False, similarity_score=0.9) ``` +GPTCache applies its `similarity_threshold` to whatever the evaluator returns, +so replacing your evaluator also drops the similarity check it did. With +`fallback` set: + +- during cold start, hits are decided by the fallback exactly as before (the + first one logs a warning); `cold_start="reject"` makes them misses instead. + Without a fallback, cold-start hits are always misses. +- `direct_hit` serves hits whose fallback score is at least that high without + a verify call. It uses the same 0–1 scale as GPTCache's `similarity_threshold`. + See [`examples/gptcache_example.py`](examples/gptcache_example.py). ## Entries to refresh diff --git a/cacheverifier/__init__.py b/cacheverifier/__init__.py index 009c96d..de3e9e5 100644 --- a/cacheverifier/__init__.py +++ b/cacheverifier/__init__.py @@ -19,7 +19,7 @@ from cacheverifier.client import CacheVerifier, CacheVerifierError, ShadowVerdict, VerifyResult from cacheverifier.local import LocalVerifier, ModelCheckFailed -__version__ = "0.7.1" +__version__ = "0.8.0" __all__ = [ "CacheVerifier", "CacheVerifierError", diff --git a/cacheverifier/client.py b/cacheverifier/client.py index e4ca68b..834f578 100644 --- a/cacheverifier/client.py +++ b/cacheverifier/client.py @@ -29,9 +29,14 @@ #: failed (timeout / connection error / 5xx) and the client fell back. VERIFY_UNAVAILABLE = "verify_unavailable" +#: model_version prefix the API uses when no model ran because the workspace +#: is still in cold start ("cold_start_fail_closed" / "cold_start_auto_pending"). +COLD_START_PREFIX = "cold_start_" + _log = logging.getLogger(__name__) __all__ = [ + "COLD_START_PREFIX", "DEFAULT_BASE_URL", "DEFAULT_TIMEOUT", "DEFAULT_VERIFY_TIMEOUT", @@ -102,6 +107,8 @@ class VerifyResult: (default `False` -> `approved=False`, i.e. fall through to your LLM). - `notice`: a plain-language reason when no model decided the call (cold start); None otherwise. + - `cold_start` (property): True when no model decided the call, i.e. + `model_version` is `"cold_start_..."`. - `shadow`: on a cold-start call, what the shared stock model would have decided (a `ShadowVerdict`); None otherwise, and on servers that don't send it. @@ -129,6 +136,14 @@ class VerifyResult: local_decision: str | None = None """`LocalVerifier` only: its handle for this decision until upload.""" + @property + def cold_start(self) -> bool: + """True when no model decided this call: the workspace has no model + of its own yet and runs fail-closed, so `approved` is always False + and `notice` says what to do next. A verdict from the shared stock + model is not a cold start in this sense: a model did run.""" + return self.model_version.startswith(COLD_START_PREFIX) + @classmethod def _from_json(cls, d: dict[str, Any]) -> VerifyResult: shadow = d.get("shadow") diff --git a/cacheverifier/integrations/_cold_start.py b/cacheverifier/integrations/_cold_start.py new file mode 100644 index 0000000..75c6be0 --- /dev/null +++ b/cacheverifier/integrations/_cold_start.py @@ -0,0 +1,52 @@ +"""What an integration does with a cold-start verdict. + +While a workspace has no model of its own, `/v1/verify` runs fail-closed and +rejects every call. Rejecting a call the caller only sends in its gray zone +is cheap. An integration, though, sends every hit its cache backend +returns, and rejecting all of them switches the cache off: the hit rate +drops to zero, LLM spend goes up, and nothing is protected that wasn't +already being served before CacheVerifier was added. So by default an +integration hands a cold-start call back to the cache's own decision, and +says so once in the log. +""" + +from __future__ import annotations + +import logging +import threading + +from cacheverifier.client import VerifyResult + +COLD_START_MODES = ("serve", "reject") + +_log = logging.getLogger("cacheverifier.integrations") + + +def check_mode(cold_start: str) -> str: + if cold_start not in COLD_START_MODES: + raise ValueError(f"cold_start must be one of {COLD_START_MODES}, got {cold_start!r}") + return cold_start + + +class ColdStartNotice: + """Logs the first cold-start verdict an integration instance sees, once.""" + + def __init__(self, integration: str) -> None: + self._integration = integration + self._lock = threading.Lock() + self._logged = False + + def seen(self, result: VerifyResult, action: str) -> None: + """`action`: what the integration does with cold-start hits, in a + phrase ("serving ... unchanged until a model is ready").""" + with self._lock: + if self._logged: + return + self._logged = True + _log.warning( + "cacheverifier %s: no model decides your calls yet (%s) -- %s. %s", + self._integration, + result.model_version, + action, + result.notice or "Run a Health Check at https://www.cacheverifier.com to get one.", + ) diff --git a/cacheverifier/integrations/gptcache.py b/cacheverifier/integrations/gptcache.py index 05169b3..284fb7d 100644 --- a/cacheverifier/integrations/gptcache.py +++ b/cacheverifier/integrations/gptcache.py @@ -8,13 +8,22 @@ required. from gptcache import cache + from gptcache.similarity_evaluation import SearchDistanceEvaluation from cacheverifier.integrations.gptcache import CacheVerifierEvaluation cache.init( - similarity_evaluation=CacheVerifierEvaluation(api_key="cv_..."), + similarity_evaluation=CacheVerifierEvaluation( + api_key="cv_...", + fallback=SearchDistanceEvaluation(), # the evaluator you used before + ), ... ) +`fallback` is the evaluator this one replaces. With it, GPTCache keeps +deciding exactly as before while your workspace has no model of its own +(cold start), and `direct_hit` can skip the verify call for hits that are +close enough on their own. Without it, every cold-start hit is a miss. + `gptcache` is an optional dependency -- `pip install "cacheverifier[gptcache]"`. """ @@ -28,6 +37,7 @@ DEFAULT_VERIFY_TIMEOUT, CacheVerifier, ) +from cacheverifier.integrations._cold_start import ColdStartNotice, check_mode try: from gptcache.similarity_evaluation import SimilarityEvaluation as _GPTCacheBase @@ -38,10 +48,28 @@ class CacheVerifierEvaluation(_GPTCacheBase): """Drop-in replacement for GPTCache's built-in similarity evaluators. - `evaluation()` returns 1.0 (reuse) or 0.0 (don't) -- binary, because the - hosted verifier already makes a binary approve/reject call per gray-zone - hit rather than a softened similarity score. Callers who want GPTCache's - own threshold logic on top can wrap this rather than replace it. + `evaluation()` returns 1.0 (reuse) or 0.0 (don't) for a verified hit -- + binary, because the hosted verifier already makes a binary approve/reject + call per gray-zone hit rather than a softened similarity score. + + `fallback` (optional, recommended): the GPTCache evaluator you ran before, + e.g. `SearchDistanceEvaluation()`. GPTCache applies its + `similarity_threshold` to whatever `evaluation()` returns, so replacing + your evaluator also drops the similarity check it did. `fallback` puts it + back where it is needed: + + - cold start (no model of your own yet, so the service decides nothing): + with `cold_start="serve"` (the default) `evaluation()` returns the + fallback's own score, rescaled so GPTCache's `similarity_threshold` + accepts exactly the hits it accepted before. The first such call is + logged as a warning. `cold_start="reject"` makes every cold-start hit a + miss instead: do that if you loosened your similarity setup because a + verifier would be checking the hits. Without a fallback there is no + earlier decision to keep, so cold-start hits are misses either way. + - `direct_hit` (needs `fallback`): a hit whose rescaled fallback score is + at least this is served without calling `/v1/verify`, the way a + gray-zone setup trusts hits above its upper bound. Same 0-1 scale as + GPTCache's `similarity_threshold`. If the verify call times out or the service is unreachable, `evaluation()` returns 0.0 (don't reuse) by default -- a verifier outage falls through to @@ -57,7 +85,21 @@ def __init__( timeout: float = DEFAULT_TIMEOUT, verify_timeout: float = DEFAULT_VERIFY_TIMEOUT, fail_open: bool = False, + fallback: Any = None, + cold_start: str = "serve", + direct_hit: float | None = None, ) -> None: + if direct_hit is not None and fallback is None: + raise ValueError("direct_hit needs fallback: it is measured on the fallback evaluator's score") + if fallback is not None: + low, high = fallback.range() + if not high > low: + raise ValueError(f"fallback.range() must be increasing, got {(low, high)!r}") + self._fallback_span = float(high - low) + self.fallback = fallback + self.cold_start = check_mode(cold_start) + self.direct_hit = direct_hit + self._cold_start_notice = ColdStartNotice("CacheVerifierEvaluation") self._cv = CacheVerifier( api_key=api_key, base_url=base_url, @@ -66,10 +108,40 @@ def __init__( fail_open=fail_open, ) - def evaluation(self, src_dict: dict[str, Any], cache_dict: dict[str, Any], **_kwargs: Any) -> float: + def _fallback_score(self, src_dict: dict[str, Any], cache_dict: dict[str, Any], **kwargs: Any) -> float: + """The fallback's score divided by the width of its range: GPTCache + accepts a hit when rank >= (max - min) * similarity_threshold, so on + this evaluator's (0, 1) range the rescaled score passes exactly when + the raw one passed on the fallback's own range. Exact for any range + that starts at 0, which every built-in GPTCache evaluator's does.""" + return float(self.fallback.evaluation(src_dict, cache_dict, **kwargs)) / self._fallback_span + + def evaluation(self, src_dict: dict[str, Any], cache_dict: dict[str, Any], **kwargs: Any) -> float: + fallback_score = None + if self.fallback is not None: + fallback_score = self._fallback_score(src_dict, cache_dict, **kwargs) + if self.direct_hit is not None and fallback_score >= self.direct_hit: + return 1.0 query = src_dict.get("question") or src_dict.get("query", "") candidate_answer = cache_dict.get("answer", "") - return 1.0 if self._cv.verify(query, candidate_answer).approved else 0.0 + result = self._cv.verify(query, candidate_answer) + if result.cold_start: + serve = self.cold_start == "serve" and fallback_score is not None + if serve: + action = ( + "deciding hits with your fallback evaluator, as before, until a model is ready " + "(cold_start='reject' makes them misses instead)" + ) + elif self.cold_start == "serve": + action = ( + "every hit is a miss until a model is ready; pass fallback= to keep its decisions meanwhile" + ) + else: + action = "every hit is a miss until a model is ready (cold_start='reject')" + self._cold_start_notice.seen(result, action) + return fallback_score if serve and fallback_score is not None else 0.0 + return 1.0 if result.approved else 0.0 def range(self) -> tuple[float, float]: return 0.0, 1.0 diff --git a/cacheverifier/integrations/langchain.py b/cacheverifier/integrations/langchain.py index edd60f3..b1af8c7 100644 --- a/cacheverifier/integrations/langchain.py +++ b/cacheverifier/integrations/langchain.py @@ -24,6 +24,14 @@ default (a verifier outage becomes a normal cache miss); pass `fail_open=True` to serve it instead. +Until your workspace has a model of its own, the service decides nothing +(cold start) and would reject every hit, which switches your cache off. So +by default a cold-start hit is served exactly as the wrapped cache returned +it, the same as without `VerifiedCache`, and the first one is logged as a +warning. Pass `cold_start="reject"` to fall through to your model instead: +do that if you loosened the wrapped cache's similarity threshold because a +verifier would be checking its hits. + `langchain-core` is an optional dependency -- `pip install "cacheverifier[langchain]"`. """ @@ -39,6 +47,7 @@ DEFAULT_VERIFY_TIMEOUT, CacheVerifier, ) +from cacheverifier.integrations._cold_start import ColdStartNotice, check_mode try: from langchain_core.caches import RETURN_VAL_TYPE, BaseCache @@ -96,7 +105,10 @@ def __init__( timeout: float = DEFAULT_TIMEOUT, verify_timeout: float = DEFAULT_VERIFY_TIMEOUT, fail_open: bool = False, + cold_start: str = "serve", ) -> None: + self.cold_start = check_mode(cold_start) + self._cold_start_notice = ColdStartNotice("VerifiedCache") if client is None: if not api_key: raise ValueError("pass api_key or client") @@ -112,7 +124,18 @@ def __init__( def _approved(self, prompt: str, hit: RETURN_VAL_TYPE) -> bool: answer = "\n".join(generation.text for generation in hit) - return self.client.verify(user_question(prompt), answer).approved + result = self.client.verify(user_question(prompt), answer) + if result.cold_start: + serve = self.cold_start == "serve" + self._cold_start_notice.seen( + result, + "serving the wrapped cache's hits unchanged until a model is ready " + "(cold_start='reject' falls through to your model instead)" + if serve + else "every hit falls through to your model until one is ready (cold_start='reject')", + ) + return serve + return result.approved def lookup(self, prompt: str, llm_string: str) -> RETURN_VAL_TYPE | None: hit = self.cache.lookup(prompt, llm_string) diff --git a/examples/gptcache_example.py b/examples/gptcache_example.py index de2fd9c..a701f42 100644 --- a/examples/gptcache_example.py +++ b/examples/gptcache_example.py @@ -14,6 +14,7 @@ from gptcache.adapter.api import get, put from gptcache.embedding import Onnx from gptcache.manager import CacheBase, VectorBase, get_data_manager +from gptcache.similarity_evaluation import SearchDistanceEvaluation from cacheverifier.integrations.gptcache import CacheVerifierEvaluation @@ -23,7 +24,12 @@ VectorBase("faiss", dimension=embedding.dimension), ) -evaluator = CacheVerifierEvaluation(api_key=os.environ["CACHEVERIFIER_API_KEY"]) +# fallback: the evaluator this replaces. It keeps deciding hits while your workspace +# has no model of its own yet (cold start), instead of every hit becoming a miss. +evaluator = CacheVerifierEvaluation( + api_key=os.environ["CACHEVERIFIER_API_KEY"], + fallback=SearchDistanceEvaluation(), +) cache.init( embedding_func=embedding.to_embeddings, diff --git a/pyproject.toml b/pyproject.toml index c8a1bed..5bcf3ba 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -4,7 +4,7 @@ build-backend = "hatchling.build" [project] name = "cacheverifier" -version = "0.7.1" +version = "0.8.0" description = "Python client for the CacheVerifier semantic-cache verification API, hosted or scored locally" readme = "README.md" requires-python = ">=3.9" diff --git a/tests/test_gptcache_integration.py b/tests/test_gptcache_integration.py index 4d5710f..9e48b15 100644 --- a/tests/test_gptcache_integration.py +++ b/tests/test_gptcache_integration.py @@ -53,3 +53,97 @@ def handler(request: httpx.Request) -> httpx.Response: assert seen["path"] == "/v1/feedback" assert seen["body"]["similarity_score"] == 0.9 assert seen["body"]["was_correct"] is False + + +import logging + +import pytest + +_COLD_START = { + "approved": False, + "score": 0.0, + "threshold": 0.0, + "model_version": "cold_start_fail_closed", + "latency_ms": 0.0, + "decision_rule": "cold_start", + "notice": "No model of your own yet.", +} + + +class _Distance: + """Stands in for GPTCache's SearchDistanceEvaluation(max_distance=4.0).""" + + def evaluation(self, src_dict, cache_dict, **_kwargs): + distance, _ = cache_dict["search_result"] + return 4.0 - min(distance, 4.0) + + def range(self): + return 0.0, 4.0 + + +def _eval_with(handler, **kwargs) -> tuple[CacheVerifierEvaluation, list]: + calls: list = [] + + def counting(request: httpx.Request) -> httpx.Response: + calls.append(request) + return handler(request) + + ev = CacheVerifierEvaluation(api_key="cv_test", **kwargs) + ev._cv._client = httpx.Client( + base_url="https://www.cacheverifier.com", + headers={"X-API-Key": "cv_test"}, + transport=httpx.MockTransport(counting), + ) + return ev, calls + + +def _cold(request: httpx.Request) -> httpx.Response: + return httpx.Response(200, json=_COLD_START) + + +def test_cold_start_with_fallback_returns_the_fallbacks_rescaled_score(caplog): + ev, _ = _eval_with(_cold, fallback=_Distance()) + with caplog.at_level(logging.WARNING, logger="cacheverifier.integrations"): + # distance 0.8 -> fallback 3.2 of 4.0 -> 0.8; GPTCache's default similarity_threshold 0.8 + # accepted it before (3.2 >= 4.0 * 0.8) and accepts it now (0.8 >= 1.0 * 0.8) + assert ev.evaluation({"question": "q"}, {"answer": "a", "search_result": (0.8, 1)}) == pytest.approx(0.8) + assert ev.evaluation({"question": "q"}, {"answer": "a", "search_result": (2.0, 1)}) == pytest.approx(0.5) + warnings = [r for r in caplog.records if r.name == "cacheverifier.integrations"] + assert len(warnings) == 1 + assert "fallback evaluator" in warnings[0].getMessage() + + +def test_cold_start_without_fallback_is_a_miss_and_says_how_to_keep_hits(caplog): + ev, _ = _eval_with(_cold) + with caplog.at_level(logging.WARNING, logger="cacheverifier.integrations"): + assert ev.evaluation({"question": "q"}, {"answer": "a"}) == 0.0 + assert "pass fallback=" in caplog.records[-1].getMessage() + + +def test_cold_start_reject_ignores_the_fallback(): + ev, _ = _eval_with(_cold, fallback=_Distance(), cold_start="reject") + assert ev.evaluation({"question": "q"}, {"answer": "a", "search_result": (0.0, 1)}) == 0.0 + + +def test_direct_hit_skips_the_verify_call(): + ev, calls = _eval_with(_cold, fallback=_Distance(), direct_hit=0.95) + assert ev.evaluation({"question": "q"}, {"answer": "a", "search_result": (0.1, 1)}) == 1.0 # 3.9/4 = 0.975 + assert calls == [] + ev.evaluation({"question": "q"}, {"answer": "a", "search_result": (1.0, 1)}) # 0.75: verified + assert len(calls) == 1 + + +def test_a_model_verdict_still_decides_when_a_fallback_is_set(): + def rejecting(request: httpx.Request) -> httpx.Response: + return httpx.Response( + 200, + json={"approved": False, "score": -1.0, "latency_ms": 5.0, "model_version": "v3", "threshold": 0.0}, + ) + + ev, _ = _eval_with(rejecting, fallback=_Distance()) + assert ev.evaluation({"question": "q"}, {"answer": "a", "search_result": (0.0, 1)}) == 0.0 + + +def test_direct_hit_needs_a_fallback(): + with pytest.raises(ValueError): + CacheVerifierEvaluation(api_key="cv_test", direct_hit=0.9) diff --git a/tests/test_langchain_integration.py b/tests/test_langchain_integration.py index 7234fc4..33b8bf6 100644 --- a/tests/test_langchain_integration.py +++ b/tests/test_langchain_integration.py @@ -88,3 +88,65 @@ def test_user_question_falls_back_to_the_raw_prompt(): def test_needs_a_key_or_a_client(): with pytest.raises(ValueError): VerifiedCache(InMemoryCache()) + + +_COLD_START = { + "approved": False, + "score": 0.0, + "threshold": 0.0, + "model_version": "cold_start_auto_pending", + "latency_ms": 0.0, + "decision_rule": "cold_start", + "notice": "Run a Health Check to let the stock model decide.", +} + + +def _cold(cold_start: str | None = None) -> VerifiedCache: + def handler(request: httpx.Request) -> httpx.Response: + return httpx.Response(200, json=_COLD_START) + + client = CacheVerifier(api_key="cv_test", transport=httpx.MockTransport(handler)) + kwargs = {} if cold_start is None else {"cold_start": cold_start} + return VerifiedCache(InMemoryCache(), client=client, **kwargs) + + +def test_cold_start_serves_the_wrapped_caches_hit_by_default_and_warns_once(caplog): + cache = _cold() + cache.update("when does my flight board", "llm", [Generation(text="40 minutes before departure.")]) + with caplog.at_level("WARNING", logger="cacheverifier.integrations"): + assert cache.lookup("when does my flight board", "llm")[0].text == "40 minutes before departure." + assert asyncio.run(cache.alookup("when does my flight board", "llm"))[0].text == "40 minutes before departure." + warnings = [r for r in caplog.records if r.name == "cacheverifier.integrations"] + assert len(warnings) == 1 + assert "cold_start_auto_pending" in warnings[0].getMessage() + assert "Run a Health Check" in warnings[0].getMessage() + + +def test_cold_start_reject_makes_every_hit_a_miss(): + cache = _cold("reject") + cache.update("q", "llm", [Generation(text="a")]) + assert cache.lookup("q", "llm") is None + + +def test_a_stock_model_rejection_is_not_a_cold_start(): + cache = _verified(False) # model_version "stock": a model ran and said no + cache.update("q", "llm", [Generation(text="a")]) + assert cache.lookup("q", "llm") is None + + +def test_an_audited_call_still_falls_through_during_serve_mode(): + def handler(request: httpx.Request) -> httpx.Response: + return httpx.Response( + 200, + json={"approved": False, "audit": True, "verification_id": 7, "score": 3.0, "latency_ms": 5.0, + "model_version": "v12", "threshold": 0.0}, + ) + + cache = VerifiedCache(InMemoryCache(), client=CacheVerifier(api_key="cv_test", transport=httpx.MockTransport(handler))) + cache.update("q", "llm", [Generation(text="a")]) + assert cache.lookup("q", "llm") is None + + +def test_bad_cold_start_mode_is_rejected(): + with pytest.raises(ValueError): + VerifiedCache(InMemoryCache(), api_key="cv_test", cold_start="open")