Description
Describe the bug
I ran into what looks like a small but pretty severe bug in MarkdownHeaderSplitter when working with nested Markdown headers.
When a parent header has its own content and is followed by nested headers, the first child chunk always loses its direct parent in their parent_headers key in the metadata.
In practice, this means the first nested section gets:
"parent_headers": []even though it should inherit the parent section header. This repeats whenever there's a level jump (from "## header 2" to "### Header 2.1", for example, the header 2.1 loses header 2 in its parent_headers).
Later sibling sections often behave correctly, which makes this especially confusing because the hierarchy looks inconsistent within the same document. More on that is provided in the To Reproduce section below.
Error message
There is no error message.
Expected behavior
The first nested header should get all its parent headers in the "parent_headers" key in the metadata. More on that is provided in the To Reproduce section below.
Additional context
Add any other context about the problem here, like document types / preprocessing steps / settings of reader etc.
To Reproduce
To reproduce, you can use exactly this code:
from haystack.components.preprocessors import MarkdownHeaderSplitter
from haystack import Document
text = """
# header 1
intro text
## header 1.1
text 1
## header 1.2
text 2
### header 1.2.1
text 3
### header 1.2.2
text 4
"""
document = Document(content=text)
splitter = MarkdownHeaderSplitter(
keep_headers=True,
secondary_split="word"
)
result = splitter.run(documents=[document])["documents"]
for doc in result:
print(f"Header: {doc.meta['header']}, parent headers: {doc.meta['parent_headers']}")Expected:
Header: header 1, parent headers: []
Header: header 1.1, parent headers: ['header 1']
Header: header 1.2, parent headers: ['header 1']
Header: header 1.2.1, parent headers: ['header 1', 'header 1.2']
Header: header 1.2.2, parent headers: ['header 1', 'header 1.2']Reality:
Header: header 1, parent headers: []
Header: header 1.1, parent headers: []
Header: header 1.2, parent headers: ['header 1']
Header: header 1.2.1, parent headers: ['header 1']
Header: header 1.2.2, parent headers: ['header 1', 'header 1.2']FAQ Check
- Have you had a look at our new FAQ page?
System:
- OS: x86_64 GNU/Linux (24.04)
- GPU/CPU: AMD Ryzen 9 8945HS, NVIDIA GeForce RTX 4070
- Haystack version (commit or version number): 2.28.0rc0
- DocumentStore: None
- Reader: None
- Retriever: None
- Splitter: MarkdownHeaderSplitter
Activity