Repository navigation
[Fix] naive: force-merge short markdown headers to prevent separate chunks - #15488
Conversation
…hunks - Add _is_short_header() helper function (module-level, for testability) - Modify markdown merge logic to not finalize chunks that are short headers - This forces short headers (< 50 tokens) to be merged with the next section - Prevents the issue where headers become separate short chunks when using delimiter ## Testing - Unit tests: 12/12 passed (test_naive_markdown_merge.py) - Manual test: Short headers are now merged with body text - Long headers (> 50 tokens) are still separate chunks (expected) ## Root Cause In deepdoc/parser/markdown_parser.py, MarkdownElementExtractor.extract_elements() skips block-level parsing when delimiter is provided, causing headers to be treated as plain text and split into separate sections. ## Solution Instead of fixing extract_elements() (which would require major refactoring), we fix the merge logic in rag/app/naive.py to force-merge short headers. ## Impact - No breaking changes (default behavior improved) - Short headers (< 50 tokens) are now merged with next section - Long headers (> 50 tokens) remain as separate chunks (if chunk_limit allows)
📝 WalkthroughWalkthroughThis PR adds markdown header detection and forced merging to the naive chunking strategy. The ChangesMarkdown short header merge fix
Estimated code review effort🎯 2 (Simple) | ⏱️ ~12 minutes Suggested labels
Suggested reviewers
Poem
🚥 Pre-merge checks | ✅ 5✅ Passed checks (5 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
There was a problem hiding this comment.
Actionable comments posted: 2
🧹 Nitpick comments (1)
rag/app/naive.py (1)
1107-1108: ⚡ Quick winAdd debug logging for forced short-header merge decisions.
This introduces a new control-flow path (bypassing finalization when a short header is detected). A debug log here will make chunk-boundary behavior diagnosable in production.
Proposed logging snippet
- if current_text and not _is_short_header(current_text) and current_tokens + sec_tokens > chunk_limit: + is_forced_header_merge = current_text and _is_short_header(current_text) + if is_forced_header_merge: + logging.debug( + "force-merge short markdown header: current_tokens=%s next_tokens=%s chunk_limit=%s", + current_tokens, sec_tokens, chunk_limit + ) + if current_text and not is_forced_header_merge and current_tokens + sec_tokens > chunk_limit:As per coding guidelines,
**/*.py: Add logging for new flows.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@rag/app/naive.py` around lines 1107 - 1108, Add a debug log when the code takes the new short-header bypass path: inside the conditional that currently checks "if current_text and not _is_short_header(current_text) and current_tokens + sec_tokens > chunk_limit" (in rag/app/naive.py), emit a debug-level message describing that finalization was skipped because the next section is a short header and include the current_text (or its snippet), current_tokens, sec_tokens, and chunk_limit so chunk-boundary decisions are diagnosable; place the log immediately where the control flow skips finalization (use the module logger used elsewhere in this file).
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@rag/app/naive.py`:
- Around line 74-78: The header-detection currently uses re.match on the whole
text which can be true when a header plus body are present; in _is_short_header
replace the whole-text regex check with a single-line full match: extract the
first line (e.g. first_line = text.strip().splitlines()[0]) and use
re.fullmatch(r"#{1,6}\s+.*", first_line) (or equivalent) to ensure only pure
header lines qualify, then keep the existing token check using
num_tokens_from_string(text) < max_tokens so chunk finalization isn't
incorrectly skipped.
In `@tests/test_naive_markdown_merge.py`:
- Around line 17-98: Add a regression test to tests/test_naive_markdown_merge.py
(near TestIsShortHeader) that exercises the actual naive merge path: call the
public markdown chunking/merging function with parser="naive" and delimiter="\n"
using input like "## Header\nBody text" and assert the result produces a single
merged chunk string that contains both the header and the body together; ensure
the test uses the same public API your codebase exposes for merging (pass
parser="naive", delimiter="\n") rather than calling _is_short_header() directly
so it verifies end-to-end behavior.
---
Nitpick comments:
In `@rag/app/naive.py`:
- Around line 1107-1108: Add a debug log when the code takes the new
short-header bypass path: inside the conditional that currently checks "if
current_text and not _is_short_header(current_text) and current_tokens +
sec_tokens > chunk_limit" (in rag/app/naive.py), emit a debug-level message
describing that finalization was skipped because the next section is a short
header and include the current_text (or its snippet), current_tokens,
sec_tokens, and chunk_limit so chunk-boundary decisions are diagnosable; place
the log immediately where the control flow skips finalization (use the module
logger used elsewhere in this file).
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro
Run ID: 0e3e15fd-18d9-4060-afca-060efcf6dc5a
📒 Files selected for processing (2)
rag/app/naive.pytests/test_naive_markdown_merge.py
| if not re.match(r"^#{1,6}\s+", text.strip()): | ||
| return False | ||
|
|
||
| # Check if token count is below threshold | ||
| return num_tokens_from_string(text) < max_tokens |
There was a problem hiding this comment.
Tighten header detection to a single-line full match.
re.match(r"^#{1,6}\s+", text.strip()) matches any text that starts with a header, including multiline header + body. That can make _is_short_header(current_text) true after body is appended, so chunk finalization is incorrectly skipped and chunks can exceed chunk_limit.
Proposed fix
def _is_short_header(text, max_tokens=50):
@@
- # Check if it matches markdown header pattern: 1-6 # followed by space
- if not re.match(r"^#{1,6}\s+", text.strip()):
+ candidate = text.strip()
+ # Only a single-line ATX header should qualify
+ if "\n" in candidate:
+ return False
+ # Match entire line: 1-6 '#' + at least one space + header text
+ if not re.fullmatch(r"#{1,6}[ \t]+.+", candidate):
return False
@@
- return num_tokens_from_string(text) < max_tokens
+ return num_tokens_from_string(candidate) < max_tokens🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@rag/app/naive.py` around lines 74 - 78, The header-detection currently uses
re.match on the whole text which can be true when a header plus body are
present; in _is_short_header replace the whole-text regex check with a
single-line full match: extract the first line (e.g. first_line =
text.strip().splitlines()[0]) and use re.fullmatch(r"#{1,6}\s+.*", first_line)
(or equivalent) to ensure only pure header lines qualify, then keep the existing
token check using num_tokens_from_string(text) < max_tokens so chunk
finalization isn't incorrectly skipped.
| class TestIsShortHeader: | ||
| """Test cases for _is_short_header() function.""" | ||
|
|
||
| def test_short_header_h1(self): | ||
| """Short level-1 header should return True.""" | ||
| text = "# Quick Start" | ||
| result = _is_short_header(text) | ||
| assert result is True | ||
|
|
||
| def test_short_header_h2(self): | ||
| """Short level-2 header should return True.""" | ||
| text = "## Quick Travel" | ||
| result = _is_short_header(text) | ||
| assert result is True | ||
|
|
||
| def test_short_header_h3(self): | ||
| """Short level-3 header should return True.""" | ||
| text = "### Setup" | ||
| result = _is_short_header(text) | ||
| assert result is True | ||
|
|
||
| def test_long_header(self): | ||
| """Long header (> 50 tokens) should return False.""" | ||
| text = "# " + "Very long header " * 20 # ~100 tokens | ||
| result = _is_short_header(text) | ||
| assert result is False | ||
|
|
||
| def test_non_header_short_text(self): | ||
| """Short text without header pattern should return False.""" | ||
| text = "This is short" | ||
| result = _is_short_header(text) | ||
| assert result is False | ||
|
|
||
| def test_empty_text(self): | ||
| """Empty text should return False.""" | ||
| text = "" | ||
| result = _is_short_header(text) | ||
| assert result is False | ||
|
|
||
| def test_whitespace_only(self): | ||
| """Whitespace-only text should return False.""" | ||
| text = " " | ||
| result = _is_short_header(text) | ||
| assert result is False | ||
|
|
||
| def test_header_exactly_50_tokens(self): | ||
| """Header with exactly 50 tokens should return False (strict <).""" | ||
| # Construct a header with exactly 50 tokens | ||
| words = ["word"] * 49 # 49 words = 49 tokens, plus "# " = 1 token | ||
| text = "# " + " ".join(words) | ||
| result = _is_short_header(text, max_tokens=50) | ||
| # 50 tokens = not < 50, so should return False | ||
| assert result is False | ||
|
|
||
| def test_header_49_tokens(self): | ||
| """Header with 49 tokens should return True (< 50).""" | ||
| words = ["word"] * 48 # 48 words = 48 tokens, plus "# " = 1 token = 49 tokens | ||
| text = "# " + " ".join(words) | ||
| result = _is_short_header(text, max_tokens=50) | ||
| assert result is True | ||
|
|
||
| def test_custom_max_tokens(self): | ||
| """Should respect custom max_tokens parameter.""" | ||
| text = "# Short" | ||
| result = _is_short_header(text, max_tokens=5) | ||
| assert result is False # "# Short" is ~2 tokens, but wait... | ||
|
|
||
| result = _is_short_header(text, max_tokens=10) | ||
| assert result is True | ||
|
|
||
| def test_header_with_special_chars(self): | ||
| """Header with special characters should still be recognized.""" | ||
| text = "## API Endpoint: /api/v1/users" | ||
| result = _is_short_header(text) | ||
| assert result is True | ||
|
|
||
| def test_header_with_cjk_chars(self): | ||
| """Header with CJK characters should be recognized.""" | ||
| text = "## 快速旅行" | ||
| result = _is_short_header(text) | ||
| assert result is True | ||
|
|
There was a problem hiding this comment.
Add a regression test for the actual naive merge path (not only the helper).
These tests validate _is_short_header(), but they don’t assert the end-to-end behavior that changed: markdown chunk merging with parser=naive and delimiter="\n". Please add at least one test that reproduces ## Header + body input and verifies a single merged chunk containing both header and body.
Suggested test shape
+def test_naive_markdown_short_header_merges_with_body():
+ text = "## Quick Travel\nThis is the body paragraph."
+ # call the same public/path entry used by naive markdown chunking
+ chunks = ... # invoke naive chunking with delimiter="\n"
+ assert len(chunks) == 1
+ assert "## Quick Travel" in chunks[0]
+ assert "This is the body paragraph." in chunks[0]As per coding guidelines, tests/**/*.py: "Add/adjust tests for behavior changes".
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@tests/test_naive_markdown_merge.py` around lines 17 - 98, Add a regression
test to tests/test_naive_markdown_merge.py (near TestIsShortHeader) that
exercises the actual naive merge path: call the public markdown chunking/merging
function with parser="naive" and delimiter="\n" using input like "##
Header\nBody text" and assert the result produces a single merged chunk string
that contains both the header and the body together; ensure the test uses the
same public API your codebase exposes for merging (pass parser="naive",
delimiter="\n") rather than calling _is_short_header() directly so it verifies
end-to-end behavior.
Codecov Report✅ All modified and coverable lines are covered by tests. Additional details and impacted files@@ Coverage Diff @@
## main #15488 +/- ##
==========================================
- Coverage 94.56% 93.16% -1.40%
==========================================
Files 10 10
Lines 717 717
Branches 118 118
==========================================
- Hits 678 668 -10
- Misses 25 29 +4
- Partials 14 20 +6 ☔ View full report in Codecov by Sentry. 🚀 New features to boost your workflow:
|
…delimiter is set
When the user configures a custom delimiter (e.g. `\n`), `extract_elements`
routes to `_extract_delimited_elements` which splits the whole markdown text
on every delimiter match. Single-line headers such as `## Quick Travel` end
up as isolated chunks with no body text, and retrieval returns the header
without any content.
After the delimiter split, scan the section list and merge any section that
is nothing but a single markdown header (matches `^#{1,6}\s+\S`, no
embedded newline) with the immediately following section. This keeps the
header attached to its body regardless of the configured delimiter, which
is the expected outcome described in issue infiniflow#15487.
The existing `naive.py` workaround (_is_short_header / force-merge in the
chunk-building loop, PR infiniflow#15488) remains in place as a defence-in-depth
layer for any edge cases not caught at the parser level.
Handles both include_meta=True (dict sections) and include_meta=False
(string sections).
Fixes infiniflow#15487
Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
Problem
When uploading
.mdfiles withparser=naiveanddelimiter="\n", markdown headers (e.g.,## Quick Travel) become separate chunks with very short content (16-18 characters). This causes retrieval issues: when the header is matched, the corresponding body text is not included in the chunk.Root Cause
In
deepdoc/parser/markdown_parser.py,MarkdownElementExtractor.extract_elements()method (lines 141-172):When
delimiteris provided, the method splits the text by delimiter and returns immediately, skipping block-level parsing (lines 173-220). As a result:## Quick Travelare treated as plain text linesnaive.pycannot merge them with the body textSolution
Modify the markdown merge logic in
rag/app/naive.pyto force-merge short headers (< 50 tokens) with the next section.Changes
rag/app/naive.py:_is_short_header()helper function (module-level, for testability)tests/test_naive_markdown_merge.py:_is_short_header()(12 test cases)Why This Solution?
markdown_parser.pyTesting
Unit Tests
tests/test_naive_markdown_merge.py)Manual Testing
.mdfile with short headers + body textRelated Issues
Closes #15487
Checklist