Skip to content

Chunker: port Python overlapped_percent normalization and BULLET_PATTERN title fallback - #17396

Merged
yuzhichang merged 3 commits into
infiniflow:mainfrom
xugangqiang:fix/batch-3-4
Jul 27, 2026
Merged

yuzhichang merged 3 commits into
infiniflow:mainfrom
xugangqiang:fix/batch-3-4

Conversation

@xugangqiang

Copy link
Copy Markdown
Contributor

Summary

Closes two Chunker migration gaps documented in docs/migration_python_go_diff.md
(diffs 2.6 and 1.7), improving parity with the Python ingestion pipeline.

This is the code portion of commit 261e1fd0b on branch fix/batch-3-4; the
migration document itself is tracked separately (untracked in this commit).

Diff 2.6 — overlapped_percent missing Python normalization

Python's normalize_overlapped_percent (common/float_utils.py:50-58) accepts a
[0,1) fraction (the flow-canvas UI validates [0,1)), multiplies it by 100,
int()-truncates, and clamps to [0,90]. Go previously only accepted a raw
[0,90] percentage and rejected out-of-range input, so a Python config
passing 0.1 (meaning 10%) silently produced ~0% overlap.

Added normalizeOverlappedPercent
(internal/ingestion/component/chunker/common.go) mirroring the Python helper:

  • parses numbers and numeric strings (mirrors Python float(); bad / NaN / Inf → 0),
  • 0 < v < 1 → v *= 100,
  • int() truncation,
  • clamps to [0,90].

Wired into tokenChunkerParam.Update (token.go); the merge math
(token.go:705, (100-x)/100) already matched Python. TokenChunkerParam.Validate
(schema/chunker.go) now only guards direct struct construction.

Tests: TestNormalizeOverlappedPercent, extended
TestTokenChunker_NewAcceptsPythonOverlappedRange (adds fraction/clamp inputs),
new TestTokenChunker_NormalizesOverlappedPercent. The existing reject-test cases
for <0 / >90 were removed because they are now normalized/clamped (Python parity).

Diff 1.7 — missing BULLET_PATTERN title-level fallback

resolveTitleLevels (title.go) now applies a 4th-level fallback: when outline +
regex + layout all yield body level, bulletsCategory selects the best-matching
bullet-pattern group (Chinese legal / numbering / Chinese numbering / English legal
— mirroring rag/nlp/__init__.py:258-320) and assigns structural levels. Guarded by
allBodyLevel so it never overrides an existing outline/regex level.

Tests: TestResolveTitleLevels_BulletFallback (4 subtests).

Incidental test adjustments included in the commit

  • token_batch1_test.go: overlap input changed 0.3 → 30.0 to reflect the
    post-normalization 30% semantics.
  • real_consumer_test.go: updated LoadFromIngestionTask(task) →
    LoadFromIngestionTask(ctx, task) for the new context-first signature.

Verification

bash build.sh --test ./internal/ingestion/component/... — chunker + schema suites
pass, no regression (CGO build).

Migration doc reference

docs/migration_python_go_diff.md §Chunker 1.7 and 2.6 are marked Fixed for
these changes.

@dosubot dosubot Bot added the size:L This PR changes 100-499 lines, ignoring generated files. label Jul 27, 2026
@coderabbitai

coderabbitai Bot commented Jul 27, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review
📝 Walkthrough

Walkthrough

The changes normalize token overlap configuration across schema, construction, validation, and merging; add bullet-pattern title recovery; expand chunker tests; and pass context directly when loading an ingestion task in the producer-consumer test.

Changes

Chunker behavior updates

Layer / File(s) Summary
Overlap normalization and token processing
internal/ingestion/component/schema/chunker.go, internal/ingestion/component/chunker/common.go, internal/ingestion/component/chunker/token.go, internal/ingestion/component/chunker/token*_test.go
Overlap inputs are normalized to [0,90], validated under the new contract, applied consistently in token merging, and covered alongside paragraph-splitting behavior.
Bullet-pattern title recovery
internal/ingestion/component/chunker/title.go, internal/ingestion/component/chunker/title_test.go
Numbered and bulleted lines receive recovered title levels when regex-based detection produces no structure, while configured regex matches retain precedence.

Consumer test context setup

Layer / File(s) Summary
Explicit ingestion task context
internal/ingestion/task/real_consumer_test.go
The producer-consumer test passes its context directly to LoadFromIngestionTask.

Estimated code review effort: 3 (Moderate) | ~25 minutes

Sequence Diagram(s)

sequenceDiagram
  participant Config
  participant Schema
  participant TokenChunker
  participant MergeLogic
  Config->>Schema: Parse and normalize overlapped_percent
  Schema->>TokenChunker: Store normalized OverlappedPercent
  TokenChunker->>MergeLogic: Pass normalized overlap value
  MergeLogic->>MergeLogic: Clamp and calculate threshold and cut
Loading

Possibly related PRs

Suggested reviewers: yingfeng, jinhai-cn, yuzhichang

Poem

I’m a bunny parsing bullets bright,
With overlap trimmed just right.
Newlines part with careful grace,
Headings hop into their place.
Context arrives where tests can see.

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly summarizes the two main Chunker changes and is concise.
Description check ✅ Passed The description includes a summary, background context, the two diffs, tests, and verification details.
Docstring Coverage ✅ Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%.
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 Jul 27, 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.

Actionable comments posted: 3

🤖 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 `@internal/ingestion/component/chunker/title.go`:
- Around line 350-363: Update the bullet assignment loop around bulletsCategory
and the notBullet check to compute the trimmed record text once and pass that
same trimmed value to both pat.MatchString and notBullet. Preserve the existing
matching and level assignment behavior while ensuring exclusions use the
normalized text.
- Around line 367-371: Hoist the `(?i)(title|head)` regular expression used by
the layout-title fallback out of the per-record loop, defining it once at
package scope alongside `bulletPatterns` and `notBulletPatterns` (or once before
the loop), then reuse it in the `rec.layout` check instead of calling
`regexp.MustCompile` for every record.

In `@internal/ingestion/component/chunker/token.go`:
- Line 93: Update tokenChunkerParam.Update so OverlappedPercent is only assigned
when the configuration contains a valid overlapped_percent value; otherwise
preserve the existing value, matching the merge-preserving behavior of the other
fields and the normalization performed by normalizeOverlappedPercent.
🪄 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 Plus

Run ID: a39101f0-14ed-467e-b357-50cb9d3ec1f6

📥 Commits

Reviewing files that changed from the base of the PR and between 53afc32 and 261e1fd.

📒 Files selected for processing (8)
  • internal/ingestion/component/chunker/common.go
  • internal/ingestion/component/chunker/title.go
  • internal/ingestion/component/chunker/title_test.go
  • internal/ingestion/component/chunker/token.go
  • internal/ingestion/component/chunker/token_batch1_test.go
  • internal/ingestion/component/chunker/token_test.go
  • internal/ingestion/component/schema/chunker.go
  • internal/ingestion/task/real_consumer_test.go

@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: 1

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
internal/ingestion/component/schema/chunker.go (1)

317-318: 🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

Reject NaN in direct TokenChunkerParam validation.

NaN is neither < 0 nor > 90, so direct construction can pass validation with a non-normalized overlap value, while NormalizeOverlappedPercent treats NaN as 0. Add math.IsNaN(p.OverlappedPercent) to this range check.

🤖 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/schema/chunker.go` around lines 317 - 318,
Update the direct validation for TokenChunkerParam.OverlappedPercent to also
reject NaN by incorporating math.IsNaN into the existing range check, while
preserving the current invalid-value error behavior for values below 0 or above
90.

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.

Inline comments:
In `@internal/ingestion/component/schema/chunker.go`:
- Around line 282-293: Update clampOverlappedPercent so values above the maximum
are clamped to 90 before converting to int, preventing out-of-range float-to-int
conversion for huge inputs such as 1e300. Preserve the existing percentage
normalization and lower-bound behavior, then truncate only after the value is
within the bounded range.

---

Outside diff comments:
In `@internal/ingestion/component/schema/chunker.go`:
- Around line 317-318: Update the direct validation for
TokenChunkerParam.OverlappedPercent to also reject NaN by incorporating
math.IsNaN into the existing range check, while preserving the current
invalid-value error behavior for values below 0 or above 90.
🪄 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 Plus

Run ID: 164f2785-52a4-4db2-8371-837ef0c16515

📥 Commits

Reviewing files that changed from the base of the PR and between 261e1fd and 8550b19.

📒 Files selected for processing (5)
  • internal/ingestion/component/chunker/common.go
  • internal/ingestion/component/chunker/title.go
  • internal/ingestion/component/chunker/token.go
  • internal/ingestion/component/chunker/token_test.go
  • internal/ingestion/component/schema/chunker.go
💤 Files with no reviewable changes (1)
  • internal/ingestion/component/chunker/common.go
🚧 Files skipped from review as they are similar to previous changes (3)
  • internal/ingestion/component/chunker/title.go
  • internal/ingestion/component/chunker/token_test.go
  • internal/ingestion/component/chunker/token.go

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

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
internal/ingestion/component/chunker/token.go (1)

78-105: 🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

OverlappedPercent still unconditionally overwritten on every Update call, unlike other fields.

Every other field in Update is only set when the config key is present/valid (merge-preserving), but OverlappedPercent is always reassigned via schema.NormalizeOverlappedPercent(conf["overlapped_percent"]). Since NormalizeOverlappedPercent(nil) returns 0, a partial config update that omits overlapped_percent silently resets a previously-configured overlap back to 0. This mirrors the issue already raised on the prior commit and remains unfixed.

🐛 Proposed fix
-	p.TokenChunkerParam.OverlappedPercent = schema.NormalizeOverlappedPercent(conf["overlapped_percent"])
+	if _, present := conf["overlapped_percent"]; present {
+		p.TokenChunkerParam.OverlappedPercent = schema.NormalizeOverlappedPercent(conf["overlapped_percent"])
+	}
🤖 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.go` around lines 78 - 105, Update
tokenChunkerParam.Update so OverlappedPercent is changed only when the
overlapped_percent configuration value is present and valid, preserving the
existing value for partial updates that omit it. Reuse
schema.NormalizeOverlappedPercent within that conditional while leaving the
other field-update behavior unchanged.
♻️ Duplicate comments (1)
internal/ingestion/component/schema/chunker.go (1)

279-294: 🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

Huge overlap values still bypass clamping before float→int conversion.

clampOverlappedPercent truncates via float64(int(value)) before clamping to [0, 90]. For a value like 1e300 (or math.MaxFloat64), int(value) is out of int's range and its result is implementation-defined per the Go spec, so it can convert to an arbitrary (even negative) value and get normalized to 0 instead of the intended 90. This exact class of bug has bitten golang.org/x/time/rate in production. Clamp to [0, 90] first, then truncate.

🐛 Proposed fix
 func clampOverlappedPercent(value float64) float64 {
 	if 0 < value && value < 1 {
 		value *= 100
 	}
-	value = float64(int(value))
 	if value < 0 {
 		value = 0
 	}
 	if value > 90 {
 		value = 90
 	}
-	return value
+	return math.Trunc(value)
 }
🤖 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/schema/chunker.go` around lines 279 - 294,
Update clampOverlappedPercent so values are clamped to the [0,90] range before
converting to int and truncating. Preserve the existing fraction-to-percent
conversion and ensure huge positive inputs such as math.MaxFloat64 normalize to
90 rather than undergoing an out-of-range float-to-int conversion.
🤖 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.

Outside diff comments:
In `@internal/ingestion/component/chunker/token.go`:
- Around line 78-105: Update tokenChunkerParam.Update so OverlappedPercent is
changed only when the overlapped_percent configuration value is present and
valid, preserving the existing value for partial updates that omit it. Reuse
schema.NormalizeOverlappedPercent within that conditional while leaving the
other field-update behavior unchanged.

---

Duplicate comments:
In `@internal/ingestion/component/schema/chunker.go`:
- Around line 279-294: Update clampOverlappedPercent so values are clamped to
the [0,90] range before converting to int and truncating. Preserve the existing
fraction-to-percent conversion and ensure huge positive inputs such as
math.MaxFloat64 normalize to 90 rather than undergoing an out-of-range
float-to-int conversion.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 95f26c95-7486-444a-a836-89aa2acbb8a8

📥 Commits

Reviewing files that changed from the base of the PR and between 8550b19 and 9f49de7.

📒 Files selected for processing (8)
  • internal/ingestion/component/chunker/common.go
  • internal/ingestion/component/chunker/title.go
  • internal/ingestion/component/chunker/title_test.go
  • internal/ingestion/component/chunker/token.go
  • internal/ingestion/component/chunker/token_batch1_test.go
  • internal/ingestion/component/chunker/token_test.go
  • internal/ingestion/component/schema/chunker.go
  • internal/ingestion/task/real_consumer_test.go
💤 Files with no reviewable changes (1)
  • internal/ingestion/component/chunker/common.go
🚧 Files skipped from review as they are similar to previous changes (5)
  • internal/ingestion/component/chunker/token_batch1_test.go
  • internal/ingestion/task/real_consumer_test.go
  • internal/ingestion/component/chunker/title.go
  • internal/ingestion/component/chunker/title_test.go
  • internal/ingestion/component/chunker/token_test.go

@xugangqiang

Copy link
Copy Markdown
Contributor Author

@yingfeng @JinHai-CN @yuzhichang pls help to review

- token.go Update: guard overlapped_percent behind key presence so a partial config update preserves the previously configured value instead of resetting it to 0 (finding #3).

- schema clampOverlappedPercent: clamp to [0,90] BEFORE the float->int truncation so huge inputs (e.g. 1e300, math.MaxFloat64) normalize to 90, matching Python's normalize_overlapped_percent, instead of 0 (finding #4).

- Tests: add overflow cases to TestNormalizeOverlappedPercent and a new TestTokenChunkerParam_UpdatePreservesOverlappedPercent regression test.

Refs infiniflow#17396
@xugangqiang

Copy link
Copy Markdown
Contributor Author

@yingfeng @JinHai-CN @yuzhichang Pls help to review

// rag/nlp/__init__.py:1156.
func mergeByTokenSizeFromJSON(perItem [][]schema.ChunkDoc, chunkTokens int, overlappedPct float64) [][]schema.ChunkDoc {
threshold := float64(chunkTokens) * (100 - overlappedPct*100) / 100.0
threshold := float64(chunkTokens) * (100 - overlappedPct) / 100.0

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Can we assert overlappedPct in range [0, 100]?

…zhichang, infiniflow#17396)

mergeByTokenSizeFromJSON (and the mergeByTokenSize method) use (100 - overlappedPct) as a percentage; out-of-range values produce a negative/inverted threshold and silently corrupt chunk boundaries. Clamp to [0,100] at function entry so the merge math is always valid. c.param.OverlappedPercent is already [0,90] via Update/Validate, so this is a defensive no-op in normal operation.

Add TestMergeByTokenSizeFromJSON_ClampsOverlappedPct covering the 150/-5/1e300/-1e300 boundaries.

Refs infiniflow#17396

@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: 1

🤖 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 `@internal/ingestion/component/chunker/token_batch1_test.go`:
- Around line 84-117: Update TestMergeByTokenSizeFromJSON_ClampsOverlappedPct to
provide a fresh deep-copied fixture for every mergeByTokenSizeFromJSON
invocation, preferably via a local fixture factory. Ensure each at100, at150,
atHuge, at0, atNeg, and atNegHuge call receives the original unmutated items.
🪄 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 Plus

Run ID: 9b9b4523-24f5-4ac2-82c2-3500b77d709a

📥 Commits

Reviewing files that changed from the base of the PR and between 8ca25d7 and 7d2f93f.

📒 Files selected for processing (2)
  • internal/ingestion/component/chunker/token.go
  • internal/ingestion/component/chunker/token_batch1_test.go
🚧 Files skipped from review as they are similar to previous changes (1)
  • internal/ingestion/component/chunker/token.go

Comment on lines +84 to +117
func TestMergeByTokenSizeFromJSON_ClampsOverlappedPct(t *testing.T) {
items := [][]schema.ChunkDoc{
{
{Text: strings.Repeat("word ", 20), DocType: "text", CKType: "text", TKNums: intPtr(100)},
{Text: "body", DocType: "text", CKType: "text", TKNums: intPtr(5)},
},
}

at100 := mergeByTokenSizeFromJSON(items, 128, 100)
if at100 == nil || len(at100) == 0 {
t.Fatalf("overlappedPct=100: nil/empty result")
}
at150 := mergeByTokenSizeFromJSON(items, 128, 150)
atHuge := mergeByTokenSizeFromJSON(items, 128, 1e300)
if !reflect.DeepEqual(at100, at150) {
t.Errorf("overlappedPct=150 should clamp to 100; output differs from 100")
}
if !reflect.DeepEqual(at100, atHuge) {
t.Errorf("overlappedPct=1e300 should clamp to 100; output differs from 100")
}

at0 := mergeByTokenSizeFromJSON(items, 128, 0)
if at0 == nil || len(at0) == 0 {
t.Fatalf("overlappedPct=0: nil/empty result")
}
atNeg := mergeByTokenSizeFromJSON(items, 128, -5)
atNegHuge := mergeByTokenSizeFromJSON(items, 128, -1e300)
if !reflect.DeepEqual(at0, atNeg) {
t.Errorf("overlappedPct=-5 should clamp to 0; output differs from 0")
}
if !reflect.DeepEqual(at0, atNegHuge) {
t.Errorf("overlappedPct=-1e300 should clamp to 0; output differs from 0")
}
}

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.

🎯 Functional Correctness | 🔴 Critical | ⚡ Quick win

Use a fresh fixture for every merge invocation.

mergeByTokenSizeFromJSON mutates perItem in place. After Line 92, items no longer contains the original input, so later calls reprocess already-merged chunks; with 100% overlap this can duplicate prefixes and make the test fail or hide regressions. Use a fixture factory or deep copy for each call. The mutation is in internal/ingestion/component/chunker/token.go.

Proposed fix
-	items := [][]schema.ChunkDoc{
-		{
-			{Text: strings.Repeat("word ", 20), DocType: "text", CKType: "text", TKNums: intPtr(100)},
-			{Text: "body", DocType: "text", CKType: "text", TKNums: intPtr(5)},
-		},
+	newItems := func() [][]schema.ChunkDoc {
+		return [][]schema.ChunkDoc{
+			{
+				{Text: strings.Repeat("word ", 20), DocType: "text", CKType: "text", TKNums: intPtr(100)},
+				{Text: "body", DocType: "text", CKType: "text", TKNums: intPtr(5)},
+			},
+		}
 	}

-	at100 := mergeByTokenSizeFromJSON(items, 128, 100)
+	at100 := mergeByTokenSizeFromJSON(newItems(), 128, 100)
-	at150 := mergeByTokenSizeFromJSON(items, 128, 150)
-	atHuge := mergeByTokenSizeFromJSON(items, 128, 1e300)
+	at150 := mergeByTokenSizeFromJSON(newItems(), 128, 150)
+	atHuge := mergeByTokenSizeFromJSON(newItems(), 128, 1e300)
-	at0 := mergeByTokenSizeFromJSON(items, 128, 0)
+	at0 := mergeByTokenSizeFromJSON(newItems(), 128, 0)
-	atNeg := mergeByTokenSizeFromJSON(items, 128, -5)
-	atNegHuge := mergeByTokenSizeFromJSON(items, 128, -1e300)
+	atNeg := mergeByTokenSizeFromJSON(newItems(), 128, -5)
+	atNegHuge := mergeByTokenSizeFromJSON(newItems(), 128, -1e300)
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
func TestMergeByTokenSizeFromJSON_ClampsOverlappedPct(t *testing.T) {
items := [][]schema.ChunkDoc{
{
{Text: strings.Repeat("word ", 20), DocType: "text", CKType: "text", TKNums: intPtr(100)},
{Text: "body", DocType: "text", CKType: "text", TKNums: intPtr(5)},
},
}
at100 := mergeByTokenSizeFromJSON(items, 128, 100)
if at100 == nil || len(at100) == 0 {
t.Fatalf("overlappedPct=100: nil/empty result")
}
at150 := mergeByTokenSizeFromJSON(items, 128, 150)
atHuge := mergeByTokenSizeFromJSON(items, 128, 1e300)
if !reflect.DeepEqual(at100, at150) {
t.Errorf("overlappedPct=150 should clamp to 100; output differs from 100")
}
if !reflect.DeepEqual(at100, atHuge) {
t.Errorf("overlappedPct=1e300 should clamp to 100; output differs from 100")
}
at0 := mergeByTokenSizeFromJSON(items, 128, 0)
if at0 == nil || len(at0) == 0 {
t.Fatalf("overlappedPct=0: nil/empty result")
}
atNeg := mergeByTokenSizeFromJSON(items, 128, -5)
atNegHuge := mergeByTokenSizeFromJSON(items, 128, -1e300)
if !reflect.DeepEqual(at0, atNeg) {
t.Errorf("overlappedPct=-5 should clamp to 0; output differs from 0")
}
if !reflect.DeepEqual(at0, atNegHuge) {
t.Errorf("overlappedPct=-1e300 should clamp to 0; output differs from 0")
}
}
func TestMergeByTokenSizeFromJSON_ClampsOverlappedPct(t *testing.T) {
newItems := func() [][]schema.ChunkDoc {
return [][]schema.ChunkDoc{
{
{Text: strings.Repeat("word ", 20), DocType: "text", CKType: "text", TKNums: intPtr(100)},
{Text: "body", DocType: "text", CKType: "text", TKNums: intPtr(5)},
},
}
}
at100 := mergeByTokenSizeFromJSON(newItems(), 128, 100)
if at100 == nil || len(at100) == 0 {
t.Fatalf("overlappedPct=100: nil/empty result")
}
at150 := mergeByTokenSizeFromJSON(newItems(), 128, 150)
atHuge := mergeByTokenSizeFromJSON(newItems(), 128, 1e300)
if !reflect.DeepEqual(at100, at150) {
t.Errorf("overlappedPct=150 should clamp to 100; output differs from 100")
}
if !reflect.DeepEqual(at100, atHuge) {
t.Errorf("overlappedPct=1e300 should clamp to 100; output differs from 100")
}
at0 := mergeByTokenSizeFromJSON(newItems(), 128, 0)
if at0 == nil || len(at0) == 0 {
t.Fatalf("overlappedPct=0: nil/empty result")
}
atNeg := mergeByTokenSizeFromJSON(newItems(), 128, -5)
atNegHuge := mergeByTokenSizeFromJSON(newItems(), 128, -1e300)
if !reflect.DeepEqual(at0, atNeg) {
t.Errorf("overlappedPct=-5 should clamp to 0; output differs from 0")
}
if !reflect.DeepEqual(at0, atNegHuge) {
t.Errorf("overlappedPct=-1e300 should clamp to 0; output differs from 0")
}
}
🤖 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_batch1_test.go` around lines 84 -
117, Update TestMergeByTokenSizeFromJSON_ClampsOverlappedPct to provide a fresh
deep-copied fixture for every mergeByTokenSizeFromJSON invocation, preferably
via a local fixture factory. Ensure each at100, at150, atHuge, at0, atNeg, and
atNegHuge call receives the original unmutated items.

@yuzhichang
yuzhichang merged commit a6a67c5 into infiniflow:main Jul 27, 2026
3 checks passed
xugangqiang added a commit to xugangqiang/ragflow that referenced this pull request Jul 27, 2026
mergeByTokenSizeFromJSON mutates its perItem argument in place and returns
the same backing array (token.go). Reusing one fixture across the four calls
let later calls reprocess already-merged chunks and silently overwrite the
earlier results via aliasing, so reflect.DeepEqual was vacuously true - the
test passed without actually exercising the clamp (review comment on PR infiniflow#17396).

Build a fresh fixture per call. The first chunk now carries TKNums 130, just
above chunk_token_size 128, so both clamp directions are exercised: at pct=0
(threshold 128) the chunks stay split, while an unclamped negative pct raises
the threshold (e.g. -5 -> 134.4) and merges them - which would otherwise make
the lower-clamp assertions pass even if the clamp were removed (review:
coderabbitai on PR infiniflow#17416).

Verified the test now fails (negative-case assertions at
token_batch1_test.go:128/131; panic at token.go:768 for the upper case) when
the clamp is disabled, confirming it is no longer a false positive.
@xugangqiang

Copy link
Copy Markdown
Contributor Author

While reviewing the overlap normalization in this PR, found a related edge case worth tracking separately: fraction inputs like overlapped_percent = 0.29 are truncated to 28 instead of 29 (caused by int() truncation after the *100 float multiplication). This matches Python exactly, so it's a shared pre-existing behavior, not a regression from this PR.

Filed as #17418 with reproduction table, root cause, impact, and the round-vs-truncate trade-off (rounding would diverge from Python). No code change in this PR for that item.

yuzhichang pushed a commit that referenced this pull request Jul 27, 2026
## Problem
`TestMergeByTokenSizeFromJSON_ClampsOverlappedPct` reused a single
`items` fixture across four calls to `mergeByTokenSizeFromJSON`.

`mergeByTokenSizeFromJSON` mutates its `perItem` argument in place and
returns the same backing array (token.go: `perItem[idx] = merged`). As a
result:
- The 2nd and later calls merged already-merged chunks instead of the
original input.
- Because the returned slice aliases the input, later calls silently
overwrote the earlier results (`at100`, `at0`, ...).
- `reflect.DeepEqual(at100, at150)` was therefore vacuously true — the
test was a **false positive** that never actually exercised the clamp.
It would still pass even if the clamp were broken.

This is exactly the defect flagged in the review comment on PR #17396.

## Fix
Add a `clampOverlapFixture()` factory and build a fresh fixture for
every call, so that 150 / 1e300 / -5 / -1e300 are applied to the
original input.

## Verification
- The test passes after the fix.
- When the clamp logic was temporarily disabled, the test **failed**
(panic at token.go:768 — the negative index produced by an out-of-range
pct), proving the fixed test is no longer a false positive and can catch
a clamp regression.

## Scope
Test file only. No production code change (verified `token.go` is
identical to `upstream/main`).

Refs: review comment on PR #17396.
@xugangqiang
xugangqiang deleted the fix/batch-3-4 branch August 7, 2026 12:27
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ci Continue Integration size:L This PR changes 100-499 lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants