From a39ca8b048008779e5e60d128e08396f6fbfae10 Mon Sep 17 00:00:00 2001 From: xin Date: Fri, 27 Nov 2026 08:17:36 +0000 Subject: [PATCH] Integrations report unserved hits through a caller-supplied judge, sent as label_method="judge" (0.9.0) - VerifiedCache (LangChain) takes judge=: rejected/audited hits are remembered, and when LangChain stores the fresh answer the judge's verdict is sent as feedback linked to the verdict, in a background thread. - CacheVerifierEvaluation.report_feedback attaches the matching unserved hit's verification_id on its own. - feedback() takes label_method ("human" default, sent only when "judge"). Judge labels train fine-tunes; the service keeps them out of its certified numbers. --- CHANGELOG.md | 23 +++++ README.md | 37 ++++++++ cacheverifier/__init__.py | 2 +- cacheverifier/client.py | 9 ++ cacheverifier/integrations/_reporting.py | 115 +++++++++++++++++++++++ cacheverifier/integrations/gptcache.py | 26 +++++ cacheverifier/integrations/langchain.py | 50 ++++++++-- cacheverifier/local.py | 2 + pyproject.toml | 2 +- tests/test_client.py | 17 ++++ tests/test_gptcache_integration.py | 23 +++++ tests/test_langchain_integration.py | 78 +++++++++++++++ tests/test_reporting.py | 50 ++++++++++ 13 files changed, 426 insertions(+), 8 deletions(-) create mode 100644 cacheverifier/integrations/_reporting.py create mode 100644 tests/test_reporting.py diff --git a/CHANGELOG.md b/CHANGELOG.md index 9330b98..c24b42b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,28 @@ # Changelog +## 0.9.0 + +The integrations can report the hits they didn't serve. Until now they never +sent feedback, so audited and rejected hits made through them produced no +labels. + +- `VerifiedCache` (LangChain) takes `judge=`, a function + `judge(question, cached_answer, fresh_answer) -> bool | None`. When a hit is + rejected or audited and your model answers instead, the fresh answer is + judged when LangChain stores it, and the verdict is sent as feedback linked + to that verdict (`verification_id`, or the result itself for a + `LocalVerifier`). It runs in a background thread; judge and report errors + are logged, not raised. `close()` waits for queued reports. These reports + are sent with `label_method="judge"`: they train fine-tunes, but the + service leaves them out of the audit risk bound, the audited CRC threshold + and ACI. +- `feedback()` (`CacheVerifier` and `LocalVerifier`) takes + `label_method="human"|"judge"`. It is sent only when `"judge"`, so + existing calls send the same request as before. +- `CacheVerifierEvaluation.report_feedback` attaches the `verification_id` of + the matching unserved hit (same query and cached answer) on its own, and + takes an explicit `verification_id=`. + ## 0.8.0 The integrations no longer switch your cache off during cold start. While a diff --git a/README.md b/README.md index 93219a7..1be1909 100644 --- a/README.md +++ b/README.md @@ -175,6 +175,37 @@ 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. +### Reporting hits that weren't served + +When a hit is rejected or picked for a randomized audit, your model answers +anyway. Pass `judge=` and `VerifiedCache` uses that fresh answer: when +LangChain stores it, `judge(question, cached_answer, fresh_answer)` decides +whether the cached answer would have been right (`True` / `False`, or `None` +to skip), and the verdict is sent as feedback, linked to the verdict it is +about. It gives fine-tuning labels on audited and rejected hits, which are +otherwise rare. It runs in a background thread, off your request path, and a +failing judge or report is logged, never raised. + +These reports are sent as `label_method="judge"`. Judge labels train your +fine-tunes, but the service leaves them out of every number it certifies +(the audit risk bound, the audited CRC threshold, ACI) until a judge can be +checked: a judge that calls wrong answers right would make those numbers look +better than they are. An audit answered only by the judge still counts as +unreported there; to complete audits, report them yourself with +`feedback(..., verification_id=...)`. + +```python +def same_answer(question, cached, fresh): # -> True, False, or None to skip + ... # your own check, e.g. an LLM call or a rule for your domain + +set_llm_cache(VerifiedCache(cache, api_key="cv_...", judge=same_answer)) +``` + +The judge is yours because "the same answer" depends on your domain: the +cheap automatic checks we measured (answer embeddings, an NLI model) did no +better than the query similarity your cache already has. Without `judge`, +nothing is reported. + ## GPTCache Drop the verifier into a GPTCache pipeline as its similarity evaluator — no fork required: @@ -205,6 +236,12 @@ so replacing your evaluator also drops the similarity check it did. With - `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`. +When the evaluator doesn't let a hit through (a rejection, or a randomized +audit), GPTCache calls your LLM. Compare its answer with the cached one and +call `report_feedback(query, cached_answer, was_correct=...)` with the same +query and cached answer: the evaluator attaches that verdict's +`verification_id` for you, which is what completes an audit. + See [`examples/gptcache_example.py`](examples/gptcache_example.py). ## Entries to refresh diff --git a/cacheverifier/__init__.py b/cacheverifier/__init__.py index de3e9e5..b650758 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.8.0" +__version__ = "0.9.0" __all__ = [ "CacheVerifier", "CacheVerifierError", diff --git a/cacheverifier/client.py b/cacheverifier/client.py index 834f578..e3d0db9 100644 --- a/cacheverifier/client.py +++ b/cacheverifier/client.py @@ -329,6 +329,7 @@ def feedback( verification_id: int | None = None, cache_entry_id: str | None = None, stale: bool = False, + label_method: str = "human", idempotency_key: str | None = None, ) -> int: """Record whether a served (or considered) hit was actually correct. @@ -349,14 +350,22 @@ def feedback( - `stale`: set instead of a bare `was_correct=False` when the answer is wrong ONLY because a fact changed (price, date, ...), not a semantic mismatch. Stale rows are excluded from training and drift. + - `label_method`: `"human"` (default: a person, or a signal you vouch + for) or `"judge"` (an automatic check decided `was_correct`). Judge + labels train fine-tunes but are left out of the certified numbers + (audit risk bound, audited CRC threshold, ACI). - `idempotency_key`: pass a stable key to make retries safe. """ + if label_method not in ("human", "judge"): + raise ValueError(f'label_method must be "human" or "judge", got {label_method!r}') payload: dict[str, Any] = { "query": query, "candidate_answer": candidate_answer, "was_correct": was_correct, "stale": stale, } + if label_method != "human": + payload["label_method"] = label_method payload.update( _drop_none( similarity_score=similarity_score, diff --git a/cacheverifier/integrations/_reporting.py b/cacheverifier/integrations/_reporting.py new file mode 100644 index 0000000..7c84208 --- /dev/null +++ b/cacheverifier/integrations/_reporting.py @@ -0,0 +1,115 @@ +"""Closing the loop on hits an integration didn't serve. + +When a verified hit is rejected or picked for an audit, the caller's model +answers the question anyway. That fresh answer is what tells you whether the +cached one would have been fine: the label an audit needs to complete, and +the rejected-side label fine-tuning otherwise rarely gets. An integration +that sees the fresh answer (LangChain's `update()` after a miss) can hand +both answers to a caller-supplied judge and report its verdict. + +The judge is yours on purpose. Whether two answers are "the same" depends on +your domain, and the cheap automatic checks we measured (answer embeddings, +an NLI model) did no better than the query similarity you already have. +""" + +from __future__ import annotations + +import logging +import threading +from collections import OrderedDict +from collections.abc import Callable, Hashable +from concurrent.futures import Future, ThreadPoolExecutor +from dataclasses import dataclass +from typing import Any + +from cacheverifier.client import VerifyResult +from cacheverifier.local import LocalVerifier + +Judge = Callable[[str, str, str], "bool | None"] +"""`judge(question, cached_answer, fresh_answer)`: True if the cached answer +would have been right for this question, False if not, None to skip.""" + +MAX_PENDING = 1024 +"""Unserved hits remembered while waiting for the fresh answer. Oldest are +dropped first: a fresh answer that never arrives (the model call failed) +must not grow memory without bound.""" + +_log = logging.getLogger("cacheverifier.integrations") + + +@dataclass(frozen=True) +class _Pending: + question: str + cached_answer: str + result: VerifyResult + + +class RejectedHitReporter: + """Remembers unserved hits by key and, when the fresh answer for the same + key arrives, reports the judge's verdict as feedback. Never raises into + the caller's request path: judge and report errors are logged.""" + + def __init__(self, client: Any, judge: Judge, *, background: bool = True) -> None: + self._client = client + self._judge = judge + self._lock = threading.Lock() + self._pending: OrderedDict[Hashable, _Pending] = OrderedDict() + self._executor = ( + ThreadPoolExecutor(max_workers=1, thread_name_prefix="cacheverifier-report") if background else None + ) + + def remember(self, key: Hashable, question: str, cached_answer: str, result: VerifyResult) -> None: + """Call for a hit that was not served: rejected by a model, an audit, + or a cold-start rejection. Outages (`degraded`) carry no verdict and + are not reported.""" + if result.degraded or result.approved: + return + with self._lock: + self._pending[key] = _Pending(question, cached_answer, result) + self._pending.move_to_end(key) + while len(self._pending) > MAX_PENDING: + self._pending.popitem(last=False) + + def fresh_answer(self, key: Hashable, fresh: str) -> Future[None] | None: + """Call with the answer the model just produced for `key`.""" + with self._lock: + pending = self._pending.pop(key, None) + if pending is None: + return None + if self._executor is None: + self._report(pending, fresh) + return None + return self._executor.submit(self._report, pending, fresh) + + def _report(self, pending: _Pending, fresh: str) -> None: + try: + verdict = self._judge(pending.question, pending.cached_answer, fresh) + except Exception as exc: # noqa: BLE001 -- the judge is caller code; never raise into the request path + _log.warning("cacheverifier: judge raised %r; hit not reported", exc) + return + if verdict is None: + return + try: + if isinstance(self._client, LocalVerifier): # links by result, not by id + self._client.feedback( + pending.question, + pending.cached_answer, + bool(verdict), + result=pending.result, + label_method="judge", + ) + else: + self._client.feedback( + pending.question, + pending.cached_answer, + bool(verdict), + verification_id=pending.result.verification_id, + label_method="judge", + ) + except Exception as exc: # noqa: BLE001 -- a failed report must not break the caller + _log.warning("cacheverifier: reporting an unserved hit failed: %s", exc) + + def close(self) -> None: + """Wait for queued reports to finish.""" + if self._executor is not None: + self._executor.shutdown(wait=True) diff --git a/cacheverifier/integrations/gptcache.py b/cacheverifier/integrations/gptcache.py index 284fb7d..5c7d6f5 100644 --- a/cacheverifier/integrations/gptcache.py +++ b/cacheverifier/integrations/gptcache.py @@ -29,6 +29,8 @@ from __future__ import annotations +import threading +from collections import OrderedDict from typing import Any from cacheverifier.client import ( @@ -38,6 +40,7 @@ CacheVerifier, ) from cacheverifier.integrations._cold_start import ColdStartNotice, check_mode +from cacheverifier.integrations._reporting import MAX_PENDING try: from gptcache.similarity_evaluation import SimilarityEvaluation as _GPTCacheBase @@ -100,6 +103,8 @@ def __init__( self.cold_start = check_mode(cold_start) self.direct_hit = direct_hit self._cold_start_notice = ColdStartNotice("CacheVerifierEvaluation") + self._unserved_lock = threading.Lock() + self._unserved: OrderedDict[tuple[str, str], int] = OrderedDict() self._cv = CacheVerifier( api_key=api_key, base_url=base_url, @@ -125,6 +130,8 @@ def evaluation(self, src_dict: dict[str, Any], cache_dict: dict[str, Any], **kwa query = src_dict.get("question") or src_dict.get("query", "") candidate_answer = cache_dict.get("answer", "") result = self._cv.verify(query, candidate_answer) + if not result.approved and result.verification_id is not None: + self._remember_unserved(query, candidate_answer, result.verification_id) if result.cold_start: serve = self.cold_start == "serve" and fallback_score is not None if serve: @@ -143,6 +150,13 @@ def evaluation(self, src_dict: dict[str, Any], cache_dict: dict[str, Any], **kwa return fallback_score if serve and fallback_score is not None else 0.0 return 1.0 if result.approved else 0.0 + def _remember_unserved(self, query: str, candidate_answer: str, verification_id: int) -> None: + with self._unserved_lock: + self._unserved[(query, candidate_answer)] = verification_id + self._unserved.move_to_end((query, candidate_answer)) + while len(self._unserved) > MAX_PENDING: + self._unserved.popitem(last=False) + def range(self) -> tuple[float, float]: return 0.0, 1.0 @@ -152,6 +166,7 @@ def report_feedback( candidate_answer: str, was_correct: bool, similarity_score: float | None = None, + verification_id: int | None = None, ) -> None: """Not part of GPTCache's interface -- call it once you know whether a served hit was actually correct (a thumbs-down, a reopened @@ -162,12 +177,23 @@ def report_feedback( score for this candidate if you still have it when you learn `was_correct` -- that is what lets the service later recommend a tau_high for your GPTCache config (`gray_zone_threshold()`). + + Audits and rejections: when this evaluator didn't let a hit through + (a rejection or a randomized audit), GPTCache calls your LLM. Compare + its answer with the cached one and report the result here with the + same `query` and `candidate_answer`: the `verification_id` of that + verdict is attached for you (it is what completes an audit), unless + you pass one yourself. """ + if verification_id is None: + with self._unserved_lock: + verification_id = self._unserved.pop((query, candidate_answer), None) self._cv.feedback( query, candidate_answer, was_correct, similarity_score=similarity_score, + verification_id=verification_id, ) def close(self) -> None: diff --git a/cacheverifier/integrations/langchain.py b/cacheverifier/integrations/langchain.py index b1af8c7..290b3be 100644 --- a/cacheverifier/integrations/langchain.py +++ b/cacheverifier/integrations/langchain.py @@ -32,6 +32,21 @@ do that if you loosened the wrapped cache's similarity threshold because a verifier would be checking its hits. +Pass `judge=` to close the loop on hits that weren't served. When a hit is +rejected or picked for an audit, your model answers anyway; `VerifiedCache` +sees that answer when LangChain stores it, calls +`judge(question, cached_answer, fresh_answer)` and reports the verdict as +feedback (True: the cached answer would have been right, False: it would +not, None: skip), as `label_method="judge"`. Those labels train fine-tunes; +the service keeps them out of its certified numbers (an audit answered only +by the judge still counts as unreported there). It runs in a background +thread, off your request path. + + def same_answer(question, cached, fresh): + return my_llm_judge(question, cached, fresh) # your own check + + VerifiedCache(cache, api_key="cv_...", judge=same_answer) + `langchain-core` is an optional dependency -- `pip install "cacheverifier[langchain]"`. """ @@ -48,6 +63,7 @@ CacheVerifier, ) from cacheverifier.integrations._cold_start import ColdStartNotice, check_mode +from cacheverifier.integrations._reporting import Judge, RejectedHitReporter try: from langchain_core.caches import RETURN_VAL_TYPE, BaseCache @@ -92,6 +108,10 @@ def user_question(prompt: str) -> str: return prompt +def _text(generations: RETURN_VAL_TYPE) -> str: + return "\n".join(generation.text for generation in generations) + + class VerifiedCache(BaseCache): """A LangChain cache that verifies another cache's hits before serving them.""" @@ -106,6 +126,7 @@ def __init__( verify_timeout: float = DEFAULT_VERIFY_TIMEOUT, fail_open: bool = False, cold_start: str = "serve", + judge: Judge | None = None, ) -> None: self.cold_start = check_mode(cold_start) self._cold_start_notice = ColdStartNotice("VerifiedCache") @@ -121,10 +142,18 @@ def __init__( ) self.cache = cache self.client = client - - def _approved(self, prompt: str, hit: RETURN_VAL_TYPE) -> bool: - answer = "\n".join(generation.text for generation in hit) - result = self.client.verify(user_question(prompt), answer) + self._reporter = RejectedHitReporter(client, judge) if judge is not None else None + + def _approved(self, prompt: str, llm_string: str, hit: RETURN_VAL_TYPE) -> bool: + answer = _text(hit) + question = user_question(prompt) + result = self.client.verify(question, answer) + served = self._served(result) + if not served and self._reporter is not None: + self._reporter.remember((prompt, llm_string), question, answer, result) + return served + + def _served(self, result: Any) -> bool: if result.cold_start: serve = self.cold_start == "serve" self._cold_start_notice.seen( @@ -141,20 +170,29 @@ def lookup(self, prompt: str, llm_string: str) -> RETURN_VAL_TYPE | None: hit = self.cache.lookup(prompt, llm_string) if not hit: return hit - return hit if self._approved(prompt, hit) else None + return hit if self._approved(prompt, llm_string, hit) else None async def alookup(self, prompt: str, llm_string: str) -> RETURN_VAL_TYPE | None: hit = await self.cache.alookup(prompt, llm_string) if not hit: return hit - approved = await asyncio.get_running_loop().run_in_executor(None, self._approved, prompt, hit) + approved = await asyncio.get_running_loop().run_in_executor(None, self._approved, prompt, llm_string, hit) return hit if approved else None def update(self, prompt: str, llm_string: str, return_val: RETURN_VAL_TYPE) -> None: self.cache.update(prompt, llm_string, return_val) + if self._reporter is not None: + self._reporter.fresh_answer((prompt, llm_string), _text(return_val)) async def aupdate(self, prompt: str, llm_string: str, return_val: RETURN_VAL_TYPE) -> None: await self.cache.aupdate(prompt, llm_string, return_val) + if self._reporter is not None: + self._reporter.fresh_answer((prompt, llm_string), _text(return_val)) + + def close(self) -> None: + """Wait for queued `judge` reports to finish (only needed with `judge=`).""" + if self._reporter is not None: + self._reporter.close() def clear(self, **kwargs: Any) -> None: self.cache.clear(**kwargs) diff --git a/cacheverifier/local.py b/cacheverifier/local.py index e2b5cc4..56c64e3 100644 --- a/cacheverifier/local.py +++ b/cacheverifier/local.py @@ -477,6 +477,7 @@ def feedback( cached_query: str | None = None, cache_entry_id: str | None = None, stale: bool = False, + label_method: str = "human", idempotency_key: str | None = None, ) -> int: """`CacheVerifier.feedback`, linked to `result` when given (always @@ -491,6 +492,7 @@ def feedback( verification_id=verification_id, cache_entry_id=cache_entry_id, stale=stale, + label_method=label_method, idempotency_key=idempotency_key, ) diff --git a/pyproject.toml b/pyproject.toml index 5bcf3ba..0184d89 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -4,7 +4,7 @@ build-backend = "hatchling.build" [project] name = "cacheverifier" -version = "0.8.0" +version = "0.9.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_client.py b/tests/test_client.py index 4194dc8..1faf7b8 100644 --- a/tests/test_client.py +++ b/tests/test_client.py @@ -308,3 +308,20 @@ def handler(request: httpx.Request) -> httpx.Response: cv.usage() assert set(seen["timeout"].values()) == {10.0} + + +def test_feedback_sends_label_method_only_for_a_judge(): + bodies = [] + + def handler(request: httpx.Request) -> httpx.Response: + bodies.append(json.loads(request.content)) + return httpx.Response(200, json={"id": 1}) + + with make_client(handler) as cv: + cv.feedback("q", "a", was_correct=True) + cv.feedback("q", "a", was_correct=False, label_method="judge") + with pytest.raises(ValueError): + cv.feedback("q", "a", was_correct=True, label_method="robot") + assert "label_method" not in bodies[0] + assert bodies[1]["label_method"] == "judge" + assert len(bodies) == 2 diff --git a/tests/test_gptcache_integration.py b/tests/test_gptcache_integration.py index 9e48b15..3b79ef0 100644 --- a/tests/test_gptcache_integration.py +++ b/tests/test_gptcache_integration.py @@ -147,3 +147,26 @@ def rejecting(request: httpx.Request) -> httpx.Response: def test_direct_hit_needs_a_fallback(): with pytest.raises(ValueError): CacheVerifierEvaluation(api_key="cv_test", direct_hit=0.9) + + +def test_report_feedback_attaches_the_verification_id_of_an_unserved_hit(): + import json + + posted: list = [] + + def handler(request: httpx.Request) -> httpx.Response: + if request.url.path == "/v1/feedback": + posted.append(json.loads(request.content)) + return httpx.Response(200, json={"id": 1}) + return httpx.Response( + 200, + json={"approved": False, "audit": True, "verification_id": 41, "score": 2.0, "latency_ms": 5.0, + "model_version": "v3", "threshold": 0.0}, + ) + + ev, _ = _eval_with(handler) + assert ev.evaluation({"question": "q"}, {"answer": "a"}) == 0.0 + ev.report_feedback("q", "a", was_correct=True) + ev.report_feedback("q", "a", was_correct=True) # already linked: no id the second time + ev.report_feedback("other", "a", was_correct=False, verification_id=5) + assert [p.get("verification_id") for p in posted] == [41, None, 5] diff --git a/tests/test_langchain_integration.py b/tests/test_langchain_integration.py index 33b8bf6..97408db 100644 --- a/tests/test_langchain_integration.py +++ b/tests/test_langchain_integration.py @@ -150,3 +150,81 @@ def handler(request: httpx.Request) -> httpx.Response: def test_bad_cold_start_mode_is_rejected(): with pytest.raises(ValueError): VerifiedCache(InMemoryCache(), api_key="cv_test", cold_start="open") + + +def _judged(verdict_json: dict, judge, posted: list) -> VerifiedCache: + def handler(request: httpx.Request) -> httpx.Response: + body = json.loads(request.content) + if request.url.path == "/v1/feedback": + posted.append(body) + return httpx.Response(200, json={"id": 1}) + return httpx.Response(200, json=verdict_json) + + client = CacheVerifier(api_key="cv_test", transport=httpx.MockTransport(handler)) + return VerifiedCache(InMemoryCache(), client=client, judge=judge) + + +_AUDIT = {"approved": False, "audit": True, "verification_id": 7, "score": 3.0, "latency_ms": 5.0, + "model_version": "v12", "threshold": 0.0} + + +def test_judge_reports_an_audited_hit_with_its_verification_id(): + posted: list = [] + seen: list = [] + + def judge(question, cached, fresh): + seen.append((question, cached, fresh)) + return cached.split(".")[0] == fresh.split(".")[0] + + cache = _judged(_AUDIT, judge, posted) + model = FakeListChatModel(responses=["Gate B12.", "Gate B12. Boarding 9:20."], cache=cache) + assert model.invoke("which gate is my flight").content == "Gate B12." # miss, cached + assert model.invoke("which gate is my flight").content == "Gate B12. Boarding 9:20." # audited -> model + cache.close() + assert seen == [("which gate is my flight", "Gate B12.", "Gate B12. Boarding 9:20.")] + assert posted == [{"query": "which gate is my flight", "candidate_answer": "Gate B12.", "was_correct": True, + "stale": False, "label_method": "judge", "verification_id": 7}] + + +def test_judge_reports_a_rejected_hit_in_the_async_path_too(): + posted: list = [] + rejected = {**_AUDIT, "audit": False, "score": -2.0} + cache = _judged(rejected, lambda q, c, f: False, posted) + asyncio.run(cache.aupdate("q", "llm", [Generation(text="old")])) + assert asyncio.run(cache.alookup("q", "llm")) is None + asyncio.run(cache.aupdate("q", "llm", [Generation(text="new")])) + cache.close() + assert [(p["candidate_answer"], p["was_correct"], p["verification_id"]) for p in posted] == [("old", False, 7)] + + +def test_served_hits_and_skipped_verdicts_are_not_reported(): + posted: list = [] + approved = {**_AUDIT, "approved": True, "audit": False} + cache = _judged(approved, lambda q, c, f: True, posted) + cache.update("q", "llm", [Generation(text="a")]) + assert cache.lookup("q", "llm") is not None + cache.update("q", "llm", [Generation(text="b")]) + + skipping = _judged(_AUDIT, lambda q, c, f: None, posted) + skipping.update("q", "llm", [Generation(text="a")]) + assert skipping.lookup("q", "llm") is None + skipping.update("q", "llm", [Generation(text="b")]) + cache.close() + skipping.close() + assert posted == [] + + +def test_a_failing_judge_is_logged_not_raised(caplog): + posted: list = [] + + def judge(q, c, f): + raise RuntimeError("judge down") + + cache = _judged(_AUDIT, judge, posted) + cache.update("q", "llm", [Generation(text="a")]) + assert cache.lookup("q", "llm") is None + with caplog.at_level("WARNING", logger="cacheverifier.integrations"): + cache.update("q", "llm", [Generation(text="b")]) # must not raise + cache.close() + assert posted == [] + assert "judge down" in caplog.text diff --git a/tests/test_reporting.py b/tests/test_reporting.py new file mode 100644 index 0000000..bbd95a7 --- /dev/null +++ b/tests/test_reporting.py @@ -0,0 +1,50 @@ +"""RejectedHitReporter: which client call it makes, and the pending bound.""" + +from cacheverifier import LocalVerifier, VerifyResult +from cacheverifier.integrations import _reporting +from cacheverifier.integrations._reporting import RejectedHitReporter + + +def _result(**kw) -> VerifyResult: + base = {"approved": False, "score": -1.0, "threshold": 0.0, "model_version": "v9", "latency_ms": 1.0} + base.update(kw) + return VerifyResult(**base) + + +class _FakeLocal(LocalVerifier): + def __init__(self) -> None: # no model download + self.calls: list = [] + + def feedback(self, query, candidate_answer, was_correct, **kwargs): + self.calls.append((query, candidate_answer, was_correct, kwargs)) + return 1 + + +def test_local_verifier_is_reported_by_result_not_by_id(): + client = _FakeLocal() + r = _result(local_decision="tok-1") + reporter = RejectedHitReporter(client, lambda q, c, f: True, background=False) + reporter.remember("k", "q", "cached", r) + reporter.fresh_answer("k", "fresh") + assert client.calls == [("q", "cached", True, {"result": r, "label_method": "judge"})] + + +def test_degraded_and_approved_results_are_not_remembered(): + client = _FakeLocal() + reporter = RejectedHitReporter(client, lambda q, c, f: True, background=False) + reporter.remember("a", "q", "c", _result(degraded=True, model_version="verify_unavailable")) + reporter.remember("b", "q", "c", _result(approved=True)) + reporter.fresh_answer("a", "f") + reporter.fresh_answer("b", "f") + assert client.calls == [] + + +def test_pending_hits_are_bounded(monkeypatch): + monkeypatch.setattr(_reporting, "MAX_PENDING", 2) + client = _FakeLocal() + reporter = RejectedHitReporter(client, lambda q, c, f: True, background=False) + for key in ("a", "b", "c"): + reporter.remember(key, key, "c", _result()) + for key in ("a", "b", "c"): + reporter.fresh_answer(key, "f") + assert [call[0] for call in client.calls] == ["b", "c"] # oldest dropped