Skip to content

fix(metadata): meta_filter loses case-insensitive matches and leaks state across dict entries - #16956

Merged
yuzhichang merged 1 commit into
infiniflow:mainfrom
chuenchen309:fix/metadata-falsy-value-empty-translation
Jul 16, 2026
Merged

yuzhichang merged 1 commit into
infiniflow:mainfrom
chuenchen309:fix/metadata-falsy-value-empty-translation

Conversation

@chuenchen309

Copy link
Copy Markdown
Contributor

What

meta_filter()'s in-memory filter_out() helper has two related bugs in how it coerces input/value for comparison operators (=, ≠, >, <, ≥, ≤):

1. Asymmetric commit on partial literal_eval failure. The original code:

input = ast.literal_eval(input)
value = ast.literal_eval(value)

runs as two separate statements inside one try. If the first succeeds and the second raises, the first assignment already committed — input and value end up as different types, and the subsequent .lower() case-folding silently no-ops for whichever side didn't get lowered as a string. Concretely: metadata cell "None" is a valid Python literal (ast.literal_eval("None") → None), but a query value "none" (lowercase) is not — so status = "none" never matches a cell whose value is "None", even though the intended semantics are case-insensitive.

2. value mutated in place, reused across dict entries. filter_out(v2docs, operator, value) loops over every (input, docids) pair in v2docs and coerces value inside the loop body without resetting it — so once one entry's literal_eval(value) succeeds and rebinds value to a non-string, every later entry in the same call compares against that already-coerced leftover instead of the original filter value.

Fix

  • Commit both literal_eval results together via tuple assignment (input, value = ast.literal_eval(input), ast.literal_eval(value)), so a failure on either side leaves both operands in their pre-coercion form instead of a mismatched mix.
  • Save the original value before the loop and reset it at the top of each iteration, so per-entry coercion never leaks into the next entry.

Testing

Added 3 tests to test/unit_test/common/test_metadata_filter_operators.py covering both symptoms (case-insensitive match against a metadata cell that's a Python keyword literal, both = and ≠; a numeric > comparison unaffected by an earlier dict entry having coerced the query value). Confirmed red on common/metadata_utils.py at HEAD (git stash the fix, tests fail with the exact symptom described above), green after. Full existing test_metadata_filter_operators.py suite (22/22, including the 3 new tests) passes. ruff check and ruff format --check clean on both touched files.

Sandbox note: this environment has no network access to install pytest/pytest-asyncio, so tests were run by importing the test module and invoking each test_* function directly (same approach as prior PRs from this account against this repo, e.g. #16949). test_apply_semi_auto_meta_data_filter.py (the other file exercising meta_filter indirectly through apply_meta_data_filter) needs pytest-asyncio + heavier mocking and wasn't run, but it exercises apply_meta_data_filter's async/LLM-filter-generation path, not filter_out's coercion logic touched here.

Cross-referenced open PR #16833 (also touches common/metadata_utils.py) — confirmed via gh pr diff it only touches convert_conditions/operator-alias normalization and apply_meta_data_filter's None-vs-["-999"] sentinel logic, not filter_out's comparison-coercion code path. No overlap.


This PR was drafted with AI assistance (Claude); I reviewed the change, independently reproduced both symptoms, and take responsibility for it.

…tate across dict entries

filter_out() coerces `input`/`value` via two sequential ast.literal_eval()
calls sharing one try block, so a failure on either side (e.g. "None" parses
as a literal but "none" doesn't) commits only one side and compares
mismatched types after lowercasing. Separately, the coerced `value` was
reassigned in place and reused verbatim for the next dict entry instead of
the original filter value, letting one entry's coercion leak into the next.

Signed-off-by: chuenchen309 <[email protected]>
@dosubot dosubot Bot added size:S This PR changes 10-29 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 Jul 15, 2026
@coderabbitai

coderabbitai Bot commented Jul 15, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

filter_out now isolates query-value coercion across metadata entries and evaluates both operands consistently. New tests cover case-insensitive "none" comparisons and repeated greater-than evaluation.

Changes

Metadata filter evaluation

Layer / File(s) Summary
Filter coercion and operator coverage
common/metadata_utils.py, test/unit_test/common/test_metadata_filter_operators.py
filter_out preserves the original query value for each metadata entry and coerce both operands together; tests cover case-insensitive equality, inequality, and greater-than comparisons.

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

Poem

I’m a rabbit with filters, hopping in line,
Each value stays fresh, each comparison fine.
“None” meets “none” with a lowercase cheer,
Greater-than hops cleanly from entry to entry here.
Test carrots are planted; the burrow is bright!

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 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 clearly summarizes the main fix: preserving case-insensitive matches and preventing state leakage across dict entries.
Description check ✅ Passed The description explains the bugs, fix, and testing well, though it does not use the template's exact Summary heading.

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)
common/metadata_utils.py (1)

43-43: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Avoid shadowing the input built-in.

The loop variable input shadows a Python built-in, which Ruff correctly flags as A001. While not a critical bug, consider renaming this variable (e.g., to candidate or input_val) throughout the function to improve code hygiene.

🤖 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/metadata_utils.py` at line 43, Rename the loop variable input in the
v2docs iteration to a non-shadowing name such as candidate, and update all
references to it throughout the containing function while preserving the
existing behavior.

Source: Linters/SAST tools

🤖 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 `@common/metadata_utils.py`:
- Around line 70-82: Update the coercion logic around the list normalization and
paired ast.literal_eval assignment: simplify the list handling, convert both
input and value to strings before literal evaluation, and replace blind except
Exception handlers with targeted handling or logic that avoids exceptions.
Preserve atomic assignment so both operands are coerced together or neither is
updated, maintaining case-insensitive and numeric comparisons.

---

Nitpick comments:
In `@common/metadata_utils.py`:
- Line 43: Rename the loop variable input in the v2docs iteration to a
non-shadowing name such as candidate, and update all references to it throughout
the containing function while preserving the existing 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

Run ID: 4ac990dc-817c-4283-bac2-00c1f585a070

📥 Commits

Reviewing files that changed from the base of the PR and between df5c8e7 and cc77055.

📒 Files selected for processing (2)
  • common/metadata_utils.py
  • test/unit_test/common/test_metadata_filter_operators.py

Comment thread common/metadata_utils.py
Comment on lines 70 to 82
try:
if isinstance(input, list):
input = input[0]
input = ast.literal_eval(input)
value = ast.literal_eval(value)
except Exception:
pass
# Commit both literal_eval results together, or neither -- assigning
# just one side (e.g. "None" parses but "none" doesn't) would compare
# mismatched types after lowercasing and silently break the
# case-insensitive match below.
try:
input, value = ast.literal_eval(input), ast.literal_eval(value)
except Exception:
pass

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 | 🔴 Critical | ⚡ Quick win

Fix coercion failure for JSON primitives and clean up blind exceptions.

While evaluating both sides together correctly prevents type mismatches for edge cases like "None" vs "none", calling ast.literal_eval() directly on value will raise a TypeError if value is already a parsed primitive (e.g., an int like 5 passed directly from the JSON filter payload). As per coding guidelines, backend code targets Python 3.13+, where ast.literal_eval() strictly expects strings, bytes, or AST nodes. When this TypeError happens, the entire tuple assignment fails, leaving input uncoerced as a string and value as an int, causing subsequent numerical comparisons (>, <) to throw a TypeError and silently fail the filter match.

Converting both arguments to strings first ensures ast.literal_eval safely coerces them without throwing. Additionally, removing the blind except Exception: blocks resolves the Ruff BLE001 and S110 static analysis warnings, and the list unpacking can be safely simplified.

🐛 Proposed fix and refactor
-                    try:
-                        if isinstance(input, list):
-                            input = input[0]
-                    except Exception:
-                        pass
+                    if isinstance(input, list) and input:
+                        input = input[0]
+
                     # Commit both literal_eval results together, or neither -- assigning
                     # just one side (e.g. "None" parses but "none" doesn't) would compare
                     # mismatched types after lowercasing and silently break the
                     # case-insensitive match below.
                     try:
-                        input, value = ast.literal_eval(input), ast.literal_eval(value)
-                    except Exception:
+                        input, value = ast.literal_eval(str(input)), ast.literal_eval(str(value))
+                    except (ValueError, SyntaxError, TypeError):
                         pass
📝 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.

Suggested change
try:
if isinstance(input, list):
input = input[0]
input = ast.literal_eval(input)
value = ast.literal_eval(value)
except Exception:
pass
# Commit both literal_eval results together, or neither -- assigning
# just one side (e.g. "None" parses but "none" doesn't) would compare
# mismatched types after lowercasing and silently break the
# case-insensitive match below.
try:
input, value = ast.literal_eval(input), ast.literal_eval(value)
except Exception:
pass
if isinstance(input, list) and input:
input = input[0]
# Commit both literal_eval results together, or neither -- assigning
# just one side (e.g. "None" parses but "none" doesn't) would compare
# mismatched types after lowercasing and silently break the
# case-insensitive match below.
try:
input, value = ast.literal_eval(str(input)), ast.literal_eval(str(value))
except (ValueError, SyntaxError, TypeError):
pass
🧰 Tools
🪛 Ruff (0.15.21)

[error] 72-72: Variable input is shadowing a Python builtin

(A001)


[error] 73-74: try-except-pass detected, consider logging the exception

(S110)


[warning] 73-73: Do not catch blind exception: Exception

(BLE001)


[error] 80-80: Variable input is shadowing a Python builtin

(A001)


[error] 81-82: try-except-pass detected, consider logging the exception

(S110)


[warning] 81-81: Do not catch blind exception: Exception

(BLE001)

🤖 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/metadata_utils.py` around lines 70 - 82, Update the coercion logic
around the list normalization and paired ast.literal_eval assignment: simplify
the list handling, convert both input and value to strings before literal
evaluation, and replace blind except Exception handlers with targeted handling
or logic that avoids exceptions. Preserve atomic assignment so both operands are
coerced together or neither is updated, maintaining case-insensitive and numeric
comparisons.

Sources: Coding guidelines, Linters/SAST tools

@zeweihan

Copy link
Copy Markdown

Both defects reduce to the same dangerous shape: a filter that reports success while silently matching fewer documents than its declared semantics. A few angles worth surfacing:

  1. The "None" / "none" case is a Python-keyword-literal trap that bites exactly the metadata values most common in regulated corpora. Boolean/status fields (True/False/None/active/inactive/superseded) are the default vocabulary for "does this clause apply", "is this obligation in force". ast.literal_eval("None") → None (valid) but ast.literal_eval("none") → ValueError, so the two operands are never compared as strings and .lower() silently no-ops on whichever side stayed a string. Result: status = "none" returns zero documents with HTTP 200, indistinguishable from "no documents match" — the same empty-result-confidently-asserts-absence signature as ES .keyword routing on date fields ([Bug]: Elasticsearch metadata date filtering — exact-match "=" returns 0 and LLM range operators are silently dropped #16832) and ISO Z vs +00:00 string-equality (haystack#11962). The tuple assignment closing it at the coercion boundary is the right place to fix it.

  2. The state leak across dict entries is the strictly more dangerous of the two because it is order-dependent. Once an earlier (input, docids) entry coerces value to a non-string, every later entry compares against the leftover. Which documents a filter returns now depends on dict iteration order, so re-ingest or a backend change that reorders the same data produces a different answer set with no error — the "which docs did this filter return on date X" question becomes unanswerable, same shape as the Confluence attachment identity drift ([Bug]: Duplicate files may occur during Confluence data source file synchronization. #16665) and the same-name-file reader collisions (llama_index#22327). A value that survives across loop iterations is the textbook version; reset-at-top-of-loop is correct and minimal.

  3. Cheap orthogonal companion (separate from this PR, which fixes the correctness half): stamping {coercion_applied: bool, input_type, value_type, lowered: bool} per comparison would make "this filter silently matched fewer docs than its semantics imply" inspectable rather than discoverable only by diffing result sets weeks later. Both the None→non-match and the order-dependent leak pass every smoke test that checks "did we get results"; they only surface when a specific corpus value hits the trap. Same text_coverage / formula_render_status philosophy — turn a silent partial match into a queryable invariant.

Good catch on the None literal specifically — that's the kind of defect that hides for months because nobody writes a test with a metadata cell whose string value happens to be a Python keyword.

@yingfeng
yingfeng requested a review from yuzhichang July 16, 2026 01:32
@yingfeng yingfeng added the ci Continue Integration label Jul 16, 2026
@yingfeng
yingfeng marked this pull request as draft July 16, 2026 01:32
@yingfeng
yingfeng marked this pull request as ready for review July 16, 2026 01:32
@chuenchen309

Copy link
Copy Markdown
Contributor Author

Thanks for the detailed writeup — the regulated-corpus framing for point 1 is a good concrete example of why this isn't just an edge case; boolean/status-style metadata values are exactly where a keyword-literal trap like "none" vs None bites in practice.

Agreed that point 2 (the order-dependent leak) is the more dangerous of the two precisely because it's silent and non-reproducible across runs unless dict iteration order happens to match — "which docs did this filter return on date X" becoming unanswerable is a good way to put it.

Point 3 (diagnostic stamping) is a genuinely useful idea, but I'd treat it as a separate, deliberately-scoped follow-up rather than folding it into this PR — this PR is specifically the correctness fix, and a {coercion_applied, input_type, value_type, lowered} observability layer touches call sites well beyond meta_filter and deserves its own design/review pass rather than riding along here. Happy to pick it up as a follow-up if a maintainer confirms it's wanted (or if you'd rather file it yourself, that works too — either way I don't think it should block this fix).

@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 Jul 16, 2026
@yingfeng
yingfeng marked this pull request as draft July 16, 2026 03:06
@yingfeng
yingfeng marked this pull request as ready for review July 16, 2026 03:06
@codecov

codecov Bot commented Jul 16, 2026 •

Copy link
Copy Markdown

Codecov Report

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

Additional details and impacted files
@@            Coverage Diff             @@
##             main   #16956      +/-   ##
==========================================
- 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.

@yuzhichang
yuzhichang merged commit 198815a into infiniflow:main Jul 16, 2026
28 of 31 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:S This PR changes 10-29 lines, ignoring generated files. 🧪 test Pull requests that update test cases.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants