Skip to content

feat: one typed detect interface for the detectors package (#126) - #204

Merged
adaamko merged 87 commits into
mainfrom
stateless_core
Dec 2, 2026
Merged

adaamko merged 87 commits into
mainfrom
stateless_core

Conversation

@adaamko

@adaamko adaamko commented Nov 22, 2026

Copy link
Copy Markdown
Collaborator

The integration branch of epic #126: one typed interface for the detectors package. Every ticket of the epic was merged into stateless_core through its own pull request; this one brings the branch into main for a single review.

What it adds

  • detect, adetect, detect_batch and adetect_batch on every detector. They take a SourcesInput or a PromptInput and return a Detection with spans, scores, optional tokens and detail, usage and warnings. A batch returns one BatchResult per request, so one failed request does not discard the others.
  • Detector classes on that interface: EncoderDetector, LLMJudgeDetector, GenerativeDetector, RAGFactCheckerDetector and VelaDetector (in process and over HTTP). They take loaded models or clients as arguments; construction reads no environment variable and writes no file.
  • load_detector(model_id, ...) with a registry of the KR Labs model ids.
  • Typed errors (InvalidInputError, ConfigurationError, UpstreamError) with stable codes, caller-controlled reply caching (ResponseCache, FileCache, InMemoryCache), and frozen pydantic request, result and config types.
  • A contract suite (tests/detector_contract.py) that every detector passes.

What happens to the existing API

TransformerDetector, LLMDetector, make_detector, CacheManager, TaxonomyTyper(model_path, ...) and the predict* methods keep working as adapters over the new classes. Used from outside the package they warn with LettuceDetectDeprecationWarning. HallucinationDetector is not deprecated and does not warn.

Some behaviour changes through the existing API. CHANGELOG.md lists each one under "Changed" with what happened before and what happens now. The ones most likely to affect callers:

  • an LLM reply that can't be parsed raises UpstreamError instead of returning no spans;
  • LLMDetector writes a cache file only when cache_file is passed;
  • spans that had no confidence now carry confidence: 1.0;
  • several constructor errors of LLMDetector are ConfigurationError, which is not a ValueError.

Where to look

The per-ticket pull requests have the detail and the readings taken where the tickets left room: #184 to #191 (golden fixtures, the error and logging convention, the deprecation helper, types, the contract suite, the cache, the encoder), #193 and #194 (Vela), #195 (fixes from #192), #196 (fact checker), #197 (LLM judge), #198 (generative), #199 (LLMDetector adapter), #200 (load_detector), #201 (batch, and the predict override bridge), #202 (changelog, the predict* warnings).

Points that deserve a reviewer's attention:

  • The batch result type and the predict override bridge in base.py (feat: run many requests with detect_batch and adetect_batch (#175) #201) were open decisions in the epic and were taken on this branch.
  • TransformerDetector.predict_prompt_batch keeps its own padded path instead of calling detect_batch (feat: run many requests with detect_batch and adetect_batch (#175) #201 explains why).
  • BaseDetector.max_concurrency defaults to 1, so VelaDetector batches run one request at a time.
  • "A batched encoder result equals a single detect" is tested with stub models, not with a real model.
  • The token output of LLMDetector and RAGFactCheckerDetector has no replacement on the new interface.
  • The package version on this branch is 0.3.0.

Testing

The test and lint workflows ran on every pull request into the branch. The suite has about 1,400 tests and needs no network and no API key.

Rights & sign-off (required)

  • I certify that I have the right to submit this code and that it may be
    distributed under the repository's MIT license
    (see CONTRIBUTING).

hslev and others added 30 commits November 5, 2026 15:37
Add tests/golden.py (assert_golden, UPDATE_GOLDEN=1 to rewrite, readable
unified diff, floats rounded to 6 places) and record predict, predict_prompt
and predict_prompt_batch in "tokens" and "spans" format on a stub model with
the local tokenizer, plus a multi-group context and spans typed by a stub typer.

Recorded as-is: "tokens" output ends with the trailing [SEP], and the
multi-group path flags a token at prob >= 0.5 while the single-group path
uses argmax.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Record predict, predict_prompt and predict_prompt_batch in "tokens" and
"spans" format through a fake LLMClient: the judge with defaults, zero_shot,
include_reasoning, each include_taxonomy form (True, list, flat dict, nested
dict), verify, and native mode with and without include_reasoning.

Also record today's behaviour in the cases the epic changes (llm_defect_*):
a reply without hallucination_list, an unparseable reply, an item that is
not found in the answer, and spans without confidence.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
…130)

Record "tokens", "spans" and "detailed" output of predict, predict_prompt
and predict_prompt_batch through a fake fact checker, a triplet matched
only by the single-word fallback (confidence 0.7), and the merge defect
where a merged span's text is shorter than its offsets
(rag_merge_overlap_text_shorter_than_offsets_*, for the fix PR to update).

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
…ior (#131)

Record the class make_detector returns for "transformer", "llm" and
"rag_fact_checker" and the error for an unknown method; assert and record
that HallucinationDetector.predict, predict_prompt and predict_prompt_batch
return what the detector alone returns (transformer, LLM, RAG); and pin the
CacheManager file after set/delete calls, the _hash strings, and the judge,
native and verify keys LLMDetector writes for fixed prompts.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
…-todays-detector-api

test: record golden fixtures for today's detector API (#127)
…ixtures-for-todays-detector-api

Revert "test: record golden fixtures for today's detector API (#127)"
Add tests/golden.py (assert_golden, UPDATE_GOLDEN=1 to rewrite, readable
unified diff, floats rounded to 6 places) and record predict, predict_prompt
and predict_prompt_batch in "tokens" and "spans" format on a stub model with
the local tokenizer, plus a multi-group context and spans typed by a stub typer.

Recorded as-is: "tokens" output ends with the trailing [SEP], and the
multi-group path flags a token at prob >= 0.5 while the single-group path
uses argmax.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Record predict, predict_prompt and predict_prompt_batch in "tokens" and
"spans" format through a fake LLMClient: the judge with defaults, zero_shot,
include_reasoning, each include_taxonomy form (True, list, flat dict, nested
dict), verify, and native mode with and without include_reasoning.

Also record today's behaviour in the cases the epic changes (llm_defect_*):
a reply without hallucination_list, an unparseable reply, an item that is
not found in the answer, and spans without confidence.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
…130)

Record "tokens", "spans" and "detailed" output of predict, predict_prompt
and predict_prompt_batch through a fake fact checker, a triplet matched
only by the single-word fallback (confidence 0.7), and the merge defect
where a merged span's text is shorter than its offsets
(rag_merge_overlap_text_shorter_than_offsets_*, for the fix PR to update).

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
…ior (#131)

Record the class make_detector returns for "transformer", "llm" and
"rag_fact_checker" and the error for an unknown method; assert and record
that HallucinationDetector.predict, predict_prompt and predict_prompt_batch
return what the detector alone returns (transformer, LLM, RAG); and pin the
CacheManager file after set/delete calls, the _hash strings, and the judge,
native and verify keys LLMDetector writes for fixed prompts.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
…convention-in-contributingmd' into 140-implement-a-detector-against-detect-and-check-it-with-a-contract-suite
…or-every-deprecated-name' into 140-implement-a-detector-against-detect-and-check-it-with-a-contract-suite
…rors' into 140-implement-a-detector-against-detect-and-check-it-with-a-contract-suite
test: record golden fixtures for today's detector API (#127)
…g-convention-in-contributingmd

(docs): add the error handling and logging convention to CONTRIBUTING.md (#133)
…-for-every-deprecated-name

See one consistent warning for every deprecated name (#134)
…read-typed-results-and-errors

Build detect requests and read typed result warning (#137)
…st-detect-and-check-it-with-a-contract-suite

Implement a detector against detect and check it with a contract suite (#140)
feat: run many requests with detect_batch and adetect_batch (#175)
…ted and head the 0.3.0 roadmap section Next (#179)
docs: changelog, roadmap and contributor guide for the typed detector interface (#179)
Conflicts: CHANGELOG.md keeps both entries; llm.py and rag_fact_checker.py keep the typed
length check of this branch. The fact checker batch tests from main mock the single-call
method the batch path now uses, and the short-backend-result test is dropped because the
batch path makes one call per pair.
@adaamko adaamko self-assigned this Nov 22, 2026
@adaamko
adaamko requested a review from trozer November 22, 2026 19:25
@trozer

trozer commented Nov 26, 2026

Copy link
Copy Markdown
Collaborator

Thanks for pulling the epic together. The per-ticket PRs made this much easier to follow, and the core design holds up well: typed requests and results, constructors that take loaded objects, stable error codes, and the contract suite.

For this review I focused on the new typed core: detect / detect_batch in base.py, the types and errors, EncoderDetector, LLMJudgeDetector, GenerativeDetector, VelaDetector with SystemOneClient, RAGFactCheckerDetector.detect, llm_client, the caches and load_detector. The deprecated wrappers, docs and release prep are out of scope for this comment.

What I checked and found right:

  • The max() aggregation across chunks is preserved, and detect spans match main's predict on a real ModernBERT-en-v1 checkpoint.
  • The golden fixtures pass against main's code, so they really pin the old behaviour.
  • Cache keys match main byte for byte for float temperatures.
  • LLM span location can't produce an invalid span, and the structured-output schemas match the parsers.
  • No customer text shows up in error messages or module logs.
  • The suite passes on CPU (1,405 tests) and ruff is clean.

There are two items I'd like fixed before merge, then a list of smaller ones.

Must fix

1. One failing request can still abort the whole detect_batch

The batch contract says one failed request doesn't discard the others. But detect_batch only captures LettuceDetectError (base.py:277), and several paths in the new detectors let other exceptions through. When that happens the whole call raises, and finished results are lost, including paid LLM calls.

  • OpenAIClient.complete (llm_client.py:289-307): only auth, rate-limit, timeout, connection and 5xx errors are translated. These come through as raw openai exceptions:
    • BadRequestError, including context length exceeded
    • PermissionDeniedError and NotFoundError
    • UnprocessableEntityError and any other APIStatusError
  • BedrockClient.complete (llm_client.py:347): nothing is translated. Throttling, validation, credential and timeout errors all come through as botocore exceptions.
  • Verify pass (_llm_shared.py:375): it falls back only on UpstreamError. So a 403 in the verify call raises, where it should return the first-pass spans with verification_skipped.
  • RAGFactCheckerDetector._detect (rag_fact_checker.py:137): detect_hallucinations isn't wrapped.
    • In a 60-request batch where the first request fails, about 31 fact-check calls run before the batch raises.
    • A None result, or a triplet with a non-string element, raises AttributeError.
  • EncoderDetector (hallucination_dataset.py:159-167, encoder.py:990-999): an answer that can't fit in max_length makes the tokenizer raise a bare Exception("Truncation error: ..."). On ModernBERT-en-v1 with max_length=64 and a 120-token answer, detect_batch([ok, long, ok]) raises for all three.
  • GenerativeDetector (generative.py:47): OpenAIClient can return None content (a refusal or an empty reply), and reply.strip() then raises AttributeError.
  • Spans built from model output (encoder.py:558, encoder.py:582, the RAG offset mapping): output that fails Span validation raises a pydantic ValidationError. Two ways to trigger it:
    • NaN logits.
    • A RAG triplet element matched case-insensitively in an answer that contains "İ". Its lowercase form is two code points, so the computed span end runs past the answer. Example: answer "İİ Barcelona is on the coast of Greece", hallucinated triplet ["Madrid", "north", "sea", "GREECE"].

Most of these also raised on main, but main didn't promise isolation. Suggested fix, following the rule this PR adds to CONTRIBUTING (translate foreign errors where they enter the library):

  • OpenAIClient: catch the remaining openai.APIStatusError / openai.APIError and raise UpstreamError, non-retryable for 4xx.
  • BedrockClient: map botocore ClientError / BotoCoreError the same way.
  • RAG: wrap detect_hallucinations and the result handling. Raise UpstreamError, with invalid_model_output for bad shapes.
  • Encoder: check the answer's token count against max_length up front, and raise InvalidInputError for that request.
  • None reply: raise UpstreamError(empty_response), as BedrockClient already does.
  • Wherever spans are built from model output, turn a ValidationError into UpstreamError(invalid_model_output).

Each detector's tests could also cover a batch where the fake client raises a provider error (for example openai.BadRequestError) for one request, and check that the other results come back.

2. load_detector is missing published model ids

registry.py:18-32 registers 13 ids. These published models are missing, so load_detector raises unknown_model_id for them:

  • lettucedect-610m-eurobert-{fr,es,it,pl,cn}-v1 (docs/getting-started/models.md lists the 610m model for all six languages)
  • lettucedect-mmbert-small-hu-v1
  • tinylettuce-ettin-{32m,68m}-en
  • tinylettuce-ettin-{17m,32m,68m}-en-bioasq

The make_detector deprecation message points users to load_detector. For these models the only path left is building EncoderDetector by hand.

Related: load_detector doesn't set lang from the id (registry.py:112). So load_detector("KRLabsOrg/lettucedect-210m-eurobert-de-v1") uses the English prompt template unless the caller passes lang="de". The registry already knows each model's language and could set it.

Should fix

Detectors can't be pickled or deep-copied after first use.

  • The scoring lock is stored on the instance on the first call (encoder.py:357, taxonomy_head.py:271), and there's no __getstate__.
  • After one detect, both pickle.dumps(det) and copy.deepcopy(det) raise TypeError: cannot pickle '_thread.RLock' object.
  • That blocks multiprocessing spawn, Ray, joblib and similar tools. It matters for a design built around passing loaded detectors around, and main's TransformerDetector could be pickled after predict.
  • Fix: a __getstate__ that drops _scoring_lock.

FileCache re-reads the whole file on every get (file_cache.py:83; set at :106).

  • At 5,000 entries (8 MB), a get takes about 16 ms and a set about 57 ms, all under one lock.
  • So re-running an evaluation from cache with 30 threads gets slow.
  • Fix: keep the parsed data in memory and reload only when the file's mtime or size changes.

FileCache changes the cache file's permissions to 0600.

  • tempfile.mkstemp (file_cache.py:172) creates the temp file as 0600, and os.replace puts it over the existing file. The umask and the old permissions are lost.
  • A cache shared between users or containers then fails with PermissionError.
  • Fix: chmod the temp file to the existing file's permissions (or 0o666 & ~umask) before the replace.

A typer and a detector that share one tokenizer object race.

  • The typer's lock is per typer instance (taxonomy_head.py:263-272), while the detector's lock is per tokenizer (encoder.py:58).
  • Both change the fast tokenizer's truncation settings. Concurrent calls on an EncoderDetector and a TaxonomyTyper built on the same tokenizer fail with RuntimeError: Already borrowed.
  • This is a likely setup for v2, where the mmBERT detector and the typing head share a tokenizer.
  • Fix: take the typer's lock from _TOKENIZER_LOCKS[id(tokenizer)] as well. The typer runs outside the scoring lock, so there's no deadlock risk.

EncoderDetector.detect_batch fails for tokenizers without a pad token.

  • It always calls the tokenizer with padding=True (encoder.py:990-999), even for a single request.
  • So it raises ValueError: Asking to pad but the tokenizer does not have a padding token, where detect works.
  • Fix: skip padding for groups of one, or fall back to the single-request path when pad_token is None.

A confidence outside [0, 1] scores 1.0 (_llm_shared.py:107-116, :215-217).

  • A reply with confidence: -0.2 or 1.3 is treated like a missing confidence: it gets score 1.0 plus the synthetic_score warning.
  • The span then passes any min_score filter, even though the model rated it low.
  • Fix: clamp numeric values into [0, 1], and use 1.0 only when the confidence is missing or not a number.

SystemOneClient error handling (vela_client.py):

  • Base URL: one without a scheme ("localhost:8001") passes the check at :123. Every call then fails as a retryable connection_failed, so a config mistake gets retried forever. Validate http/https in __init__.
  • Decoding errors: only httpx.TransportError is caught (:175), so a broken gzip body raises a raw httpx.DecodingError. Catching httpx.RequestError covers both.
  • Retry-After: values like -5, nan or inf pass straight through (:26-31), so time.sleep(err.retry_after) can raise. Reject negative and non-finite values.
  • close() (:201-203): it also closes an http_client the caller passed in and owns. Only close a client the class created itself.

Smaller items

  • retry_after is never set for OpenAI 429s, although the retry-after header is available on exc.response.headers (llm_client.py:294-301).
  • The judge parser doesn't strip code fences (llm_judge.py:149-167), while the generative parser does (generative.py:47-49). A fenced judge reply from a backend without strict structured output raises unparseable_response.
  • from_pretrained only maps OSError (encoder.py:316, taxonomy_head.py:231).
    • A local folder with an unknown model_type, or an empty folder, raises a raw ValueError.
    • A local path that doesn't exist is reported as an UpstreamError telling the user to check the network.
  • TaxonomyTyper.from_pretrained (taxonomy_head.py:201) has no max_length parameter. Passing one sends it to the model loader, which raises TypeError.
  • The EncoderDetector.detect_batch docstring says each result equals detect (encoder.py:402).
    • That holds in fp32 (differences ≤ 3.5e-6).
    • In fp16, a token scored 0.4995 alone and 0.5039 in a padded batch, which changed a span.
    • Worth adding "up to floating-point noise".
  • 7 tests in tests/test_taxonomy_typer_pytest.py fail on a machine with a GPU. CI is CPU-only, so it doesn't see this, and the real TaxonomyTyper works on GPU.
    • Cause: _StubEncoder.to() records the device, but __call__ returns CPU tensors (:41-52), and the tests don't pass device=.
    • Fix: return hidden.to(self.device), or pass device="cpu".
  • With a custom fact_checker, RAGFactCheckerDetector still reports usage.model_id as the default "gpt-4o" (rag_fact_checker.py:84).

Happy to go through any of these together, or re-review once they're in.

…and keep span offsets in the answer

A fact checker that raises now gives UpstreamError, so detect_batch reports
that request as failed and returns the others. A result that is no dict, or
whose hallucinated triplets are not lists of strings, raises
UpstreamError(invalid_model_output). Case-insensitive matches are located in
the answer itself, so offsets stay right after characters whose lowercase form
is longer. With a custom fact checker, usage.model_id is the checker's model
or None.
… request error, ignore invalid Retry-After, close only an owned client
…ading and locking

- An answer that does not fit in max_length raises InvalidInputError (input_too_long) for its own request; in detect_batch the other requests are still scored.
- NaN scores and spans or token scores that fail validation raise UpstreamError (invalid_model_output).
- EncoderDetector and TaxonomyTyper can be pickled and deep-copied after use.
- A TaxonomyTyper takes the scoring lock of its tokenizer, shared with detectors built on it.
- detect_batch works with a tokenizer that has no pad token (one forward pass per request).
- from_pretrained reports a missing or unreadable local model folder as ConfigurationError.
- TaxonomyTyper.from_pretrained takes max_length.
- The typer test stub returns tensors on the device of its input.
…udge replies

OpenAIClient and BedrockClient raise typed errors for every provider failure,
so one failed request no longer aborts detect_batch. A reply without content
raises empty_response. OpenAI 429s carry retry_after from the header.
A confidence outside [0, 1] is clamped, and the judge parser strips code
fences with the helper the generative parser uses.
fix: isolate request failures in detect_batch and complete the load_detector registry
@adaamko

adaamko commented Nov 30, 2026

Copy link
Copy Markdown
Collaborator Author

Thanks for the review, this was very useful. Everything in it is addressed in #205, which is merged into stateless_core, so it is part of this PR now.

Must fix

  1. detect_batch isolation. Each place where a foreign error enters now translates it:
    • OpenAIClient: every remaining status error raises UpstreamError (request_rejected, not retryable). A 408 is treated as a timeout and is retryable. A reply without content raises empty_response.
    • BedrockClient: credential problems raise ConfigurationError (authentication_failed), throttling, timeouts and 5xx raise a retryable upstream_unavailable, and other client errors raise request_rejected.
    • Verify pass: a 403 is now an UpstreamError, so the existing fallback returns the first-pass spans with verification_skipped. A ConfigurationError in the verify call still propagates, because a bad key is for the operator to fix.
    • RAGFactCheckerDetector: the fact checker call is wrapped, and the result shape is checked before spans are built. The İ case is fixed at the source: case-insensitive matches take their offsets from the answer itself.
    • EncoderDetector: the answer length is checked up front and raises InvalidInputError (input_too_long) for that request only. Preparation is per request in the batch path, so a bad request joins no padded group.
    • A ValidationError from spans built out of model output is UpstreamError (invalid_model_output) in the encoder and the fact checker.
    • Each detector has a batch test where one request fails with a provider error and the other results come back.
  2. load_detector registers the 11 missing ids, each checked on the hub, and lang defaults to the language of the model. A lang the caller passes, as an option or in config, is kept.

Should fix and smaller items: all done as you suggested, with these details:

  • Pickling: __getstate__ drops the lock on both EncoderDetector and TaxonomyTyper.
  • FileCache: the file is parsed again only when its mtime, size or inode changed. The temp file is created with os.open(..., 0o666), so the kernel applies the umask, and it takes the mode of an existing file.
  • SystemOneClient: a broken body is invalid_model_output, and the other non-transport request errors are request_rejected. Both are not retryable.
  • A confidence outside [0, 1] is clamped. NaN still counts as missing.

Where the result differs from your notes

  • NaN logits did not raise without include_tokens. argmax of NaN is 0, so detect silently returned no spans. Both cases raise now.
  • I could not reproduce the typer and detector race with the test tokenizer (4 threads, 300 calls each). The lock is shared anyway, since the mechanism is the same as for two detectors, and the test checks lock identity.
  • A missing relative path such as models/foo has the form of a hub id and cannot be told apart from one, so it stays an UpstreamError. The message now also says to check that the directory exists. Absolute paths, ./x and ~/x give ConfigurationError.
  • With a custom fact_checker, model_id is the checker's model attribute when it is a string, otherwise None.
  • The Bedrock error tests need botocore, which the dev extra does not install, so 14 of them skip in CI. They pass locally.

Two things I left alone: context-length errors from OpenAI stay request_rejected (matching the error body would not work for every OpenAI-compatible backend), and FileCache.set still writes the whole file.

A re-review would be welcome whenever you have time.

@adaamko
adaamko merged commit dc96157 into main Dec 2, 2026
4 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants