Skip to content

Validate float chunk_overlap in TokenChunker, not just int - #633

Open
santhreal wants to merge 2 commits into
feyninc:mainfrom
santhreal:fix/token-chunker-float-overlap-validation
Open

Validate float chunk_overlap in TokenChunker, not just int#633
santhreal wants to merge 2 commits into
feyninc:mainfrom
santhreal:fix/token-chunker-float-overlap-validation

Conversation

@santhreal

@santhreal santhreal commented Jul 16, 2026

Copy link
Copy Markdown

chunk_overlap accepts an int or a float (a fraction of chunk_size), but only the int case was checked against chunk_size. A float that resolves to int(chunk_overlap * chunk_size) >= chunk_size slipped through and made the stride chunk_size - chunk_overlap zero or negative:

  • chunk_overlap=1.0 (with chunk_size=10) crashed chunk() with ValueError: range() arg 3 must not be zero;
  • chunk_overlap=1.5 produced a negative stride and chunk() silently returned zero chunks, dropping the entire input.

Now the resolved chunk_overlap is validated after the int/float conversion, so both paths share the same less than chunk_size invariant (a negative overlap is rejected too). Added regression tests covering the int and float cases and a valid fractional overlap.

Summary by CodeRabbit

  • Bug Fixes

    • Improved validation for token chunk overlap, including stricter handling of fractional values.
    • Added checks to reject negative overlaps.
    • Ensured overlap always results in a positive, non-zero chunk stride.
  • Tests

    • Added rejection tests for overlaps equal to or exceeding the chunk size.
    • Added coverage confirming valid fractional overlaps produce multiple chunks that span the full input.

chunk_overlap accepts an int or a float (a fraction of chunk_size). Only the
int case was checked against chunk_size, so a float that resolves to
int(chunk_overlap * chunk_size) >= chunk_size slipped through. That made the
stride chunk_size - chunk_overlap zero or negative: chunk_overlap=1.0 crashed
chunk() with 'range() arg 3 must not be zero', and chunk_overlap=1.5 silently
returned zero chunks, dropping the entire input.

Validate the resolved chunk_overlap after the int/float conversion so both
paths are held to the same 'less than chunk_size' invariant, and reject a
negative overlap as well.
@coderabbitai

coderabbitai Bot commented Jul 16, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 62beb637-41ed-4564-9e79-5e60988f359a

📥 Commits

Reviewing files that changed from the base of the PR and between 3653417 and c5e05db.

📒 Files selected for processing (2)
  • src/chonkie/chunker/token.py
  • tests/chunkers/test_token_chunker.py
🚧 Files skipped from review as they are similar to previous changes (2)
  • src/chonkie/chunker/token.py
  • tests/chunkers/test_token_chunker.py

📝 Walkthrough

Walkthrough

TokenChunker validates raw and resolved overlap values, rejecting negative or non-stride-producing overlaps. Tests cover invalid integer and fractional overlaps, negative inputs, and valid fractional chunk coverage.

Changes

Token overlap validation

Layer / File(s) Summary
Resolved overlap guard and coverage tests
src/chonkie/chunker/token.py, tests/chunkers/test_token_chunker.py
Validation checks negative inputs and resolved overlap against chunk_size; tests cover invalid boundaries, negative values, and successful fractional-overlap chunking.

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

Suggested reviewers: chonk-lain

Poem

A rabbit checks each token’s stride,
No overlap may turn the tide.
Fractions bloom to chunks just right,
Bad bounds hop away from sight.
The input’s covered, from left to end.

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly matches the main change: validating float chunk_overlap values in TokenChunker.
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.
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

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.

@coderabbitai
coderabbitai Bot requested a review from chonk-lain July 16, 2026 07:16

@gemini-code-assist gemini-code-assist 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.

Code Review

This pull request improves the validation of the chunk_overlap parameter in TokenChunker by ensuring that resolved float overlaps are held to the same invariants as integer overlaps, preventing zero or negative strides. It also adds several unit tests to verify these constraints. The review feedback highlights a potential issue where small negative float overlaps (e.g., -0.05) could bypass the non-negative check due to integer truncation, and suggests validating the input chunk_overlap before resolution. Additionally, it recommends adding test cases to verify that negative overlaps are correctly rejected.

Important

The consumer version of Gemini Code Assist on GitHub is being sunset. Starting June 18, 2026, new organization installations will be blocked, and all code review activity will officially cease on July 17, 2026.
For more details on the timeline and next steps, please review the Help Documentation.

Comment thread src/chonkie/chunker/token.py Outdated
Comment on lines +61 to +64
if self.chunk_overlap < 0:
raise ValueError("chunk_overlap must be non-negative")
if self.chunk_overlap >= chunk_size:
raise ValueError("chunk_overlap must be less than chunk_size")

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.

medium

Checking self.chunk_overlap < 0 after resolving it to an integer can lead to inconsistent behavior for small negative float values due to truncation. For example, if chunk_overlap = -0.05 and chunk_size = 10, int(-0.05 * 10) resolves to 0, which silently bypasses the non-negative check. However, if chunk_size = 100, int(-0.05 * 100) resolves to -5, which correctly raises a ValueError.

To ensure consistent validation regardless of the chunk_size, we should validate that the input chunk_overlap is non-negative before resolving it.

Suggested change
if self.chunk_overlap < 0:
raise ValueError("chunk_overlap must be non-negative")
if self.chunk_overlap >= chunk_size:
raise ValueError("chunk_overlap must be less than chunk_size")
if chunk_overlap < 0:
raise ValueError("chunk_overlap must be non-negative")
if self.chunk_overlap >= chunk_size:
raise ValueError("chunk_overlap must be less than chunk_size")

assert "".join(dict.fromkeys([c.text[0] for c in chunks])) == "x"
# Every original character is covered by the first chunk's start through the last chunk's end.
assert chunks[0].start_index == 0
assert chunks[-1].end_index == len(text)

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.

medium

It would be beneficial to add test cases to verify that negative values for chunk_overlap (both integer and float) are correctly rejected by the chunker.

Suggested change
assert chunks[-1].end_index == len(text)
assert chunks[-1].end_index == len(text)
def test_token_chunker_rejects_negative_overlap() -> None:
"""Negative chunk_overlap values must be rejected."""
with pytest.raises(ValueError, match="chunk_overlap must be non-negative"):
TokenChunker(tokenizer="character", chunk_size=10, chunk_overlap=-1)
with pytest.raises(ValueError, match="chunk_overlap must be non-negative"):
TokenChunker(tokenizer="character", chunk_size=10, chunk_overlap=-0.1)

Small negative floats truncated to 0 via int() and bypassed the post-resolution check.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant