Skip to content

fix(metadata): Infinity push-down must reject multi-valued-unsafe negative ops (≠, not in) - #16943

Merged
yuzhichang merged 1 commit into
infiniflow:mainfrom
chuenchen309:fix/infinity-metadata-pushdown-multivalue-guard
Jul 18, 2026
Merged

yuzhichang merged 1 commit into
infiniflow:mainfrom
chuenchen309:fix/infinity-metadata-pushdown-multivalue-guard

Conversation

@chuenchen309

Copy link
Copy Markdown
Contributor

What problem does this PR solve?

The Elasticsearch and Infinity metadata push-down translators are meant to be
interchangeable pre-filters that both mirror the in-memory meta_filter
fallback — the shared test section is even titled "is_pushdown_supported
pre-check (same logic for both backends)"
. But the two is_pushdown_supported
implementations diverge:

  • common/metadata_es_filter.py defines
    MULTIVALUE_UNSAFE_NEGATIVE_OPS = frozenset({"≠", "not in"}) and refuses
    push-down for those operators.
  • common/metadata_infinity_filter.py has no such guard and pushes them
    down.

Why the guard exists: meta_fields.<key> can hold a JSON array, and the
in-memory meta_filter matches a document when any of its values satisfies
the predicate (per-value-bucket semantics). A document whose tag is [a, b]
therefore still matches tag ≠ a — bucket b satisfies it. The Infinity
push-down emits NOT JSON_CONTAINS(meta_fields, '$.tag', '"a"'), which means
"the array contains no a at all", so it silently drops that document.
Same divergence for not in. The result: tag ≠ a / tag not in (...)
under-counts results for any document that has the excluded value alongside
others, but only on the Infinity backend.

This is on a live production path:
DocMetadataService._filter_doc_ids_by_metadata_infinity
(api/db/services/doc_metadata_service.py:948) calls this exact
is_pushdown_supported as the sole gate before building the Infinity SQL,
mirroring the ES branch at line 880 which uses the guarded ES version.

Reproduction (both real modules, no services needed):

>>> from common import metadata_es_filter as es, metadata_infinity_filter as inf
>>> f = [{"op": "≠", "key": "tag", "value": "a"}]
>>> es.is_pushdown_supported(f), inf.is_pushdown_supported(f)
(False, True)   # ES falls back to in-memory (correct); Infinity pushes down (wrong)

Type of change

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

Fix

Add the same MULTIVALUE_UNSAFE_NEGATIVE_OPS set to
metadata_infinity_filter and reject those operators in
is_pushdown_supported, so a single such filter forces the whole request to
the in-memory path — the only place the per-bucket semantics are reproduced.
not contains is intentionally still allowed, matching the ES backend
(all(not contains) == not any(contains), which the push-down expresses
correctly on multi-valued fields). The ≠ / not in translators themselves
are unchanged — they remain correct for the in-memory-fallback path; only the
push-down eligibility gate is fixed.

Testing

  • Confirmed is_pushdown_supported([{op}]) now returns False for ≠ and
    not in on both backends (previously ES=False, Infinity=True).
  • Added test_pushdown_check_rejects_multivalue_unsafe_negative_ops, which
    asserts both backends reject these ops. Confirmed red→green: it fails against
    the pre-fix Infinity module, passes after.
  • ruff check / ruff format --check clean.

Note on overlap

Open PR #16833 also edits test/unit_test/common/test_metadata_filter.py, but
only appends at the end of the file (line 640+) and changes
metadata_es_filter.py / metadata_utils.py, not the Infinity module — no
overlap with this change.

Disclosure

AI-assisted (Claude Code): the divergence was surfaced by an AI-assisted review
pass, but I independently reproduced it against the real modules, confirmed the
production call path, and verified the fix and test before submitting.

…ative ops (≠, not in)

The Elasticsearch and Infinity metadata push-down translators are meant to be
interchangeable pre-filters that both mirror the in-memory `meta_filter`
fallback -- the shared test section is even titled "is_pushdown_supported
pre-check (same logic for both backends)". But the two `is_pushdown_supported`
implementations diverge: `metadata_es_filter` defines
`MULTIVALUE_UNSAFE_NEGATIVE_OPS = frozenset({"≠", "not in"})` and refuses
push-down for those operators, while `metadata_infinity_filter` has no such
guard and happily pushes them down.

Why that guard exists: `meta_fields.<key>` can hold a JSON array, and the
in-memory `meta_filter` matches a document when ANY of its values satisfies the
predicate (per-value-bucket semantics). A document whose `tag` is `[a, b]`
therefore still matches `tag ≠ a` -- bucket `b` satisfies it. The Infinity
push-down emits `NOT JSON_CONTAINS(meta_fields, '$.tag', '"a"')`, which means
"the array contains no `a` at all", so it silently drops that document. Same
divergence for `not in`. The ES backend avoids this by forcing the whole
request to the in-memory fallback; the Infinity backend did not, so
`tag ≠ a` / `tag not in (...)` under-counted results for any doc that has the
excluded value alongside others.

This is on a live production path: `DocMetadataService._filter_doc_ids_by_
metadata_infinity` (`api/db/services/doc_metadata_service.py:948`) calls this
exact `is_pushdown_supported` as the sole gate before building the Infinity
SQL, mirroring the ES branch at line 880 which uses the guarded ES version.

Fix: add the same `MULTIVALUE_UNSAFE_NEGATIVE_OPS` set to
`metadata_infinity_filter` and reject those operators in
`is_pushdown_supported`, so a single such filter forces the whole request to
the in-memory path -- the only place the per-bucket semantics are reproduced.
`not contains` is intentionally still allowed, matching the ES backend
(`all(not contains)` == `not any(contains)`, which the push-down expresses
correctly on multi-valued fields).

Verified by importing both real modules and confirming
`is_pushdown_supported([{op}])` now returns `False` for `≠` and `not in` on
both backends (previously ES=False, Infinity=True). Added
`test_pushdown_check_rejects_multivalue_unsafe_negative_ops`, which asserts
both backends reject these ops; confirmed red->green (fails on the pre-fix
Infinity module, passes after). `ruff check` / `ruff format --check` clean.

The `≠` / `not in` translators themselves are unchanged -- they remain correct
for the in-memory-fallback path; only the push-down eligibility gate is fixed.

Note: open PR infiniflow#16833 also edits `test/unit_test/common/test_metadata_filter.py`
but only appends at the end of the file (line 640+) and changes
`metadata_es_filter.py` / `metadata_utils.py`, not the Infinity module -- no
overlap with this change.

Signed-off-by: Andrew Chen <[email protected]>
Co-authored-by: Claude Opus 4.8 <[email protected]>
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. labels Jul 15, 2026
@coderabbitai

coderabbitai Bot commented Jul 15, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

Changes

Metadata pushdown eligibility

Layer / File(s) Summary
Reject unsafe negative operators
common/metadata_infinity_filter.py, test/unit_test/common/test_metadata_filter.py
Defines unsafe multivalue negative operators, rejects them during Infinity pushdown checks, and verifies matching rejection in Infinity and ES backends.

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

Suggested reviewers: wangq8

Poem

I’m a rabbit guarding fields in the night,
Keeping unsafe pushes from taking flight.
“≠” and “not in” stay safely behind,
While Infinity and ES walk in kind.
Sniff, test, and hop—everything’s right!

🚥 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 is concise, specific, and accurately summarizes the Infinity push-down fix for unsafe negative metadata operators.
Description check ✅ Passed The description thoroughly explains the problem, fix, and testing, and effectively covers the required summary context.

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.

@yingfeng
yingfeng requested a review from qinling0210 July 15, 2026 08:25
@yingfeng
yingfeng marked this pull request as draft July 15, 2026 08:25
@yingfeng yingfeng added the ci Continue Integration label Jul 15, 2026
@yingfeng
yingfeng marked this pull request as ready for review July 15, 2026 08:25
@codecov

codecov Bot commented Jul 15, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 93.16%. Comparing base (5cf95d2) to head (428f5a4).
⚠️ Report is 15 commits behind head on main.

Additional details and impacted files
@@            Coverage Diff             @@
##             main   #16943      +/-   ##
==========================================
- 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 requested review from yuzhichang and removed request for qinling0210 July 15, 2026 09:14
@zeweihan

Copy link
Copy Markdown

Excellent root-cause analysis — the per-value-bucket quantifier shift is the crux and you nailed exactly why not contains is safe while ≠/not in aren't. Adding a regulated-domain angle:

1. Silent under-counting on negation is the worst-case asymmetry for audit scope. A privilege filter tag ≠ "privileged" should include a document tagged [privileged, public] — bucket public satisfies ≠privileged. But Infinity's NOT JSON_CONTAINS asks "does the array contain no privileged at all?" → excludes the document. Same query, same corpus, different answer set depending on backend, zero error signal. For a production-scope or privilege-review query, "what came back" IS the operative answer — a backend-specific under-count means the scope of what was reviewed is materially different from what should have been reviewed, and nothing in the result set flags it. Same plausible-but-wrong family as the silent-loss class: content correctly present, correctly matches the reference predicate, silently dropped by the push-down shortcut.

2. The asymmetry is quantifier-level, not backend-level. Positive ops (=, in) align because JSON_CONTAINS is ∃v(v=a) which matches per-bucket semantics. Negation (≠, not in) breaks because NOT JSON_CONTAINS is ¬∃v(v=a) = "no value is a", when the correct per-bucket negation is ∀v(v≠a) = "every value isn't a". For multi-valued fields these are not equivalent: ∃v(v≠a) (the in-memory contract) holds whenever any value isn't a. The push-down translation inverts the quantifier from existential to universal — the same predicate string, structurally different meaning. This is why the fix belongs at the push-down eligibility gate (reject, fall back to the only faithful path) rather than attempting a corrected negation translation, which would require a fundamentally different SQL shape.

3. not contains being safe is the subtle confirmation of the model. all(not contains) == not any(contains) — for containment, universal and existential negation coincide. For membership-with-exclusion (≠, not in) they diverge. This distinction is load-bearing for anyone reasoning about which operators are push-down-safe: the safe set isn't "all except negation" but "operators where the existential↔universal shift is a no-op."

4. Companion — cross-backend parity assertion + evaluation-path stamp. The shared test section titled "same logic for both backends" shows the intent was parity, but the divergence survived because there was no runtime parity assertion on a multi-valued test corpus. A metadata_filter_parity_check invariant — same filter expression through both backends and the in-memory reference, assert identical result sets — would have caught this class by construction. Second: a filter_evaluation_backend stamp per result set (es_pushdown / infinity_pushdown / in_memory_fallback) makes "was this query shortcut-evaluated?" queryable, turning the silent backend-specific divergence into an inspectable provenance signal — same philosophy as text_coverage / formula_render_status.

This connects to #16832 (ES .keyword routing silently fatal for date/numeric fields): both are cases where the push-down layer honors most of the filter contract but silently diverges on a specific operator/field-type combination, and the caller has no signal that the shortcut produced a different answer than the reference path would have.

@chuenchen309

Copy link
Copy Markdown
Contributor Author

Thanks @zeweihan — the audit-scope framing is spot on. Silent under-counting on ≠/not in is the dangerous mode precisely because it fails quiet: a doc tagged [privileged, public] should satisfy tag ≠ privileged (bucket public matches), but NOT JSON_CONTAINS drops it. That's exactly why the guard routes those ops to the in-memory fallback (per-value-bucket semantics) instead of pushing down, while not contains stays pushed down since all(not contains) == not any(contains) holds. Appreciate the careful review.

@JinHai-CN
JinHai-CN requested review from qinling0210 and removed request for yuzhichang July 16, 2026 11:19
@JinHai-CN

Copy link
Copy Markdown
Member

@qinling0210 Would you please review this PR?

@qinling0210 qinling0210 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.

LGTM

@yuzhichang
yuzhichang merged commit b7a3a27 into infiniflow:main Jul 18, 2026
24 of 25 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 🌈 python Pull requests that update Python code size:S This PR changes 10-29 lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

6 participants