Skip to content

Fix filter to use Chinese - #16673

Merged
wangq8 merged 1 commit into
infiniflow:mainfrom
wangq8:bugfix/fix-to-filter-using-chinese
Jul 6, 2026
Merged

wangq8 merged 1 commit into
infiniflow:mainfrom
wangq8:bugfix/fix-to-filter-using-chinese

Conversation

@wangq8

@wangq8 wangq8 commented Jul 6, 2026

Copy link
Copy Markdown
Collaborator
image

@dosubot dosubot Bot added the size:S This PR changes 10-29 lines, ignoring generated files. label Jul 6, 2026
@wangq8 wangq8 changed the title Fix filter to use chinese Fix filter to use Chinese Jul 6, 2026
if keywords:
sessions = sessions.where(peewee.fn.LOWER(cls.model.message).contains(keywords.lower()))
keywords = keywords.lower()
escaped_keywords = json_dumps(keywords)[1:-1]

@wangq8 wangq8 Jul 6, 2026 •

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Trim the double quote "the-word"

@wangq8 wangq8 added the ci Continue Integration label Jul 6, 2026
@wangq8
wangq8 marked this pull request as draft July 6, 2026 09:36
@wangq8
wangq8 marked this pull request as ready for review July 6, 2026 09:36
@coderabbitai

coderabbitai Bot commented Jul 6, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

Both the Python API4ConversationService.get_list method and the Go ListAgentSessions function were modified to escape special characters in search keywords before filtering. Each now lowercases the keyword, computes an escaped variant, and applies either a single filter or an OR-combined filter depending on whether escaping changes the value.

Changes

Keyword Search Escaping

Layer / File(s) Summary
Python keyword escaping
api/db/services/api_service.py
Imports json_dumps and reworks the keywords filter to compute an escaped form and conditionally apply a single or OR-combined contains filter.
Go keyword escaping
internal/dao/chat_session.go
Imports strconv and reworks the keyword filter to compute an ASCII-escaped form and conditionally apply a single or OR-combined LIKE filter.

Estimated code review effort: 2 (Simple) | ~10 minutes

Poem

A rabbit typed with careful paws,
Escaping quotes to dodge the flaws,
LOWER, LIKE, and JSON dumps too,
Now keywords search both old and new,
Hop, hop, hooray — the filters pass! 🐇

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Description check ⚠️ Warning The description does not follow the template; it only contains an image and is missing the required Summary section and context. Add a Summary section describing the problem, the change made, and any relevant background or reviewer context.
✅ Passed checks (4 passed)
Check name Status Explanation
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
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.
Title check ✅ Passed The title matches the main change: it updates filter behavior for Chinese/escaped keyword matching.

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.

@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)
api/db/services/api_service.py (1)

68-75: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Add logging for this new escaping/fallback flow.

This introduces a new conditional search-matching flow (raw vs. escaped keyword), but nothing is logged. Adding a debug-level log (e.g., when the OR-fallback path with escaped_keywords is taken) would help diagnose search-matching issues for CJK/Unicode keywords in production.

As per coding guidelines, "Add logging for new flows" applies to **/*.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 `@api/db/services/api_service.py` around lines 68 - 75, The new
keyword-matching branch in the search logic currently has no visibility, so add
a debug log in the keyword filtering path to record when the fallback OR
condition is used with escaped_keywords. Update the method in api_service.py
that builds the sessions query so the logging clearly distinguishes the raw
match path from the escaped fallback path, making it easier to diagnose
Unicode/CJK search behavior in cls.model.message filtering.

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/dao/chat_session.go`:
- Around line 200-208: The keyword escaping in the chat session query is using
strings.Trim on the result of strconv.QuoteToASCII, which can remove valid
escaped boundary quotes and corrupt the pattern. Update the keyword handling in
the query-building block inside the chat session DAO so the quoted string is
unwrapped with positional slicing instead of trimming, preserving escaped
leading or trailing quote characters while keeping the existing LOWER(message)
LIKE fallback logic intact.

---

Nitpick comments:
In `@api/db/services/api_service.py`:
- Around line 68-75: The new keyword-matching branch in the search logic
currently has no visibility, so add a debug log in the keyword filtering path to
record when the fallback OR condition is used with escaped_keywords. Update the
method in api_service.py that builds the sessions query so the logging clearly
distinguishes the raw match path from the escaped fallback path, making it
easier to diagnose Unicode/CJK search behavior in cls.model.message filtering.
🪄 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: f4be350b-4df6-4f2c-993b-9d5ae08d885c

📥 Commits

Reviewing files that changed from the base of the PR and between 57625c9 and a76a7b6.

📒 Files selected for processing (2)
  • api/db/services/api_service.py
  • internal/dao/chat_session.go

Comment on lines 200 to 208
if params.Keywords != "" {
query = query.Where("LOWER(message) LIKE ?", "%"+strings.ToLower(params.Keywords)+"%")
keywords := strings.ToLower(params.Keywords)
escapedKeywords := strings.Trim(strconv.QuoteToASCII(keywords), `"`)
if escapedKeywords == keywords {
query = query.Where("LOWER(message) LIKE ?", "%"+keywords+"%")
} else {
query = query.Where("(LOWER(message) LIKE ? OR LOWER(message) LIKE ?)", "%"+keywords+"%", "%"+escapedKeywords+"%")
}
}

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.

🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
set -euo pipefail

# Inspect the Go implementation around the reported lines
sed -n '190,220p' internal/dao/chat_session.go

echo
echo "---- Python counterpart search ----"
rg -n "json_dumps\\(|QuoteToASCII|strings.Trim\\(|Trim\\(.*\"\\\"" -S api internal . || true

echo
echo "---- Locate the specific Python file if present ----"
fd -a 'api_service.py' . || true

Repository: infiniflow/ragflow

Length of output: 1667


🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "---- Go keyword filter ----"
sed -n '198,210p' internal/dao/chat_session.go

echo
echo "---- Python helper around json_dumps ----"
rg -n -A 4 -B 4 "json_dumps\(" /home/jailuser/git/api/db/services/api_service.py

echo
echo "---- Trim/QuoteToASCII boundary check using a minimal Python model ----"
python3 - <<'PY'
def trim_quotes(s):
    return s.strip('"')

samples = [
    'abc',
    'abc"',
    '"abc',
    '"abc"',
]
for x in samples:
    # emulate the important shape: quoted string with possible escaped quote near an edge
    quoted = '"' + x.replace('\\', '\\\\').replace('"', '\\"') + '"'
    print(repr(x), '->', repr(quoted), '->', repr(trim_quotes(quoted)))
PY

Repository: infiniflow/ragflow

Length of output: 1271


strings.Trim can corrupt escaped boundary quotes in the keyword pattern. strconv.QuoteToASCII may emit an escaped " at the start or end of the keyword, and strings.Trim(..., "\"") removes every leading/trailing quote rune, not just the outer delimiters. That turns inputs like abc" into a broken pattern (abc\). Use positional slicing (q := strconv.QuoteToASCII(keywords); escapedKeywords := q[1:len(q)-1]) instead.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@internal/dao/chat_session.go` around lines 200 - 208, The keyword escaping in
the chat session query is using strings.Trim on the result of
strconv.QuoteToASCII, which can remove valid escaped boundary quotes and corrupt
the pattern. Update the keyword handling in the query-building block inside the
chat session DAO so the quoted string is unwrapped with positional slicing
instead of trimming, preserving escaped leading or trailing quote characters
while keeping the existing LOWER(message) LIKE fallback logic intact.

@codecov

codecov Bot commented Jul 6, 2026

Copy link
Copy Markdown

Codecov Report

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

Additional details and impacted files
@@           Coverage Diff           @@
##             main   #16673   +/-   ##
=======================================
  Coverage   93.16%   93.16%           
=======================================
  Files          10       10           
  Lines         717      717           
  Branches      118      118           
=======================================
  Hits          668      668           
  Misses         29       29           
  Partials       20       20           

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

@wangq8
wangq8 merged commit 3a247db into infiniflow:main Jul 6, 2026
9 of 12 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ci Continue Integration size:S This PR changes 10-29 lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant