Skip to content

Fix: is_english() returns False for any list argument (broken language detection) - #15489

Merged
yingfeng merged 1 commit into
infiniflow:mainfrom
devYRPauli:fix/is-english-list-detection
Jun 8, 2026
Merged

yingfeng merged 1 commit into
infiniflow:mainfrom
devYRPauli:fix/is-english-list-detection

Conversation

@devYRPauli

@devYRPauli devYRPauli commented Jun 1, 2026 •

Copy link
Copy Markdown
Contributor

What problem does this PR solve?

is_english() in rag/nlp/__init__.py compiles a single-character regex class and fullmatches it against each item:

pattern = re.compile(r"[`a-zA-Z0-9\s.,':;/\"?<>!\(\)\-]")   # no quantifier
...
eng = sum(1 for t in texts if pattern.fullmatch(t.strip()))

For a string argument the text is first split into single characters (texts = list(texts)), so each fullmatch sees one character and works. But for a list argument each item is a whole multi-character string, and fullmatch of a one-character pattern against a multi-character string always fails — so is_english() returns False for any list, regardless of content.

is_english("This is English")                              # True   (ok)
is_english(["The quick brown fox jumps.", "Hello world."]) # False  (bug — should be True)
is_english(["这是中文。"])                                    # False  (right answer, wrong reason)

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 at max_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.
  • plus 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:

pattern = re.compile(r"[`a-zA-Z0-9\s.,':;/\"?<>!\(\)\-]+")

The string path is unchanged (single characters still match) and non-English lists still return False. Adds test/unit_test/rag/test_is_english.py; the two list cases fail before this change and pass after.

Type of change

  • Bug Fix (non-breaking change which fixes an issue)

Used the Claude CLI while working on this.

@dosubot dosubot Bot added size:XS This PR changes 0-9 lines, ignoring generated files. 🌈 python Pull requests that update Python code 🐞 bug Something isn't working, pull request that fix bug. 🧪 test Pull requests that update test cases. labels Jun 1, 2026
@coderabbitai

coderabbitai Bot commented Jun 1, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

The PR changes the is_english regex to accept multi-character ASCII-only strings and adds a unit test module (with dependency stubs) that checks is_english on single strings, lists, and non-English input.

Changes

is_english Pattern and Test Coverage

Layer / File(s) Summary
is_english regex pattern update
rag/nlp/__init__.py
The allowed-character regex in is_english adds a + quantifier to match one-or-more allowed characters instead of a single character, expanding the strings that qualify as English text.
Test module and dependency stubs
test/unit_test/rag/test_is_english.py
New test module registers lightweight ModuleType stubs for heavy/optional dependencies in sys.modules to allow importing rag.nlp in isolation.
Unit tests for is_english
test/unit_test/rag/test_is_english.py
Adds four pytest cases: single English string, list of English sentences, single English item in a list, and list containing Chinese text (expected False).

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~12 minutes

Suggested labels

ci

Poem

I’m a rabbit with a regex bright,
I hopped from one char to many in flight,
Stubs in place so tests can run,
English strings now match as one —
🐇✨ code, tests, and quiet delight!

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly and specifically describes the main bug being fixed: is_english() incorrectly returning False for list arguments due to broken language detection.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Description check ✅ Passed The PR description comprehensively explains the bug, includes code examples, identifies affected call sites, and describes the fix with test coverage.

✏️ 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.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@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)
test/unit_test/rag/test_is_english.py (1)

41-54: ⚡ Quick win

Add pytest priority markers to match test conventions.

These tests are missing the required p1/p2/p3 markers. 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

📥 Commits

Reviewing files that changed from the base of the PR and between 3aea80f and 8942505.

📒 Files selected for processing (2)
  • rag/nlp/__init__.py
  • test/unit_test/rag/test_is_english.py

Comment on lines +21 to +37
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")

@coderabbitai coderabbitai Bot Jun 1, 2026 •

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.

⚠️ Potential issue | 🟠 Major | ⚡ Quick win

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.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

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.

@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.
@devYRPauli
devYRPauli force-pushed the fix/is-english-list-detection branch from 8942505 to 3e15cd7 Compare June 1, 2026 17:44
@yingfeng
yingfeng requested a review from KevinHuSh June 8, 2026 08:34
@KevinHuSh KevinHuSh added the ci Continue Integration label Jun 8, 2026
@KevinHuSh
KevinHuSh marked this pull request as draft June 8, 2026 08:53
@KevinHuSh
KevinHuSh marked this pull request as ready for review June 8, 2026 08:53
@dosubot dosubot Bot added the lgtm This PR has been approved by a maintainer label Jun 8, 2026
@codecov

codecov Bot commented Jun 8, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 93.16%. Comparing base (3aea80f) to head (3e15cd7).
⚠️ Report is 128 commits behind head on main.

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

@yingfeng
yingfeng merged commit f2aadd3 into infiniflow:main Jun 8, 2026
2 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

🐞 bug Something isn't working, pull request that fix bug. ci Continue Integration lgtm This PR has been approved by a maintainer 🌈 python Pull requests that update Python code size:XS This PR changes 0-9 lines, ignoring generated files. 🧪 test Pull requests that update test cases.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants