Skip to content

fix(chunker): align custom-delimiter text/json paths with Python - #17744

Closed
xugangqiang wants to merge 1 commit into
infiniflow:mainfrom
xugangqiang:fix/chunker-custom-delim-align
Closed

xugangqiang wants to merge 1 commit into
infiniflow:mainfrom
xugangqiang:fix/chunker-custom-delim-align

Conversation

@xugangqiang

Copy link
Copy Markdown
Contributor

Summary

Fixes the go_bug custom-delimiter newline divergences tracked in known_diffs.json (these rules live in the parity-infra PR #17735; this PR is the production fix only):

  • token-custom-delim-newline-and-field — text / markdown / html paths with a backtick delimiter kept the delimiter glued to the preceding segment. Now the text path drops the delimiter and .strip()s each segment, mirroring Python's _split_text_by_pattern + .strip() (rag/flow/chunker/token_chunker.py:316-338). A chunk now reads first sentence here instead of first sentence here + trailing newline.
  • token-json-custom-delim-drops-newline — the json path ran every chunk through strings.TrimSpace, which deleted the delimiter's trailing newline that Python keeps (_build_json_chunks / _finalize_json_chunks never strip). The json path no longer trims, so first segment line one + trailing newline survives like Python.

doc_type_kwd is intentionally kept

The divergence rule also listed doc_type_kwd as a Go-only field. It is not a defect: doc_type_kwd is a load-bearing Go field (Infinity index column + media/PDF dispatch — engine/infinity/chunk.go:741, *_vision_dispatch.go, media_dispatch.go, parser.go). Python's JSON path emits it too (token_chunker.py:125); only its text path omits it. It is reclassified as go_intentional (extra_fields) in known_diffs.json (part of #17735), not removed here.

Changes

  • common.go: add splitDroppingDelim (delimiter discarded, mirrors Python).
  • token.go: text path uses splitDroppingDelim + per-segment TrimSpace; json path drops the TrimSpace in invokeJSONPayload.
  • Updated 3 existing unit tests that encoded the old keep-delimiter behaviour.
  • Added custom_delim_test.go: 4 self-contained RED→GREEN tests reproducing the parity cases (token__text/markdown/html/json_backtick); they also assert doc_type_kwd:"text" stays present.

Test plan

bash build.sh --test ./internal/ingestion/component/chunker/ — green, including the 4 new tests and no regression to the existing suite.

Note

Independent of #17729 / #17735 / #17739; based on upstream/main. The known_diffs.json rules token-custom-delim-newline-and-field and token-json-custom-delim-drops-newline should be removed/reclassified once this lands (handled in #17735).

Text path now drops the delimiter and trims each segment, mirroring
Python's _split_text_by_pattern + .strip() (token_chunker.py:316-338).
Previously splitKeepingDelim glued the delimiter onto the preceding
segment, so a chunk read "first sentence here\n" instead of
"first sentence here".

JSON path no longer TrimSpace-es each chunk, so the delimiter's trailing
newline survives like Python's _build_json_chunks / _finalize_json_chunks
(which never strip). Previously that newline was deleted (token.go:659).

doc_type_kwd is intentionally retained on the text path: it is a
load-bearing Go field (Infinity index column + media dispatch) and is
classified go_intentional in known_diffs.json, not a bug to fix here.

Updates the three existing unit tests that encoded the old keep-delimiter
behaviour, and adds custom_delim_test.go reproducing the four parity cases
(text/markdown/html/json backtick newline).
@dosubot dosubot Bot added size:M This PR changes 30-99 lines, ignoring generated files. 🐞 bug Something isn't working, pull request that fix bug. labels Aug 3, 2026
@coderabbitai

coderabbitai Bot commented Aug 3, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

The chunker now removes matched delimiters from text-like chunks, trims resulting text segments, and preserves JSON delimiter newlines. Tests cover custom delimiters across text, JSON, Markdown, HTML, and case-sensitive splitting paths.

Changes

Delimiter chunking behavior

Layer / File(s) Summary
Implement delimiter removal
internal/ingestion/component/chunker/common.go, internal/ingestion/component/chunker/token.go
Added delimiter-dropping splitting for text input. Text segments are trimmed before further processing. JSON parser-tag cleanup no longer trims surrounding whitespace.
Validate format-specific behavior
internal/ingestion/component/chunker/custom_delim_test.go, internal/ingestion/component/chunker/delimiter_case_sensitive_test.go, internal/ingestion/component/chunker/token_test.go
Added and updated tests for delimiter removal, JSON newline preservation, document types, chunk counts, case-sensitive matching, and delimiter-mode output.

Estimated code review effort: 2 (Simple) | ~10 minutes

Possibly related PRs

Suggested labels: ci, 🧪 test

Suggested reviewers: buua436, yuzhichang

Poem

I split each line with a tidy hop,
The matched marks now safely stop.
Text stays clean, JSON keeps its rhyme,
Tests guard every format in time.
— A pleased chunking rabbit 🐇

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly summarizes the primary change: aligning custom-delimiter text and JSON paths with Python behavior.
Description check ✅ Passed The description includes the required Summary section and clearly explains the problem, implementation, intentional behavior, and test plan.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

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.

@xugangqiang xugangqiang added the ci Continue Integration label Aug 3, 2026

@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.

🧹 Nitpick comments (2)
internal/ingestion/component/chunker/custom_delim_test.go (1)

115-135: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Assert the exact Markdown chunks.

The test checks only strings.HasSuffix(got, "\n"). A single unsplit chunk with internal newlines can pass. Compare chunkTexts(chunks) with the expected three segments.

Proposed assertion
  if len(chunks) == 0 {
    t.Fatal("want >=1 chunk, got 0")
  }
+ want := []string{"# Title", "Paragraph one.", "Paragraph two."}
+ got := chunkTexts(chunks)
+ if len(got) != len(want) {
+   t.Fatalf("chunk texts = %#v, want %#v", got, want)
+ }
+ for i, w := range want {
+   if got[i] != w {
+     t.Errorf("chunk[%d] text = %q, want %q", i, got[i], w)
+   }
+ }
  for i, c := range chunks {
🤖 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 `@internal/ingestion/component/chunker/custom_delim_test.go` around lines 115 -
135, The test TestCustomDelimMarkdownDropsDelimiter currently verifies only
trailing newlines, so it can pass without confirming the intended split. Replace
the suffix-only validation with an exact chunkTexts(chunks) comparison against
the three expected Markdown segments, while retaining the doc_type_kwd assertion
for each chunk.
internal/ingestion/component/chunker/token_test.go (1)

135-138: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Remove the stale delimiter assertion comment.

The updated expectations require delimiter-free chunks, but the comment at Lines 95-97 still says that chunks contain the matched delimiter. The comment is now false. Update it and make the basic test assert exact chunk values instead of checking only that chunks are non-empty.

Proposed comment update
-	// Every emitted chunk's text should be non-empty and contain the
-	// matched delimiter (we use the regex join-of-escaped literal so
-	// '\n' matches the literal text).
+	// Every emitted chunk's text should be non-empty and exclude the
+	// matched delimiter.

As per coding guidelines, remove stale documentation instead of preserving it.

🤖 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 `@internal/ingestion/component/chunker/token_test.go` around lines 135 - 138,
Remove the stale comment claiming chunks include the matched delimiter, and
update the basic chunking test to assert exact delimiter-free text values for
each expected chunk. Use the existing chunks assertions around chunks[0]["text"]
and chunks[1]["text"] as the expected-value pattern, while preserving the test’s
other checks.

Source: Coding guidelines

🤖 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.

Nitpick comments:
In `@internal/ingestion/component/chunker/custom_delim_test.go`:
- Around line 115-135: The test TestCustomDelimMarkdownDropsDelimiter currently
verifies only trailing newlines, so it can pass without confirming the intended
split. Replace the suffix-only validation with an exact chunkTexts(chunks)
comparison against the three expected Markdown segments, while retaining the
doc_type_kwd assertion for each chunk.

In `@internal/ingestion/component/chunker/token_test.go`:
- Around line 135-138: Remove the stale comment claiming chunks include the
matched delimiter, and update the basic chunking test to assert exact
delimiter-free text values for each expected chunk. Use the existing chunks
assertions around chunks[0]["text"] and chunks[1]["text"] as the expected-value
pattern, while preserving the test’s other checks.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro Plus

Run ID: d80cea31-7e08-4a0a-b1d5-39a648f828c9

📥 Commits

Reviewing files that changed from the base of the PR and between 1d141af and 17ec9a3.

📒 Files selected for processing (5)
  • internal/ingestion/component/chunker/common.go
  • internal/ingestion/component/chunker/custom_delim_test.go
  • internal/ingestion/component/chunker/delimiter_case_sensitive_test.go
  • internal/ingestion/component/chunker/token.go
  • internal/ingestion/component/chunker/token_test.go

@xugangqiang

Copy link
Copy Markdown
Contributor Author

Superseded by the combined Go PR #17835 (delimiter boundary + OVER_CAP merge sync). Closing in favor of #17835.

@xugangqiang xugangqiang closed this Aug 5, 2026
xugangqiang added a commit to xugangqiang/ragflow that referenced this pull request Aug 5, 2026
Extract a shared mergeDecision helper (mergeAction + allowBoundaryOverflow)
and newChunkText, and rewrite the text (addChunk) and JSON (addTextChunk)
merge paths to use it. Go now matches Python's canonical OVER_CAP default
(rag/nlp MergeStrategy): greedily accumulate adjacent units, allow one
boundary overflow then close the chunk, but never merge a unit that already
exceeds the cap (it stands alone, mirroring Python's `if pt > cap` branch).

Update the cap/overlap tests to the OVER_CAP contract (a chunk may exceed
budget by at most one incoming unit) and restructure the overlap-tag test to
exercise the overlap path under OVER_CAP.

Part of consolidating infiniflow#17744/infiniflow#17748 into a single Go PR that syncs the chunker
with Python PR infiniflow#17808 (OVER_CAP default).
@xugangqiang
xugangqiang deleted the fix/chunker-custom-delim-align branch August 12, 2026 10:59
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 size:M This PR changes 30-99 lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant