← Back to all articles

Catching Silent AI Citation Hallucinations With Zero-Dependency Deterministic Verification

How claimcite v0.7.0 uses pure Python 3.10+ stdlib and a 4-state deterministic engine (26/26 recorded-fixture benchmark, 0 false errors, 182+ offline tests in <1s) to catch 4 classic citation failure modes and verify local xerj:// UTF-8 byte spans without caching private docs.

🌐 阅读中文版本 →
#claimcite#Python#MCP#Hallucination#RAG
On this page

The most dangerous hallucinations in AI-written research notes, health summaries, and technical drafts rarely look obviously wrong. They look impeccably formatted, carry clickable links that return HTTP 200, and read like legitimate scholarship.

A plain link checker misses them — the DOI resolves just fine, except it belongs to an unrelated paper from a decade earlier. Asking a second LLM to “audit the citations” fails just as quietly: another model still cannot inspect live registry metadata, retraction records, or exact byte offsets, and it happily hallucinates false alarms on niche real papers.

This post walks through how claimcite (v0.7.0, pure Python 3.10+ stdlib, zero third-party runtime dependencies) tackles citation verification deterministically:

  1. Four classic silent AI citation failure modes, demonstrated with exact, reproducible outputs replayed against real recorded registry payloads;
  2. Why zero runtime dependencies + “false alarms are worse than misses” drives a strict 4-state verdict model (26/26 recorded-fixture benchmark with 0 false errors, and 182+ offline tests finishing in <1s);
  3. Bridging public papers to private local knowledge bases (sessfork → XERJ + kbwall → claimcite) by verifying host-free xerj:// UTF-8 byte spans offline without ever caching private documents to disk;
  4. Honest boundaries (Not tested ≠ clean) — what deterministic verification proves and what it intentionally refuses to guess.

Every CLI snippet, benchmark metric, and xerj:// verification output below comes directly from running benchmarks/run.py, recorded real responses in tests/fixtures/, and a local loopback XERJ check — zero fabricated outputs. Offline reproduction steps are at the end.


1. Four Classic Silent AI Citation Failure Modes (With Exact Verifiable Outputs)

Across real drafts, AI-generated references consistently fail in four quiet ways that slip past skimming eyes. Each output below is produced directly by claimcite replaying real recorded registry responses (53 recorded payloads in tests/fixtures/).

Failure Mode 1: Real DOI Attached to the Wrong Paper or Year (“DOI Laundering”)

LLMs routinely emit a valid, high-citation DOI and bolt it onto a fabricated or misremembered title and year. In examples/sample.md (line 7), a claim about green tea halving stroke risk cites doi:10.1016/s0140-6736(10)61388-8 as a 2021 Stroke cohort — when that real DOI actually resolves to a 2011 Lancet paper on the global burden of second-hand smoke. Any HTTP-200 link checker passes it silently.

In the recorded offline benchmark (err_title_mismatch_doi), pairing real DOI 10.1007/s10654-019-00524-3 with Tanaka H (2019). Deep Residual Learning for Image Recognition. Stroke. triggers a hard title-mismatch error:

- **Error** · line 1 · `doi:10.1007/s10654-019-00524-3`
  - Coffee consumption and all-cause and cause-specific mortality: a meta-analysis by potential modifiers. (2019)
  - Study type (as tagged by PubMed): Systematic review / meta-analysis
  - Title does not match this identifier. Registry title: Coffee consumption and all-cause and cause-specific mortality: a meta-analysis by potential modifiers.

Notice the restraint when only the year is wrong: in warn_year_mismatch (pmid:30221596, citing the 2018 ASPREE aspirin trial as 2024), the title matches, so claimcite emits a Warning rather than a hard CI-breaking Error (and grants a ±1 year tolerance for online-first vs. print publication):

- **Warning** · line 1 · `pmid:30221596`
  - Effect of Aspirin on Disability-free Survival in the Healthy Elderly. (2018)
  - Study type (as tagged by PubMed): Randomized controlled trial
  - Year differs: document 2024, registry 2018

Failure Mode 2: Nonexistent DOI / PMID / arXiv ID (and Invented Unlinked References)

Models synthesize syntactically spotless fake identifiers — doi:10.1001/jama.2022.99999, doi:10.9999/does-not-exist-claimcite, PMID: 99999999, or arXiv:9912.99999.

claimcite checks DOIs against the registrar-agnostic doi.org/api/handles/ API first, then resolves metadata across PubMed, Crossref, OpenAlex, and the arXiv Atom API (including DataCite 10.48550/arXiv.* DOIs). It emits an Error only when the authoritative registry definitively reports the identifier does not exist:

- **Error** · line 1 · `doi:10.9999/does-not-exist-claimcite`
  - Identifier does not exist

Even more common are hallucinated citations with no identifier at all (Carter M, Rivera L. (2024). Daily brisk walking reverses neuronal telomere shortening in sedentary adults...). claimcite parses APA, Harvard, MLA, Vancouver, and GB/T 7714 bibliography entries and searches Crossref followed by PubMed by title:

  • Found (ok_unlinked_title_search) → resolves the real identifier and runs full title/year/quote verification;
  • Missing from both (warn_unlinked_invented) → emits a Warning, not an Error (technical reports or slightly reworded titles can also be absent);
  • Books & non-open registries (not_checked_book, e.g., Kahneman’s Thinking, Fast and Slow, or Chinese references where CNKI/Wanfang offer no open API) → stays explicitly Not checked instead of crying wolf.

Failure Mode 3: Retracted Paper Cited Uncritically (Without Flagging Retraction Notices)

Training corpora are packed with famous retracted studies. Checking retractions sounds trivial until you inspect real Crossref JSON payloads: Crossref puts update-to on the retraction notice, not on the retracted paper. The retracted paper carries updated-by and relation.is-retracted-by (PubMed tags Retracted Publication / RetractionIn; OpenAlex exposes is_retracted).

On top of that, publishers frequently prepend RETRACTED: to the registered title after retraction. claimcite strips _RETRACTED_PREFIX before fuzzy title comparison so you see a clean retraction error (complete with the notice DOI) rather than a spurious title-mismatch error:

- **Error** · line 1 · `doi:10.1016/s0140-6736(97)11096-0`
  - RETRACTED: Ileal-lymphoid-nodular hyperplasia, non-specific colitis, and pervasive developmental disorder in children (1998)
  - This paper has been retracted (notice: doi:10.1016/s0140-6736(10)60175-4)

Crucially, the paired control case ok_retraction_notice_doi verifies that citing the retraction notice itself (doi:10.1016/s0140-6736(10)60175-4) passes cleanly as OK:

- **OK** · line 1 · `doi:10.1016/s0140-6736(10)60175-4`
  - Retraction—Ileal-lymphoid-nodular hyperplasia, non-specific colitis, and pervasive developmental disorder in children (2010)

Failure Mode 4: Fabricated Quotes on Real PMIDs + Dangling [n] / Uncited [^n] Markers

In the sneakiest failure mode, the paper, authors, year, and PMID are 100% real — only the quoted words inside quotation marks were invented or exaggerated by the model.

Line 11 of examples/sample.md cites real meta-analysis pmid:33237064 (Food & Function, 2020), then fabricates the quote "calcium and vitamin D supplementation cured osteoporosis in all women":

- **Warning** · line 11 · `pmid:33237064`
  - Effects of combined calcium and vitamin D supplementation on osteoporosis in postmenopausal women: a systematic review and meta-analysis of randomized controlled trials. (2020)
  - Study type (as tagged by PubMed): Systematic review / meta-analysis
  - Quoted text not found in the abstract (it may be in the full text): “calcium and vitamin D supplementation cured osteoporosis in all women”

Because legitimate quotes often live in the paper body rather than the abstract, claimcite falls back on demand to PubMed Central (PMC) and Europe PMC open-access JATS XML full text (stripping <xref> footnote tags and nested <ref-list> blocks):

  • ok_pmc_fulltext_quote (pmid:38555664): a body-only quote absent from the abstract is verified against PMC open-access full text → OK;
  • warn_missing_quote_oa_fulltext (pmid:40132810): a fabricated quote ("tuberculosis was eradicated globally in 2020") misses both abstract and OA full text, sharpening the diagnostic:
- **Warning** · line 1 · `pmid:40132810`
  - Thinking fast and slow: the urgency of crisis response must not lead us to overlook chronic needs such as tuberculosis. (2025)
  - Quoted text not found in the abstract or open-access full text: “tuberculosis was eradicated globally in 2020”

When Crossref lacks an abstract altogether (for example, ACM’s doi:10.1145/3442188.3445922, On the Dangers of Stochastic Parrots), claimcite queries OpenAlex and reconstructs the abstract from abstract_inverted_index. And when a document places a Chinese paraphrase in corner brackets (「…」) beside an English paper (ok_cjk_paraphrase_quote), quote_found() recognizes the cross-language boundary instead of firing a false missing-quote warning.

Finally, iterative LLM edits routinely leave structural bibliography drift behind — a dangling body marker [2] with no reference entry, or an orphaned footnote [^1] never referenced in the prose. claimcite flags both as Error, while explicitly guarding against false alarms on statistical/IQR intervals (60 [52-68] years, [0, 1], [1-5] scale), fenced code blocks, and Markdown reference links:

- **Error** · line 1 · `[2]`
  - Citation [2] has no matching entry in the reference list (line 1)

- **Error** · line 3 · `doi:10.1007/s10654-019-00524-3`
  - Coffee consumption and all-cause and cause-specific mortality: a meta-analysis by potential modifiers. (2019)
  - Study type (as tagged by PubMed): Systematic review / meta-analysis
  - Reference [^1] is never cited in the text

2. Why Pure Python 3.10+ Stdlib, Determinism, and Zero False Errors

1. Why Keep dependencies = [] at Runtime?

claimcite specifies dependencies = [] in pyproject.toml (Python 3.10+ stdlib only). That constraint directly optimizes for deployment and auditability:

  • Frictionless drop-in everywhere: uvx claimcite, pipx install claimcite, GitHub Actions, pre-commit, and stdio claimcite mcp start cleanly on Linux, macOS, and Windows with zero native wheel build failures and zero transitive supply-chain churn.
  • Stdlib already covers the entire problem:
    • urllib.request + ipaddress: per-host polite rate limiting (Crossref 1 req/s, arXiv 3 s/req, PubMed 0.4 s/req, OpenAlex 0.2 s/req, general web 1 req/s), SSRF guards across redirects (blocking loopback, RFC 1918, IMDS, and IPv6 ULA while permitting resolved public domains routed through Clash/Surge TUN Fake-IP 198.18.0.0/15), 1 KB header peeks for binary/PDF early-exit, and GB2312/GBK/GB18030 charset fallback.
    • sqlite3 + zlib: 30-day compressed registry cache (~/.cache/claimcite/v1/cache.sqlite3) with automatic startup pruning, credential scrubbing (api_key/mailto) on cache keys, and strict refusal to cache lookup failures.
    • xml.etree.ElementTree + difflib.SequenceMatcher: parses PubMed/PMC JATS XML and arXiv Atom feeds and normalizes punctuation/whitespace before fuzzy title and quote matching.
  • Wall-clock time is network-bound, not CPU-bound: live runs spend their time respecting free public API rate limits, while offline parsing and verification finish in milliseconds.

2. Core Invariant: False Alarms Are Worse Than Misses

A citation gate that blocks CI on legitimate references gets disabled in a week. claimcite enforces a clean 4-state separation:

Status Exit Code (default --fail-on error) When It Fires Hard Non-Trigger Invariant
ok 0 Identifier exists, not retracted, title & year match, verbatim quotes verified (or cross-language noted), xerj:// span & quote verified —
warning 0 (1 under --fail-on warning) Partial title match, year drift beyond ±1, quote missing from abstract / OA full text, unlinked title missing from Crossref & PubMed, dead 404 web link Never turns shifting web pages or bot walls into hard errors
error 1 Authoritative “does not exist”, title mismatch, retracted paper, dangling [n] / uncited [^n], missing or tampered xerj:// span Never reports “does not exist” when a network request fails
not_checked 0 Network/API error, robots.txt disallow, binary/PDF page, books, Chinese unlinked references, unconfigured XERJ node Explicit uncertainty — never disguised as ok or error

3. Verified Offline Benchmark & Test Suite (<1s)

Running both the recorded-fixture benchmark and the full offline test suite locally inside claimcite (v0.7.0 baseline, zero network calls):

$ uv run python benchmarks/run.py
claimcite offline benchmark: 26/26 (100.0%), false_errors=0
  error       : 8/8
  not_checked : 1/1
  ok          : 11/11
  warning     : 6/6

$ uv run pytest -q
........................................................................ [ 39%]
........................................................................ [ 79%]
......................................                                   [100%]
182 passed in 0.80s
  • Recorded-fixture benchmark: 26/26 (100.0%) in 0.15s with 0 false errors, backed exclusively by 53 real recorded API/HTML responses in tests/fixtures/.
  • Offline test suite: 182+ offline unit tests (baseline measured: 182 passed in 0.80s), zero API keys, zero network calls.

3. Bridging Academic Papers to Local Private Knowledge Bases (sessfork → XERJ + kbwall → claimcite)

In private RAG pipelines and internal research notebooks, hallucinations take a subtler form: retrieval finds the exact right filing or policy paragraph, and then the LLM silently swaps $42.8M into $48.2M while summarizing — or drifts the span offset right into the middle of a multi-byte UTF-8 character.

claimcite v0.7.0 extends the exact same deterministic verifier to local private corpora via a 4-stage open-source loop:

sessfork ──► XERJ + kbwall ──► claimcite
│            │                 └─ Zero-dep offline verification of xerj:// UTF-8 byte spans (zero disk cache)
│            └─ ~1 MB air-gapped read-only Rust MCP firewall emitting canonical host-free xerj:// URIs
└─ Headless Chrome auth fork (zero focus stealing) + <REDACTED> secret scrubbing before ingestion

1. Canonical Host-Free xerj:// Evidence Contract

kbwall and claimcite share a strict byte-for-byte URI contract that forbids host:port inside documents (so local topology and ports never leak into Markdown files or Git history):

  • xerj://<index>/<doc_id>#b=<byte_start>[-<byte_end>][&f=<field>] (UTF-8 byte span)
  • xerj://<index>/<doc_id>#c=<char_start>[-<char_end>][&f=<field>] (Unicode char span)
  • xerj://<index>/<doc_id>#offset=<byte_start>[&f=<field>] (single-point byte anchor alias)
  • When f= is omitted, _source text fields are probed deterministically in order: text -> body -> content -> code.

2. Verified Loopback xerj:// Run: Catching a Single-Digit Flip & a Mid-UTF-8 Byte Split

Running claimcite against a local loopback XERJ test server holding a 161-byte bilingual memo (including trailing newline: Sec 4.2 Revenue recognized in Q3 2026 reached $42.8M (up 18.4% YoY). followed by a Chinese line starting with 3-byte character 第 at byte 69), we verify four citations in one pass:

  1. Line 1 (#b=8-68): exact English verbatim quote ($42.8M) → OK;
  2. Line 2 (#b=69-160): exact Chinese UTF-8 byte span → OK;
  3. Line 3 (#b=8-68): single-digit hallucination ($48.2M) → Error (quote_mismatch);
  4. Line 4 (#b=70-160): byte offset 70 landing inside the 3-byte UTF-8 character 第 (0xe7 0xac ...) → Error (offset_out_of_range).

Exact output from claimcite:

# Citation check

2 ok · 0 warnings · 2 errors · 0 not checked

- **OK** · line 1 · `xerj://fin-filings/q3-2026-memo#b=8-68&f=text`
  - XERJ span verified (fin-filings/q3-2026-memo, field text)
- **OK** · line 2 · `xerj://fin-filings/q3-2026-memo#b=69-160&f=text`
  - XERJ span verified (fin-filings/q3-2026-memo, field text)
- **Error** · line 3 · `xerj://fin-filings/q3-2026-memo#b=8-68&f=text`
  - Quoted text not found in XERJ span: “Revenue recognized in Q3 2026 reached $48.2M”
- **Error** · line 4 · `xerj://fin-filings/q3-2026-memo#b=70-160&f=text`
  - XERJ span offset is out of range or splits a UTF-8 character (byte range 70-160 starts inside a UTF-8 codepoint)

_Automated check. It confirms that sources exist and match; it does not judge whether a claim is true and is not medical advice._

With 2 errors reported, the CLI exits with status 1, stopping subtle numerical hallucinations before a report is committed or sent to a reader.

3. Five Hard Security & Privacy Invariants for Local KB Verification

Verifying private documents must never open a side-channel leak. src/claimcite/xerj.py enforces five non-negotiable guardrails:

  1. Zero disk caching of private docs: public academic metadata is cached for 30 days in SQLite, but xerj:// responses are verified strictly in memory and never written to ~/.cache/claimcite/v1/cache.sqlite3.
  2. Loopback-only by default, never auto-probed: if --xerj-url / XERJ_URL is unset, claimcite never probes localhost:9200; by default only 127.0.0.1, ::1, and localhost are accepted (remote endpoints require explicit --xerj-allow-remote and default to mandatory https://).
  3. Explicit proxy bypass & zero redirects: uses a dedicated ProxyHandler({}) and _NoRedirectHandler() so HTTP_PROXY/ALL_PROXY and 3xx redirects can never intercept local traffic or leak Authorization headers, with a hard 10 MiB response cap.
  4. Strict read-only batch fetch: sends read-only POST /_mget (batched up to 100 docs, falling back to GET /{index}/_doc/{doc_id} on 403/405) — never writes or mutates indices.
  5. MCP prompt-injection isolation: under claimcite mcp, XERJ endpoints and credentials are read strictly from process environment variables (XERJ_URL, XERJ_AUTH, XERJ_API_KEY, XERJ_DATA_DIR) and are never exposed as MCP tool arguments, blocking prompt-injected SSRF.

4. Honest Limits (Not Tested ≠ Clean)

A verification tool earns trust by stating clearly where determinism ends:

  • Unquoted paraphrases are not checked: only text inside quotation marks ("…", “…”, 「…」) is compared word-for-word against abstracts, OA full text, web pages, or xerj:// spans. A sentence that subtly misrepresents a paper without quotation marks is neither extracted nor flagged.
  • No semantic entailment or claim-truth judging: proving that a paper exists, is unretracted, and contains a verbatim quote does not prove the paper supports the author’s broader conclusion (e.g., presenting an animal study as clinical proof — though PubMed study-type tags surface animal/observational/RCT/meta-analysis labels for human review). claimcite is not medical, legal, or investment advice.
  • Paywalled full text, PDFs, and closed registries: quotes living only inside closed-access full text or PDF web links conservatively stay warning or not_checked; Chinese-language references lacking open registry APIs (CNKI/Wanfang) stay not_checked; pages blocked by robots.txt or anti-bot walls stay not_checked.
  • Explicit Not tested ≠ clean:
    • A 0 errors run proves only that checked identifiers exist, metadata matches, papers are unretracted, numbered/footnote references balance, and verbatim quotes/spans match — it does not guarantee the document is factually error-free.
    • The 26/26 offline benchmark guards deterministic regressions against real recorded payloads; it is not a statistical recall guarantee over arbitrary messy documents in the wild.
    • General web fetching uses Python’s urllib with resolved-IP SSRF checks (which still carry standard DNS-rebinding TOCTOU windows and do not replace network-layer egress policy).

5. Reproduce Everything Offline & Wire Into Your Workflow

Zero API keys and zero network calls required to reproduce the offline benchmark and unit tests locally:

git clone https://github.com/wasabihu/claimcite.git
cd claimcite

# 1. Offline unit test suite (182+ tests, <1s)
uv run pytest -q

# 2. 26-case recorded-fixture offline benchmark (0.15s, 0 false errors)
uv run python benchmarks/run.py

Drop claimcite into daily writing, CI gates, or MCP-enabled coding agents:

# Install CLI (Python 3.10+, zero runtime deps)
pipx install claimcite                   # or: uv tool install claimcite

# Audit academic citations & web links
claimcite check article.md
claimcite check article.md --format json

# Audit local XERJ byte-span citations (loopback-only by default)
claimcite check notes.md --xerj-url http://127.0.0.1:9200

Configure the zero-dependency stdio MCP server (published on PyPI and the Official MCP Registry as io.github.wasabihu/claimcite):

{
  "mcpServers": {
    "claimcite": {
      "command": "uvx",
      "args": ["claimcite", "mcp"]
    }
  }
}
Discussion & Feedback Join the discussion or share feedback on GitHub Discussions →