Repository navigation
fix(api): default delimiter must be a real newline, not the r"\n" escape - #17591
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:
📝 WalkthroughWalkthroughDelimiter processing now decodes escapes, filters unsafe unquoted values, preserves quoted delimiters, logs discarded values, and avoids character-by-character splitting when no valid delimiters remain. Tests cover parser, chunker, and merge behavior. ChangesDelimiter safety
Estimated code review effort: 3 (Moderate) | ~20 minutes Possibly related PRs
Suggested labels: Poem
🚥 Pre-merge checks | ✅ 3 | ❌ 2❌ Failed checks (2 warnings)
✅ Passed checks (3 passed)
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 |
1e8a405 to
c620985
Compare
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 `@rag/nlp/__init__.py`:
- Around line 1635-1638: Update the delimiter decoding logic in the surrounding
initializer to avoid the Latin-1 round trip for non-Latin Unicode escapes such
as \u3002. Decode Unicode escapes directly, preserve the resolved delimiter
characters, and keep the existing delimiter expansion behavior; do not fall back
to a raw backslash form that can drop the escape marker.
In `@test/unit_test/rag/test_naive_merge.py`:
- Around line 225-235: Update test/unit_test/rag/test_naive_merge.py lines
225-235 in test_letter_delimiter_does_not_drop_letters to construct
bad_delimiter with two backslashes followed by n, so decoding leaves the bare n
corruption case; update lines 238-242 in the related test to append the same
double-escaped delimiter. No other sites require changes.
🪄 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: 48451fed-c248-4d12-8a90-2545697ba56d
📒 Files selected for processing (5)
deepdoc/parser/txt_parser.pyinternal/ingestion/component/chunker/delimiter_safety_test.gorag/nlp/__init__.pytest/unit_test/deepdoc/parser/test_txt_parser.pytest/unit_test/rag/test_naive_merge.py
c620985 to
6750c37
Compare
There was a problem hiding this comment.
Actionable comments posted: 2
🧹 Nitpick comments (2)
test/unit_test/rag/test_naive_merge.py (2)
244-249: 🎯 Functional Correctness | 🔵 Trivial | ⚡ Quick winExercise the raw-backslash fallback for
\u3002.With the supplied
get_delimitersimplementation, this value falls back to raw characters. The filter removesuand the digits but can retain\. The current input,"2024 results", contains no backslash, so the test can pass while the pattern still splits on\. Add a backslash-containing input and assert the intended fallback behavior, or assert the decoded。delimiter if Unicode escapes should be supported.🤖 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_naive_merge.py` around lines 244 - 249, The test_get_delimiters_ignores_escaped_non_ascii_digits test does not exercise the retained backslash in the raw fallback. Update its input and assertion to include a backslash-containing string and verify that the generated pattern does not split on that backslash, or instead validate the decoded 。 delimiter if get_delimiters is intended to support Unicode escapes.
237-242: 🎯 Functional Correctness | 🔵 Trivial | ⚡ Quick winAssert each delimiter that the test claims to retain.
The test only proves that
!remains active. It does not prove that newline or?remains active. Add one match for each retained delimiter.Proposed test strengthening
assert not re.search(pattern, "information") assert re.search(pattern, "a!b") + assert re.search(pattern, "a\nb") + assert re.search(pattern, "a?b")🤖 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_naive_merge.py` around lines 237 - 242, Strengthen test_get_delimiters_drops_bare_letters_keeps_punctuation by adding separate assertions that the generated pattern matches text containing a newline and text containing “?”. Keep the existing assertions for excluding “n” and retaining “!”, so each delimiter claimed by the test is explicitly verified.
🤖 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/txt_parser.py`:
- Around line 35-40: Update the delimiter escape handling near the round-trip
conversion and the related filtering logic around the parser’s escape-token
processing so invalid escape tokens are discarded with their leading backslash,
while valid tokens in mixed input such as `r"\n\u3002"` are decoded
independently. Ensure inputs like `r"\u3002"` cannot leave a standalone
backslash that affects splitting or document text, and add regression coverage
for mixed escapes and literal backslashes.
In `@test/unit_test/deepdoc/parser/test_txt_parser.py`:
- Around line 20-31: Strengthen the regression assertions in the
malformed-escape tests around test_letter_delimiter_does_not_eat_content and the
related tests at the referenced ranges: assert the joined parsed text exactly
matches the original input, add a backslash to the Unicode-escape test input so
residual delimiters are detected, and require len(chunks) > 1 in the punctuation
test to verify splitting occurred.
---
Nitpick comments:
In `@test/unit_test/rag/test_naive_merge.py`:
- Around line 244-249: The test_get_delimiters_ignores_escaped_non_ascii_digits
test does not exercise the retained backslash in the raw fallback. Update its
input and assertion to include a backslash-containing string and verify that the
generated pattern does not split on that backslash, or instead validate the
decoded 。 delimiter if get_delimiters is intended to support Unicode escapes.
- Around line 237-242: Strengthen
test_get_delimiters_drops_bare_letters_keeps_punctuation by adding separate
assertions that the generated pattern matches text containing a newline and text
containing “?”. Keep the existing assertions for excluding “n” and retaining
“!”, so each delimiter claimed by the test is explicitly verified.
🪄 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: bf354dea-6ebf-4b0d-9e41-1d43cc7d352d
📒 Files selected for processing (5)
deepdoc/parser/txt_parser.pyinternal/ingestion/component/chunker/delimiter_safety_test.gorag/nlp/__init__.pytest/unit_test/deepdoc/parser/test_txt_parser.pytest/unit_test/rag/test_naive_merge.py
🚧 Files skipped from review as they are similar to previous changes (1)
- rag/nlp/init.py
6750c37 to
276b82c
Compare
There was a problem hiding this comment.
Actionable comments posted: 2
🧹 Nitpick comments (1)
common/string_utils.py (1)
83-100: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueAdd debug logging when the decoder changes a delimiter.
A valid escaped delimiter changes split behavior without a diagnostic. Log a debug message only when the decoded value differs from
delimiters. Do not include document content in the message.Proposed change
def decode_delimiter_escapes(delimiters: str) -> str: + ... + decoded = _DELIMITER_ESCAPE.sub(_decode, delimiters) + if decoded != delimiters: + logging.debug("Decoded escape sequences in configured delimiter") + return decoded - return _DELIMITER_ESCAPE.sub(_decode, delimiters)As per coding guidelines, “
**/*.py: Add logging for new flows”.🤖 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 `@common/string_utils.py` around lines 83 - 100, Add debug logging to decode_delimiter_escapes only when the final decoded result differs from the original delimiters value, using the module’s existing logger and a message that excludes document content; leave unchanged inputs silent and preserve the per-token decoding behavior in _decode.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/txt_parser.py`:
- Around line 52-72: The delimiter list in RAGFlowTxtParser.parser_txt must
prefer longer alternatives to prevent shorter delimiters from partially matching
them. After filtering invalid delimiters and before re.escape, sort dels by
descending length; apply this ordering consistently to both quoted and unquoted
delimiter-processing paths while preserving the existing filtering behavior.
- Around line 52-72: Preserve quote provenance by tracking whether each
delimiter token came from backtick quoting rather than storing quoted delimiter
values in a shared set. Update both the delimiter-processing logic in
RAGFlowTxtParser.parser_txt and rag.nlp.get_delimiters so duplicate values such
as a quoted “n” followed by an unquoted “n” filter only the unquoted unsafe
token. Add a regression covering that quoted-then-unquoted sequence and verify
the unquoted character cannot split or be removed from chunks.
---
Nitpick comments:
In `@common/string_utils.py`:
- Around line 83-100: Add debug logging to decode_delimiter_escapes only when
the final decoded result differs from the original delimiters value, using the
module’s existing logger and a message that excludes document content; leave
unchanged inputs silent and preserve the per-token decoding behavior in _decode.
🪄 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: b49f638e-c2e3-4d1e-97bf-573ef8b57e22
📒 Files selected for processing (6)
common/string_utils.pydeepdoc/parser/txt_parser.pyinternal/ingestion/component/chunker/delimiter_safety_test.gorag/nlp/__init__.pytest/unit_test/deepdoc/parser/test_txt_parser.pytest/unit_test/rag/test_naive_merge.py
🚧 Files skipped from review as they are similar to previous changes (1)
- rag/nlp/init.py
276b82c to
a163a57
Compare
There was a problem hiding this comment.
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 `@deepdoc/parser/txt_parser.py`:
- Line 36: Align delimiter normalization between RAGFlowTxtParser.parser_txt and
naive_merge by decoding the delimiter once before selecting the custom-delimiter
parsing path, ensuring backtick-quoted escaped sequences produce the same
delimiter in both flows. Preserve literal backtick handling and add a focused
regression test covering the escaped newline delimiter and section splitting.
In `@test/unit_test/deepdoc/parser/test_txt_parser.py`:
- Around line 64-72: Update test_mixed_escape_delimiter_splits_on_both to assert
that the decoded CJK period character is absent from joined parsed content,
while retaining the existing word-presence and multi-chunk assertions.
- Around line 97-107: The test_quoted_char_tracked_by_position_not_value test
assertions do not actually verify that the bare `n` is being ignored by
position-based filtering. To properly validate this behavior, capture and assert
on the warning message that reports the discarded bare `n` token. Add an
assertion that checks for this warning to confirm position-based filtering is
working, since the current end-result assertions alone could be satisfied even
if both `n` tokens remained active.
🪄 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: 5fb20e23-7d64-4ac3-a1bb-5276df158099
📒 Files selected for processing (6)
common/string_utils.pydeepdoc/parser/txt_parser.pyinternal/ingestion/component/chunker/delimiter_safety_test.gorag/nlp/__init__.pytest/unit_test/deepdoc/parser/test_txt_parser.pytest/unit_test/rag/test_naive_merge.py
🚧 Files skipped from review as they are similar to previous changes (2)
- rag/nlp/init.py
- common/string_utils.py
| def test_mixed_escape_delimiter_splits_on_both(): | ||
| # "\n。" means newline and the CJK period. Both must split, letters kept. | ||
| delimiter = chr(92) + "n" + chr(92) + "u3002" # \n。 | ||
| text = "alpha。beta\ngamma" | ||
| chunks = RAGFlowTxtParser.parser_txt(text, chunk_token_num=1, delimiter=delimiter) | ||
| joined = " ".join(c for c, _ in chunks) | ||
| for word in ("alpha", "beta", "gamma"): | ||
| assert word in joined | ||
| assert len(chunks) > 1 |
There was a problem hiding this comment.
🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win
Assert that the decoded CJK delimiter is consumed.
len(chunks) > 1 can pass when only the decoded newline delimiter works. The test does not prove that \u3002 decodes and splits. Assert that the CJK period is absent from the parsed content.
Proposed test change
for word in ("alpha", "beta", "gamma"):
assert word in joined
+ assert "。" not in joined
assert len(chunks) > 1📝 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.
| def test_mixed_escape_delimiter_splits_on_both(): | |
| # "\n。" means newline and the CJK period. Both must split, letters kept. | |
| delimiter = chr(92) + "n" + chr(92) + "u3002" # \n。 | |
| text = "alpha。beta\ngamma" | |
| chunks = RAGFlowTxtParser.parser_txt(text, chunk_token_num=1, delimiter=delimiter) | |
| joined = " ".join(c for c, _ in chunks) | |
| for word in ("alpha", "beta", "gamma"): | |
| assert word in joined | |
| assert len(chunks) > 1 | |
| def test_mixed_escape_delimiter_splits_on_both(): | |
| # "\n。" means newline and the CJK period. Both must split, letters kept. | |
| delimiter = chr(92) + "n" + chr(92) + "u3002" # \n。 | |
| text = "alpha。beta\ngamma" | |
| chunks = RAGFlowTxtParser.parser_txt(text, chunk_token_num=1, delimiter=delimiter) | |
| joined = " ".join(c for c, _ in chunks) | |
| for word in ("alpha", "beta", "gamma"): | |
| assert word in joined | |
| assert "。" not in joined | |
| assert len(chunks) > 1 |
🤖 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/deepdoc/parser/test_txt_parser.py` around lines 64 - 72,
Update test_mixed_escape_delimiter_splits_on_both to assert that the decoded CJK
period character is absent from joined parsed content, while retaining the
existing word-presence and multi-chunk assertions.
| def test_quoted_char_tracked_by_position_not_value(): | ||
| # A backtick-quoted "n" is honored as an explicit delimiter even with a literal | ||
| # "n" in the same config. Quote status is tracked per token position, so the | ||
| # literal "n" is still filtered on its own rather than shielded by the quoted | ||
| # one sharing its value. | ||
| delimiter = "`n`n" # quoted n, then literal n | ||
| text = "an informative analysis" | ||
| chunks = RAGFlowTxtParser.parser_txt(text, chunk_token_num=1, delimiter=delimiter) | ||
| joined = "".join(c for c, _ in chunks) | ||
| assert "n" not in joined # the explicit quoted n splits, consuming the n's | ||
| assert "iformative" in joined # non-n content preserved |
There was a problem hiding this comment.
🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win
Assert that the bare n is ignored.
The quoted and bare n tokens produce the same parsed output if both remain active. The current assertions therefore do not verify position-based filtering. Capture the warning that reports the discarded bare n.
Proposed test change
-def test_quoted_char_tracked_by_position_not_value():
+def test_quoted_char_tracked_by_position_not_value(caplog):
...
assert "n" not in joined # the explicit quoted n splits, consuming the n's
assert "iformative" in joined # non-n content preserved
+ assert any(
+ "ignoring delimiter character(s) ['n']" in record.getMessage()
+ for record in caplog.records
+ )📝 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.
| def test_quoted_char_tracked_by_position_not_value(): | |
| # A backtick-quoted "n" is honored as an explicit delimiter even with a literal | |
| # "n" in the same config. Quote status is tracked per token position, so the | |
| # literal "n" is still filtered on its own rather than shielded by the quoted | |
| # one sharing its value. | |
| delimiter = "`n`n" # quoted n, then literal n | |
| text = "an informative analysis" | |
| chunks = RAGFlowTxtParser.parser_txt(text, chunk_token_num=1, delimiter=delimiter) | |
| joined = "".join(c for c, _ in chunks) | |
| assert "n" not in joined # the explicit quoted n splits, consuming the n's | |
| assert "iformative" in joined # non-n content preserved | |
| def test_quoted_char_tracked_by_position_not_value(caplog): | |
| # A backtick-quoted "n" is honored as an explicit delimiter even with a literal | |
| # "n" in the same config. Quote status is tracked per token position, so the | |
| # literal "n" is still filtered on its own rather than shielded by the quoted | |
| # one sharing its value. | |
| delimiter = "`n`n" # quoted n, then literal n | |
| text = "an informative analysis" | |
| chunks = RAGFlowTxtParser.parser_txt(text, chunk_token_num=1, delimiter=delimiter) | |
| joined = "".join(c for c, _ in chunks) | |
| assert "n" not in joined # the explicit quoted n splits, consuming the n's | |
| assert "iformative" in joined # non-n content preserved | |
| assert any( | |
| "ignoring delimiter character(s) ['n']" in record.getMessage() | |
| for record in caplog.records | |
| ) |
🤖 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/deepdoc/parser/test_txt_parser.py` around lines 97 - 107, The
test_quoted_char_tracked_by_position_not_value test assertions do not actually
verify that the bare `n` is being ignored by position-based filtering. To
properly validate this behavior, capture and assert on the warning message that
reports the discarded bare `n` token. Add an assertion that checks for this
warning to confirm position-based filtering is working, since the current
end-result assertions alone could be satisfied even if both `n` tokens remained
active.
a163a57 to
b9cb89b
Compare
|
@xugangqiang could you add the Latest push addresses CodeRabbit's delimiter-parity Major - |
get_parser_config's knowledge_graph default and the ParserConfig /
ParentChildConfig validation defaults used r"\n" - a raw string, so a backslash
plus the letter n. rag.nlp.delim.parse_delimiter_field honours bare characters,
so that default splits documents on every n ("information" -> "i", "formatio")
and on the stray backslash. A dataset created via the API without an explicit
delimiter got this shredding default.
Use an actual newline, matching the naive default and what the frontend already
sends. Regression test asserts the three defaults parse to a single newline.
Co-Authored-By: Claude Opus 4.8 <[email protected]>
b9cb89b to
093c69d
Compare
|
Separate from this PR, noticed while checking the round-trip. The delimiter help text in Not touching it here since it is the delim.py design call. But the doc and the parser disagree - either the help drops the |
Codecov Report✅ All modified and coverable lines are covered by tests. Additional details and impacted files@@ Coverage Diff @@
## main #17591 +/- ##
=======================================
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:
|
|
@deadtrickster Appreciate your contribution. For this PR, I think it's good and I will merge it. For other issues that's related to ingestion, I'd like to suggest that you can raise issues firstly but on-hold fixing(PR) for a while: since we are in the middle of migration from python to golang and we need a fixed baseline (though the baseline may not be good). Once golang migration completed (most likely no later than next month), we can continue bug fixing on ingestion related issues. Thank you. |
Found this reading arXiv chunks back from storage, every
nwas gone. "analysis increasingly involves information" came back as "a\nalysis i\ncreasi\ngly i\nvolves i\nformatio". No error, chunk count normal, status 100%. The stored .txt on disk was fine.The cause - a dataset created via the API without an explicit delimiter stores the default as the escape
\n(backslash + the literal letter n). Two chunker paths read it and disagree.deepdoc/parser/txt_parser.pyruns the delimiter through aunicode_escaperound-trip (txt_parser.py:34), so\nbecomes a real newline and it splits correctly. Butrag/nlp/get_delimiters(used bynaive_merge) does not decode. It splits the delimiter into individual characters (list(delimiter)), so\nbecomes backslash and the letter n, and every oversized section gets split on the letter n and drops it.For a
.txtfile both run.TxtParsersplits it into sections (fine, it decoded), thennaive_mergere-splits every oversized section on the letter n. So the corpus comes back with every n gone. It hid for a long time. Non-Latin corpora look fine (nonto lose), and small sections never reach thenaive_mergere-split.Reproduced on v0.26.4 (the version I ingested arxiv with, image
infiniflow/ragflow:v0.26.4) and still on current main611e0596. The repro is a normal API create with aparser_configpresent but nodelimiter, then a large.txt.Fix, both in
get_delimiters- decode escape sequences the same waytxt_parserdoes, so\nsplits on a newline. And drop bare ASCII-letter delimiter characters with a warning, keeping backtick-quoted delimiters, so any residual letter degrades to no split instead of silent corruption.txt_parserkeeps the same letter guard and stays whole when nothing is left to split on.markdown_parser.get_delimitersis backtick-only already and is safe. GocompileDelimPatterncompiles only backtick delimiters and splits oversized sections on a fixed newline/punctuation pattern, so Go never char-splits the config delimiter. Added Go tests that assert it.Splitting a document on a letter is never a real config, so nothing legitimate changes. Normal delimiters (newline,
!?。;!?, backtick groups) are untouched.Tests -
test/unit_test/deepdoc/parser/test_txt_parser.py,test/unit_test/rag/test_naive_merge.py, andinternal/ingestion/component/chunker/delimiter_safety_test.gocover the letter delimiter (red before the fix), the\nescape, normal delimiters, the all-letters case, and the Go parity.UPD: main refactored the delimiter parsers into one canonical helper
rag.nlp.delim.parse_delimiter_field(#17383), so the original two-path fix no longer applies -get_delimitersand the txt_parser inline split are gone.Re-checked against current main and the shred is still live, but the cause narrows to the stored default, not the parser. The canonical parser is correct on a real newline. What reaches it as backslash + n is the default itself - three configs default the delimiter to a raw
r"\n"(a Python raw string, so backslash + the literal letter n):api/utils/api_utils.py:393(knowledge_graph)api/utils/validation_utils.py:427(ParserConfig)api/utils/validation_utils.py:399(ParentChildConfig children_delimiter)parse_delimiter_field(r"\n")returns['\\', 'n']and splits "information" into "i","formatio". Thenaivedefault atapi_utils.py:341is already a real"\n"and the frontend sends a real newline, so these three were just missed.Fix is now those three defaults,
r"\n"->"\n", matching thenaivedefault. No parser change, sodelim.pyand its tests are untouched. Regression test intest/unit_test/api/utils/test_default_delimiter.pyasserts the three defaults parse to a single newline. Dropped the old txt_parser / naive_merge / Go changes - they targeted code that no longer exists.