Skip to content

[Fix] naive: force-merge short markdown headers to prevent separate chunks - #15488

Merged
JinHai-CN merged 1 commit into
infiniflow:mainfrom
VictorECDSA:fix/markdown-short-header-chunks
Jun 3, 2026
Merged

JinHai-CN merged 1 commit into
infiniflow:mainfrom
VictorECDSA:fix/markdown-short-header-chunks

Conversation

@VictorECDSA

Copy link
Copy Markdown
Contributor

Problem

When uploading .md files with parser=naive and delimiter="\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):

if len(dels) > 0:  # When delimiter is provided (e.g., `\n`)
    # Split by delimiter and return immediately
    parts = re.split(dels, text)
    sections = [p.strip() for p in parts if p and p.strip()]
    return sections  # ⚠️ Skips block-level parsing (headers, code blocks, etc.)

When delimiter is provided, the method splits the text by delimiter and returns immediately, skipping block-level parsing (lines 173-220). As a result:

  • Headers like ## Quick Travel are treated as plain text lines
  • They are split into separate sections
  • The subsequent merge logic in naive.py cannot merge them with the body text

Solution

Modify the markdown merge logic in rag/app/naive.py to force-merge short headers (< 50 tokens) with the next section.

Changes

  1. rag/app/naive.py:

    • Add _is_short_header() helper function (module-level, for testability)
    • Modify merge logic to not finalize chunks that are short headers
  2. tests/test_naive_markdown_merge.py:

    • Add unit tests for _is_short_header() (12 test cases)

Why This Solution?

  • Minimal change: Only modifies merge logic, no changes to markdown_parser.py
  • No breaking change: Default behavior improved, no config change needed
  • Testable: Helper function is module-level, easy to test

Testing

Unit Tests

  • 12/12 passed (see tests/test_naive_markdown_merge.py)

Manual Testing

  1. Upload .md file with short headers + body text
  2. Before fix: Headers are separate chunks (16 chars)
  3. After fix: Headers merged with body text (correct)

Related Issues

Closes #15487

Checklist

  • Code changes are minimal and focused
  • Unit tests added (12/12 passed)
  • No breaking changes
  • Ready for review

…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)
@dosubot dosubot Bot added size:S This PR changes 10-29 lines, ignoring generated files. 🌈 python Pull requests that update Python code 🐞 bug Something isn't working, pull request that fix bug. 🧪 test Pull requests that update test cases. labels Jun 1, 2026
@coderabbitai

coderabbitai Bot commented Jun 1, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

This PR adds markdown header detection and forced merging to the naive chunking strategy. The _is_short_header() helper identifies headers under a token threshold, and the chunk-merging logic prevents these headers from becoming isolated short chunks by merging them into the following content.

Changes

Markdown short header merge fix

Layer / File(s) Summary
Short header detection helper
rag/app/naive.py
New _is_short_header(text, max_tokens=50) function validates Markdown heading syntax via regex (1–6 # followed by whitespace) and uses token counting to determine if a header is "short" below the threshold.
Chunk-merging loop integration
rag/app/naive.py
Modified Markdown chunk-merging loop now checks if accumulated text is a short header and skips finalization when true, forcing the header to merge with the following section instead of becoming an isolated chunk.
Comprehensive test coverage
tests/test_naive_markdown_merge.py
New pytest module with TestIsShortHeader suite validating header detection across levels (H1–H3), token boundary conditions (exactly 50 vs. 49), rejection of non-header and empty text, custom max_tokens override, and special character/CJK recognition; includes module-level __main__ runner.

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~12 minutes

Suggested labels

🐞 bug, 🌈 python, size:M

Suggested reviewers

  • JinHai-CN

Poem

🐰 A header once stood all alone,
Separated from text, cold as stone.
Now short headers cling to content below,
Merged together—what a delightful flow!
With tests to ensure it works just right,
Chunks now unite in chunky delight! ✨

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly and concisely describes the main change: forcing short markdown headers to merge with following content rather than forming separate chunks.
Description check ✅ Passed The description comprehensively addresses the problem statement, root cause analysis, solution approach, implementation details, testing results, and issue closure, following the template's intent.
Linked Issues check ✅ Passed The PR implementation fulfills the linked issue #15487 objectives by adding merge logic to force-merge short headers (<50 tokens) with subsequent content, preventing them from forming separate chunks.
Out of Scope Changes check ✅ Passed All changes are within scope: the new _is_short_header() helper and modified merge logic in naive.py directly address the issue, and test coverage is appropriate for the implementation.
Docstring Coverage ✅ Passed Docstring coverage is 93.33% which is sufficient. The required threshold is 80.00%.

✏️ 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.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

🧹 Nitpick comments (1)
rag/app/naive.py (1)

1107-1108: ⚡ Quick win

Add 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

📥 Commits

Reviewing files that changed from the base of the PR and between 3aea80f and 10677d9.

📒 Files selected for processing (2)
  • rag/app/naive.py
  • tests/test_naive_markdown_merge.py

Comment thread rag/app/naive.py
Comment on lines +74 to +78
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

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major | ⚡ Quick win

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.

Comment on lines +17 to +98
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

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major | ⚡ Quick win

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.

@yingfeng
yingfeng requested a review from KevinHuSh June 2, 2026 07:57
@yingfeng
yingfeng marked this pull request as draft June 2, 2026 07:58
@yingfeng
yingfeng marked this pull request as ready for review June 2, 2026 07:58
@dosubot dosubot Bot added the lgtm This PR has been approved by a maintainer label Jun 2, 2026
@KevinHuSh KevinHuSh added the ci Continue Integration label Jun 2, 2026
@KevinHuSh
KevinHuSh marked this pull request as draft June 2, 2026 08:46
@KevinHuSh
KevinHuSh marked this pull request as ready for review June 2, 2026 08:46
@codecov

codecov Bot commented Jun 2, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 93.16%. Comparing base (3aea80f) to head (10677d9).
⚠️ Report is 23 commits behind head on main.

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.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@JinHai-CN
JinHai-CN merged commit ff59714 into infiniflow:main Jun 3, 2026
2 checks passed
@coderabbitai coderabbitai Bot mentioned this pull request Jun 9, 2026
jason020818 added a commit to jason020818/ragflow that referenced this pull request Jun 18, 2026
…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]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

🐞 bug Something isn't working, pull request that fix bug. ci Continue Integration lgtm This PR has been approved by a maintainer 🌈 python Pull requests that update Python code size:S This PR changes 10-29 lines, ignoring generated files. 🧪 test Pull requests that update test cases.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug] Markdown headers become separate short chunks when using custom delimiter

3 participants