{"slug": "unicode-normalization-broke-my-rag-3914-chunks-failed-to-match", "title": "Unicode Normalization Broke My RAG: 3,914 Chunks Failed to Match", "summary": "A developer traced a RAG retrieval failure to inconsistent Unicode normalization, finding that 3,914 of 41,200 indexed chunks (9.5%) were not in NFC form, causing identical-looking text to hash and tokenize differently. PDF extraction produced decomposed accents and ligatures like U+FB01, while filenames from an HFS+ backup injected NFD characters into chunk headers, and 612 duplicate chunks slipped past hash-based dedup. The fix was applying unicodedata.normalize(\"NFC\", text) at ingestion and auditing with unicodedata.is_normalized.", "body_md": "I searched my own notes for \"naïve Bayes\" and my RAG pipeline returned 3 documents. `grep -ril` on the same folder found 11.\n\nSame corpus, same word, same machine. The retriever was not dumb and the embeddings were not bad. The problem was that half of my \"ï\" characters were one code point and the other half were two. That is Unicode normalization, and it had been quietly corrupting my search index for months.\n\nThis is the autopsy: what I measured, what I broke while fixing it, and the 12 lines that fixed it.\n\n`U+00E9`) or two (NFD, `e` + `U+0301`). Python says they are not equal.` naïve` became `nai` + `ve`).` unicodedata.normalize(\"NFC\", text)` on every document `ﬁ` explicitly.`x²` into `x2` and `H₂O` into `H2O`. Use it only for the search key, never for stored text.\nUnicode normalization is the process of converting text into one canonical byte sequence, because Unicode allows several sequences to render as the same character. If you skip it, two strings that look identical on screen will fail `==`, produce different hashes, and tokenize differently.\n\nHere is the whole bug in five lines of a Python REPL:\n\n```\n>>> a = \"café\"      # NFC: é is one code point\n>>> b = \"café\"     # NFD: e + combining acute accent\n>>> print(a, b)\ncafé café\n>>> a == b\nFalse\n>>> len(a), len(b)\n(4, 5)\n>>> a.encode(), b.encode()\n(b'caf\\xc3\\xa9', b'cafe\\xcc\\x81')\n```\n\nYour terminal, your editor, and your LLM's chat UI all render these the same. Your SHA-256, your dict keys, your SQL `WHERE`, and your tokenizer do not.\n\nTwo sources, neither of which I'd have guessed.\n\n**1. PDF text extraction.** About 400 of my 2,870 documents are papers and vendor docs saved as PDFs. Depending on how the PDF was produced, the extractor hands back accented letters as base letter plus combining mark. It also hands back typographic ligatures: \"configuration\" arrives as `conﬁguration`, where `ﬁ` is a single code point, `U+FB01`. That word will never match a query typed on a keyboard.\n\n**2. Filenames from an old Mac backup.** HFS+, the macOS filesystem before APFS, stored filenames in a decomposed form. A chunk of my notes came off an HFS+-era backup drive. My ingestion prepends the filename to each chunk as a title line, so every chunk from a file named \"Café notes.md\" carried an NFD \"é\" in its header, while the body (typed later on a newer machine) used NFC.\n\nThat second one is nasty because it gives you *mixed* normalization inside a single chunk.\n\nI wrote a 20-line audit and ran it over every chunk in the index:\n\n``` python\nimport unicodedata\n\nLIGATURES = range(0xFB00, 0xFB07)  # ff fi fl ffi ffl long-st st\n\ndef audit(text: str) -> dict:\n    return {\n        \"not_nfc\": not unicodedata.is_normalized(\"NFC\", text),\n        \"ligature\": any(ord(ch) in LIGATURES for ch in text),\n    }\n```\n\n`unicodedata.is_normalized` has been in the standard library since Python 3.8 and is much faster than normalizing and comparing.\n\nResults on my index:\n\n| Check | Chunks | Share | \n|---|---|---|\n| Total chunks | 41,200 | 100% | \n| Not in NFC | 3,914 | 9.5% | \n| Contains a Latin ligature | 1,106 | 2.7% | \n| Byte-different but equal after NFC | 612 | 1.5% | \n\nThat last row is the dedup failure. My pipeline deduplicates chunks by hashing their text. 612 chunks were the same paragraph ingested twice (once from a PDF, once from my own notes quoting it), but the hashes differed, so both went into the vector store. On queries that hit those paragraphs, the duplicates took 2 of my top 5 retrieval slots, which means the LLM saw the same context twice and lost a slot for something useful.\n\nMy BM25 tokenizer split NFD words in half. I used the classic `re.findall(r\"\\w+\", text)`. In Python, `\\w` matches characters where `str.isalnum()` is true, and a combining mark like `U+0308` is not alphanumeric. So:\n\n``` python\n>>> import re\n>>> re.findall(r\"\\w+\", \"naïve\")    # NFC\n['naïve']\n>>> re.findall(r\"\\w+\", \"naïve\")   # NFD\n['nai', 've']\n```\n\nThe NFD document never indexed the token `naïve`. It indexed `nai` and `ve`. A query for \"naïve Bayes\", typed on a keyboard in NFC, could only match through \"Bayes\", and it lost to every document that matched both terms. Hybrid search didn't save me either, because the dense side ranked the duplicate NFC chunks above the NFD originals.\n\nThat's how 11 relevant files became 3 results.\n\nNormalize to NFC at the boundary, on both sides: every document at ingestion and every query at search time. Then handle ligatures explicitly, because NFC leaves them alone.\n\n``` python\nimport unicodedata\n\n_LIGATURE_MAP = str.maketrans({\n    \"ﬀ\": \"ff\", \"ﬁ\": \"fi\", \"ﬂ\": \"fl\",\n    \"ﬃ\": \"ffi\", \"ﬄ\": \"ffl\", \"ﬅ\": \"st\", \"ﬆ\": \"st\",\n})\n\ndef clean(text: str) -> str:\n    return unicodedata.normalize(\"NFC\", text).translate(_LIGATURE_MAP)\n\ndef search_key(text: str) -> str:\n    # only for BM25 tokens and dedup hashes, never stored or shown\n    return unicodedata.normalize(\"NFKC\", clean(text)).casefold()\n```\n\n`clean()` runs before anything touches the text: chunking, hashing, embedding, storage. `search_key()` runs only to build BM25 tokens and dedup hashes. The query goes through the same two functions. Forgetting the query side is the classic half-fix: your index is pristine and users still type into a different normal form.\n\nI re-ran ingestion only on the 3,914 affected chunks plus the 612 duplicates, which re-embedded about 4,500 chunks instead of the full 41,200.\n\nBecause NFKC changes meaning, not just encoding. This is the part I got wrong first.\n\nMy first fix was one line: `normalize(\"NFKC\", text)` on everything. It killed the ligatures for free, so I shipped it. Two days later I noticed an answer that said a formula used \"x2\" where my notes said \"x²\". NFKC folds \"compatibility\" characters into plain equivalents:\n\n`½` becomes `1⁄2`\n`™` becomes `TM`\n`Ａ` becomes `A`\nFor search keys that's exactly what you want: someone typing \"H2O\" should find \"H₂O\". For the text you store and feed to the model, it is data corruption. Hence the split: NFC for storage and context, NFKC plus casefold only for matching.\n\nHighlighting. My UI shows the matched passage with the query term highlighted, using character offsets saved at ingestion. Normalization changes string length (NFD \"é\" is 2 code points, NFC is 1), so every offset after an accented character in a re-ingested chunk drifted left by one per accent.\n\nBefore, a highlight on \"Bayes\" in an NFD chunk landed on \"ayes \" instead. I stopped storing offsets entirely and now find highlight spans at render time by re-matching the term against the stored NFC text. Offsets computed on one normal form are worthless on another. If you store spans anywhere (citations, highlights, NER annotations), normalize *before* you compute them.\n\nSame corpus, same retriever, same embedding model:\n\n`grep`.\nThe 4 remaining misses are a different problem: transliteration. Someone writes \"Muller\" without the umlaut and my notes say \"Müller\". Normalization doesn't touch that, and I'm not convinced stripping diacritics globally is safe, so it's still open.\n\nTotal time: one evening of debugging, one afternoon re-ingesting, and two days running a quietly wrong NFKC build before I caught it.\n\nYes. Unicode normalization differences make visually identical text fail equality, so exact-hash deduplication keeps duplicates, regex tokenizers split decomposed (NFD) words like `naïve` into fragments, and keyword search misses documents that contain the exact query term. In my 41,200-chunk index, 9.5% of chunks were not NFC, which cost 612 duplicate chunks and dropped non-ASCII query recall to 35 of 60. The fix is to apply `unicodedata.normalize(\"NFC\", ...)` to every document and every query before chunking, hashing, tokenizing or embedding, map PDF ligatures explicitly, and reserve NFKC with casefolding for search keys only, never for the text you store or send to the model.\n\n*Written by the developer behind [Preterview](https://preterview.com/en), an interview prep platform.*", "url": "https://wpnews.pro/news/unicode-normalization-broke-my-rag-3914-chunks-failed-to-match", "canonical_source": "https://dev.to/ji_ai/unicode-normalization-broke-my-rag-3914-chunks-failed-to-match-1d3", "published_at": "2026-11-28 21:10:29+00:00", "updated_at": "2026-11-28 21:15:00.538970+00:00", "lang": "en", "topics": ["natural-language-processing", "ai-tools"], "entities": ["Python", "Unicode", "HFS+", "macOS"], "also_reported_by": [], "takeaway": "Normalizing every chunk to NFC at ingestion catches 9.5% of chunks that otherwise fail exact match, hash dedup, and \\w tokenization, since NFD combining marks split words like naïve into nai and ve.", "recommendation": {"advice": "Apply unicodedata.normalize(\"NFC\", text) to every document and chunk at ingestion, and audit existing indexes with unicodedata.is_normalized to catch NFD text and ligatures before they break matching and dedup.", "playbook": "rag-retrieval", "playbook_url": "https://wpnews.pro/playbooks/rag-retrieval"}, "alternates": {"html": "https://wpnews.pro/news/unicode-normalization-broke-my-rag-3914-chunks-failed-to-match", "markdown": "https://wpnews.pro/news/unicode-normalization-broke-my-rag-3914-chunks-failed-to-match.md", "text": "https://wpnews.pro/news/unicode-normalization-broke-my-rag-3914-chunks-failed-to-match.txt", "jsonld": "https://wpnews.pro/news/unicode-normalization-broke-my-rag-3914-chunks-failed-to-match.jsonld"}}