Repository navigation
fix(metadata): meta_filter loses case-insensitive matches and leaks state across dict entries - #16956
Conversation
…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]>
📝 WalkthroughWalkthrough
ChangesMetadata filter evaluation
Estimated code review effort: 2 (Simple) | ~10 minutes Poem
🚥 Pre-merge checks | ✅ 5✅ Passed checks (5 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 |
There was a problem hiding this comment.
Actionable comments posted: 1
🧹 Nitpick comments (1)
common/metadata_utils.py (1)
43-43: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueAvoid shadowing the
inputbuilt-in.The loop variable
inputshadows a Python built-in, which Ruff correctly flags asA001. While not a critical bug, consider renaming this variable (e.g., tocandidateorinput_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
📒 Files selected for processing (2)
common/metadata_utils.pytest/unit_test/common/test_metadata_filter_operators.py
| 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 |
There was a problem hiding this comment.
🎯 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.
| 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
|
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:
Good catch on the |
|
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 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 |
Codecov Report✅ All modified and coverable lines are covered by tests. 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. 🚀 New features to boost your workflow:
|
What
meta_filter()'s in-memoryfilter_out()helper has two related bugs in how it coercesinput/valuefor comparison operators (=,≠,>,<,≥,≤):1. Asymmetric commit on partial
literal_evalfailure. The original code:runs as two separate statements inside one
try. If the first succeeds and the second raises, the first assignment already committed —inputandvalueend 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 — sostatus = "none"never matches a cell whose value is"None", even though the intended semantics are case-insensitive.2.
valuemutated in place, reused across dict entries.filter_out(v2docs, operator, value)loops over every(input, docids)pair inv2docsand coercesvalueinside the loop body without resetting it — so once one entry'sliteral_eval(value)succeeds and rebindsvalueto a non-string, every later entry in the same call compares against that already-coerced leftover instead of the original filter value.Fix
literal_evalresults 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.valuebefore 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.pycovering 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 oncommon/metadata_utils.pyat HEAD (git stashthe fix, tests fail with the exact symptom described above), green after. Full existingtest_metadata_filter_operators.pysuite (22/22, including the 3 new tests) passes.ruff checkandruff format --checkclean 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 eachtest_*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 exercisingmeta_filterindirectly throughapply_meta_data_filter) needspytest-asyncio+ heavier mocking and wasn't run, but it exercisesapply_meta_data_filter's async/LLM-filter-generation path, notfilter_out's coercion logic touched here.Cross-referenced open PR #16833 (also touches
common/metadata_utils.py) — confirmed viagh pr diffit only touchesconvert_conditions/operator-alias normalization andapply_meta_data_filter'sNone-vs-["-999"]sentinel logic, notfilter_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.