cacheverifier 0.7.1__tar.gz → 0.9.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (34) hide show
  1. {cacheverifier-0.7.1 → cacheverifier-0.9.0}/CHANGELOG.md +39 -0
  2. {cacheverifier-0.7.1 → cacheverifier-0.9.0}/PKG-INFO +66 -3
  3. {cacheverifier-0.7.1 → cacheverifier-0.9.0}/README.md +65 -2
  4. {cacheverifier-0.7.1 → cacheverifier-0.9.0}/cacheverifier/__init__.py +1 -1
  5. {cacheverifier-0.7.1 → cacheverifier-0.9.0}/cacheverifier/client.py +24 -0
  6. cacheverifier-0.9.0/cacheverifier/integrations/_cold_start.py +52 -0
  7. cacheverifier-0.9.0/cacheverifier/integrations/_reporting.py +115 -0
  8. cacheverifier-0.9.0/cacheverifier/integrations/gptcache.py +200 -0
  9. {cacheverifier-0.7.1 → cacheverifier-0.9.0}/cacheverifier/integrations/langchain.py +67 -6
  10. {cacheverifier-0.7.1 → cacheverifier-0.9.0}/cacheverifier/local.py +2 -0
  11. {cacheverifier-0.7.1 → cacheverifier-0.9.0}/examples/gptcache_example.py +7 -1
  12. {cacheverifier-0.7.1 → cacheverifier-0.9.0}/pyproject.toml +1 -1
  13. {cacheverifier-0.7.1 → cacheverifier-0.9.0}/tests/test_client.py +17 -0
  14. cacheverifier-0.9.0/tests/test_gptcache_integration.py +172 -0
  15. cacheverifier-0.9.0/tests/test_langchain_integration.py +230 -0
  16. cacheverifier-0.9.0/tests/test_reporting.py +50 -0
  17. cacheverifier-0.7.1/cacheverifier/integrations/gptcache.py +0 -102
  18. cacheverifier-0.7.1/tests/test_gptcache_integration.py +0 -55
  19. cacheverifier-0.7.1/tests/test_langchain_integration.py +0 -90
  20. {cacheverifier-0.7.1 → cacheverifier-0.9.0}/.github/workflows/ci.yml +0 -0
  21. {cacheverifier-0.7.1 → cacheverifier-0.9.0}/.github/workflows/publish.yml +0 -0
  22. {cacheverifier-0.7.1 → cacheverifier-0.9.0}/.gitignore +0 -0
  23. {cacheverifier-0.7.1 → cacheverifier-0.9.0}/LICENSE +0 -0
  24. {cacheverifier-0.7.1 → cacheverifier-0.9.0}/cacheverifier/__main__.py +0 -0
  25. {cacheverifier-0.7.1 → cacheverifier-0.9.0}/cacheverifier/_healthcheck/__init__.py +0 -0
  26. {cacheverifier-0.7.1 → cacheverifier-0.9.0}/cacheverifier/_healthcheck/_base_models.py +0 -0
  27. {cacheverifier-0.7.1 → cacheverifier-0.9.0}/cacheverifier/_healthcheck/_finetune.py +0 -0
  28. {cacheverifier-0.7.1 → cacheverifier-0.9.0}/cacheverifier/_healthcheck/cli.py +0 -0
  29. {cacheverifier-0.7.1 → cacheverifier-0.9.0}/cacheverifier/_inference.py +0 -0
  30. {cacheverifier-0.7.1 → cacheverifier-0.9.0}/cacheverifier/integrations/__init__.py +0 -0
  31. {cacheverifier-0.7.1 → cacheverifier-0.9.0}/cacheverifier/py.typed +0 -0
  32. {cacheverifier-0.7.1 → cacheverifier-0.9.0}/examples/quickstart.py +0 -0
  33. {cacheverifier-0.7.1 → cacheverifier-0.9.0}/tests/test_healthcheck.py +0 -0
  34. {cacheverifier-0.7.1 → cacheverifier-0.9.0}/tests/test_local.py +0 -0
@@ -1,5 +1,44 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.9.0
4
+
5
+ The integrations can report the hits they didn't serve. Until now they never
6
+ sent feedback, so audited and rejected hits made through them produced no
7
+ labels.
8
+
9
+ - `VerifiedCache` (LangChain) takes `judge=`, a function
10
+ `judge(question, cached_answer, fresh_answer) -> bool | None`. When a hit is
11
+ rejected or audited and your model answers instead, the fresh answer is
12
+ judged when LangChain stores it, and the verdict is sent as feedback linked
13
+ to that verdict (`verification_id`, or the result itself for a
14
+ `LocalVerifier`). It runs in a background thread; judge and report errors
15
+ are logged, not raised. `close()` waits for queued reports. These reports
16
+ are sent with `label_method="judge"`: they train fine-tunes, but the
17
+ service leaves them out of the audit risk bound, the audited CRC threshold
18
+ and ACI.
19
+ - `feedback()` (`CacheVerifier` and `LocalVerifier`) takes
20
+ `label_method="human"|"judge"`. It is sent only when `"judge"`, so
21
+ existing calls send the same request as before.
22
+ - `CacheVerifierEvaluation.report_feedback` attaches the `verification_id` of
23
+ the matching unserved hit (same query and cached answer) on its own, and
24
+ takes an explicit `verification_id=`.
25
+
26
+ ## 0.8.0
27
+
28
+ The integrations no longer switch your cache off during cold start. While a
29
+ workspace has no model of its own, `/v1/verify` rejects every call; an
30
+ integration sends every hit, so that rejected all of them, silently.
31
+
32
+ - `VerifiedCache` (LangChain) now serves cold-start hits exactly as the
33
+ wrapped cache returned them, and logs the service's notice once. Pass
34
+ `cold_start="reject"` for the old behavior.
35
+ - `CacheVerifierEvaluation` (GPTCache) takes `fallback=`, the evaluator it
36
+ replaces (e.g. `SearchDistanceEvaluation()`): during cold start GPTCache
37
+ decides with it exactly as before. Without a fallback, cold-start hits stay
38
+ misses, now with a warning saying how to keep them. `direct_hit=` serves
39
+ hits whose fallback score is at least that high without a verify call.
40
+ - `VerifyResult.cold_start`: True when no model decided the call.
41
+
3
42
  ## 0.7.1
4
43
 
5
44
  README only, no code change, so the PyPI page matches the docs: the
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: cacheverifier
3
- Version: 0.7.1
3
+ Version: 0.9.0
4
4
  Summary: Python client for the CacheVerifier semantic-cache verification API, hosted or scored locally
5
5
  Project-URL: Homepage, https://www.cacheverifier.com
6
6
  Project-URL: Documentation, https://www.cacheverifier.com/docs
@@ -139,10 +139,13 @@ cv.feedback(query, candidate, was_correct=candidate_was_right, similarity_score=
139
139
  | `latency_ms` | server-side inference time |
140
140
  | `degraded` | `True` when the call failed and this result was synthesized client-side |
141
141
  | `notice` | why no model decided the call (cold start); `None` otherwise |
142
+ | `cold_start` | property: `True` when no model decided the call (`model_version` is `"cold_start_..."`) |
142
143
  | `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 |
143
144
 
144
145
  A new account starts in cold start: every call returns `approved=False` until a
145
- Health Check shows the shared model is accurate enough on your data. Look at
146
+ Health Check shows the shared model is accurate enough on your data. (The
147
+ LangChain and GPTCache integrations hand cold-start hits back to your cache's
148
+ own decision instead, see below.) Look at
146
149
  `result.shadow` to see what it would have decided in the meantime:
147
150
 
148
151
  ```python
@@ -203,21 +206,81 @@ set_llm_cache(
203
206
  )
204
207
  ```
205
208
 
209
+ Until your workspace has a model of its own (cold start), the service
210
+ decides nothing and would reject every hit, which would switch your cache
211
+ off. So during cold start `VerifiedCache` serves each hit exactly as the
212
+ wrapped cache returned it, the same as without it, and logs a warning the
213
+ first time. Pass `cold_start="reject"` to fall through to your model instead,
214
+ for example if you loosened the wrapped cache's similarity threshold because
215
+ a verifier would be checking its hits.
216
+
217
+ ### Reporting hits that weren't served
218
+
219
+ When a hit is rejected or picked for a randomized audit, your model answers
220
+ anyway. Pass `judge=` and `VerifiedCache` uses that fresh answer: when
221
+ LangChain stores it, `judge(question, cached_answer, fresh_answer)` decides
222
+ whether the cached answer would have been right (`True` / `False`, or `None`
223
+ to skip), and the verdict is sent as feedback, linked to the verdict it is
224
+ about. It gives fine-tuning labels on audited and rejected hits, which are
225
+ otherwise rare. It runs in a background thread, off your request path, and a
226
+ failing judge or report is logged, never raised.
227
+
228
+ These reports are sent as `label_method="judge"`. Judge labels train your
229
+ fine-tunes, but the service leaves them out of every number it certifies
230
+ (the audit risk bound, the audited CRC threshold, ACI) until a judge can be
231
+ checked: a judge that calls wrong answers right would make those numbers look
232
+ better than they are. An audit answered only by the judge still counts as
233
+ unreported there; to complete audits, report them yourself with
234
+ `feedback(..., verification_id=...)`.
235
+
236
+ ```python
237
+ def same_answer(question, cached, fresh): # -> True, False, or None to skip
238
+ ... # your own check, e.g. an LLM call or a rule for your domain
239
+
240
+ set_llm_cache(VerifiedCache(cache, api_key="cv_...", judge=same_answer))
241
+ ```
242
+
243
+ The judge is yours because "the same answer" depends on your domain: the
244
+ cheap automatic checks we measured (answer embeddings, an NLI model) did no
245
+ better than the query similarity your cache already has. Without `judge`,
246
+ nothing is reported.
247
+
206
248
  ## GPTCache
207
249
 
208
250
  Drop the verifier into a GPTCache pipeline as its similarity evaluator — no fork required:
209
251
 
210
252
  ```python
211
253
  from gptcache import cache
254
+ from gptcache.similarity_evaluation import SearchDistanceEvaluation
212
255
  from cacheverifier.integrations.gptcache import CacheVerifierEvaluation
213
256
 
214
- evaluator = CacheVerifierEvaluation(api_key="cv_...")
257
+ evaluator = CacheVerifierEvaluation(
258
+ api_key="cv_...",
259
+ fallback=SearchDistanceEvaluation(), # the evaluator you used before
260
+ direct_hit=0.95, # optional: trust hits this close without verifying
261
+ )
215
262
  cache.init(similarity_evaluation=evaluator, ...)
216
263
 
217
264
  # when you learn a served hit's real outcome:
218
265
  evaluator.report_feedback(query, answer, was_correct=False, similarity_score=0.9)
219
266
  ```
220
267
 
268
+ GPTCache applies its `similarity_threshold` to whatever the evaluator returns,
269
+ so replacing your evaluator also drops the similarity check it did. With
270
+ `fallback` set:
271
+
272
+ - during cold start, hits are decided by the fallback exactly as before (the
273
+ first one logs a warning); `cold_start="reject"` makes them misses instead.
274
+ Without a fallback, cold-start hits are always misses.
275
+ - `direct_hit` serves hits whose fallback score is at least that high without
276
+ a verify call. It uses the same 0–1 scale as GPTCache's `similarity_threshold`.
277
+
278
+ When the evaluator doesn't let a hit through (a rejection, or a randomized
279
+ audit), GPTCache calls your LLM. Compare its answer with the cached one and
280
+ call `report_feedback(query, cached_answer, was_correct=...)` with the same
281
+ query and cached answer: the evaluator attaches that verdict's
282
+ `verification_id` for you, which is what completes an audit.
283
+
221
284
  See [`examples/gptcache_example.py`](examples/gptcache_example.py).
222
285
 
223
286
  ## Entries to refresh
@@ -100,10 +100,13 @@ cv.feedback(query, candidate, was_correct=candidate_was_right, similarity_score=
100
100
  | `latency_ms` | server-side inference time |
101
101
  | `degraded` | `True` when the call failed and this result was synthesized client-side |
102
102
  | `notice` | why no model decided the call (cold start); `None` otherwise |
103
+ | `cold_start` | property: `True` when no model decided the call (`model_version` is `"cold_start_..."`) |
103
104
  | `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 |
104
105
 
105
106
  A new account starts in cold start: every call returns `approved=False` until a
106
- Health Check shows the shared model is accurate enough on your data. Look at
107
+ Health Check shows the shared model is accurate enough on your data. (The
108
+ LangChain and GPTCache integrations hand cold-start hits back to your cache's
109
+ own decision instead, see below.) Look at
107
110
  `result.shadow` to see what it would have decided in the meantime:
108
111
 
109
112
  ```python
@@ -164,21 +167,81 @@ set_llm_cache(
164
167
  )
165
168
  ```
166
169
 
170
+ Until your workspace has a model of its own (cold start), the service
171
+ decides nothing and would reject every hit, which would switch your cache
172
+ off. So during cold start `VerifiedCache` serves each hit exactly as the
173
+ wrapped cache returned it, the same as without it, and logs a warning the
174
+ first time. Pass `cold_start="reject"` to fall through to your model instead,
175
+ for example if you loosened the wrapped cache's similarity threshold because
176
+ a verifier would be checking its hits.
177
+
178
+ ### Reporting hits that weren't served
179
+
180
+ When a hit is rejected or picked for a randomized audit, your model answers
181
+ anyway. Pass `judge=` and `VerifiedCache` uses that fresh answer: when
182
+ LangChain stores it, `judge(question, cached_answer, fresh_answer)` decides
183
+ whether the cached answer would have been right (`True` / `False`, or `None`
184
+ to skip), and the verdict is sent as feedback, linked to the verdict it is
185
+ about. It gives fine-tuning labels on audited and rejected hits, which are
186
+ otherwise rare. It runs in a background thread, off your request path, and a
187
+ failing judge or report is logged, never raised.
188
+
189
+ These reports are sent as `label_method="judge"`. Judge labels train your
190
+ fine-tunes, but the service leaves them out of every number it certifies
191
+ (the audit risk bound, the audited CRC threshold, ACI) until a judge can be
192
+ checked: a judge that calls wrong answers right would make those numbers look
193
+ better than they are. An audit answered only by the judge still counts as
194
+ unreported there; to complete audits, report them yourself with
195
+ `feedback(..., verification_id=...)`.
196
+
197
+ ```python
198
+ def same_answer(question, cached, fresh): # -> True, False, or None to skip
199
+ ... # your own check, e.g. an LLM call or a rule for your domain
200
+
201
+ set_llm_cache(VerifiedCache(cache, api_key="cv_...", judge=same_answer))
202
+ ```
203
+
204
+ The judge is yours because "the same answer" depends on your domain: the
205
+ cheap automatic checks we measured (answer embeddings, an NLI model) did no
206
+ better than the query similarity your cache already has. Without `judge`,
207
+ nothing is reported.
208
+
167
209
  ## GPTCache
168
210
 
169
211
  Drop the verifier into a GPTCache pipeline as its similarity evaluator — no fork required:
170
212
 
171
213
  ```python
172
214
  from gptcache import cache
215
+ from gptcache.similarity_evaluation import SearchDistanceEvaluation
173
216
  from cacheverifier.integrations.gptcache import CacheVerifierEvaluation
174
217
 
175
- evaluator = CacheVerifierEvaluation(api_key="cv_...")
218
+ evaluator = CacheVerifierEvaluation(
219
+ api_key="cv_...",
220
+ fallback=SearchDistanceEvaluation(), # the evaluator you used before
221
+ direct_hit=0.95, # optional: trust hits this close without verifying
222
+ )
176
223
  cache.init(similarity_evaluation=evaluator, ...)
177
224
 
178
225
  # when you learn a served hit's real outcome:
179
226
  evaluator.report_feedback(query, answer, was_correct=False, similarity_score=0.9)
180
227
  ```
181
228
 
229
+ GPTCache applies its `similarity_threshold` to whatever the evaluator returns,
230
+ so replacing your evaluator also drops the similarity check it did. With
231
+ `fallback` set:
232
+
233
+ - during cold start, hits are decided by the fallback exactly as before (the
234
+ first one logs a warning); `cold_start="reject"` makes them misses instead.
235
+ Without a fallback, cold-start hits are always misses.
236
+ - `direct_hit` serves hits whose fallback score is at least that high without
237
+ a verify call. It uses the same 0–1 scale as GPTCache's `similarity_threshold`.
238
+
239
+ When the evaluator doesn't let a hit through (a rejection, or a randomized
240
+ audit), GPTCache calls your LLM. Compare its answer with the cached one and
241
+ call `report_feedback(query, cached_answer, was_correct=...)` with the same
242
+ query and cached answer: the evaluator attaches that verdict's
243
+ `verification_id` for you, which is what completes an audit.
244
+
182
245
  See [`examples/gptcache_example.py`](examples/gptcache_example.py).
183
246
 
184
247
  ## Entries to refresh
@@ -19,7 +19,7 @@ Research behind it: https://github.com/imxinchengyou/CacheVerifier
19
19
  from cacheverifier.client import CacheVerifier, CacheVerifierError, ShadowVerdict, VerifyResult
20
20
  from cacheverifier.local import LocalVerifier, ModelCheckFailed
21
21
 
22
- __version__ = "0.7.1"
22
+ __version__ = "0.9.0"
23
23
  __all__ = [
24
24
  "CacheVerifier",
25
25
  "CacheVerifierError",
@@ -29,9 +29,14 @@ DEFAULT_VERIFY_TIMEOUT = 1.0
29
29
  #: failed (timeout / connection error / 5xx) and the client fell back.
30
30
  VERIFY_UNAVAILABLE = "verify_unavailable"
31
31
 
32
+ #: model_version prefix the API uses when no model ran because the workspace
33
+ #: is still in cold start ("cold_start_fail_closed" / "cold_start_auto_pending").
34
+ COLD_START_PREFIX = "cold_start_"
35
+
32
36
  _log = logging.getLogger(__name__)
33
37
 
34
38
  __all__ = [
39
+ "COLD_START_PREFIX",
35
40
  "DEFAULT_BASE_URL",
36
41
  "DEFAULT_TIMEOUT",
37
42
  "DEFAULT_VERIFY_TIMEOUT",
@@ -102,6 +107,8 @@ class VerifyResult:
102
107
  (default `False` -> `approved=False`, i.e. fall through to your LLM).
103
108
  - `notice`: a plain-language reason when no model decided the call (cold
104
109
  start); None otherwise.
110
+ - `cold_start` (property): True when no model decided the call, i.e.
111
+ `model_version` is `"cold_start_..."`.
105
112
  - `shadow`: on a cold-start call, what the shared stock model would have
106
113
  decided (a `ShadowVerdict`); None otherwise, and on servers that don't
107
114
  send it.
@@ -129,6 +136,14 @@ class VerifyResult:
129
136
  local_decision: str | None = None
130
137
  """`LocalVerifier` only: its handle for this decision until upload."""
131
138
 
139
+ @property
140
+ def cold_start(self) -> bool:
141
+ """True when no model decided this call: the workspace has no model
142
+ of its own yet and runs fail-closed, so `approved` is always False
143
+ and `notice` says what to do next. A verdict from the shared stock
144
+ model is not a cold start in this sense: a model did run."""
145
+ return self.model_version.startswith(COLD_START_PREFIX)
146
+
132
147
  @classmethod
133
148
  def _from_json(cls, d: dict[str, Any]) -> VerifyResult:
134
149
  shadow = d.get("shadow")
@@ -314,6 +329,7 @@ class CacheVerifier:
314
329
  verification_id: int | None = None,
315
330
  cache_entry_id: str | None = None,
316
331
  stale: bool = False,
332
+ label_method: str = "human",
317
333
  idempotency_key: str | None = None,
318
334
  ) -> int:
319
335
  """Record whether a served (or considered) hit was actually correct.
@@ -334,14 +350,22 @@ class CacheVerifier:
334
350
  - `stale`: set instead of a bare `was_correct=False` when the answer
335
351
  is wrong ONLY because a fact changed (price, date, ...), not a
336
352
  semantic mismatch. Stale rows are excluded from training and drift.
353
+ - `label_method`: `"human"` (default: a person, or a signal you vouch
354
+ for) or `"judge"` (an automatic check decided `was_correct`). Judge
355
+ labels train fine-tunes but are left out of the certified numbers
356
+ (audit risk bound, audited CRC threshold, ACI).
337
357
  - `idempotency_key`: pass a stable key to make retries safe.
338
358
  """
359
+ if label_method not in ("human", "judge"):
360
+ raise ValueError(f'label_method must be "human" or "judge", got {label_method!r}')
339
361
  payload: dict[str, Any] = {
340
362
  "query": query,
341
363
  "candidate_answer": candidate_answer,
342
364
  "was_correct": was_correct,
343
365
  "stale": stale,
344
366
  }
367
+ if label_method != "human":
368
+ payload["label_method"] = label_method
345
369
  payload.update(
346
370
  _drop_none(
347
371
  similarity_score=similarity_score,
@@ -0,0 +1,52 @@
1
+ """What an integration does with a cold-start verdict.
2
+
3
+ While a workspace has no model of its own, `/v1/verify` runs fail-closed and
4
+ rejects every call. Rejecting a call the caller only sends in its gray zone
5
+ is cheap. An integration, though, sends every hit its cache backend
6
+ returns, and rejecting all of them switches the cache off: the hit rate
7
+ drops to zero, LLM spend goes up, and nothing is protected that wasn't
8
+ already being served before CacheVerifier was added. So by default an
9
+ integration hands a cold-start call back to the cache's own decision, and
10
+ says so once in the log.
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ import logging
16
+ import threading
17
+
18
+ from cacheverifier.client import VerifyResult
19
+
20
+ COLD_START_MODES = ("serve", "reject")
21
+
22
+ _log = logging.getLogger("cacheverifier.integrations")
23
+
24
+
25
+ def check_mode(cold_start: str) -> str:
26
+ if cold_start not in COLD_START_MODES:
27
+ raise ValueError(f"cold_start must be one of {COLD_START_MODES}, got {cold_start!r}")
28
+ return cold_start
29
+
30
+
31
+ class ColdStartNotice:
32
+ """Logs the first cold-start verdict an integration instance sees, once."""
33
+
34
+ def __init__(self, integration: str) -> None:
35
+ self._integration = integration
36
+ self._lock = threading.Lock()
37
+ self._logged = False
38
+
39
+ def seen(self, result: VerifyResult, action: str) -> None:
40
+ """`action`: what the integration does with cold-start hits, in a
41
+ phrase ("serving ... unchanged until a model is ready")."""
42
+ with self._lock:
43
+ if self._logged:
44
+ return
45
+ self._logged = True
46
+ _log.warning(
47
+ "cacheverifier %s: no model decides your calls yet (%s) -- %s. %s",
48
+ self._integration,
49
+ result.model_version,
50
+ action,
51
+ result.notice or "Run a Health Check at https://www.cacheverifier.com to get one.",
52
+ )
@@ -0,0 +1,115 @@
1
+ """Closing the loop on hits an integration didn't serve.
2
+
3
+ When a verified hit is rejected or picked for an audit, the caller's model
4
+ answers the question anyway. That fresh answer is what tells you whether the
5
+ cached one would have been fine: the label an audit needs to complete, and
6
+ the rejected-side label fine-tuning otherwise rarely gets. An integration
7
+ that sees the fresh answer (LangChain's `update()` after a miss) can hand
8
+ both answers to a caller-supplied judge and report its verdict.
9
+
10
+ The judge is yours on purpose. Whether two answers are "the same" depends on
11
+ your domain, and the cheap automatic checks we measured (answer embeddings,
12
+ an NLI model) did no better than the query similarity you already have.
13
+ """
14
+
15
+ from __future__ import annotations
16
+
17
+ import logging
18
+ import threading
19
+ from collections import OrderedDict
20
+ from collections.abc import Callable, Hashable
21
+ from concurrent.futures import Future, ThreadPoolExecutor
22
+ from dataclasses import dataclass
23
+ from typing import Any
24
+
25
+ from cacheverifier.client import VerifyResult
26
+ from cacheverifier.local import LocalVerifier
27
+
28
+ Judge = Callable[[str, str, str], "bool | None"]
29
+ """`judge(question, cached_answer, fresh_answer)`: True if the cached answer
30
+ would have been right for this question, False if not, None to skip."""
31
+
32
+ MAX_PENDING = 1024
33
+ """Unserved hits remembered while waiting for the fresh answer. Oldest are
34
+ dropped first: a fresh answer that never arrives (the model call failed)
35
+ must not grow memory without bound."""
36
+
37
+ _log = logging.getLogger("cacheverifier.integrations")
38
+
39
+
40
+ @dataclass(frozen=True)
41
+ class _Pending:
42
+ question: str
43
+ cached_answer: str
44
+ result: VerifyResult
45
+
46
+
47
+ class RejectedHitReporter:
48
+ """Remembers unserved hits by key and, when the fresh answer for the same
49
+ key arrives, reports the judge's verdict as feedback. Never raises into
50
+ the caller's request path: judge and report errors are logged."""
51
+
52
+ def __init__(self, client: Any, judge: Judge, *, background: bool = True) -> None:
53
+ self._client = client
54
+ self._judge = judge
55
+ self._lock = threading.Lock()
56
+ self._pending: OrderedDict[Hashable, _Pending] = OrderedDict()
57
+ self._executor = (
58
+ ThreadPoolExecutor(max_workers=1, thread_name_prefix="cacheverifier-report") if background else None
59
+ )
60
+
61
+ def remember(self, key: Hashable, question: str, cached_answer: str, result: VerifyResult) -> None:
62
+ """Call for a hit that was not served: rejected by a model, an audit,
63
+ or a cold-start rejection. Outages (`degraded`) carry no verdict and
64
+ are not reported."""
65
+ if result.degraded or result.approved:
66
+ return
67
+ with self._lock:
68
+ self._pending[key] = _Pending(question, cached_answer, result)
69
+ self._pending.move_to_end(key)
70
+ while len(self._pending) > MAX_PENDING:
71
+ self._pending.popitem(last=False)
72
+
73
+ def fresh_answer(self, key: Hashable, fresh: str) -> Future[None] | None:
74
+ """Call with the answer the model just produced for `key`."""
75
+ with self._lock:
76
+ pending = self._pending.pop(key, None)
77
+ if pending is None:
78
+ return None
79
+ if self._executor is None:
80
+ self._report(pending, fresh)
81
+ return None
82
+ return self._executor.submit(self._report, pending, fresh)
83
+
84
+ def _report(self, pending: _Pending, fresh: str) -> None:
85
+ try:
86
+ verdict = self._judge(pending.question, pending.cached_answer, fresh)
87
+ except Exception as exc: # noqa: BLE001 -- the judge is caller code; never raise into the request path
88
+ _log.warning("cacheverifier: judge raised %r; hit not reported", exc)
89
+ return
90
+ if verdict is None:
91
+ return
92
+ try:
93
+ if isinstance(self._client, LocalVerifier): # links by result, not by id
94
+ self._client.feedback(
95
+ pending.question,
96
+ pending.cached_answer,
97
+ bool(verdict),
98
+ result=pending.result,
99
+ label_method="judge",
100
+ )
101
+ else:
102
+ self._client.feedback(
103
+ pending.question,
104
+ pending.cached_answer,
105
+ bool(verdict),
106
+ verification_id=pending.result.verification_id,
107
+ label_method="judge",
108
+ )
109
+ except Exception as exc: # noqa: BLE001 -- a failed report must not break the caller
110
+ _log.warning("cacheverifier: reporting an unserved hit failed: %s", exc)
111
+
112
+ def close(self) -> None:
113
+ """Wait for queued reports to finish."""
114
+ if self._executor is not None:
115
+ self._executor.shutdown(wait=True)