Beyond Document Grounding: Span-Level Hallucination Detection over Code, Tool Output, and Documents

Ádám Kovács, Bowei He, Xue Liu, István Boros, Szilveszter Tóth, Gabor Recski

TL;DR

While hallucination detection in Retrieval-Augmented Generation (RAG) has traditionally focused on natural language text, modern AI agents increasingly generate structured outputs like code and tool logs. This paper introduces a unified benchmark and specialized fine-tuned models for span-level hallucination detection across code, markdown, and tool outputs. The authors demonstrate that their compact, fine-tuned 2B model drastically outperforms massive zero-shot LLM judges, which frequently fail by misidentifying valid, newly written code as hallucinations.

What Problem Does This Paper Address?

Most existing RAG hallucination benchmarks evaluate systems using natural language documents as both the evidence and the generated answer. However, real-world applications—such as coding assistants and autonomous agents—operate over highly structured data: source code, git histories, terminal outputs, markdown tables, and API documentation.

In these structured domains, a simple binary "accept/reject" label for an entire answer is insufficient. A single incorrect character, variable name, or configuration flag can completely break a program or mislead a developer, even if 99% of the generated response is correct. To address this, we need span-level detection that can pinpoint the exact unsupported substrings within structured text.

Furthermore, evaluating code is uniquely challenging because valid code often references external libraries or repository modules that might be missing from a truncated prompt context, causing standard detectors to throw false positives.

Methods

The authors developed a systematic pipeline to construct a high-quality dataset and train robust detectors:

  1. Edit-Based Injection Pipeline: Instead of trying to diff two completely different model answers, the authors started with known correct, grounded answers (e.g., gold patches from developer repositories). They used powerful LLMs (Gemma 4 31B and Qwen 3.6 35B) as "injectors" to introduce localized, subtle hallucinations—classified as either intent errors (changing logic/values) or structural errors (fabricating methods/attributes). This allowed them to track exact character offsets for the hallucinated spans.
  2. Reference Grounding: To prevent the detector from penalizing valid code that references unseen external elements, the authors actively expanded the context. They appended definitions of referenced modules from the base repository and integrated third-party API signatures by querying a library-documentation index (Context7).
Figure 3: Reference grounding for code examples. Cor- rect references missing from the truncated source con- text are resolved at the base commit and appended to the verifier context; third-party APIs are grounded with compact signatures.
  1. Model Training: They trained two detector families on this unified data:
  2. LettuceDetect-Qwen-2B: A generative model fine-tuned via LoRA to output JSON spans containing the exact text, category, and subcategory of the hallucination.
  3. LettuceDetect-mmBERT-base: A 307M-parameter encoder baseline trained for token classification.

Datasets

The paper introduces a massive unified benchmark containing 74,285 newly constructed examples across five structured sources, alongside converted versions of two established natural-language RAG datasets:

  • Code: Built using real GitHub issues and gold patches from SWE-bench.
  • Tool Output: Built from Squeez, featuring terminal/command observations.
  • Papers (ACL): Markdown-formatted paper chunks from ACL-Verbatim.
  • READMEs & Wikipedia: Markdown documentation and articles.
  • RAGTruth & PsiloQA: Converted natural-language benchmarks to ensure the models maintain strong performance on standard text.

Key Insights and Ideas

  • The Zero-Shot Blindspot: Massive off-the-shelf LLM judges (like Nemotron-3-Ultra-550B and GPT-4) perform poorly at verifying code. Because they lack task-specific training, they tend to over-predict hallucinations, flagging correct, newly written patch code as "unsupported" simply because it doesn't verbatim match the context.
  • Subtle Logic Reversals: In code, hallucinations are rarely completely random gibberish. They are often highly plausible but logically inverted (e.g., changing minor=minor to minor=not minor), making span-level tracking essential for debugging.
  • Context is Nothing Without Grounding: Truncating context is a reality of LLM applications. Without active reference grounding (pulling in API signatures and sibling methods), a hallucination detector cannot reliably distinguish between an invented function and a valid external library call.

Key Results

The fine-tuned LettuceDetect-Qwen-2B emerged as the clear winner, demonstrating that smaller, task-specialized models can handily defeat frontier models at verification tasks.

  • Overall Performance: The 2B model achieved a 0.689 span-F1 score across the entire unified test set.
  • Code-Agent Superiority: On the highly challenging code-agent split, LettuceDetect-Qwen-2B achieved a 0.602 span-F1, completely dominating LettuceDetect-large (0.172) and the strongest zero-shot LLM judges (Nemotron-3-Ultra at 0.216 and gpt-oss-120b at 0.212).
Detailed breakdown of baseline performance on the code-agent test set, highlighting the massive gap between fine-tuned models and zero-shot LLMs.
  • No Regression on Text: Despite being optimized for structured data, the model remained highly competitive on standard natural-language benchmarks, scoring 81.8 example-F1 on RAGTruth and setting a new state-of-the-art 0.724 English IoU on PsiloQA.
Per-source evaluation results across all modalities in the unified benchmark.

Limitations and Future Work

While the code test set underwent rigorous human verification and arbitration, the training and development sets rely heavily on synthetic hallucination injection. Consequently, the detectors might inadvertently learn patterns specific to how the injector models generate errors rather than capturing naturally occurring human or model errors.

Additionally, this framework evaluates final, post-generation answers statically. The authors note that extending this to evaluate full, multi-step agent trajectories in real-time remains an open and promising direction for future research.

Summary updated

BibTeX
@inproceedings{kovacs2026beyond,
  author = {Ádám Kovács and Bowei He and Xue Liu and István Boros and Szilveszter Tóth and Gabor Recski},
  title = {{Beyond Document Grounding: Span-Level Hallucination Detection over Code, Tool Output, and Documents}},
  booktitle = {GroundLM @ EMNLP},
  year = {2026},
  url = {https://openreview.net/forum?id=yW7LIRvTdh},
}
Figure