RecursiveDocumentSplitter corrupts Unicode characters when splitting by token
Describe the bug
RecursiveDocumentSplitter can replace parts of Unicode characters with � when splitting documents by token. This can happen when a token boundary falls inside a UTF-8 character.
The resulting chunks contain text that differs from the original document.
Error message
No exception is raised. The splitter silently returns corrupted text.
Expected behavior
The splitter should preserve the original Unicode characters and should not introduce � when it is absent from the input.
Additional context
The reproduction uses English text containing an emoji. The repeated text deliberately places the emoji at a token boundary that triggers the problem.
The same type of corruption was also reproduced with Korean and Japanese text. Corrupted chunks may affect downstream indexing and retrieval, but this reproduction does not establish how frequently the problem occurs in production.
The underlying character-decoding problem was previously noted in [PR #12974](https://github.com/deepset-ai/haystack/pull/12974), but it was outside that PR’s scope.
AI assistance was used to investigate, run the reproduction, and prepare this report.
To Reproduce
from haystack import Document
from haystack.components.preprocessors import (
DocumentSplitter,
RecursiveDocumentSplitter,
)
text = "hello " * 198 + "Enjoy 🍕 and 🚀"
splitters = [
(
"RecursiveDocumentSplitter",
RecursiveDocumentSplitter(
split_unit="token",
split_length=200,
split_overlap=0,
separators=["\n\n"],
tokenizer_encoding="cl100k_base",
),
),
(
"DocumentSplitter",
DocumentSplitter(
split_by="token",
split_length=200,
split_overlap=0,
tokenizer_encoding="cl100k_base",
),
),
]
for name, splitter in splitters:
chunks = splitter.run(documents=[Document(content=text)])["documents"]
combined = "".join(doc.content for doc in chunks)
print(name)
print(" matches original:", combined == text)
print(" replacement characters:", combined.count("�"))
print(" ending:", repr(combined[-25:]))
Actual output:
RecursiveDocumentSplitter
matches original: False
replacement characters: 3
ending: 'llo hello Enjoy ��� and 🚀'
DocumentSplitter
matches original: True
replacement characters: 0
ending: 'hello hello Enjoy 🍕 and 🚀'
The tokenizer encoding file may need to be downloaded on first use if it is not already cached.
FAQ Check
- [ ] Have you had a look at [our new FAQ page](https://docs.haystack.deepset.ai/docs/faq)?
System:
- OS: macOS, Apple Silicon
- Python: 3.12.7
- Haystack version:
mainatbbe4efe50c716d6d05a0637980db3b641236e613(3.6.0-rc0) tiktoken: 0.14.0
I’d like to work on a fix for this issue. Would a pull request be welcome?