Repository navigation
feat: accept array_any_match lambda filters by rewriting them to any_element - #10947
Merged
BubbleCal merged 1 commit intoNov 11, 2026
Merged
Conversation
…element
Filters can now use the lambda form for per-element predicates on
list<struct> columns:
array_any_match(detections, d -> d.label = 'car' AND d.confidence > 0.9)
While parsing the filter, Lance rewrites it to
any_element(detections, 'label = ''car'' AND confidence > 0.9'), so the
lambda never reaches DataFusion's lambda planning, Substrait or execution.
any_match is an alias, and fields can be written d.label or d['label'].
Other lambda shapes are rejected with a clear error.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
BubbleCal
approved these changes
Nov 11, 2026
Xuanwo
added a commit
that referenced
this pull request
Nov 11, 2026
## Summary `Planner::parse_filter` rewrites `array_any_match` lambdas before planning (#10947). Both rewrite passes use sqlparser's recursive visitors, but a filter such as `a AND b AND ...` parses as a chain as deep as its number of operands. The visitors therefore overflowed the stack in `planner::tests::test_parse_deep_logical_filter`, aborting the test process on current main (`67b2821`) and on #10716's integrated head, before #7510's iterative `flatten_logical_binary_exprs` / `balanced_binary_expr` protection could run. This change balances each `AND`/`OR` chain in the parsed SQL AST before those visitors traverse it. Balancing uses an explicit stack and rebuilds a chain only with the same operator, so `AND` and `OR` are never mixed. `binary_expr` already rebuilds the same chains balanced after parsing, so parsed expressions and evaluation are unchanged. The pre-pass also makes a deep lambda body shallow before it is cloned, checked and printed. The function documentation now states this regrouping and why it bounds visitor depth. ## Tests Added regressions in `udf::element` using the existing `any_element` fixture: - a 1000-operand `OR` chain of real `array_any_match` calls below `NOT`, evaluated against independent expected rows; - a lambda body with 1000 `OR` predicates, covering the body clone/check/format path. Added the far-end-lambda AST regression adapted from #10953 (thanks @sarwarbhuiyan): a 1000-condition `AND`/`OR` chain with a lambda at the end is walked by its leaves with an explicit stack, checking that the last leaf is the rewritten `any_element` call and that no lambda remains. The walk does not assume the parsed left-deep shape, which this change rebalances. All three abort with SIGABRT on unfixed main and pass with this change. The existing 1000-operand `AND`/`OR` `test_parse_deep_logical_filter` is unchanged in depth and assertions. Commands run on this head: - `cargo test --profile ci -p lance-datafusion --lib` (381 passed) - `cargo test --profile ci -p lance-datafusion --all-features --lib` (431 passed) - `cargo test --profile ci -p lance --lib -- dataset::tests::dataset_scanner::test_any_element` (13 passed) - `cargo test --profile ci -p lance --lib -- dataset::tests::dataset_scanner::test_lambda_filter_rejects_unsupported_forms` (2 passed) - `cargo fmt --all -- --check` - `cargo clippy --profile ci --all --tests --benches -- -D warnings` ## Context Regression introduced by #10947 over the deep-filter protection added for #7510. This PR repairs that base failure and does not close either issue. No performance measurement is claimed: the regrouping cost is only derived statically as O(n log n) per logical node. --------- Co-authored-by: Sarwar Bhuiyan <[email protected]>
BubbleCal
pushed a commit
that referenced
this pull request
Nov 12, 2026
… elements (#10950) ## Summary Adds `listelement`, an experimental built-in scalar index over fields inside the elements of a `list<struct>` column. It answers `any_element` filters (#10901) from the index, with every condition on the same element: ```python dataset.create_scalar_index( "detections", IndexConfig(index_type="listelement", parameters={"keys": ["label", "confidence"]}), ) dataset.to_table(filter="any_element(detections, 'label = ''car'' AND confidence > 0.9')") ``` This is the second part of #10900. The format is specified in #10949, and the design discussion is #10948. **Depends on #10949.** This PR carries the identical `protos/index.proto` change and generated source so that it compiles. Those changes drop out when this branch is rebased after #10949 merges. ## Design - **Training:** one entry per element. - The key is the element's `keys` fields as a tuple, encoded with Arrow's row format (ascending, nulls first), so the bytes sort like the tuples. - The posting is the row address. - Entries are sorted with spilling, and an ordinary BTREE is trained over the `Binary` keys. The index wraps the BTREE the way the JSON index wraps its target. - **Search:** `visit_scalar_function` claims `any_element(<indexed column>, '<literal>')`. The predicate is planned exactly as `any_element` plans it, then with the tuple planner (`plan_tuple_predicate`) over the keys. - **Seeks:** an `=`, `IN` or `IS NULL` prefix, then one range on the next key, becomes byte-range seeks in the BTREE. - **Superset and recheck:** conditions the keys can't express, such as a field that isn't a key, make the answer a superset. The scan then rechecks it with `any_element`. - **No first key, no index:** without a condition on the first key, the index declines. - **NULLs:** NULL lists, and elements on which the predicate is NULL, are tracked, so `NOT` is exact. - **Maintenance:** update encodes the new fragments the same way, then defers to the BTREE. Remap defers to the BTREE. - **Row addresses:** in `lance-table`, the index joins the row-address and eager-remap lists. On stable-row-ID tables, the #10352 writer fence applies and compaction remaps the index. - **`lance-datafusion` API:** it exports `ANY_ELEMENT`, `any_element_predicate` and `plan_element_predicate`, so the index plans the same expression the scan evaluates. `lance-index` now depends on `lance-datafusion` as a normal dependency; there's no cycle. ## Fix included On a stable-row-ID table, `optimize_indices` dropped old entries of a row-address index outside fragment 0. The generic update arm in `merge_scalar_indices` only treated the JSON index as storing row addresses, so it filtered row addresses against row IDs. That arm now also covers this index. JSON behavior is unchanged. ## Tests - **Index unit tests** (13): - same-element trap, every range operator, `IN`, label-only prefix, recheck; - NULL rows for `NOT`; - shapes the index declines; - details round trip, and invalid parameters (no keys, unknown key, repeated key, nested key type, unknown parameter, non-struct list); - segment key mismatch, an all-null column, and the spec's encoding bytes. - **`lance-table`:** row-address and eager-remap classification. - **Dataset tests:** #10901's fixture is extended rather than duplicated. - Every filter case, plus the edge-row and invalid-predicate tests, runs with and without the index, checking the plan and whether it rechecks. - New: declining when the first key isn't constrained; `fast_search` plus `optimize_indices`; delete plus compaction remap, with and without stable row IDs. ## Docs The read and write guide covers creating the index and which filters it answers, and the scalar indexing guide has a row for it. Both mark it experimental. ## Not in this PR - **Training memory:** there's no explicit budget. Like the JSON index, training uses the default spill pool. At 100M elements the prototype needed `LANCE_MEM_POOL_SIZE=8GiB`. - **Merging segments** for distributed builds. - **Fragment reuse index:** batch row-ID remapping isn't supported. Like JSON, the index is reported incompatible on stable-row-ID tables that use a fragment reuse index. Closes #10900. This conflicts with #10947 in the dataset scanner tests and the guide. Whichever merges second will rebase. Lint: `cargo fmt --all`, and `cargo clippy --no-deps -p lance-datafusion -p lance-index -p lance-table -p lance --tests --benches --features lance-datafusion/substrait -- -D warnings`. With dependencies included, clippy on arm64 currently fails in `lance-encoding` (`unreachable_code` from #10905), which this PR doesn't touch. 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Opus 5.5 <[email protected]>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
Filters can now use the lambda form for per-element predicates on
list<struct>columns:While parsing the filter, Lance rewrites it to the
any_elementcall from #10901:any_element(detections, 'label = ''car'' AND confidence > 0.9')The two forms behave the same. The lambda never reaches DataFusion's lambda planning, Substrait or execution, so the DataFusion gaps listed in #10873 don't apply.
This is track 1 of #10873. General lambda support, track 2, still waits on DataFusion.
Design
LanceDialectenablessupports_lambda_functions. Without it,->parses as the JSON arrow operator, which Lance already rejects, so no accepted filter changes meaning.->>is unaffected.Planner::parse_filterrewrites the parsed SQL before planning it.array_any_matchand its aliasany_matchwith a one-parameter lambda becomeany_element(list, '<body>'):d.label,d.details.kindandd['my field']becomelabel,details.kindand`my field`.list<struct>column. Its type is checked against the schema.any_elementcan't express:labelwithout the parameter;d IS NOT NULL);d[1]);list<struct>;array_filter, or outside a function.Tests
->>is not a lambda.NOT,ANDand another function call. 9 error cases, each checked for a message that says what to change.NOTcombined with an indexed column. Each is checked against a reference evaluation with and without the scalar index, and throughcount_rows.count_rows.Docs
A paragraph on the lambda form in the "Filtering on elements of a list of structs" section of the read and write guide.
Part of #10873.
Lint:
cargo fmt --all, andcargo clippy --no-deps -p lance-datafusion -p lance --features lance-datafusion/substrait --tests -- -D warnings. With dependencies included, clippy on arm64 currently fails inlance-encoding(unreachable_codeinbyte_stream_split.rs, from #10905). That code isn't touched here, and x86 CI doesn't hit it.🤖 Generated with Claude Code