Repository navigation
fix(nlp): drop dead re.I from delimiter finditer calls - #17386
Conversation
|
Note Reviews pausedIt 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 Use the following commands to manage reviews:
Use the checkboxes below for quick actions:
No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info⚙️ Run configurationConfiguration used: Organization UI Review profile: CHILL Plan: Pro Plus Run ID: 📒 Files selected for processing (1)
🚧 Files skipped from review as they are similar to previous changes (1)
📝 WalkthroughWalkthroughDelimiter parsing now preserves letter casing in Python and Go paths. Regression tests cover literal patterns, case-sensitive splitting, chunking behavior, and prevention of case-insensitive flags. ChangesCase-sensitive delimiter parsing
Estimated code review effort: 3 (Moderate) | ~25 minutes Possibly related PRs
Suggested labels: Suggested reviewers: Poem
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✨ Finishing Touches 💡 1🛠️ Fix failing CI checks 💡
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. Comment |
There was a problem hiding this comment.
Actionable comments posted: 2
🤖 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 `@test/unit_test/rag/test_delimiter_case_sensitive.py`:
- Around line 165-195: Update test_no_re_I_on_re_finditer to locate and inspect
the re.finditer call structurally within get_delimiters and parser_txt rather
than using hard-coded line numbers and a ±2-line window. Preserve the assertion
that neither re.I nor re.IGNORECASE is passed at those target calls.
- Around line 59-69: Move the `_pdf_parser` injection out of module-level
collection code and into an autouse pytest fixture using `monkeypatch.setitem`
on `sys.modules`, ensuring the stub replaces any existing parser entry and
pytest restores prior state after each test. Keep `_StubPdfParser` behavior
unchanged and avoid shared mutable mock state across tests.
🪄 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: 606338b6-8483-4564-a3a2-47f2828aed69
📒 Files selected for processing (3)
deepdoc/parser/txt_parser.pyrag/nlp/__init__.pytest/unit_test/rag/test_delimiter_case_sensitive.py
|
@yuzhichang @Lynn-Inf @wangq8 @dcc123456 please review! |
|
@yuzhichang @Lynn-Inf @wangq8 @dcc123456 @JinHai-CN please review! |
|
@skbs-eng We are actively porting from python to golang. Could you implement the go part in this same PR? |
Implement getDelimiters for the Go chunker path and align compileDelimPattern with Python's _compile_delimiter_pattern (join then extract backtick tokens, case-sensitive). Adds regression tests so bare-char and backtick-wrapped delimiters stay case-sensitive (infiniflow#17384 / PR infiniflow#17386). Co-authored-by: kiloconnect[bot] <240665456+kiloconnect[bot]@users.noreply.github.com>
|
@yuzhichang Done — Go parity is in this PR now. Go changes
Validation |
|
@skbs-eng Please format test/unit_test/rag/test_delimiter_case_sensitive.py via ruff. |
There was a problem hiding this comment.
Actionable comments posted: 1
🧹 Nitpick comments (1)
internal/ingestion/component/chunker/common.go (1)
152-166: 🗄️ Data Integrity & Integration | 🔵 Trivial | ⚡ Quick winAvoid concatenating delimiter entries without a separator before backtick extraction.
compileDelimPatternjoins alldelimsentries into onerawstring with no separator, then runsbacktickDelimREagainst the combined string. If one entry ends with an unpaired backtick and the next entry begins with one, concatenation can create a backtick pair that spans two independent entries, or otherwise misparse token boundaries that would be correct if each entry were matched independently. Extract backtick tokens per entry instead of after concatenation, to remove the dependency on entry order and content at the join boundary.The existing regression tests (
delimiter_case_sensitive_test.goLines 93-115) only pass single-element slices, so this path is untested with multiple entries.♻️ Proposed fix: extract per entry instead of after concatenation
func compileDelimPattern(delims []string) *regexp.Regexp { - var b strings.Builder - for _, d := range delims { - if d != "" { - b.WriteString(d) - } - } - raw := b.String() - if raw == "" { - return nil - } - matches := backtickDelimRE.FindAllStringSubmatch(raw, -1) - if len(matches) == 0 { - return nil - } seen := make(map[string]struct{}, len(delims)) - custom := make([]string, 0, len(matches)) - for _, m := range matches { - tok := m[1] - if _, ok := seen[tok]; ok { - continue - } - seen[tok] = struct{}{} - custom = append(custom, regexp.QuoteMeta(tok)) + custom := make([]string, 0, len(delims)) + for _, d := range delims { + for _, m := range backtickDelimRE.FindAllStringSubmatch(d, -1) { + tok := m[1] + if _, ok := seen[tok]; ok { + continue + } + seen[tok] = struct{}{} + custom = append(custom, regexp.QuoteMeta(tok)) + } + } + if len(custom) == 0 { + return nil } sort.SliceStable(custom, func(i, j int) bool { return len(custom[i]) > len(custom[j]) }) return regexp.MustCompile(strings.Join(custom, "|")) }Run the following to confirm how
Delimitersis populated and whether multi-entry slices reachcompileDelimPatternin production:#!/bin/bash # Description: Inspect Delimiters field type/population and call sites of compileDelimPattern. rg -n -C4 'Delimiters\s+\[\]string|Delimiters\s+string' internal/ingestion/component/chunker rg -n -C4 'compileDelimPattern\(' internal/ingestion/component/chunker🤖 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/common.go` around lines 152 - 166, Update compileDelimPattern to run backtickDelimRE independently on each non-empty delimiter entry, accumulating the extracted tokens without concatenating entries first. Preserve the existing nil behavior when no entries or matches are found, and ensure token boundaries cannot span separate delims elements.
🤖 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/common.go`:
- Around line 145-179: Extract the shared token escaping and length-descending
sorting logic used by getDelimiters and compileDelimPattern into a helper such
as escapeAndSort, including an explicit deduplication option to preserve each
caller’s current behavior. Update both functions to use the helper while
retaining their existing case-sensitive matching and output semantics.
---
Nitpick comments:
In `@internal/ingestion/component/chunker/common.go`:
- Around line 152-166: Update compileDelimPattern to run backtickDelimRE
independently on each non-empty delimiter entry, accumulating the extracted
tokens without concatenating entries first. Preserve the existing nil behavior
when no entries or matches are found, and ensure token boundaries cannot span
separate delims elements.
🪄 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: 7fb1ffcf-1a05-4646-ba31-024b634af9a1
📒 Files selected for processing (2)
internal/ingestion/component/chunker/common.gointernal/ingestion/component/chunker/delimiter_case_sensitive_test.go
Codecov Report✅ All modified and coverable lines are covered by tests. Additional details and impacted files@@ Coverage Diff @@
## main #17386 +/- ##
=======================================
Coverage 90.65% 90.65%
=======================================
Files 10 10
Lines 717 717
Branches 118 118
=======================================
Hits 650 650
Misses 39 39
Partials 28 28 ☔ View full report in Codecov by Harness. 🚀 New features to boost your workflow:
|
The `re.finditer` calls at the two outlier delimiter-parsing sites -- `rag.nlp.get_delimiters` (line 1633) and `deepdoc.parser.txt_parser.parser_txt` (line 51) -- passed `re.I` (case-insensitive) as a flag. The flag is dead code today: it doesn't propagate from `re.finditer` to `m.group(1)` or to the downstream `re.split` / `re.match` calls (which all omit `re.I`), so the actual splitting behavior has always been case-sensitive. The flag was inconsistent with the three sibling implementations that already correctly omit it: - `rag.nlp.naive_merge` custom-delimiter path (line 1195) - `rag.nlp.naive_merge_with_images` custom-delimiter path (line 1269) - `rag.nlp._build_cks` (line 1389) This change brings the two outliers in line, removes a misleading flag, and adds regression tests so a future refactor can't silently introduce `re.I` to a downstream `re.split` / `re.match` where it would actually change behavior. Closes infiniflow#17384.
- Move the deepdoc.parser.pdf_parser stub into an autouse fixture using monkeypatch.setitem so it is installed/restored per test instead of leaking across tests via sys.modules.setdefault at collection time. - Replace the fragile +/-2-line window scan with an AST-based structural check that locates get_delimiters / parser_txt, walks every re.finditer(...) call inside them, and asserts that neither re.I nor re.IGNORECASE is passed positionally or via the flags keyword. Co-authored-by: Copilot App <[email protected]>
Implement getDelimiters for the Go chunker path and align compileDelimPattern with Python's _compile_delimiter_pattern (join then extract backtick tokens, case-sensitive). Adds regression tests so bare-char and backtick-wrapped delimiters stay case-sensitive (infiniflow#17384 / PR infiniflow#17386). Co-authored-by: kiloconnect[bot] <240665456+kiloconnect[bot]@users.noreply.github.com>
- Format test_delimiter_case_sensitive.py with ruff (preflight CI). - Extract shared escapeAndSort helper used by getDelimiters and compileDelimPattern. - Scan backtick tokens per delimiter entry so pairs cannot span adjacent slice elements; add multi-entry regression coverage. Co-authored-by: kiloconnect[bot] <240665456+kiloconnect[bot]@users.noreply.github.com>
182aabb to
5eac8be
Compare
…anonical helper (infiniflow#17383) Six sites used to read the same `parser_config.delimiter` field with divergent grammars: * rag.nlp.get_delimiters (PDF/DOCX/HTML/EPUB/JSON/CSV/XLSX/email/book) * rag.nlp.naive_merge (custom-delimiter branch) * rag.nlp.naive_merge_with_images * rag.nlp._build_cks * deepdoc.parser.txt_parser.parser_txt (.txt, code) * deepdoc.parser.markdown_parser.MarkdownElementExtractor.get_delimiters The six implementations disagreed on bare-vs-wrapped chars, dedupe, sort order, CRLF normalization, and `re.I` (infiniflow#17384). The shipped default `\n!?;。;!?` was a no-op for .md because the markdown path only matched backtick-wrapped tokens. This PR lands the consolidation on top of infiniflow#17385 (UX layer) and infiniflow#17386 (re.I removal). Both land independently first; the new branch is a 3-way merge base with the refactor + tests on top. Changes ------- * new: `rag/nlp/delim.py` with `parse_delimiter_field` and `compile_delimiter_pattern`. Single source of truth. CRLF normalization at the top; longest-first stable sort; insertion-ordered dedupe; no `re.I`. * refactor: all six call sites delegate to the helper. - `rag/nlp/__init__.py::get_delimiters` becomes a thin shim. - `deepdoc/parser/txt_parser.py::parser_txt` drops the encode/decode/unicode_escape round-trip on the delimiter. - `deepdoc/parser/markdown_parser.py` `get_delimiters` honors bare chars (fixes bug infiniflow#1: markdown default is no longer a no-op). * tests: `test/unit_test/rag/test_delim.py` (85 tests) covers the helper directly, the acceptance table from the issue, frontend parity with `web/src/utils/delimiter-preview.ts`, and a static guard that no site re-inlines the backtick regex. * tests: `test/unit_test/rag/test_delimiter_case_sensitive.py` (from infiniflow#17386) updated to point the static check at the new helper location and broadened with an AST-based scan. Acceptance criteria ------------------- * All six sites produce the same regex pattern for the same input. * Shipped default keeps working for .txt/.pdf/.docx. * Shipped default for .md now splits (was a silent no-op). * Tooltip example `\n`##`;` produces three effective delimiters regardless of file type. * Bare whitespace inputs (" ", "\t", "\n") split on every occurrence. * Backtick-wrapped whitespace (`` `\n\n` ``) splits only on the exact N-char sequence. * CRLF-line-ending documents split identically to LF-line-ending documents, regardless of file type. * New unit tests in test_delim.py cover every row of the issue's Proposed-solution table. * Existing tests in test_naive_merge.py still pass.
…anonical helper (#17383) (#17387) ## Summary Six sites used to read the same `parser_config.delimiter` field with divergent grammars: - `rag.nlp.get_delimiters` (PDF/DOCX/HTML/EPUB/JSON/CSV/XLSX/email/book) - `rag.nlp.naive_merge` (custom-delimiter branch) - `rag.nlp.naive_merge_with_images` - `rag.nlp._build_cks` - `deepdoc.parser.txt_parser.parser_txt` (.txt, code) - `deepdoc.parser.markdown_parser.MarkdownElementExtractor.get_delimiters` The six implementations disagreed on bare-vs-wrapped chars, dedupe, sort order, CRLF normalization, and `re.I` (#17384). The shipped default `` `\n!?;。;!?` `` was a no-op for `.md` because the markdown path only matched backtick-wrapped tokens. ## Changes - **new:** `rag/nlp/delim.py` with `parse_delimiter_field` and `compile_delimiter_pattern`. Single source of truth. CRLF normalization at the top; longest-first stable sort; insertion-ordered dedupe; no `re.I`. - **refactor:** all six call sites delegate to the helper. - `rag/nlp/__init__.py::get_delimiters` becomes a thin shim. - `deepdoc/parser/txt_parser.py::parser_txt` drops the `[encode/decode/unicode_escape]` round-trip. - `deepdoc/parser/markdown_parser.py::get_delimiters` honors bare chars (fixes [1]). - **tests:** `test/unit_test/rag/test_delim.py` (85 tests) — helper, acceptance table, frontend parity, static guard against re-inlining. - **tests:** `test/unit_test/rag/test_delimiter_case_sensitive.py` (from #17386) updated to retarget the static check at the new helper + AST-based broader scan. ## Acceptance criteria - All six sites produce the same regex pattern for the same input. - Shipped default keeps working for `.txt` / `.pdf` / `.docx`. - Shipped default for `.md` now splits (was a silent no-op). - Tooltip example `` `\n##;` `` produces three effective delimiters regardless of file type. - Bare whitespace inputs split on every occurrence. - Backtick-wrapped whitespace splits only on the exact N-char sequence. - CRLF-line-ending documents split identically to LF-line-ending documents. - 123 tests pass (85 new + 38 existing). ## Rebase protocol As #17385 and #17386 evolve, this branch will be rebased on top. The only overlap between this PR's diff and the other two is `test_delimiter_case_sensitive.py`, where #17383 modifies the static check to point at the new helper location. --------- Co-authored-by: kiloconnect[bot] <240665456+kiloconnect[bot]@users.noreply.github.com>
Closes #17384.
Summary
Drops a dead
re.Iflag from two outlier delimiter-parsing sites and adds regression tests so the inconsistency can't creep back.What's wrong
Two of the six delimiter-parsing implementations pass
re.Itore.finditer:rag/nlp/__init__.py::get_delimiters(line 1633)deepdoc/parser/txt_parser.py::parser_txt(line 51)The other four implementations correctly omit
re.I:rag/nlp/__init__.py::naive_mergecustom-delimiter path (line 1195)rag/nlp/__init__.py::naive_merge_with_imagescustom-delimiter path (line 1269)rag/nlp/__init__.py::_build_cks(line 1389)rag/flow/chunker/token_chunker.py(line 73)Why this matters (and why it doesn't break anything)
The flag is dead code today. Verified empirically with a Python REPL:
re.Idoes not propagate fromre.finditertom.group(1)or to downstreamre.split/re.matchcalls (which all omitre.I). So the actual splitting behavior has always been case-sensitive — removing the flag is a defensive cleanup, not a behavioral fix.So why bother?
rag/nlp/__init__.pyalready omitre.I, which strongly suggests the flag was accidental.re.splitcall where it would change behavior. The tests added here pin the case-sensitive semantics so that regression fails loudly.re.finditer(..., re.I)reasonably assumes case-insensitive matching, then has to trace all downstream calls to discover it's a no-op.Changes
rag/nlp/__init__.py— dropre.Ifromget_delimiters(line 1633).deepdoc/parser/txt_parser.py— dropre.Ifromparser_txt(line 51).test/unit_test/rag/test_delimiter_case_sensitive.py— new test file with:get_delimiters(pattern output +re.splitround-trip).naive_merge(bare-char + backtick-wrapped, both cases).re.I/re.IGNORECASEis not present at either of the twore.finditersites.Testing
All tests pass on the patched code. Before the patch, the 2 static checks fail with a clear assertion message (the 7 behavioral tests pass either way, confirming
re.Iwas dead code).Related
re.I(case-insensitive), causing unintended splits on both cases of the same character #17384 — the issue this PR closes. Note the issue's reproduction code (re.split(..., flags=re.I)) doesn't actually match what the production code does — the productionre.splitcalls all omitre.I, which is why current behavior is already case-sensitive. The fix here is still valuable as a defensive cleanup + test coverage, but it's not a behavioral fix per se.parser_config.delimiterfield #17383 — broader parser consolidation (six implementations → one). The fix here is independent and small enough to land first.web/src/**vsrag/nlp/**+deepdoc/parser/**), so no interaction.