Repository navigation
Fix: is_english() returns False for any list argument (broken language detection) - #15489
Conversation
📝 WalkthroughWalkthroughThe PR changes the Changesis_english Pattern and Test Coverage
Estimated code review effort🎯 2 (Simple) | ⏱️ ~12 minutes Suggested labels
Poem
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. 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: 1
🧹 Nitpick comments (1)
test/unit_test/rag/test_is_english.py (1)
41-54: ⚡ Quick winAdd pytest priority markers to match test conventions.
These tests are missing the required
p1/p2/p3markers. Please annotate each test (or the module) with the appropriate priority marker.As per coding guidelines, "
test/**/*.py: Use pytest with priority markers (p1/p2/p3) for Python backend tests".🤖 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_is_english.py` around lines 41 - 54, The tests lack pytest priority markers; add the appropriate marker (e.g., `@pytest.mark.p1/`@pytest.mark.p2/@pytest.mark.p3) to each test function or add a module-level marker so they follow conventions: annotate test_is_english_string_path_unchanged, test_is_english_list_of_english_sentences, test_is_english_single_english_answer_in_list, and test_is_english_chinese_list_is_false with the correct priority marker (or apply pytestmark = [pytest.mark.pX] at module scope) so the file conforms to the required p1/p2/p3 test categorization.
🤖 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_is_english.py`:
- Around line 21-37: The test currently calls the helper function _stub which
mutates sys.modules at import-time (via sys.modules.setdefault) causing global
pollution; move these stubs into a pytest fixture that uses monkeypatch.setitem
to inject the fake modules (e.g., replace calls that create
"common.token_utils", "roman_numbers", "word2number", "cn2an", "PIL",
"PIL.Image", "chardet" via _stub) so the module entries are applied per-test and
automatically reverted after each test; update the test to import or depend on
the new fixture and remove the top-level _stub calls so no import-time mutation
of sys.modules occurs.
---
Nitpick comments:
In `@test/unit_test/rag/test_is_english.py`:
- Around line 41-54: The tests lack pytest priority markers; add the appropriate
marker (e.g., `@pytest.mark.p1/`@pytest.mark.p2/@pytest.mark.p3) to each test
function or add a module-level marker so they follow conventions: annotate
test_is_english_string_path_unchanged,
test_is_english_list_of_english_sentences,
test_is_english_single_english_answer_in_list, and
test_is_english_chinese_list_is_false with the correct priority marker (or apply
pytestmark = [pytest.mark.pX] at module scope) so the file conforms to the
required p1/p2/p3 test categorization.
🪄 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
Run ID: 23cd67d1-63e4-4920-838e-22947308c365
📒 Files selected for processing (2)
rag/nlp/__init__.pytest/unit_test/rag/test_is_english.py
| def _stub(name, **attrs): | ||
| mod = types.ModuleType(name) | ||
| for key, value in attrs.items(): | ||
| setattr(mod, key, value) | ||
| sys.modules.setdefault(name, mod) | ||
| return mod | ||
|
|
||
|
|
||
| # Stub heavy module-level imports so rag.nlp can be imported in isolation. | ||
| _stub("common.token_utils", num_tokens_from_string=lambda *a, **k: 0) | ||
| _stub("roman_numbers") | ||
| _stub("word2number", w2n=types.SimpleNamespace()) | ||
| _stub("cn2an", cn2an=lambda *a, **k: 0) | ||
| _pil = _stub("PIL") | ||
| _pil.Image = _stub("PIL.Image") | ||
| _stub("chardet") | ||
|
|
There was a problem hiding this comment.
Avoid global sys.modules pollution from import-time stubs.
Line 25 mutates sys.modules at module import time and never restores it. This can leak into unrelated tests and cause order-dependent failures. Move stubbing into a pytest fixture using monkeypatch.setitem(...) so state is reverted after each test/module run.
🤖 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_is_english.py` around lines 21 - 37, The test
currently calls the helper function _stub which mutates sys.modules at
import-time (via sys.modules.setdefault) causing global pollution; move these
stubs into a pytest fixture that uses monkeypatch.setitem to inject the fake
modules (e.g., replace calls that create "common.token_utils", "roman_numbers",
"word2number", "cn2an", "PIL", "PIL.Image", "chardet" via _stub) so the module
entries are applied per-test and automatically reverted after each test; update
the test to import or depend on the new fixture and remove the top-level _stub
calls so no import-time mutation of sys.modules occurs.
There was a problem hiding this comment.
#20926 removes these stubs instead of moving them into a fixture, because the stubs are not necessary. Since #18986, common.token_utils builds the tiktoken encoder on first use, so an import of rag.nlp does not go to the network. CI installs the other stubbed packages with uv sync --group test. test_remove_contents_table.py had the same stubs and gets the same change. The fix targets 0.27.x, because main no longer has this file.
The leak is real. On 0.27.x, pytest test/unit_test/rag/test_is_english.py test/unit_test/common/test_token_utils.py stops with a collection error: ImportError: cannot import name 'get_encoder' from 'common.token_utils' (unknown location). A full test/unit_test run does not show the leak, because files that pytest collects earlier load the real modules.
There was a problem hiding this comment.
@devYRPauli Thanks for the clarification. Removing the unnecessary stubs is better than moving them into a fixture. The lazy encoder initialization from #18986 and the dependencies installed by uv sync --group test remove the need for those stubs.
Your targeted reproduction explains why the full suite can hide the leak: earlier imports populate sys.modules with the real modules. Applying the same removal to test_remove_contents_table.py addresses the same risk.
The finding remains valid. #20926 provides the fix for 0.27.x; this does not invalidate the original concern.
✏️ Learnings added
Learnt from: devYRPauli
Repo: infiniflow/ragflow PR: 15489
File: test/unit_test/rag/test_is_english.py:23-39
Timestamp: 2026-10-13T23:49:46.636Z
Learning: In infiniflow/ragflow, since #18986, common.token_utils initializes the tiktoken encoder on first use rather than at import time. Importing rag.nlp therefore does not require network access for encoder initialization. CI installs the other dependencies previously stubbed in test/unit_test/rag/test_is_english.py and test_remove_contents_table.py with `uv sync --group test`. Prefer real imports over unnecessary sys.modules stubs in these tests.
Note: Learnings are effective only in the context of similar code segments. To apply general coding guidelines, please configure review instructions. You can manage existing learnings in the app.
You are interacting with an AI system.
is_english() compiled a single-character pattern and fullmatch'd it against each item. For a string argument the text is first split into single characters, so it works; but for a list argument each item is a whole multi-character string and fullmatch always fails, so is_english() returns False for any list regardless of language. Add a `+` quantifier so an all-English item matches. The string path is unchanged (single characters still match) and non-English lists still return False. This affects callers that pass lists: rag/app/book.py (table-of-contents stripping ran in Chinese mode for English books) and the truncated-answer continuation suffix in rag/llm/chat_model.py / cv_model.py (English replies received the Chinese "continue?" suffix). Adds test/unit_test/rag/test_is_english.py.
8942505 to
3e15cd7
Compare
Codecov Report✅ All modified and coverable lines are covered by tests. Additional details and impacted files@@ Coverage Diff @@
## main #15489 +/- ##
==========================================
- Coverage 94.56% 93.16% -1.40%
==========================================
Files 10 10
Lines 717 717
Branches 118 118
==========================================
- Hits 678 668 -10
- Misses 25 29 +4
- Partials 14 20 +6 ☔ View full report in Codecov by Harness. 🚀 New features to boost your workflow:
|
What problem does this PR solve?
is_english()inrag/nlp/__init__.pycompiles a single-character regex class andfullmatches it against each item:For a string argument the text is first split into single characters (
texts = list(texts)), so eachfullmatchsees one character and works. But for a list argument each item is a whole multi-character string, andfullmatchof a one-character pattern against a multi-character string always fails — sois_english()returnsFalsefor any list, regardless of content.Many call sites pass lists and were therefore silently always-
False, e.g.:rag/llm/chat_model.py:1088,rag/llm/cv_model.py:168,1155—is_english([ans])when an answer is truncated atmax_tokens, so an English reply gets the Chinese "······由于长度的原因,回答被截断了,要继续吗?" continuation suffix instead of the English one.rag/app/book.py—remove_contents_table(..., eng=is_english([...sections...])), so English books have their contents table stripped in Chinese mode.common/doc_store/es_conn_base.py:339,rag/utils/opensearch_conn.py:733—is_english(txt.split())in highlight handling.rag/app/qa.py,rag/flow/parser/utils.py,common/doc_store/infinity_conn_base.py.Fix
Add a
+quantifier so an all-English multi-character item matches:The string path is unchanged (single characters still match) and non-English lists still return
False. Addstest/unit_test/rag/test_is_english.py; the two list cases fail before this change and pass after.Type of change
Used the Claude CLI while working on this.