Repository navigation
Perf: push metadata filters down to Elasticsearch - #14576
Conversation
The meta_filter helper has been loading every document's metadata into memory and applying user conditions in Python, which doesn't scale once a knowledge base grows past a few thousand documents (issue infiniflow#14412). Add common/metadata_es_filter.py — a translator from RAGflow's filter list into Elasticsearch bool DSL — and a new DocMetadataService.filter_doc_ids_by_meta_pushdown method that runs the translated query against ES and returns just the matching doc IDs. apply_meta_data_filter now tries the push-down first when callers pass kb_ids, falling back to the existing in-memory meta_filter whenever the backend isn't ES, the operator can't be expressed, or the request fails. Fixes infiniflow#14412
|
Note Reviews pausedIt looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the Use the following commands to manage reviews:
Use the checkboxes below for quick actions:
No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info⚙️ Run configurationConfiguration used: Organization UI Review profile: CHILL Plan: Pro Run ID: 📒 Files selected for processing (1)
✅ Files skipped from review due to trivial changes (1)
📝 WalkthroughWalkthroughMetadata-filter evaluation now attempts Elasticsearch push-down: new translator and pushdown planner translate filters to ES DSL; DocMetadataService can run pushdown queries; apply_meta_data_filter accepts kb_ids and a lazy metas_loader, trying ES pushdown and falling back to in-memory filtering. Call sites updated to pass kb_ids and metas_loader. ChangesElasticsearch Push-Down Metadata Filtering
sequenceDiagram
participant Client
participant MetadataUtils as apply_meta_data_filter
participant Pushdown as _try_meta_pushdown
participant Service as DocMetadataService
participant ES as Elasticsearch
Client->>MetadataUtils: apply_meta_data_filter(conditions, kb_ids, metas_loader, ...)
MetadataUtils->>Pushdown: _evaluate(conditions, logic, kb_ids)
alt kb_ids present AND plan pushdownable
Pushdown->>Service: filter_doc_ids_by_meta_pushdown(kb_ids, conditions)
alt pushdown supported
Service->>ES: search(translated ES DSL)
ES-->>Service: hits (doc ids)
Service-->>Pushdown: List[str] doc IDs
Pushdown-->>MetadataUtils: doc IDs
else pushdown unsupported or failed
Service-->>Pushdown: None
Pushdown->>MetadataUtils: fallback -> meta_filter(metas_loader())
end
else fallback
Pushdown->>MetadataUtils: meta_filter(metas_loader())
end
MetadataUtils-->>Client: filtered doc IDs or sentinel
Estimated code review effort🎯 4 (Complex) | ⏱️ ~60 minutes Suggested labels
Poem
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. Tip 💬 Introducing Slack Agent: The best way for teams to turn conversations into code.Slack Agent is built on CodeRabbit's deep understanding of your code, so your team can collaborate across the entire SDLC without losing context.
Built for teams:
One agent for your entire SDLC. Right inside Slack. 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: 2
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
common/metadata_utils.py (1)
166-209:⚠️ Potential issue | 🟠 Major | 🏗️ Heavy liftMake
metaslazy or optional here.This function now advertises ES pushdown, but its contract still forces every caller to build
metasfirst. In the updated flows, manual filters still doget_flatted_meta_by_kbs(...)before_try_meta_pushdown()runs, so the full metadata table is still loaded and flattened even when pushdown succeeds. That keeps the original memory/latency bottleneck on the hot path this PR is trying to remove.
🤖 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_es_filter.py`:
- Around line 105-112: to_clauses() currently returns multiple top-level clauses
for a single positive filter which lets parts of that filter be OR'ed
independently; change it so a filter always yields a single atomic clause when
it will be OR'd by the parent. Specifically, update to_clauses() (and the
analogous code at the 136–147 block) so that when self.must is non-empty and the
parent logic is OR (i.e. when the caller will put these into a parent "should"),
you wrap the must list into a single {"bool": {"must": [...]} } entry instead of
returning list(self.must); also ensure the negative-case wrap remains as
{"bool": {"must": list(self.must), "must_not": list(self.must_not)}}. This keeps
each translated filter atomic when to_query() flattens into parent should.
In `@common/metadata_utils.py`:
- Around line 203-209: The ES push-down in _evaluate incorrectly sends negative
operators (≠, not in, not contains) to _try_meta_pushdown when the metadata key
may be multi-valued, producing different results than meta_filter; change
_evaluate to detect any negative operators in the incoming conditions and only
call _try_meta_pushdown for those conditions when you can prove the target key
is single-valued (use the available metas/kb metadata or the same single-valued
check used by get_flatted_meta_by_kbs); otherwise fall back to meta_filter for
those conditions. Apply the same guard to the other affected block (around the
247-267 logic) so negative filters are never pushed into must_not unless the
field is known single-valued.
🪄 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: bf2dfa1d-9c7b-447d-b437-ddf3a379eda8
📒 Files selected for processing (8)
agent/tools/retrieval.pyapi/apps/sdk/session.pyapi/apps/services/dataset_api_service.pyapi/db/services/dialog_service.pyapi/db/services/doc_metadata_service.pycommon/metadata_es_filter.pycommon/metadata_utils.pytest/unit_test/common/test_metadata_es_filter.py
Three correctness/perf fixes from infiniflow#14576 review: 1. Lazy-load `metas` via a new optional `metas_loader` callable so manual filters served by ES push-down skip the full `get_flatted_meta_by_kbs` round-trip — the original bottleneck. Auto and semi_auto modes still materialise `metas` because the LLM needs it; the in-memory fallback also still materialises on demand. 2. `TranslatedFilter.to_clauses()` now wraps multi-clause positive filters in a single `bool: must` so an OR-logic parent `should` cannot match on just one half (e.g. range = `exists` + `range` previously could have leaked the `exists` branch). 3. Reject `≠` and `not in` from push-down (`is_pushdown_supported`). These diverge from `meta_filter` on multi-valued metadata fields: in-memory checks per value bucket, while `must_not term` excludes any doc with the term at all. Without a cheap field-cardinality probe at query time, the only correct answer is in-memory fallback. `not contains` is unaffected — `all(not contains)` ≡ `not any(contains)` so its push-down stays correct. Tests updated for the new range wrap shape; new tests added for push-down rejection of multi-value-unsafe negatives and OR-atomicity. 54/54 unit tests pass.
|
@euvre Could you please review and add any feedbacks? |
qinling0210
left a comment
There was a problem hiding this comment.
Please test to make sure your change works.
Based on my test, apply_meta_data_filter() does not return the doc ids containing the requested meta data when we use Elasticsearch
The dynamic mapping under meta_fields indexes string values as text with a .keyword multi-field. term/terms/prefix/wildcard against the analyzed parent broke for any multi-word value because the inverted index stores per-token entries, not the original phrase. A filter for author="Alice Wonderland" emitted term: meta_fields.author="alice wonderland" against text tokens ["alice", "wonderland"] and matched nothing. Routing string values through <field>.keyword with case_insensitive=true keeps phrase matching aligned with the in-memory meta_filter (full-string compare after lower-casing). Numeric/bool values keep the parent path because dynamic mapping creates no .keyword sub-field for those. Also wraps the empty/not-empty blank check on .keyword so the analyzer's empty-token elision does not let blank-string docs leak through. Verified end-to-end against ES 8.11 with the actual doc_meta_es_mapping: all 9 parity cases now match the in-memory path (was 4 divergences). Reported by qinling0210 in PR review.
|
@qinling0210 thanks — reproduced your finding end-to-end, root-caused it, and pushed a fix in Root cause
The fix routes string values through Before fix — reproReal ES 8.11.3, real After fixUnit testsUpdated the operator-shape assertions in The other metadata test files ( PTAL when you have a moment. |
There was a problem hiding this comment.
🧹 Nitpick comments (2)
common/metadata_es_filter.py (2)
1-67: ⚡ Quick winAdd logging for the new pushdown translation flow.
Per coding guidelines, this new flow should emit logs. Useful breadcrumbs: when a filter is rejected as unsupported (operator/value reason), and ideally a debug-level dump of the rendered ES body so post-fix parity issues like the recent
.keywordmismatch can be diagnosed without redeploys. Today the module has no logging at all, which leaves the routing layer to infer reasons from exception strings only.♻️ Sketch
import ast import re +import logging from dataclasses import dataclass, field from typing import Any, Dict, Iterable, List, Optional, Sequence + +logger = logging.getLogger(__name__)Then, e.g., in
plan_pushdown/translate:for flt in filters: - plan.translated.append(t.translate(flt)) + try: + plan.translated.append(t.translate(flt)) + except UnsupportedMetaFilter as e: + logger.debug("meta pushdown unsupported: %s (filter=%s)", e.reason, flt) + raise return planAs per coding guidelines: "Add logging for new flows".
🤖 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_es_filter.py` around lines 1 - 67, Add logging to the pushdown translation flow: import and create a module-level logger (use Python's logging), then instrument functions plan_pushdown and translate to log (1) WARN when a filter is rejected by raising UnsupportedMetaFilter including the operator/value and a short reason (reference symbols: UnsupportedMetaFilter, SUPPORTED_OPERATORS, META_FIELDS_PREFIX, _DATE_RE), and (2) DEBUG to emit the final rendered Elasticsearch bool body before returning so callers can inspect the exact ES DSL that was produced; ensure the debug dump happens after all field/key normalization (e.g., where ".keyword" selection is applied) and include context like the original filter input and the constructed ES dict.
86-86: ⚡ Quick winDefensively reject multi-value-unsafe negatives in the translator too.
MULTIVALUE_UNSAFE_NEGATIVE_OPS(≠,not in) is only enforced insideis_pushdown_supported.build_meta_filter_queryandplan_pushdownare public entry points that don't run that precheck — calling them directly with≠/not insilently emits an ES body whose semantics diverge from the legacy in-memory path on multi-valued metadata, exactly the parity class the comment at lines 77‑86 warns against. Either gate insidetranslate(raisingUnsupportedMetaFilter) or insideplan_pushdown, so the only way to bypass the guard is the explicit precheck.♻️ Suggested gate
def translate(self, flt: Dict[str, Any]) -> TranslatedFilter: ... if op not in SUPPORTED_OPERATORS: raise UnsupportedMetaFilter(f"unknown operator {op!r}", flt) + if op in MULTIVALUE_UNSAFE_NEGATIVE_OPS: + raise UnsupportedMetaFilter( + f"operator {op!r} cannot be safely pushed down on multi-valued fields", + flt, + )Also applies to: 194-236
🤖 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_es_filter.py` at line 86, The translator currently only enforces MULTIVALUE_UNSAFE_NEGATIVE_OPS inside is_pushdown_supported, but public entry points build_meta_filter_query and plan_pushdown (and translate) can be called directly and must defensively reject multi-value-unsafe negatives; update translate (or plan_pushdown) to check for any operator in MULTIVALUE_UNSAFE_NEGATIVE_OPS and raise UnsupportedMetaFilter when present, so build_meta_filter_query/plan_pushdown cannot produce divergent ES bodies without this explicit guard; reference MULTIVALUE_UNSAFE_NEGATIVE_OPS, translate, plan_pushdown, build_meta_filter_query, is_pushdown_supported, and UnsupportedMetaFilter when adding the check.
🤖 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.
Nitpick comments:
In `@common/metadata_es_filter.py`:
- Around line 1-67: Add logging to the pushdown translation flow: import and
create a module-level logger (use Python's logging), then instrument functions
plan_pushdown and translate to log (1) WARN when a filter is rejected by raising
UnsupportedMetaFilter including the operator/value and a short reason (reference
symbols: UnsupportedMetaFilter, SUPPORTED_OPERATORS, META_FIELDS_PREFIX,
_DATE_RE), and (2) DEBUG to emit the final rendered Elasticsearch bool body
before returning so callers can inspect the exact ES DSL that was produced;
ensure the debug dump happens after all field/key normalization (e.g., where
".keyword" selection is applied) and include context like the original filter
input and the constructed ES dict.
- Line 86: The translator currently only enforces MULTIVALUE_UNSAFE_NEGATIVE_OPS
inside is_pushdown_supported, but public entry points build_meta_filter_query
and plan_pushdown (and translate) can be called directly and must defensively
reject multi-value-unsafe negatives; update translate (or plan_pushdown) to
check for any operator in MULTIVALUE_UNSAFE_NEGATIVE_OPS and raise
UnsupportedMetaFilter when present, so build_meta_filter_query/plan_pushdown
cannot produce divergent ES bodies without this explicit guard; reference
MULTIVALUE_UNSAFE_NEGATIVE_OPS, translate, plan_pushdown,
build_meta_filter_query, is_pushdown_supported, and UnsupportedMetaFilter when
adding the check.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro
Run ID: 8100ef25-f309-4a33-8474-653d60af8227
📒 Files selected for processing (2)
common/metadata_es_filter.pytest/unit_test/common/test_metadata_es_filter.py
🚧 Files skipped from review as they are similar to previous changes (1)
- test/unit_test/common/test_metadata_es_filter.py
Codecov Report✅ All modified and coverable lines are covered by tests. Additional details and impacted files@@ Coverage Diff @@
## main #14576 +/- ##
=======================================
Coverage 94.16% 94.16%
=======================================
Files 10 10
Lines 703 703
Branches 112 112
=======================================
Hits 662 662
Misses 25 25
Partials 16 16 ☔ View full report in Codecov by Sentry. 🚀 New features to boost your workflow:
|
|
@sxxtony , please analyze the CI failure, it failed on test/testcases/test_http_api/test_session_management/test_session_sdk_routes_unit.py::test_searchbots_retrieval_test_embedded_matrix_unit |
### What problem does this PR solve? Fixes infiniflow#14412. `common.metadata_utils.meta_filter` evaluates user-defined metadata conditions in Python after `DocMetadataService.get_flatted_meta_by_kbs` loads the entire `meta_fields` table into memory. Past a few thousand documents per knowledge base this becomes a memory bottleneck and a wasted ES round-trip — every filter request currently fetches up to 10000 metadata rows even when the resulting `doc_ids` list is tiny. This PR adds an ES push-down path that translates the same filter language into a `bool` query and returns just the matching document IDs. **Changes** - `common/metadata_es_filter.py` *(new)*: pure-Python translator from the RAGflow filter list to ES DSL. Covers every operator the in-memory path supports (`=`, `≠`, `>`, `<`, `≥`, `≤`, `in`, `not in`, `contains`, `not contains`, `start with`, `end with`, `empty`, `not empty`) with `case_insensitive: true` on `prefix` and `wildcard` for parity with the existing lower-cased Python comparisons. User wildcard metacharacters are escaped before being injected into `wildcard` patterns. Negative operators (`≠`, `not in`, `not contains`, ranges) are wrapped with an `exists` guard so they do not accidentally match documents missing the key, matching the legacy `if k not in metas` behaviour. - `api/db/services/doc_metadata_service.py`: new `DocMetadataService.filter_doc_ids_by_meta_pushdown(kb_ids, filters, logic)` that returns the doc IDs ES matched, or `None` to signal the caller should fall back to the in-memory path. Returns `None` when the active doc store is Infinity (`meta_fields` is a JSON column, not a dotted-object mapping), when any filter cannot be expressed in DSL (`UnsupportedMetaFilter`), or when the ES request or metadata index lookup errors. - `common/metadata_utils.py`: `apply_meta_data_filter` accepts an optional `kb_ids` argument. When supplied, conditions go through push-down first via a new `_try_meta_pushdown` helper; on `None` the function falls back to the original `meta_filter` call. Default behaviour is unchanged for callers that don't pass `kb_ids`. - Updated all four callers (`agent/tools/retrieval.py`, `api/db/services/dialog_service.py` ×2, `api/apps/services/dataset_api_service.py`, `api/apps/sdk/session.py`) to forward `kb_ids` so the push-down path is exercised in production. - `test/unit_test/common/test_metadata_es_filter.py` *(new)*: 35 unit tests covering every operator's DSL shape, value coercion (`ast.literal_eval`, lowercasing, ISO-date pass-through), wildcard escaping, OR-logic wrapping that protects negative clauses, and the doc-ID extractor. **Behaviour preserved** - The in-memory `meta_filter` is untouched and still services every fallback case (Infinity backend, unknown operators, ES outages). - The eligibility / credibility / issue-multiplier semantics described in the LLM-driven `auto` and `semi_auto` modes still hand the LLM the full in-memory `metas` dict to choose conditions from. Only the *evaluation* of those generated conditions is pushed down. - Existing tests in `test/unit_test/common/test_metadata_filter_operators.py` continue to pass (14/14). **Test plan** - `pytest test/unit_test/common/test_metadata_es_filter.py` — 35 passed. - `pytest test/unit_test/common/test_metadata_filter_operators.py` — 14 passed. - `ruff check` clean on every modified file. - Reviewer please validate the ES query shapes against a live cluster — particularly `case_insensitive` on `wildcard` and `prefix` (requires ES 7.10+) and the `exists` + `must_not` pairing for `≠`. **Notes** - The first cut caps each push-down request at 10000 results, matching the existing `get_flatted_meta_by_kbs` limit, and logs a warning when the cap is hit. A `search_after` follow-up would let us drop the cap entirely once the push-down path is validated. - Operator parity with the in-memory path is exact for the canonical unicode operators (`≥`, `≤`, `≠`) used internally; the ASCII aliases (`>=`, `<=`, `!=`) are normalised by `convert_conditions` before they reach the translator. ### Type of change - [x] Performance Improvement --------- Co-authored-by: sxxtony <[email protected]>
### What problem does this PR solve? Fixes infiniflow#14412. `common.metadata_utils.meta_filter` evaluates user-defined metadata conditions in Python after `DocMetadataService.get_flatted_meta_by_kbs` loads the entire `meta_fields` table into memory. Past a few thousand documents per knowledge base this becomes a memory bottleneck and a wasted ES round-trip — every filter request currently fetches up to 10000 metadata rows even when the resulting `doc_ids` list is tiny. This PR adds an ES push-down path that translates the same filter language into a `bool` query and returns just the matching document IDs. **Changes** - `common/metadata_es_filter.py` *(new)*: pure-Python translator from the RAGflow filter list to ES DSL. Covers every operator the in-memory path supports (`=`, `≠`, `>`, `<`, `≥`, `≤`, `in`, `not in`, `contains`, `not contains`, `start with`, `end with`, `empty`, `not empty`) with `case_insensitive: true` on `prefix` and `wildcard` for parity with the existing lower-cased Python comparisons. User wildcard metacharacters are escaped before being injected into `wildcard` patterns. Negative operators (`≠`, `not in`, `not contains`, ranges) are wrapped with an `exists` guard so they do not accidentally match documents missing the key, matching the legacy `if k not in metas` behaviour. - `api/db/services/doc_metadata_service.py`: new `DocMetadataService.filter_doc_ids_by_meta_pushdown(kb_ids, filters, logic)` that returns the doc IDs ES matched, or `None` to signal the caller should fall back to the in-memory path. Returns `None` when the active doc store is Infinity (`meta_fields` is a JSON column, not a dotted-object mapping), when any filter cannot be expressed in DSL (`UnsupportedMetaFilter`), or when the ES request or metadata index lookup errors. - `common/metadata_utils.py`: `apply_meta_data_filter` accepts an optional `kb_ids` argument. When supplied, conditions go through push-down first via a new `_try_meta_pushdown` helper; on `None` the function falls back to the original `meta_filter` call. Default behaviour is unchanged for callers that don't pass `kb_ids`. - Updated all four callers (`agent/tools/retrieval.py`, `api/db/services/dialog_service.py` ×2, `api/apps/services/dataset_api_service.py`, `api/apps/sdk/session.py`) to forward `kb_ids` so the push-down path is exercised in production. - `test/unit_test/common/test_metadata_es_filter.py` *(new)*: 35 unit tests covering every operator's DSL shape, value coercion (`ast.literal_eval`, lowercasing, ISO-date pass-through), wildcard escaping, OR-logic wrapping that protects negative clauses, and the doc-ID extractor. **Behaviour preserved** - The in-memory `meta_filter` is untouched and still services every fallback case (Infinity backend, unknown operators, ES outages). - The eligibility / credibility / issue-multiplier semantics described in the LLM-driven `auto` and `semi_auto` modes still hand the LLM the full in-memory `metas` dict to choose conditions from. Only the *evaluation* of those generated conditions is pushed down. - Existing tests in `test/unit_test/common/test_metadata_filter_operators.py` continue to pass (14/14). **Test plan** - `pytest test/unit_test/common/test_metadata_es_filter.py` — 35 passed. - `pytest test/unit_test/common/test_metadata_filter_operators.py` — 14 passed. - `ruff check` clean on every modified file. - Reviewer please validate the ES query shapes against a live cluster — particularly `case_insensitive` on `wildcard` and `prefix` (requires ES 7.10+) and the `exists` + `must_not` pairing for `≠`. **Notes** - The first cut caps each push-down request at 10000 results, matching the existing `get_flatted_meta_by_kbs` limit, and logs a warning when the cap is hit. A `search_after` follow-up would let us drop the cap entirely once the push-down path is validated. - Operator parity with the in-memory path is exact for the canonical unicode operators (`≥`, `≤`, `≠`) used internally; the ASCII aliases (`>=`, `<=`, `!=`) are normalised by `convert_conditions` before they reach the translator. ### Type of change - [x] Performance Improvement --------- Co-authored-by: sxxtony <[email protected]>
What problem does this PR solve?
Fixes #14412.
common.metadata_utils.meta_filterevaluates user-defined metadata conditions in Python afterDocMetadataService.get_flatted_meta_by_kbsloads the entiremeta_fieldstable into memory. Past a few thousand documents per knowledge base this becomes a memory bottleneck and a wasted ES round-trip — every filter request currently fetches up to 10000 metadata rows even when the resultingdoc_idslist is tiny.This PR adds an ES push-down path that translates the same filter language into a
boolquery and returns just the matching document IDs.Changes
common/metadata_es_filter.py(new): pure-Python translator from the RAGflow filter list to ES DSL. Covers every operator the in-memory path supports (=,≠,>,<,≥,≤,in,not in,contains,not contains,start with,end with,empty,not empty) withcase_insensitive: trueonprefixandwildcardfor parity with the existing lower-cased Python comparisons. User wildcard metacharacters are escaped before being injected intowildcardpatterns. Negative operators (≠,not in,not contains, ranges) are wrapped with anexistsguard so they do not accidentally match documents missing the key, matching the legacyif k not in metasbehaviour.api/db/services/doc_metadata_service.py: newDocMetadataService.filter_doc_ids_by_meta_pushdown(kb_ids, filters, logic)that returns the doc IDs ES matched, orNoneto signal the caller should fall back to the in-memory path. ReturnsNonewhen the active doc store is Infinity (meta_fieldsis a JSON column, not a dotted-object mapping), when any filter cannot be expressed in DSL (UnsupportedMetaFilter), or when the ES request or metadata index lookup errors.common/metadata_utils.py:apply_meta_data_filteraccepts an optionalkb_idsargument. When supplied, conditions go through push-down first via a new_try_meta_pushdownhelper; onNonethe function falls back to the originalmeta_filtercall. Default behaviour is unchanged for callers that don't passkb_ids.agent/tools/retrieval.py,api/db/services/dialog_service.py×2,api/apps/services/dataset_api_service.py,api/apps/sdk/session.py) to forwardkb_idsso the push-down path is exercised in production.test/unit_test/common/test_metadata_es_filter.py(new): 35 unit tests covering every operator's DSL shape, value coercion (ast.literal_eval, lowercasing, ISO-date pass-through), wildcard escaping, OR-logic wrapping that protects negative clauses, and the doc-ID extractor.Behaviour preserved
meta_filteris untouched and still services every fallback case (Infinity backend, unknown operators, ES outages).autoandsemi_automodes still hand the LLM the full in-memorymetasdict to choose conditions from. Only the evaluation of those generated conditions is pushed down.test/unit_test/common/test_metadata_filter_operators.pycontinue to pass (14/14).Test plan
pytest test/unit_test/common/test_metadata_es_filter.py— 35 passed.pytest test/unit_test/common/test_metadata_filter_operators.py— 14 passed.ruff checkclean on every modified file.case_insensitiveonwildcardandprefix(requires ES 7.10+) and theexists+must_notpairing for≠.Notes
get_flatted_meta_by_kbslimit, and logs a warning when the cap is hit. Asearch_afterfollow-up would let us drop the cap entirely once the push-down path is validated.≥,≤,≠) used internally; the ASCII aliases (>=,<=,!=) are normalised byconvert_conditionsbefore they reach the translator.Type of change