Skip to content

refactor(nlp): collapse 6 delimiter-parser implementations into one canonical helper (#17383) - #17387

Merged
yuzhichang merged 9 commits into
infiniflow:mainfrom
skbs-eng:fix/delimiter-parser-consolidation
Aug 2, 2026
Merged

yuzhichang merged 9 commits into
infiniflow:mainfrom
skbs-eng:fix/delimiter-parser-consolidation

Conversation

@skbs-eng

@skbs-eng skbs-eng commented Jul 25, 2026 •

Copy link
Copy Markdown
Contributor

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 fix(nlp): drop dead re.I from delimiter finditer calls #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.

@coderabbitai

coderabbitai Bot commented Jul 25, 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 PR adds canonical delimiter parsing in Python and Go. It aligns backend splitting with frontend preview parsing, normalizes line endings, preserves case sensitivity, and adds tests for parsing, merging, delegation, and parity.

Changes

Delimiter Consolidation

Layer / File(s) Summary
Canonical delimiter parser
rag/nlp/delim.py, internal/parser/chunk/delim.go
The new helpers normalize line endings, parse wrapped and bare delimiters, remove duplicates, sort longest-first, detect wrapped tokens, and compile escaped patterns.
Backend delimiter integration
deepdoc/parser/*.py, rag/nlp/__init__.py, internal/ingestion/component/chunker/*.go
Markdown, text, merge, image-aware merge, DOCX, and Go chunker paths use the shared delimiter helpers.
Frontend delimiter preview
web/src/utils/delimiter-preview.ts
The new preview utility parses delimiters, preserves raw values, and renders whitespace with visible glyphs.
Delimiter behavior validation
test/unit_test/rag/*, internal/parser/chunk/delim_test.go, web/src/utils/__tests__/*
Tests cover parsing, compilation, ordering, case sensitivity, merge behavior, delegation, frontend/backend parity, and import fixtures.

Estimated code review effort: 4 (Complex) | ~60 minutes

Sequence Diagram(s)

sequenceDiagram
  participant Parser
  participant DelimiterHelpers
  participant Chunker
  Parser->>DelimiterHelpers: normalize and parse delimiters
  DelimiterHelpers-->>Parser: ordered delimiter list
  Parser->>DelimiterHelpers: compile delimiter pattern
  DelimiterHelpers-->>Parser: escaped regex pattern
  Parser->>Chunker: split normalized text
  Chunker-->>Parser: delimiter-separated sections
Loading

Possibly related issues

Possibly related PRs

Suggested reviewers: yuzhichang, dcc123456

Poem

A rabbit parses tokens in a row,
Normalizes newlines as they flow.
Wrapped or bare, each mark is clear,
Python and Go now match ear to ear.
Chunks split cleanly. Hop! 🐇

🚥 Pre-merge checks | ✅ 2 | ❌ 3

❌ Failed checks (2 warnings, 1 inconclusive)

Check name Status Explanation Resolution
Out of Scope Changes check ⚠️ Warning The linked issue title concerns DAO implementation, while the pull request changes delimiter parsing and related tests. Link the correct delimiter-related issue or update issue #1 to include the delimiter-parser refactor scope.
Docstring Coverage ⚠️ Warning Docstring coverage is 31.08% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
Linked Issues check ❓ Inconclusive Linked issue #1 only states “feat: impl dao” and provides no requirements that can validate this delimiter-parser refactor. Link the correct delimiter-related issue or add coding requirements and acceptance criteria to issue #1.
✅ Passed checks (2 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly and concisely describes consolidating six delimiter-parser implementations into one canonical helper.
Description check ✅ Passed The description includes a clear summary, background, detailed changes, tests, acceptance criteria, and dependency context.

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.

@skbs-eng
skbs-eng marked this pull request as ready for review July 31, 2026 09:09
@dosubot dosubot Bot added size:L This PR changes 100-499 lines, ignoring generated files. ☯️ refactor Pull request that refactor/refine code 🌈 python Pull requests that update Python code 🧪 test Pull requests that update test cases. 🧰 typescript Pull requests that update Typescript code labels Jul 31, 2026
@skbs-eng

Copy link
Copy Markdown
Contributor Author

@yuzhichang @Lynn-Inf @wangq8 @dcc123456 @JinHai-CN please review!

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

🧹 Nitpick comments (1)
rag/nlp/delim.py (1)

84-129: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Add debug logging for the canonical parsing flow.

This new parsing flow has no diagnostic output. Log the normalized delimiter count and delimiter lengths after parsing. Do not log raw delimiter values.

Proposed change
+import logging
+
 def parse_delimiter_field(s: str) -> list[str]:
 ...
-    return sorted(delimiters, key=len, reverse=True)
+    result = sorted(delimiters, key=len, reverse=True)
+    logging.debug(
+        "parse_delimiter_field: parsed %d delimiters with lengths %s",
+        len(result),
+        [len(delimiter) for delimiter in result],
+    )
+    return result
🤖 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 `@rag/nlp/delim.py` around lines 84 - 129, Add debug logging in
parse_delimiter_field after delimiter parsing and before returning the sorted
result, recording the normalized delimiter count and each delimiter’s length
without including raw delimiter values. Preserve the existing deduplication and
longest-first sorting behavior.

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 `@deepdoc/parser/markdown_parser.py`:
- Around line 162-168: Normalize source text line endings from CRLF and
standalone CR to LF before applying compiled delimiter patterns: update
markdown_parser.py lines 162-168 before constructing self.lines or calling
_extract_delimited_elements, txt_parser.py lines 49-54 before re.split,
rag/nlp/__init__.py lines 1318-1318 for each text_str before image-aware
splitting, and rag/nlp/__init__.py lines 1416-1418 for each text value before
_build_cks applies the pattern. Ensure CRLF input produces the same splits as LF
input at all four sites.

In `@deepdoc/parser/txt_parser.py`:
- Around line 55-57: Update the splitting logic in the parser to use [txt]
directly when the compiled delimiter pattern dels is empty, and only call
re.split when dels is non-empty. Preserve the existing delimiter-matching loop
behavior for non-empty patterns.

In `@rag/nlp/__init__.py`:
- Around line 1212-1216: Separate delimiter presence from the multi-character
bypass decision across the delimiter-processing paths. In rag/nlp/__init__.py
lines 1212-1216, preserve whether the original field contains a wrapped
delimiter before parse_delimiter_field and use it for custom chunk behavior;
apply the same mode decision in naive_merge_with_images at lines 1290-1294. At
lines 1413-1418, add a delimiter-presence signal so _build_cks splits on every
parsed delimiter, including bare one-character values, while keeping chunk-token
bypass logic independent.

In `@test/unit_test/rag/test_delim.py`:
- Around line 44-73: Remove the duplicated deepdoc import-stub setup from this
test module and reuse the shared fixture or helper established for the identical
stub in test_delimiter_case_sensitive.py. Preserve the existing imports and
delimiter test behavior while ensuring rag.nlp can still be imported without the
heavy dependency chain.
- Around line 460-484: Bound the function-body check in
test_site_delegates_to_canonical_helper to only the target function identified
by function_name, rather than scanning source through the end of the file. Use
AST line ranges or the next same-indentation top-level def/class boundary so
forbidden regexes in later functions cannot trigger a false failure or
misattribute the violation.
- Around line 80-89: Rename test_whitespace_only_string_returns_empty_list to
reflect that whitespace-only input returns its whitespace characters as
delimiters, preserving the existing assertions and behavior in
parse_delimiter_field.
- Around line 566-581: Update test_frontend_and_backend_agree_on_delimiter_set
to stop overwriting frontend_set for "\r" and "\r\n"; compare the actual
_frontend_parse output against backend normalization, or adjust the
parser/normalization so both sides produce the same delimiter sets. Preserve
detection of frontend outputs {"\r"} and {"\r", "\n"} rather than coercing them
before the assertion.

In `@test/unit_test/rag/test_delimiter_case_sensitive.py`:
- Around line 170-200: Bound the inspected source to the actual body of the
target function in test_no_re_I_on_re_finditer instead of slicing from fn_start
to end of module. Reuse the AST-based function extent logic from
test_no_re_I_on_backtick_regex_anywhere_in_parser_module, while preserving the
existing finditer and case-insensitive-flag assertions within
parse_delimiter_field.
- Around line 1-81: Remove the duplicated deepdoc.parser.pdf_parser import-stub
setup from this test and reuse the shared stub provided by test_delim.py or the
common test setup. Preserve the _StubPdfParser.remove_tag behavior and ensure
imports of rag.nlp, naive_merge, and get_delimiters still occur only after the
lightweight module stub is installed.

In `@web/src/utils/delimiter-preview.ts`:
- Around line 6-12: Update the delimiter preview parser to normalize CRLF
sequences before parsing, deduplicate delimiters, and sort them longest-first
with stable ordering to match canonical backend semantics. Adjust the
implementation covering the delimiter parsing and rendering flow, and remove the
comment stating that the preview is not a contract or intentionally diverges
from backend behavior.

---

Nitpick comments:
In `@rag/nlp/delim.py`:
- Around line 84-129: Add debug logging in parse_delimiter_field after delimiter
parsing and before returning the sorted result, recording the normalized
delimiter count and each delimiter’s length without including raw delimiter
values. Preserve the existing deduplication and longest-first sorting behavior.
🪄 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: 33d1a1b1-03b5-4e56-ad99-2a758e3a7d1a

📥 Commits

Reviewing files that changed from the base of the PR and between d2a769c and 8334500.

📒 Files selected for processing (11)
  • deepdoc/parser/markdown_parser.py
  • deepdoc/parser/txt_parser.py
  • rag/nlp/__init__.py
  • rag/nlp/delim.py
  • test/unit_test/rag/test_delim.py
  • test/unit_test/rag/test_delimiter_case_sensitive.py
  • web/src/components/children-delimiter-form.tsx
  • web/src/components/delimiter-form-field.tsx
  • web/src/components/delimiter-preview.tsx
  • web/src/locales/en.ts
  • web/src/utils/delimiter-preview.ts

Comment thread deepdoc/parser/markdown_parser.py Resolved
Comment thread deepdoc/parser/txt_parser.py Resolved
Comment thread rag/nlp/__init__.py Resolved
Comment thread test/unit_test/rag/test_delim.py Resolved
Comment thread test/unit_test/rag/test_delim.py Resolved
Comment thread test/unit_test/rag/test_delim.py Resolved
Comment thread test/unit_test/rag/test_delim.py Resolved
Comment thread web/src/utils/delimiter-preview.ts Resolved

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

Caution

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

⚠️ Outside diff range comments (1)
rag/nlp/delim.py (1)

133-137: 🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

Match preserved wrapped delimiters without trimming.

parse_delimiter_field returns wrapped tokens verbatim. The supplied _build_cks consumer in rag/nlp/__init__.py checks re.fullmatch(split_pattern, sub_sec.strip()). For a token with leading or trailing spaces and other non-whitespace characters, this changes the captured delimiter before matching. The delimiter is then appended as content.

Match sub_sec exactly in _build_cks. Trim only normal chunk text.

Suggested consumer fix
-                if re.fullmatch(split_pattern, sub_sec.strip()):
+                if re.fullmatch(split_pattern, sub_sec):

This finding uses the supplied _build_cks downstream context in rag/nlp/__init__.py.

🤖 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 `@rag/nlp/delim.py` around lines 133 - 137, Update the `_build_cks` consumer to
run delimiter matching against the exact `sub_sec` value without calling
`.strip()`, preserving leading and trailing spaces inside wrapped delimiters;
apply trimming only when appending ordinary chunk text. Keep
`parse_delimiter_field`’s verbatim token behavior unchanged.
🧹 Nitpick comments (3)
test/unit_test/rag/test_delim.py (1)

538-599: 🗄️ Data Integrity & Integration | 🔵 Trivial | 🏗️ Heavy lift

Test the actual frontend parser.

_frontend_parse is a Python reimplementation. test_frontend_and_backend_agree_on_delimiter_set compares that model with the backend helper. It does not execute or inspect web/src/utils/delimiter-preview.ts.

A frontend regression can therefore pass this test while the preview behavior differs from backend behavior. Add the same acceptance cases to the frontend test suite, or consume a shared acceptance fixture from both test runners.

🤖 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 `@test/unit_test/rag/test_delim.py` around lines 538 - 599, The
test_frontend_and_backend_agree_on_delimiter_set currently validates only the
Python model _frontend_parse, not the actual frontend parser. Add equivalent
acceptance coverage to the frontend test suite for the existing parameterized
delimiter cases, or establish a shared fixture consumed by both frontend and
backend tests, ensuring web/src/utils/delimiter-preview.ts is directly
exercised.
rag/nlp/delim.py (1)

82-98: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Add debug logging for the new helper flows.

normalize_text_newlines and has_wrapped_delimiter are new parsing flows without diagnostics. Add debug logs when normalization changes input, when a wrapped token is detected, and when pattern compilation processes a non-empty input. Do not log delimiter contents.

As per coding guidelines, **/*.py: Add logging for new flows.

Also applies to: 156-170

🤖 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 `@rag/nlp/delim.py` around lines 82 - 98, Add debug logging to
normalize_text_newlines when the normalized value differs from the input, and to
has_wrapped_delimiter when _BACKTICK_RE detects a wrapped token, without
including delimiter contents. Also log at debug level whenever the relevant
pattern-compilation flow processes non-empty input, using existing logging
conventions and avoiding sensitive pattern contents.

Source: Coding guidelines

deepdoc/parser/txt_parser.py (1)

54-56: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Add an explicit log for delimiter mode.

This change adds a normalization and delimiter-compilation flow, but parser_txt does not record whether delimiter splitting is active. Log the parsed delimiter count and bool(dels). Do not log the document text.

As per coding guidelines, **/*.py: Add logging for new flows.

Proposed fix
-        dels = compile_delimiter_pattern(parse_delimiter_field(delimiter))
+        parsed_dels = parse_delimiter_field(delimiter)
+        dels = compile_delimiter_pattern(parsed_dels)
+        logging.debug(
+            "RAGFlowTxtParser.parser_txt: delimiter_count=%d, splitting=%s",
+            len(parsed_dels),
+            bool(dels),
+        )
🤖 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 `@deepdoc/parser/txt_parser.py` around lines 54 - 56, Add logging in parser_txt
after delimiter parsing/compilation to record the parsed delimiter count and
whether delimiter splitting is active via bool(dels). Do not include the
document text or other document contents in the log, and preserve the existing
normalization and splitting behavior.

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 `@rag/nlp/__init__.py`:
- Around line 1215-1217: Skip empty sub_sec values before delimiter matching in
the custom merge path around rag/nlp/__init__.py lines 1215-1217, and apply the
same guard before appending text_seg and image around lines 1297-1299. Preserve
processing of non-empty segments and delimiter matches.
- Around line 1471-1472: Update the matched-delimiter check in the surrounding
delimiter-parsing logic to pass the captured sub_sec directly to re.fullmatch
instead of stripping it first. Preserve whitespace inside wrapped delimiters so
values such as "` , `" remain valid matches and are removed as delimiters rather
than retained as text.

In `@test/unit_test/rag/conftest.py`:
- Around line 58-78: Add debug logging within _install_pdf_parser_stub for both
outcomes: when deepdoc.parser.pdf_parser already exists and when the stub module
is installed. Use the test module’s existing logging convention, and include
enough context to distinguish retention from installation.
- Around line 58-78: Replace the module-level _install_pdf_parser_stub call with
a yielding pdf_parser_stub fixture that saves and restores the relevant
sys.modules entries, including removing the stub after each test and preserving
any pre-existing modules. Apply this fixture only to the delimiter test modules,
and reset any shared mock or module state per test to prevent cross-test
contamination.

---

Outside diff comments:
In `@rag/nlp/delim.py`:
- Around line 133-137: Update the `_build_cks` consumer to run delimiter
matching against the exact `sub_sec` value without calling `.strip()`,
preserving leading and trailing spaces inside wrapped delimiters; apply trimming
only when appending ordinary chunk text. Keep `parse_delimiter_field`’s verbatim
token behavior unchanged.

---

Nitpick comments:
In `@deepdoc/parser/txt_parser.py`:
- Around line 54-56: Add logging in parser_txt after delimiter
parsing/compilation to record the parsed delimiter count and whether delimiter
splitting is active via bool(dels). Do not include the document text or other
document contents in the log, and preserve the existing normalization and
splitting behavior.

In `@rag/nlp/delim.py`:
- Around line 82-98: Add debug logging to normalize_text_newlines when the
normalized value differs from the input, and to has_wrapped_delimiter when
_BACKTICK_RE detects a wrapped token, without including delimiter contents. Also
log at debug level whenever the relevant pattern-compilation flow processes
non-empty input, using existing logging conventions and avoiding sensitive
pattern contents.

In `@test/unit_test/rag/test_delim.py`:
- Around line 538-599: The test_frontend_and_backend_agree_on_delimiter_set
currently validates only the Python model _frontend_parse, not the actual
frontend parser. Add equivalent acceptance coverage to the frontend test suite
for the existing parameterized delimiter cases, or establish a shared fixture
consumed by both frontend and backend tests, ensuring
web/src/utils/delimiter-preview.ts is directly exercised.
🪄 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: b29eef37-c6fa-490e-8589-73d848d87be8

📥 Commits

Reviewing files that changed from the base of the PR and between 8334500 and 5a2e92b.

📒 Files selected for processing (8)
  • deepdoc/parser/markdown_parser.py
  • deepdoc/parser/txt_parser.py
  • rag/nlp/__init__.py
  • rag/nlp/delim.py
  • test/unit_test/rag/conftest.py
  • test/unit_test/rag/test_delim.py
  • test/unit_test/rag/test_delimiter_case_sensitive.py
  • web/src/utils/delimiter-preview.ts
🚧 Files skipped from review as they are similar to previous changes (2)
  • deepdoc/parser/markdown_parser.py
  • web/src/utils/delimiter-preview.ts

Comment thread rag/nlp/__init__.py Resolved
Comment thread rag/nlp/__init__.py Resolved
Comment thread test/unit_test/rag/conftest.py Resolved
@skbs-eng skbs-eng changed the title [WIP] refactor(nlp): collapse 6 delimiter-parser implementations into one canonical helper (#17383) refactor(nlp): collapse 6 delimiter-parser implementations into one canonical helper (#17383) Jul 31, 2026
@yuzhichang yuzhichang self-assigned this Jul 31, 2026
@yuzhichang
yuzhichang self-requested a review July 31, 2026 11:00

@yuzhichang yuzhichang left a comment

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.

@skbs-eng We are actively porting from python to golang. Could you implement the go part in this same PR?

@yuzhichang yuzhichang removed their assignment Jul 31, 2026
@dosubot dosubot Bot added size:XL This PR changes 500-999 lines, ignoring generated files. and removed size:L This PR changes 100-499 lines, ignoring generated files. labels Jul 31, 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: 1

🧹 Nitpick comments (1)
rag/nlp/__init__.py (1)

1653-1664: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Remove the compatibility-only get_delimiters export.

No in-repo caller uses rag.nlp.get_delimiters; the test import only asserts the helper still produces compile_delimiter_pattern(parse_delimiter_field(...)), and other delimiter parsing is already delegated through lower-level helpers. Drop the shim, the docstring, and its test import/assertions unless an external caller requires this API.

🤖 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 `@rag/nlp/__init__.py` around lines 1653 - 1664, Remove the compatibility-only
get_delimiters wrapper from rag.nlp, including its docstring and implementation.
Update the related tests to remove the import and assertions that exercise
get_delimiters, while preserving coverage of the canonical parse_delimiter_field
and compile_delimiter_pattern helpers.

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/parser/chunk/delim.go`:
- Around line 152-173: Update CompileDelimiterListPattern to retain each
unescaped inner delimiter, sort the originals by utf8.RuneCountInString(inner)
in descending order, then apply regexp.QuoteMeta when building the alternation.
Preserve filtering of empty and invalid backtick delimiters, and join the
escaped patterns only after sorting.

---

Nitpick comments:
In `@rag/nlp/__init__.py`:
- Around line 1653-1664: Remove the compatibility-only get_delimiters wrapper
from rag.nlp, including its docstring and implementation. Update the related
tests to remove the import and assertions that exercise get_delimiters, while
preserving coverage of the canonical parse_delimiter_field and
compile_delimiter_pattern helpers.
🪄 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: c2992297-4152-4787-92ce-f97a52709fdf

📥 Commits

Reviewing files that changed from the base of the PR and between 5a2e92b and 3940436.

📒 Files selected for processing (10)
  • deepdoc/parser/txt_parser.py
  • internal/ingestion/component/chunker/common.go
  • internal/ingestion/component/chunker/token.go
  • internal/parser/chunk/delim.go
  • internal/parser/chunk/delim_test.go
  • rag/nlp/__init__.py
  • test/unit_test/rag/conftest.py
  • test/unit_test/rag/test_delim.py
  • test/unit_test/rag/test_delimiter_case_sensitive.py
  • web/src/utils/__tests__/delimiter-preview.test.ts
🚧 Files skipped from review as they are similar to previous changes (3)
  • test/unit_test/rag/conftest.py
  • test/unit_test/rag/test_delimiter_case_sensitive.py
  • test/unit_test/rag/test_delim.py

Comment thread internal/parser/chunk/delim.go Resolved
skbs-eng and others added 4 commits July 31, 2026 18:45
…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.
Consolidate delimiter parsing logic to ensure consistency between the
canonical backend implementation and the web UI preview.

- Implement `normalize_text_newlines` to handle CRLF/CR to LF conversion
  consistently across `markdown_parser`, `txt_parser`, and `rag.nlp`.
- Update `rag.nlp.delim` with `has_wrapped_delimiter` to correctly
  identify "custom" delimiters (backtick-wrapped) for bypassing
  `chunk_token_num`.
- Refactor `naive_merge` and `naive_merge_with_images` to use the
  canonical `parse_delimiter_field` and `has_wrapped_delimiter` helpers.
- Update `web/src/utils/delimiter-preview.ts` to match backend
  normalization, deduplication, and longest-first sorting semantics.
- Improve test suite by moving `pdf_parser` stubbing to `conftest.py`
  and adding coverage for CRLF normalization and wrapped single-character
  delimiters.

Co-authored-by: kiloconnect[bot] <240665456+kiloconnect[bot]@users.noreply.github.com>
- Skip empty re.split segments in naive_merge custom paths
- Match _build_cks delimiters without stripping whitespace captures
- Scope pdf_parser stub with logging + optional fixture
- Port canonical delimiter parser to internal/parser/chunk (Go)
- Wire TokenChunker list compile through the shared Go helper
- Add frontend Jest coverage for delimiter-preview parity

Co-authored-by: kiloconnect[bot] <240665456+kiloconnect[bot]@users.noreply.github.com>
@skbs-eng
skbs-eng force-pushed the fix/delimiter-parser-consolidation branch from 3940436 to 7d656d2 Compare July 31, 2026 13:24
@skbs-eng

Copy link
Copy Markdown
Contributor Author

Rebased on latest origin/main and addressed review feedback:

  • Go List Pattern Compiler (internal/parser/chunk/delim.go): Updated CompileDelimiterListPattern to sort inner unescaped delimiter tokens by utf8.RuneCountInString prior to applying regexp.QuoteMeta. Added test coverage for multi-byte rune length sorting and escaping order.
  • Removed get_delimiters Shim: Removed unused rag.nlp.get_delimiters wrapper and Go GetDelimiters shim to keep public API surface minimal and free of legacy wrappers.
  • _build_cks Whitespace Delimiter Handling (rag/nlp/__init__.py): Reordered delimiter pattern evaluation in _build_cks to check re.fullmatch(split_pattern, sub_sec) before checking not sub_sec.strip(), ensuring wrapped whitespace delimiters match correctly as delimiters.

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

♻️ Duplicate comments (1)
deepdoc/parser/markdown_parser.py (1)

167-167: 📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick win

Resolve the RUF003 warning in the comment.

Ruff reports ambiguous Unicode punctuation on Line 167. Keep the delimiter example, but use Unicode escapes or code-point names.

Proposed change
-        # (``\n!?;。;!?``) a no-op for the markdown path. The helper
+        # (``\n!?;。\uFF1B\uFF01\uFF1F``) a no-op for the markdown path. The helper
🤖 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 `@deepdoc/parser/markdown_parser.py` at line 167, Update the comment near the
markdown delimiter example to replace the ambiguous Unicode punctuation with
Unicode escape sequences or explicit code-point names, while preserving the
example’s meaning and delimiter set.

Source: Linters/SAST tools

🧹 Nitpick comments (1)
deepdoc/parser/markdown_parser.py (1)

23-24: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Reuse the canonical newline normalizer.

deepdoc/parser/txt_parser.py already uses rag.nlp.delim.normalize_text_newlines, but this file duplicates the replacement chain on Lines 158-160. Import and call the helper here so both parsers keep one CRLF/CR normalization contract.

Proposed change
-from rag.nlp.delim import compile_delimiter_pattern, parse_delimiter_field
+from rag.nlp.delim import (
+    compile_delimiter_pattern,
+    normalize_text_newlines,
+    parse_delimiter_field,
+)
...
-        self.markdown_content = markdown_content.replace("\r\n", "\n").replace("\r", "\n")
+        self.markdown_content = normalize_text_newlines(markdown_content)

As per coding guidelines: **/* requires us to “collapse duplicate implementations” and “center refactors on the owning abstraction.”

Also applies to: 158-162

🤖 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 `@deepdoc/parser/markdown_parser.py` around lines 23 - 24, Replace the
duplicated newline replacement chain in the markdown parser’s text-normalization
flow with the canonical rag.nlp.delim.normalize_text_newlines helper, importing
it alongside the existing delimiter utilities. Preserve the current
normalization behavior while ensuring markdown and txt parsing use the same
helper contract.

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.

Duplicate comments:
In `@deepdoc/parser/markdown_parser.py`:
- Line 167: Update the comment near the markdown delimiter example to replace
the ambiguous Unicode punctuation with Unicode escape sequences or explicit
code-point names, while preserving the example’s meaning and delimiter set.

---

Nitpick comments:
In `@deepdoc/parser/markdown_parser.py`:
- Around line 23-24: Replace the duplicated newline replacement chain in the
markdown parser’s text-normalization flow with the canonical
rag.nlp.delim.normalize_text_newlines helper, importing it alongside the
existing delimiter utilities. Preserve the current normalization behavior while
ensuring markdown and txt parsing use the same helper contract.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro Plus

Run ID: a67cb432-3686-439a-ab3e-93efb12f7baf

📥 Commits

Reviewing files that changed from the base of the PR and between 3940436 and 7d656d2.

📒 Files selected for processing (2)
  • deepdoc/parser/markdown_parser.py
  • deepdoc/parser/txt_parser.py

…consolidation

# Conflicts:
#	deepdoc/parser/txt_parser.py
#	internal/ingestion/component/chunker/common.go
#	rag/nlp/__init__.py
#	test/unit_test/rag/test_delimiter_case_sensitive.py

@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/delimiter_case_sensitive_test.go`:
- Around line 232-238: Update TestBacktickDelimRE_HasNoIgnoreCaseFlag so it
exercises the compiled delimiter pattern rather than only checking
ParseDelimiterField extraction. Compile the parsed delimiter and assert that
“End” matches while “end” and “END” do not, or rename the test to accurately
describe parser behavior if compiled-pattern verification is not intended.
🪄 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: a4ff2187-b6b1-440a-b65a-f34a4dceb04a

📥 Commits

Reviewing files that changed from the base of the PR and between 7d656d2 and cdc34e2.

📒 Files selected for processing (2)
  • internal/ingestion/component/chunker/delimiter_case_sensitive_test.go
  • rag/nlp/__init__.py
🚧 Files skipped from review as they are similar to previous changes (1)
  • rag/nlp/init.py

@yuzhichang yuzhichang left a comment

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.

LGTM

@dosubot dosubot Bot added the lgtm This PR has been approved by a maintainer label Aug 1, 2026
@yuzhichang yuzhichang added the ci Continue Integration label Aug 1, 2026
…consolidation

# Conflicts:
#	deepdoc/parser/txt_parser.py
#	rag/nlp/__init__.py
Strengthen case-sensitive compiled-pattern coverage, reuse
normalize_text_newlines in the markdown extractor, and fix gofmt/ruff
formatting that failed preflight after the main merge.
@codecov

codecov Bot commented Aug 1, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 90.65%. Comparing base (deb3d0c) to head (487e8b5).
⚠️ Report is 1 commits behind head on main.

Additional details and impacted files
@@           Coverage Diff           @@
##             main   #17387   +/-   ##
=======================================
  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.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@skbs-eng

skbs-eng commented Aug 2, 2026

Copy link
Copy Markdown
Contributor Author

LGTM

All set.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ci Continue Integration lgtm This PR has been approved by a maintainer 🌈 python Pull requests that update Python code ☯️ refactor Pull request that refactor/refine code size:XL This PR changes 500-999 lines, ignoring generated files. 🧪 test Pull requests that update test cases. 🧰 typescript Pull requests that update Typescript code

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants