Skip to content

fix(chunk): count merge budget in runes, not bytes - #20690

Merged
JinHai-CN merged 2 commits into
infiniflow:mainfrom
kassdinzheng123:chunk-merge-rune-budget
Oct 10, 2026
Merged

JinHai-CN merged 2 commits into
infiniflow:mainfrom
kassdinzheng123:chunk-merge-rune-budget

Conversation

@kassdinzheng123

@kassdinzheng123 kassdinzheng123 commented Oct 9, 2026 •

Copy link
Copy Markdown
Contributor

Summary

mergeChunks mixed length units: the running buffer total came from strings.Builder.Len() (bytes) while target_size and the per-chunk overflow check count runes. For CJK text every rune is 3 bytes, so the effective merge budget was target_size / 3 — the merge flushed early and every merged chunk stayed far below the configured size.

The fix tracks the buffer length in runes alongside the builder, so all three checks (per-chunk overflow, merge budget, flush threshold) operate in the same unit. ASCII behaviour is unchanged.

Root cause

In internal/parser/chunk/postprocess.go:

  • the single-chunk overflow check is len([]rune(c.Content)) >= target — rune based;
  • target_size is documented as a rune count;
  • but the running total used buf.Len(), which is bytes.

nextLen was computed in runes and then added to a byte count, so for multi-byte text the budget check buf.Len()+nextLen+1 > target fired roughly 3x too early for CJK.

Preserved invariant

  • target_size remains a rune-based budget everywhere;
  • the per-chunk overflow path (single chunk >= target stands alone) is untouched;
  • separator accounting (+1 per join) and metadata merge semantics are unchanged;
  • ASCII output is byte-identical to before (covered by TestMergeChunksASCIIBehaviourUnchanged).

Tests

  • Regression test fails on unmodified main (verified on worktree at ebb71552a):

    --- FAIL: TestMergeChunksTargetCountsRunes (0.00s)
        merge budget must count runes, not bytes: got ["甲乙丙丁" "戊己庚辛" "壬癸子丑"],
        want ["甲乙丙丁 戊己庚辛" "壬癸子丑"]
    
  • After the fix: go test ./internal/parser/chunk/ -count=1 passes (full package), go vet clean, gofmt clean.

  • internal/parser/parser package does not build in my environment (missing office_oxide.h C header for github.com/yfedoseev/office_oxide); this is a pre-existing environment limitation unrelated to this change — the touched package builds and passes fully.

  • The original fix was rebased onto main at ebb71552a before submission. The review follow-up only documents the rune budget on ChunkOptions.MergeTargetSize in options.go; the full diff is limited to postprocess.go, postprocess_test.go, and options.go.

Risk

Low: single function, unit-only change, no API or persistence impact. Chunks for non-ASCII text will now actually reach the configured target_size (visible behaviour change for CJK users, which is the point of the fix); ASCII paths are pinned by tests.

mergeChunks accumulated the running buffer length via strings.Builder.Len()
(bytes) but compared it against the rune-based target_size and the rune-based
per-chunk overflow check. For CJK text every rune is 3 bytes, so the budget
was effectively divided by three: chunks flushed early and every merged chunk
stayed far below the configured target_size.

Track the buffer length in runes alongside the builder so all three checks
(the per-chunk overflow, the merge budget, and the flush threshold) operate
in the same unit. ASCII behaviour is unchanged.

Adds regression tests covering CJK merge budget, ASCII behaviour, and the
oversize-unit path for multi-byte text.
@coderabbitai

coderabbitai Bot commented Oct 9, 2026 •

Copy link
Copy Markdown
Contributor

Review in Change Stack →Review in Change Stack →

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration
  • Configuration used: Organization UI
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: 0369de31-da28-4c5e-82c9-c5cb9c24950f


📥 Commits

Reviewing files that changed from the base of the PR and between 3fd7026 and 5b532e0.



📒 Files selected for processing (1)
  • internal/parser/chunk/options.go


Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 9 remain after this review.




📝 Walkthrough
📝 Walkthrough

Walkthrough

mergeChunks now measures accumulated content in runes when checking the target size. Tests cover chunk grouping for CJK and ASCII text. The MergeTargetSize comment describes the per-chunk rune budget.

Changes

Chunk merging

Layer / File(s) Summary
Rune-based merge accounting
internal/parser/chunk/postprocess.go, internal/parser/chunk/postprocess_test.go, internal/parser/chunk/options.go
mergeChunks tracks accumulated runes when adding chunks and resets the count when it flushes the buffer. Tests cover CJK grouping at the target size, unchanged ASCII grouping, and keeping a four-rune chunk separate when the target is four. The option comment describes the rune budget.

Priority: ⬇️ Low

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

Change: Bug fix

Suggested reviewers: zpf121



Merge Risk: ⚪ Minimal · up to 5b532

Chunk merging now measures its budget in runes as intended. The inspected code and regression assertions show no concrete merge-blocking risk.

Pre-merge checks | Passed 5
✅ Passed checks (5 passed)
Check name Status Explanation
Docstring Coverage Passed Docstring coverage is 80.00% which is sufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 5 functions across 3 files.
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.
Description check Passed The description includes the required Summary section and clearly explains the problem, root cause, fix, tests, and risk.
Title check Passed The title clearly and concisely describes the main change: measuring the chunk merge budget in runes instead of bytes.

  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

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

A rabbit counts each rune with care,
CJK hops, and ASCII is there.
The buffer joins, then knows to part,
A tidy count guides every start.
Four runes pause, then stand alone,
The rabbit thumps beside the code.

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

@JinHai-CN
JinHai-CN requested a review from zpf121 October 10, 2026 02:03
@JinHai-CN JinHai-CN assigned JinHai-CN and zpf121 and unassigned JinHai-CN Oct 10, 2026

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

LGTM — the fix is correct, and the byte/rune mix-up in mergeChunks is properly resolved.

One suggestion before this lands: please pin the unit on the config itself.

ChunkOptions.MergeTargetSize in internal/parser/chunk/options.go carries no unit annotation, while the field right below it is explicit:

	// Postprocess configuration. Zero values mean "do not run that
	// step"; non-zero values enable it.
	MergeTargetSize int

	// FilterMinLength > 0 drops chunks shorter than that (rune count).
	FilterMinLength int

The mixed-unit expression this PR fixes could survive for so long precisely because nothing stated which unit target_size is in, so a byte count and a rune count were allowed to sit on opposite sides of > unnoticed. After this change every size threshold in the package is rune-based (FilterMinLength is documented as "(rune count)", defaultLengthChunkSize as "in runes", splitByLength as "by rune count (not bytes)", and now mergeChunks), so it is worth writing that invariant down:

	// MergeTargetSize > 0 enables the merge step; its value is the
	// per-chunk budget in runes (Unicode code points).
	MergeTargetSize int

Not blocking — this is only about making the invariant explicit, and it also settles the point the description has to argue for indirectly, namely that target_size is a rune budget rather than a token budget.

@zpf121 zpf121 added the ci Continue Integration label Oct 10, 2026
@kassdinzheng123

kassdinzheng123 commented Oct 10, 2026 •

Copy link
Copy Markdown
Contributor Author

Thanks, @zpf121 — addressed in 5b532e0.

ChunkOptions.MergeTargetSize now explicitly documents that a positive value enables merging and that the budget is measured in runes (Unicode code points), rather than bytes or tokens. This follow-up changes only the field comment in internal/parser/chunk/options.go; runtime behavior is unchanged.

Validation on this head:

  • All three TestMergeChunks* regressions pass.
  • go test ./internal/parser/chunk/ -count=1, go vet ./internal/parser/chunk/, gofmt, and git diff --check pass.
  • The official bash build.sh --test ./internal/parser/chunk/ entry point is still blocked locally by the missing office_oxide native library. The chunk package has only standard-library dependencies and no CGO files, so its checks were run directly.

For visibility, the previous head's Go integration run fails in TestRunAgent_AllFixture_LoopInterruptResume with GraphRunError: no tasks to execute. The same test and error also occurred on upstream main. The chunk package passed in the PR run; I have not changed unrelated agent code or tests.

CI update for this head (run 38024391980):

  • Preflight, Infinity, Go integration, and CodeRabbit pass.
  • The Elasticsearch job fails in the sibling TestRunAgent_AllFixture_LoopInterruptResume_MultiTurn test with GraphRunError: no tasks to execute, last completed nodes: [Message:LoopDone]. The chunk package passes in this job too.
  • Cleanup then fails because COMPOSE_PROJECT_NAME is unset; the native-backend job is skipped.

The earlier upstream-main evidence is from the non-MultiTurn sibling test, not an independent reproduction of this exact MultiTurn failure. I have kept the patch focused on chunk accounting and the requested documentation. Could a maintainer rerun the failed job?

@zpf121 zpf121 added ci Continue Integration and removed ci Continue Integration labels Oct 10, 2026

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

LGTM — approving.

Verified locally on 5b532e0b3:

  • go test ./internal/parser/chunk/ — 30/30 pass, stable at -count=20, clean under -race, coverage 76.4%
  • go vet and gofmt -l clean
  • The new regression test fails on the pre-fix postprocess.go and passes after it, and only that CJK case flips: the ASCII and oversize-single-chunk cases are unaffected

The unit annotation on MergeTargetSize addresses the earlier review point — thanks for the quick turnaround.

Two non-blocking follow-ups, neither of which belongs in this PR:

  • ChunkData.Size is still assigned len(content) (bytes) in PostprocessOperator.Execute, which overrides the rune count splitByLength sets. Same root cause as this bug, worth a separate fix.
  • CI on this run: ragflow_go_integration failed after 10s (looks like a setup/infra failure rather than a test failure — logs were not yet available while the run was still in progress), and ragflow_tests_elasticsearch / ragflow_tests_infinity are still pending. The earlier ragflow_tests_elasticsearch failure was the pre-existing flaky TestRunAgent_AllFixture_LoopInterruptResume_MultiTurn in internal/service, which also fails on main (e.g. 1673c3e61) and is unrelated to this change.

@zpf121 zpf121 added ci Continue Integration and removed ci Continue Integration labels Oct 10, 2026
@JinHai-CN
JinHai-CN merged commit 637224d into infiniflow:main Oct 10, 2026
20 of 26 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ci Continue Integration

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants