From 04bf27af9d44c152c9310b597935c2b7c70ee98e Mon Sep 17 00:00:00 2001 From: wangshun <96341168+xixi-box@users.noreply.github.com> Date: Mon, 30 Nov 2026 20:38:51 +0800 Subject: [PATCH] feat: support IN subqueries in Embedded search filters (#5223) Fixes #5222 ## Summary Embedded vector and full-text searches rejected `IN (SELECT ...)` because Lance's scanner parsed the filter as a single-table expression. A team-scoped search with `limit(1)` needs to rank eligible documents using keys from the sharing table. Resolve unqualified lookup tables through the originating database and use DataFusion to evaluate the predicate on the search snapshot. Pass the matching row IDs to Lance before ranking. The syntax applies to base-table prefilters within one namespace. Literal filters use the existing scanner path. ## Tests Tests: `/bin/sh -c 'cd nodejs && corepack pnpm test --runInBand __test__/query.test.ts -t '"'"'prefilters by keys from another table'"'"''`. Result: cd nodejs && corepack pnpm test --runInBand __test__/query.test.ts on the exact-HEAD published native binary before adding tests: 41 passed. Result: cd nodejs && corepack pnpm test --runInBand __test__/query.test.ts -t 'prefilters by keys from another table' on the exact-HEAD published native binary: 2 failed with the reported unsupported SQL expression, exit 1 (OSSCOUT_BASE.log). Result: cd nodejs && corepack pnpm lint: passed after correcting new fixture key style. Result: cargo fmt --all && git diff --check: passed. Result: cd nodejs && corepack pnpm test --runInBand --runTestsByPath __test__/expr.test.ts __test__/remote.test.ts on the exact-HEAD published native binary: 179 passed across 2 suites. Result: cd nodejs && corepack pnpm tsc && corepack pnpm run docs with the exact-HEAD native declarations: passed, with no generated documentation changes. Result: cd nodejs && corepack pnpm build:debug --profile ci && corepack pnpm tsc: passed from the patched source. Result: cd nodejs && corepack pnpm test --runInBand __test__/query.test.ts -t 'prefilters by keys from another table' on the source-built patch: 2 passed, exit 0 (OSSCOUT_PATCHED.log). Result: cd nodejs && corepack pnpm test --runInBand --runTestsByPath __test__/query.test.ts __test__/expr.test.ts __test__/remote.test.ts on the source-built patch: 225 passed across 3 suites, exit 0 (OSSCOUT_PATCHED.log). Result: cd nodejs && corepack pnpm run docs on the source-built patch: passed, with no generated documentation changes. Regression coverage: `nodejs/__test__/query.test.ts`. --------- Signed-off-by: wangshun <96341168+xixi-box@users.noreply.github.com> --- docs/web/search/filtering.mdx | 51 + nodejs/__test__/query.test.ts | 95 ++ python/python/lancedb/_lancedb.pyi | 4 + python/python/lancedb/query.py | 56 +- python/python/lancedb/table.py | 5 +- python/python/tests/test_namespace.py | 116 +++ python/src/lib.rs | 7 + python/src/query.rs | 17 + rust/lancedb/src/expr.rs | 2 +- rust/lancedb/src/expr/sql.rs | 6 +- rust/lancedb/src/query.rs | 56 + rust/lancedb/src/table.rs | 2 +- rust/lancedb/src/table/query.rs | 80 +- .../src/table/query/subquery_filter.rs | 985 ++++++++++++++++++ 14 files changed, 1464 insertions(+), 18 deletions(-) create mode 100644 rust/lancedb/src/table/query/subquery_filter.rs diff --git a/docs/web/search/filtering.mdx b/docs/web/search/filtering.mdx index 58c974614..a1721a6ad 100644 --- a/docs/web/search/filtering.mdx +++ b/docs/web/search/filtering.mdx @@ -59,6 +59,57 @@ vector and full-text searches. SDK filters use SQL expressions without requiring a SQL connection. For Enterprise SQL queries, see [SELECT](/sql/dql/select#filtering). +## Prefilter with keys from another table {#prefilter-with-subquery} + +In LanceDB Embedded, use `IN (SELECT ...)` to restrict vector or full-text +search to keys in another table in the same namespace. Use unqualified table +names in the subquery. LanceDB computes the matching row IDs before ranking +candidates, so `limit(1)` returns the best eligible row. When namespace query +pushdown is enabled, this filter requires the client to have access to the +table storage. + +Use a positive `IN (SELECT ...)` predicate on its own or join it to other +conditions with `AND`. `OR` is allowed in a separate condition, such as +`(status = 'draft' OR status = 'published') AND document_id IN (SELECT document_id FROM team_documents)`. +A membership subquery wrapped in `OR`, `NOT`, or `IS NULL`, a `NOT IN (SELECT ...)` +predicate, or a nested membership subquery returns an error. Literal `IN` +and `NOT IN` lists keep their usual behavior. + + +```python Python icon="python" +matches = ( + chunks.search(query_vector) + .where( + "document_id IN (SELECT document_id FROM team_documents WHERE team_id = 'Team 1')" + ) + .limit(1) + .to_arrow() +) +``` + +```typescript TypeScript icon="square-js" +const matches = await chunks + .vectorSearch(queryVector) + .where( + "document_id IN (SELECT document_id FROM team_documents WHERE team_id = 'Team 1')", + ) + .limit(1) + .toArray(); +``` + +```rust Rust icon="rust" +use lancedb::query::{ExecutableQuery, QueryBase}; + +let matches = chunks + .query() + .nearest_to(query_vector)? + .only_if("document_id IN (SELECT document_id FROM team_documents WHERE team_id = 'Team 1')") + .limit(1) + .execute() + .await?; +``` + + ## Filtering examples by language {#example-metadata-filtering} The following excerpts use a connected `db` handle. Create this sample table diff --git a/nodejs/__test__/query.test.ts b/nodejs/__test__/query.test.ts index a911372ec..dd2424d67 100644 --- a/nodejs/__test__/query.test.ts +++ b/nodejs/__test__/query.test.ts @@ -15,6 +15,101 @@ import { } from "../lancedb/arrow"; import { Index } from "../lancedb/indices"; +describe("Search subquery filters", () => { + const documentIdColumn = "document_id"; + const teamIdColumn = "team_id"; + let tmpDir: tmp.DirResult; + let chunks: Table; + let teamDocuments: Table; + + beforeEach(async () => { + tmpDir = tmp.dirSync({ unsafeCleanup: true }); + const db = await connect(tmpDir.name); + chunks = await db.createTable("chunks", [ + { [documentIdColumn]: "AAA", text: "cat cat cat cat", vector: [0, 0] }, + { [documentIdColumn]: "BBB", text: "cat dog dog dog", vector: [1, 1] }, + ]); + await chunks.createIndex("text", { config: Index.fts() }); + teamDocuments = await db.createTable("team_documents", [ + { [teamIdColumn]: "Team 1", [documentIdColumn]: "BBB" }, + { [teamIdColumn]: "Team 1", [documentIdColumn]: "BBB" }, + { [teamIdColumn]: "Team 2", [documentIdColumn]: "AAA" }, + ]); + }); + + afterEach(() => { + tmpDir.removeCallback(); + }); + + it.each(["vector", "fts"])( + "%s search prefilters by keys from another table", + async (kind) => { + const search = () => + (kind === "vector" + ? chunks.vectorSearch([0, 0]) + : chunks.search("cat", "fts") + ).limit(1); + const ids = async (query: ReturnType) => + (await query.toArray()).map((row) => row[documentIdColumn]); + + expect(await ids(search())).toEqual(["AAA"]); + expect(await ids(search().where("document_id IN ('BBB')"))).toEqual([ + "BBB", + ]); + + const predicate = (team: string) => + `document_id IN (SELECT "document_id" FROM team_documents WHERE team_id = '${team}')`; + expect( + await ids( + search().where("document_id IS NOT NULL").where(predicate("Team 1")), + ), + ).toEqual(["BBB"]); + expect( + await ids( + search().where("document_id = 'AAA'").where(predicate("Team 1")), + ), + ).toEqual([]); + expect(await ids(search().where(predicate("Missing team")))).toEqual([]); + }, + ); + + it.each(["flat", "indexed"])( + "%s vector search reads current keys on repeated execution", + async (kind) => { + if (kind === "indexed") { + await chunks.createIndex("vector", { + config: Index.ivfFlat({ numPartitions: 1 }), + }); + } + const query = chunks + .vectorSearch([0, 0]) + .where( + "document_id IN (SELECT document_id FROM team_documents WHERE team_id = 'Team 1')", + ) + .limit(1); + expect( + (await query.toArray()).map((row) => row[documentIdColumn]), + ).toEqual(["BBB"]); + await teamDocuments.add([ + { [teamIdColumn]: "Team 1", [documentIdColumn]: "AAA" }, + ]); + expect( + (await query.toArray()).map((row) => row[documentIdColumn]), + ).toEqual(["AAA"]); + }, + ); + + it("rejects a missing lookup table and explicit postfiltering", async () => { + const filter = "document_id IN (SELECT document_id FROM missing_table)"; + await expect( + chunks.vectorSearch([0, 0]).where(filter).toArray(), + ).rejects.toThrow(/missing_table/); + await expect( + chunks.vectorSearch([0, 0]).postfilter().where(filter).toArray(), + ).rejects.toThrow("SQL subquery filters require prefiltering"); + }); +}); + describe("Query outputSchema", () => { let tmpDir: tmp.DirResult; let table: Table; diff --git a/python/python/lancedb/_lancedb.pyi b/python/python/lancedb/_lancedb.pyi index be19b1210..0468d9033 100644 --- a/python/python/lancedb/_lancedb.pyi +++ b/python/python/lancedb/_lancedb.pyi @@ -46,6 +46,10 @@ _experimental_functions_enabled: bool def _doc_url(campaign: str) -> str: ... def _append_doc_url(message: str, campaign: str) -> str: ... +def _uses_sql_subquery_filter(sql: str) -> bool: ... +async def _share_hybrid_subquery_filter( + fts: FTSQuery, vector: VectorQuery +) -> tuple[FTSQuery, VectorQuery]: ... def _parse_field_path(path: str) -> List[str]: ... IvfHnswPq: type[HnswPq] = HnswPq diff --git a/python/python/lancedb/query.py b/python/python/lancedb/query.py index 1809775c5..e2b1f475c 100644 --- a/python/python/lancedb/query.py +++ b/python/python/lancedb/query.py @@ -32,7 +32,11 @@ import pydantic from pydantic_core import PydanticUndefined from typing_extensions import Annotated -from lancedb._lancedb import fts_query_to_json +from lancedb._lancedb import ( + _share_hybrid_subquery_filter, + _uses_sql_subquery_filter, + fts_query_to_json, +) from lancedb.background_loop import LOOP from . import __version__ from .arrow import AsyncRecordBatchReader @@ -3392,11 +3396,26 @@ class LanceHybridQueryBuilder(LanceQueryBuilder): if self._pk_fusion is None: fts_query = fts_query.with_row_id(True) vector_query = vector_query.with_row_id(True) - with ThreadPoolExecutor() as executor: - fts_future = executor.submit(fts_query.to_arrow, timeout=timeout) - vector_future = executor.submit(vector_query.to_arrow, timeout=timeout) - fts_results = fts_future.result() - vector_results = vector_future.result() + if ( + isinstance(self._where, str) + and _uses_sql_subquery_filter(self._where) + and not _is_remote_query_table(self._table) + ): + # Keep the existing Python reranker, but prepare the two native + # legs together so they use the same snapshot and eligibility mask. + self._table._ensure_no_legacy_fts_index() + async_table = self._table._table + fts = async_table._sync_query_to_async(fts_query.to_query_object()) + vec = async_table._sync_query_to_async(vector_query.to_query_object()) + fts_results, vector_results = LOOP.run( + _execute_hybrid_subquery_legs(fts, vec, timeout) + ) + else: + with ThreadPoolExecutor() as executor: + fts_future = executor.submit(fts_query.to_arrow, timeout=timeout) + vector_future = executor.submit(vector_query.to_arrow, timeout=timeout) + fts_results = fts_future.result() + vector_results = vector_future.result() if self._pk_fusion is not None: # WAL-PK-FUSION: delete. vector_results, fts_results = self._pk_fusion.stamp( vector_results, fts_results @@ -5738,6 +5757,18 @@ class AsyncVectorQuery(AsyncStandardQuery, AsyncVectorQueryBase): return AsyncRecordBatchReader(results, max_batch_length=max_batch_length) +async def _execute_hybrid_subquery_legs( + fts: AsyncFTSQuery, vector: AsyncVectorQuery, timeout: Optional[timedelta] +) -> tuple[pa.Table, pa.Table]: + fts._inner, vector._inner = await _share_hybrid_subquery_filter( + fts._inner, vector._inner + ) + fts_results, vector_results = await asyncio.gather( + fts.to_arrow(timeout=timeout), vector.to_arrow(timeout=timeout) + ) + return fts_results, vector_results + + class AsyncHybridQuery(AsyncStandardQuery, AsyncVectorQueryBase): """ A query builder that performs hybrid vector and full text search. @@ -5908,10 +5939,15 @@ class AsyncHybridQuery(AsyncStandardQuery, AsyncVectorQueryBase): self._blob_auto_row_id = blob_auto_row_id self._blob_paths = blob_paths - fts_results, vector_results = await asyncio.gather( - fts_query.to_arrow(timeout=timeout), - vec_query.to_arrow(timeout=timeout), - ) + if isinstance(req.filter, str) and _uses_sql_subquery_filter(req.filter): + fts_results, vector_results = await _execute_hybrid_subquery_legs( + fts_query, vec_query, timeout + ) + else: + fts_results, vector_results = await asyncio.gather( + fts_query.to_arrow(timeout=timeout), + vec_query.to_arrow(timeout=timeout), + ) if self._pk_fusion is not None: # WAL-PK-FUSION: delete. vector_results, fts_results = self._pk_fusion.stamp( vector_results, fts_results diff --git a/python/python/lancedb/table.py b/python/python/lancedb/table.py index 299243b45..5dc627eb3 100644 --- a/python/python/lancedb/table.py +++ b/python/python/lancedb/table.py @@ -35,7 +35,7 @@ from urllib.parse import urlparse from lancedb.scannable import _hf_batches, _register_optional_converters, to_scannable from . import __version__ -from ._lancedb import FunctionColumnStatus, _parse_field_path +from ._lancedb import FunctionColumnStatus, _parse_field_path, _uses_sql_subquery_filter from ._blob import ( BlobFile, _normalize_blob_descriptor, @@ -145,7 +145,8 @@ def _should_push_down_query_table( def _requires_local_namespace_execution(query: Query) -> bool: # The namespace QueryTable request does not support these query options. return ( - query.take_offsets is not None + (isinstance(query.filter, str) and _uses_sql_subquery_filter(query.filter)) + or query.take_offsets is not None or query.take_row_ids is not None or query.search_effort is not None or query.approx_mode is not None diff --git a/python/python/tests/test_namespace.py b/python/python/tests/test_namespace.py index 2c999d1b0..d04da4568 100644 --- a/python/python/tests/test_namespace.py +++ b/python/python/tests/test_namespace.py @@ -2067,3 +2067,119 @@ def test_namespace_fts_count_fast_search(tmp_path): query = pushed.search("gripper", query_type="fts").fast_search() assert query.count_rows() == 15 assert len(query.limit(100).to_list()) == 15 + + +@pytest.fixture +def subquery_namespace(tmp_path): + properties = {"root": str(tmp_path)} + db = lancedb.connect_namespace("dir", properties) + path = ["team"] + db.create_namespace(path) + schema = pa.schema( + [ + ("id", pa.int32()), + ("text", pa.string()), + ("vector", pa.list_(pa.float32(), 2)), + ] + ) + table = db.create_table( + "chunks", + [ + {"id": 1, "text": "alpha alpha", "vector": [0.0, 0.0]}, + {"id": 2, "text": "alpha", "vector": [1.0, 1.0]}, + ], + schema=schema, + namespace_path=path, + ) + table.create_index("text", config=FTS()) + db.create_table("acl", [{"id": 1}]) + db.create_table("acl", [{"id": 2}], namespace_path=path) + return properties, path + + +@pytest.mark.parametrize("python_dispatch", [False, True]) +def test_subquery_filter_query_table_pushdown(subquery_namespace, python_dispatch): + properties, path = subquery_namespace + filter_sql = "id IN (SELECT id FROM acl)" + for enabled in (False, True): + db = lancedb.connect_namespace( + "dir", + properties, + namespace_client_pushdown_operations=["QueryTable"] if enabled else [], + ) + table = db.open_table("chunks", namespace_path=path) + client = _NamespaceClient() + if python_dispatch: + table._route_pushdown_to_rust = False + table._namespace_client = client + table._table._route_pushdown_to_rust = False + table._table._namespace_client = client + + query = table.search([0.0, 0.0]).where(filter_sql).limit(1) + assert query.to_arrow()["id"].to_pylist() == [2] + assert query.to_batches().read_all()["id"].to_pylist() == [2] + assert table.search("alpha", query_type="fts").where(filter_sql).limit( + 1 + ).to_arrow()["id"].to_pylist() == [2] + assert client.requests == [] + + +def test_hybrid_subquery_filter_sync(subquery_namespace): + properties, path = subquery_namespace + table = lancedb.connect_namespace("dir", properties).open_table( + "chunks", namespace_path=path + ) + result = ( + table.search(query_type="hybrid") + .vector([0.0, 0.0]) + .text("alpha") + .where("id IN (SELECT id FROM acl)") + .limit(1) + .to_arrow() + ) + assert result["id"].to_pylist() == [2] + + +@pytest.mark.asyncio +async def test_hybrid_subquery_filter_async(subquery_namespace): + properties, path = subquery_namespace + db = lancedb.connect_namespace_async("dir", properties) + table = await db.open_table("chunks", namespace_path=path) + result = await ( + table.vector_search([0.0, 0.0]) + .nearest_to_text("alpha") + .where("id IN (SELECT id FROM acl)") + .limit(1) + .to_arrow() + ) + assert result["id"].to_pylist() == [2] + + +def test_subquery_filter_rejects_wrapped_nullable_membership(tmp_path): + db = lancedb.connect(tmp_path) + table = db.create_table( + "chunks", + pa.table( + { + "id": [1, 2, 3], + "key": [10, 20, None], + "vector": pa.array( + [[0, 0], [1, 1], [2, 2]], type=pa.list_(pa.float32(), 2) + ), + } + ), + ) + db.create_table("acl", pa.table({"key": [20, None]})) + membership = "key IN (SELECT key FROM acl)" + assert ( + table.search([0.0, 0.0]) + .where(f"(id = 2 OR id = 3) AND ({membership})") + .to_arrow()["id"] + .to_pylist() + ) == [2] + for predicate in [ + f"({membership}) IS NULL", + "key NOT IN (SELECT key FROM acl) OR id = 3", + ]: + with pytest.raises(NotImplementedError, match="positive IN"): + table.search([0.0, 0.0]).where(predicate).to_arrow() diff --git a/python/src/lib.rs b/python/src/lib.rs index 4680aab4c..c9f382090 100644 --- a/python/src/lib.rs +++ b/python/src/lib.rs @@ -76,6 +76,11 @@ fn _append_doc_url(message: &str, campaign: &str) -> PyResult { Ok(link.append_to(message)) } +#[pyfunction] +fn _uses_sql_subquery_filter(sql: &str) -> bool { + lancedb::table::query::uses_sql_subquery_filter(sql) +} + #[pymodule] pub fn _lancedb(py: Python, m: &Bound<'_, PyModule>) -> PyResult<()> { lancedb::docs::set_sdk_ident("python", env!("CARGO_PKG_VERSION")); @@ -110,6 +115,8 @@ pub fn _lancedb(py: Python, m: &Bound<'_, PyModule>) -> PyResult<()> { m.add_class::()?; m.add_class::()?; m.add_class::()?; + m.add_function(wrap_pyfunction!(_uses_sql_subquery_filter, m)?)?; + m.add_function(wrap_pyfunction!(query::_share_hybrid_subquery_filter, m)?)?; m.add_class::()?; m.add_class::()?; m.add_class::()?; diff --git a/python/src/query.rs b/python/src/query.rs index f14276d74..5e30546ae 100644 --- a/python/src/query.rs +++ b/python/src/query.rs @@ -1509,6 +1509,23 @@ impl HybridQuery { } } +/// Share a fresh eligibility plan without changing Python's reranking path. +#[pyfunction] +pub fn _share_hybrid_subquery_filter( + py: Python<'_>, + mut fts: FTSQuery, + mut vector: VectorQuery, +) -> PyResult> { + future_into_py(py, async move { + vector + .inner + .share_subquery_filter_with(&mut fts.inner) + .await + .infer_error()?; + Ok((fts, vector)) + }) +} + /// Convert a Python FTS query to JSON string #[pyfunction] pub fn fts_query_to_json(query_obj: &Bound<'_, PyAny>) -> PyResult { diff --git a/rust/lancedb/src/expr.rs b/rust/lancedb/src/expr.rs index 04d1b0e9e..1682dcab5 100644 --- a/rust/lancedb/src/expr.rs +++ b/rust/lancedb/src/expr.rs @@ -19,8 +19,8 @@ mod sql; -pub(crate) use sql::canonicalize_sql_predicate; pub use sql::expr_to_sql_string; +pub(crate) use sql::{PredicateDialect, canonicalize_sql_predicate}; use std::sync::Arc; diff --git a/rust/lancedb/src/expr/sql.rs b/rust/lancedb/src/expr/sql.rs index 96bb5b60c..64ed7cf23 100644 --- a/rust/lancedb/src/expr/sql.rs +++ b/rust/lancedb/src/expr/sql.rs @@ -55,7 +55,7 @@ impl UnparserDialect for LanceSqlDialect { /// delegates only identifier recognition, leaving every other dialect option at /// its default. In particular, `/*! ... */` remains an ordinary block comment. #[derive(Debug, Default)] -struct PredicateDialect(GenericDialect); +pub(crate) struct PredicateDialect(GenericDialect); impl SqlParserDialect for PredicateDialect { fn dialect(&self) -> TypeId { @@ -73,6 +73,10 @@ impl SqlParserDialect for PredicateDialect { fn is_delimited_identifier_start(&self, ch: char) -> bool { ch == '"' || ch == '`' } + + fn supports_lambda_functions(&self) -> bool { + true + } } /// Canonicalize a raw SQL predicate for Lance's parser. diff --git a/rust/lancedb/src/query.rs b/rust/lancedb/src/query.rs index bc460dc35..93a026a04 100644 --- a/rust/lancedb/src/query.rs +++ b/rust/lancedb/src/query.rs @@ -2,6 +2,7 @@ // SPDX-FileCopyrightText: Copyright The LanceDB Authors use std::collections::{HashMap, HashSet}; +use std::fmt; use std::pin::Pin; use std::sync::Arc; use std::{future::Future, time::Duration}; @@ -39,6 +40,7 @@ use lance_index::scalar::FullTextSearchQuery; use lance_index::scalar::inverted::SCORE_COL; use lance_index::vector::DIST_COL; +use crate::database::Database; use crate::error::{Error, Result}; use crate::rerankers::rrf::RRFReranker; use crate::rerankers::{NormalizeMethod, Reranker, check_reranker_result}; @@ -422,6 +424,10 @@ pub trait QueryBase { /// Identifiers may be delimited with SQL-standard double quotes or /// backticks. String literals must use single quotes. /// + /// Embedded prefilters support positive `IN (SELECT ...)` predicates + /// alone or combined with other conditions using `AND`. Use unqualified + /// table names in the same namespace inside the subquery. + /// /// Filtering performance can often be improved by creating a scalar index /// on the filter column(s). /// @@ -613,6 +619,7 @@ impl QueryBase for T { } fn postfilter(mut self) -> Self { + self.mut_query().prepared_subquery = None; self.mut_query().prefilter = false; self } @@ -890,6 +897,12 @@ pub struct QueryRequest { /// `Result`. pub(crate) filter_error: Option, + /// Resolves tables referenced by Embedded SQL query filters. + pub(crate) database: Option, + + /// Per-execution eligibility plan and snapshot shared by the two hybrid legs. + pub(crate) prepared_subquery: Option>, + /// Perform a full text search on the table. pub full_text_search: Option, @@ -948,6 +961,16 @@ pub struct QueryRequest { pub use_rte: Option, } +#[derive(Clone)] +pub(crate) struct QueryDatabase(pub(crate) Arc); + +impl fmt::Debug for QueryDatabase { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + // Connection options may contain credentials. + f.debug_struct("QueryDatabase").finish_non_exhaustive() + } +} + impl Default for QueryRequest { fn default() -> Self { Self { @@ -958,6 +981,8 @@ impl Default for QueryRequest { preserve_order: false, filter: None, filter_error: None, + database: None, + prepared_subquery: None, full_text_search: None, select: Select::All, fast_search: false, @@ -984,6 +1009,7 @@ impl QueryRequest { /// use different representations) the error is recorded and surfaced later /// by [`Self::check_filter`]. pub(crate) fn add_filter(&mut self, new: QueryFilter) { + self.prepared_subquery = None; let new = match new { QueryFilter::Sql(filter) => match crate::expr::canonicalize_sql_predicate(&filter) { Ok(filter) => QueryFilter::Sql(filter), @@ -1049,6 +1075,11 @@ impl Query { } } + pub(crate) fn with_database(mut self, database: Option>) -> Self { + self.request.database = database.map(QueryDatabase); + self + } + /// Helper method to convert the query to a VectorQuery with a `query_vector` /// of None. This retrofits to some existing inner paths that work with a /// single query object for both vector and plain queries. @@ -1601,6 +1632,28 @@ impl VectorQuery { self } + /// Share one eligibility plan when a binding executes its hybrid legs separately. + #[doc(hidden)] + pub async fn share_subquery_filter_with(&mut self, fts_query: &mut Query) -> Result<()> { + let Some(table) = self.parent.as_native() else { + return Ok(()); + }; + let base = &self.request.base; + let fts = &fts_query.request; + if !Arc::ptr_eq(&self.parent, &fts_query.parent) + || base.use_rte != fts.use_rte + || base.prefilter != fts.prefilter + || !matches!((&base.filter, &fts.filter), (Some(QueryFilter::Sql(a)), Some(QueryFilter::Sql(b))) if a == b) + { + return Ok(()); + } + fts.check_filter()?; + let prepared = crate::table::query::prepare_hybrid_subquery(table, base).await?; + fts_query.request.prepared_subquery = prepared.clone(); + self.request.base.prepared_subquery = prepared; + Ok(()) + } + pub async fn execute_hybrid( &self, options: QueryExecutionOptions, @@ -1637,6 +1690,9 @@ impl VectorQuery { } vector_query.request.base.full_text_search = None; + vector_query + .share_subquery_filter_with(&mut fts_query) + .await?; let (fts_results, vec_results) = try_join!( fts_query.execute_with_options(internal_options.clone()), vector_query.inner_execute_with_options(internal_options) diff --git a/rust/lancedb/src/table.rs b/rust/lancedb/src/table.rs index b34d4a55b..280e9a5c4 100644 --- a/rust/lancedb/src/table.rs +++ b/rust/lancedb/src/table.rs @@ -2062,7 +2062,7 @@ impl Table { /// # }); /// ``` pub fn query(&self) -> Query { - Query::new(self.inner.clone()) + Query::new(self.inner.clone()).with_database(self.database.clone()) } /// Extract rows from the dataset using dataset offsets. diff --git a/rust/lancedb/src/table/query.rs b/rust/lancedb/src/table/query.rs index f63bf50bf..8e001e220 100644 --- a/rust/lancedb/src/table/query.rs +++ b/rust/lancedb/src/table/query.rs @@ -7,6 +7,9 @@ use std::{ }; mod lsm; +mod subquery_filter; + +pub(crate) use subquery_filter::PreparedSubquery; use super::NativeTable; use crate::connection::NamespaceClientPushdownOperation; @@ -123,7 +126,8 @@ fn requires_local_namespace_execution(query: &AnyQuery) -> bool { // RTE read routing lives only in `create_plan`, so a pushed-down query would return // stale base-only data. A dropped order_by would return the wrong top-K rows, and a // dropped ordered scan would silently stop guaranteeing manifest order. - if query.base().use_rte.is_some() + if subquery_filter::predicate(query.base().filter.as_ref()).is_some() + || query.base().use_rte.is_some() || query.base().has_take() || query.base().scan_in_order == Some(true) || query @@ -145,6 +149,32 @@ fn requires_local_namespace_execution(query: &AnyQuery) -> bool { ) } +/// Returns whether an Embedded SQL filter needs cross-table eligibility resolution. +#[doc(hidden)] +pub fn uses_sql_subquery_filter(sql: &str) -> bool { + subquery_filter::parse_predicate(sql).is_some() +} + +pub(crate) async fn prepare_hybrid_subquery( + table: &NativeTable, + query: &QueryRequest, +) -> Result>> { + let Some(predicate) = subquery_filter::predicate(query.filter.as_ref()) else { + return Ok(None); + }; + query.check_filter()?; + let dataset = table.dataset.get().await?; + // Let create_plan report the ordinary validation error for an LSM scan. + if query.use_rte == Some(true) + || (query.use_rte.is_none() && dataset.mem_wal_index_details().await?.is_some()) + { + return Ok(None); + } + Ok(Some(Arc::new( + PreparedSubquery::try_new(table, dataset, query, predicate, true).await?, + ))) +} + pub async fn analyze_query_plan( table: &NativeTable, query: &AnyQuery, @@ -233,7 +263,10 @@ pub async fn create_plan( query.base.check_filter()?; query.validate_search_effort()?; - let ds_ref = table.dataset.get().await?; + let ds_ref = match &query.base.prepared_subquery { + Some(prepared) => prepared.dataset.clone(), + None => table.dataset.get().await?, + }; // RTE read routing driven by `use_rte`: // * unset — route through the LSM scanner iff the table carries a write spec @@ -254,6 +287,11 @@ pub async fn create_plan( None => has_spec, }; if use_rte { + if subquery_filter::predicate(query.base.filter.as_ref()).is_some() { + return Err(Error::NotSupported { + message: "SQL subquery filters require a base table scan. Use use_rte(false) to search the base table.".into(), + }); + } return lsm::create_lsm_plan(table, ds_ref, query).await; } @@ -441,10 +479,26 @@ pub async fn create_plan( scanner.fast_search(); } + let mut eligibility = query.base.prepared_subquery.clone(); if let Some(filter) = &query.base.filter { match filter { QueryFilter::Sql(sql) => { - scanner.filter(sql)?; + if eligibility.is_none() { + if let Some(predicate) = subquery_filter::predicate(Some(filter)) { + eligibility = Some(Arc::new( + PreparedSubquery::try_new( + table, + ds_ref.clone(), + &query.base, + predicate, + false, + ) + .await?, + )); + } else { + scanner.filter(sql)?; + } + } } QueryFilter::Substrait(substrait) => { scanner.filter_substrait(substrait)?; @@ -486,6 +540,26 @@ pub async fn create_plan( } } + if let Some(eligibility) = eligibility { + // Planning can translate the bounds for ANN. The deferred scanner + // must start with the original bounds for its exact fallback. + let mut preview_scanner = scanner.clone(); + let preview = create_scanner_plan(&mut preview_scanner, schema, &query).await?; + return Ok(Arc::new(subquery_filter::SubqueryPrefilterExec::new( + eligibility, + scanner, + query, + preview, + ))); + } + create_scanner_plan(&mut scanner, schema, &query).await +} + +async fn create_scanner_plan( + scanner: &mut Scanner, + schema: &lance_core::datatypes::Schema, + query: &VectorQueryRequest, +) -> Result> { let mut plan = scanner .create_plan() .await diff --git a/rust/lancedb/src/table/query/subquery_filter.rs b/rust/lancedb/src/table/query/subquery_filter.rs new file mode 100644 index 000000000..20749be23 --- /dev/null +++ b/rust/lancedb/src/table/query/subquery_filter.rs @@ -0,0 +1,985 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright The LanceDB Authors + +use std::{collections::HashMap, fmt, ops::ControlFlow, sync::Arc}; + +use arrow_array::{cast::AsArray, types::UInt64Type}; +use arrow_schema::{DataType, Field, Schema}; +use datafusion::{ + dataframe::DataFrame, + execution::SessionStateBuilder, + prelude::SessionContext, + sql::{ + parser::Statement as DfStatement, + sqlparser::{ + ast::{ + Expr, Ident, SelectItem, SetExpr, Statement, Value, ValueWithSpan, VisitMut, + VisitorMut, visit_expressions, + }, + parser::Parser, + tokenizer::Token, + }, + }, +}; +use datafusion_catalog::TableProvider; +use datafusion_common::{ + DataFusionError, Result as DfResult, TableReference, + tree_node::{Transformed, TreeNode, TreeNodeRecursion}, +}; +use datafusion_execution::{SendableRecordBatchStream, TaskContext}; +use datafusion_expr::{Expr as DfExpr, LogicalPlan, LogicalPlanBuilder, col}; +use datafusion_physical_expr::{EquivalenceProperties, Partitioning}; +use datafusion_physical_plan::{ + DisplayAs, DisplayFormatType, ExecutionPlan, PlanProperties, execute_stream, + execution_plan::{Boundedness, EmissionType}, + stream::RecordBatchStreamAdapter, +}; +use futures::{TryStreamExt, stream}; +use lance::{ + Dataset, + datafusion::LanceTableProvider, + dataset::scanner::{RowAddrMask, RowAddrTreeMap, Scanner}, +}; +use lance_core::ROW_ID; +use lance_datafusion::{planner::Planner, udf::register_functions}; +use tokio::sync::OnceCell; + +use crate::{ + Error, Result, + database::OpenTableRequest, + expr::PredicateDialect, + query::{QueryDatabase, QueryFilter, QueryRequest}, + table::{NativeTable, datafusion::BaseTableAdapter}, +}; + +/// Leave ordinary SQL filters to Lance, including literals containing SQL keywords. +pub(super) fn predicate(filter: Option<&QueryFilter>) -> Option { + let Some(QueryFilter::Sql(sql)) = filter else { + return None; + }; + parse_predicate(sql) +} + +pub(super) fn parse_predicate(sql: &str) -> Option { + if !sql + .as_bytes() + .windows(6) + .any(|word| word.eq_ignore_ascii_case(b"select")) + { + return None; + } + + let dialect = PredicateDialect::default(); + let mut parser = Parser::new(&dialect).try_with_sql(sql).ok()?; + let expr = parser.parse_expr().ok()?; + if parser.peek_token().token != Token::EOF { + return None; + } + visit_expressions(&expr, |expr| match expr { + Expr::InSubquery { .. } => ControlFlow::Break(()), + _ => ControlFlow::Continue(()), + }) + .is_break() + .then_some(expr) +} + +// DataFusion can lose UNKNOWN when it lowers membership embedded in a +// Boolean expression to a mark join. A positive top-level conjunct only +// retains matches, so FALSE and UNKNOWN are equivalent there. +fn validate_membership_predicate(predicate: &Expr) -> Result<()> { + use datafusion::sql::sqlparser::ast::BinaryOperator; + + fn positive_conjuncts(expr: &Expr) -> usize { + match expr { + Expr::Nested(inner) => positive_conjuncts(inner), + Expr::BinaryOp { + left, + op: BinaryOperator::And, + right, + } => positive_conjuncts(left) + positive_conjuncts(right), + Expr::InSubquery { negated: false, .. } => 1, + _ => 0, + } + } + + let mut total = 0; + let _ = visit_expressions(predicate, |expr| { + if matches!(expr, Expr::InSubquery { .. }) { + total += 1; + } + ControlFlow::<()>::Continue(()) + }); + if total != positive_conjuncts(predicate) { + return Err(Error::NotSupported { + message: "SQL subquery filters require positive IN (SELECT ...) as a standalone predicate or directly joined by AND. NOT IN, Boolean expressions wrapping membership, and nested IN subqueries are not supported.".into(), + }); + } + Ok(()) +} + +/// Replace membership tests with Boolean columns for Lance's scalar planner. +/// Keep the subqueries intact for DataFusion, which resolves their own scopes. +struct MembershipSlots<'a> { + sql: &'a str, + schema: &'a Schema, + names: Vec, + memberships: Vec, + operands: Vec, + candidate: usize, +} + +impl VisitorMut for MembershipSlots<'_> { + type Break = (); + + fn pre_visit_expr(&mut self, expr: &mut Expr) -> ControlFlow<()> { + if let Expr::InSubquery { + expr: operand, + subquery, + negated, + } = expr + { + let name = loop { + let name = format!("__lancedb_subquery_{}", self.candidate); + self.candidate += 1; + if !self.sql.contains(&name) + && !self + .schema + .fields() + .iter() + .any(|f| f.name().eq_ignore_ascii_case(&name)) + { + break name; + } + }; + self.operands.push(*std::mem::replace( + operand, + Box::new(Expr::Value(Value::Null.into())), + )); + self.memberships.push(Expr::InSubquery { + expr: operand.clone(), + subquery: subquery.clone(), + negated: *negated, + }); + self.names.push(name.clone()); + *expr = Expr::Identifier(Ident::new(name)); + } + ControlFlow::Continue(()) + } +} + +// SQLParser's formatter also treats a backslash as an escape, which Lance's +// tokenizer does not. Double quotes in decoded literals before rendering them +// so a value such as a backslash followed by an apostrophe round-trips. +fn render_scalar_sql(mut expr: Expr) -> String { + struct EscapeQuotes; + impl VisitorMut for EscapeQuotes { + type Break = (); + + fn post_visit_value(&mut self, value: &mut ValueWithSpan) -> ControlFlow<()> { + if let Value::SingleQuotedString(text) = &mut value.value { + *text = text.replace('\'', "''"); + } + ControlFlow::Continue(()) + } + } + + let _ = expr.visit(&mut EscapeQuotes); + expr.to_string() +} + +pub(crate) struct PreparedSubquery { + pub(super) dataset: Arc, + plan: Arc, + context: Arc, + // Only hybrid legs share a cache. A normal plan can be executed repeatedly. + shared_mask: Option>>, +} + +impl fmt::Debug for PreparedSubquery { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_struct("PreparedSubquery").finish_non_exhaustive() + } +} + +impl PreparedSubquery { + pub(super) async fn try_new( + table: &NativeTable, + dataset: Arc, + query: &QueryRequest, + mut predicate: Expr, + shared: bool, + ) -> Result { + if !query.prefilter { + return Err(Error::NotSupported { + message: "SQL subquery filters require prefiltering.".into(), + }); + } + let Some(QueryDatabase(database)) = &query.database else { + return Err(Error::NotSupported { + message: + "SQL subquery filters require a table opened through a database connection." + .into(), + }); + }; + + validate_membership_predicate(&predicate)?; + + // Use the same snapshot for the outer scan and the ranked scan. + let provider = LanceTableProvider::new_with_ordering(dataset.clone(), true, false, false); + let schema = provider.schema(); + let sql = predicate.to_string().to_ascii_lowercase(); + let mut slots = MembershipSlots { + sql: &sql, + schema: &schema, + names: Vec::new(), + memberships: Vec::new(), + operands: Vec::new(), + candidate: 0, + }; + let _ = predicate.visit(&mut slots); + let slot_fields = slots + .names + .iter() + .map(|name| Arc::new(Field::new(name, DataType::Boolean, true))); + let outer_schema = Schema::new_with_metadata( + schema + .fields() + .iter() + .cloned() + .chain(slot_fields) + .collect::>(), + schema.metadata().clone(), + ); + + // Parse the outer scalar predicate, including the left operand of each + // IN, exactly as a Lance filter. DataFusion must not rebind these + // columns, or reinterpret Lance-specific functions and coercions. + let filter = + Planner::new(Arc::new(outer_schema)).parse_filter(&render_scalar_sql(predicate))?; + let operand_planner = Planner::new(schema.clone()); + let operands = slots + .operands + .into_iter() + .map(|expr| operand_planner.parse_expr(&render_scalar_sql(expr))) + .collect::>>()?; + + // Only expose the originating connection's tables. In particular, do not + // enable DataFusion table functions such as readers of arbitrary paths. + let ctx = SessionContext::new_with_state( + SessionStateBuilder::new_with_default_features() + .with_table_functions(HashMap::new()) + .build(), + ); + register_functions(&ctx); + let name = Ident::with_quote('`', &table.name); + let state = ctx.state(); + let DfStatement::Statement(mut statement) = + state.sql_to_statement(&format!("SELECT 1 FROM {name}"), &Default::default())? + else { + unreachable!("generated statement is a SELECT"); + }; + let Statement::Query(query) = statement.as_mut() else { + unreachable!("generated statement is a SELECT"); + }; + let SetExpr::Select(select) = query.body.as_mut() else { + unreachable!("generated statement is a SELECT"); + }; + select.projection = slots + .memberships + .into_iter() + .zip(&slots.names) + .map(|(expr, name)| SelectItem::ExprWithAlias { + expr, + alias: Ident::new(name), + }) + .collect(); + let statement = DfStatement::Statement(statement); + + ctx.register_table(TableReference::bare(table.name.clone()), Arc::new(provider))?; + for reference in state.resolve_table_references(&statement)? { + let TableReference::Bare { table: name } = reference else { + return Err(Error::NotSupported { + message: "Use unqualified table names in SQL subquery filters.".into(), + }); + }; + if name.as_ref() == table.name { + continue; + } + let source = database + .open_table(OpenTableRequest { + name: name.to_string(), + namespace_path: table.namespace.clone(), + index_cache_size: None, + lance_read_params: None, + location: None, + namespace_client: None, + managed_versioning: None, + }) + .await?; + let provider = BaseTableAdapter::try_new(source).await?; + ctx.register_table(TableReference::bare(name), Arc::new(provider))?; + } + let state = ctx.state(); + let LogicalPlan::Projection(memberships) = state.statement_to_plan(statement).await? else { + return Err(Error::Runtime { + message: "Expected a SQL subquery projection.".into(), + }); + }; + let mut bindings = HashMap::new(); + for ((name, membership), operand) in + slots.names.into_iter().zip(memberships.expr).zip(operands) + { + let DfExpr::InSubquery(mut membership) = membership.unalias() else { + return Err(Error::Runtime { + message: "Expected an IN subquery.".into(), + }); + }; + membership.expr = Box::new(operand); + bindings.insert(name, DfExpr::InSubquery(membership)); + } + let filter = filter + .transform_up(|expr| { + if let DfExpr::Column(column) = &expr + && let Some(membership) = bindings.get(&column.name).cloned() + { + return Ok(Transformed::yes(membership)); + } + Ok(Transformed::no(expr)) + })? + .data; + let plan = LogicalPlanBuilder::from(Arc::unwrap_or_clone(memberships.input)) + .filter(filter)? + .project([col(ROW_ID)])? + .build()?; + let frame = DataFrame::new(state, plan); + let context = Arc::new(frame.task_ctx()); + let plan = frame.create_physical_plan().await?; + Ok(Self { + dataset, + plan, + context, + shared_mask: shared.then(OnceCell::new), + }) + } + + async fn materialize(&self) -> DfResult> { + let mut batches = execute_stream(self.plan.clone(), self.context.clone())?; + let mut rows = RowAddrTreeMap::default(); + while let Some(batch) = batches.try_next().await? { + rows.extend( + batch + .column(0) + .as_primitive::() + .iter() + .flatten(), + ); + } + Ok(Arc::new(RowAddrMask::from_allowed(rows))) + } + + async fn row_mask(&self) -> DfResult> { + match &self.shared_mask { + Some(cell) => cell.get_or_try_init(|| self.materialize()).await.cloned(), + None => self.materialize().await, + } + } +} + +/// The Lance scanner needs a concrete mask to build the ranked plan. Build a +/// schema-only preview during planning and defer the actual masked plan until +/// the returned stream is polled, inside the query execution timeout. +pub(super) struct SubqueryPrefilterExec { + eligibility: Arc, + scanner: Scanner, + query: crate::query::VectorQueryRequest, + preview: Arc, + properties: Arc, +} + +impl SubqueryPrefilterExec { + pub(super) fn new( + eligibility: Arc, + scanner: Scanner, + query: crate::query::VectorQueryRequest, + preview: Arc, + ) -> Self { + let properties = Arc::new(PlanProperties::new( + EquivalenceProperties::new(preview.schema()), + Partitioning::UnknownPartitioning(1), + EmissionType::Final, + Boundedness::Bounded, + )); + Self { + eligibility, + scanner, + query, + preview, + properties, + } + } +} + +impl fmt::Debug for SubqueryPrefilterExec { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_struct("SubqueryPrefilterExec") + .finish_non_exhaustive() + } +} + +impl DisplayAs for SubqueryPrefilterExec { + fn fmt_as(&self, _: DisplayFormatType, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!( + f, + "SubqueryPrefilterExec: eligibility before {}", + self.preview.name() + ) + } +} + +impl ExecutionPlan for SubqueryPrefilterExec { + fn name(&self) -> &str { + "SubqueryPrefilterExec" + } + + fn properties(&self) -> &Arc { + &self.properties + } + + fn children(&self) -> Vec<&Arc> { + // The scanner's preview is not executed and cannot be rewritten. + vec![] + } + + fn with_new_children( + self: Arc, + children: Vec>, + ) -> DfResult> { + if !children.is_empty() { + return Err(DataFusionError::Internal( + "SubqueryPrefilterExec does not have children".into(), + )); + } + Ok(self) + } + + fn apply_expressions( + &self, + _f: &mut dyn FnMut( + &Arc, + ) -> DfResult, + ) -> DfResult { + Ok(TreeNodeRecursion::Continue) + } + + fn execute( + &self, + partition: usize, + context: Arc, + ) -> DfResult { + if partition != 0 { + return Err(DataFusionError::Internal(format!( + "Invalid SubqueryPrefilterExec partition {partition}" + ))); + } + let eligibility = self.eligibility.clone(); + let mut scanner = self.scanner.clone(); + let query = self.query.clone(); + let stream = stream::once(async move { + let mask = eligibility.row_mask().await?; + scanner.with_row_id_prefilter((*mask).clone()); + let plan = + super::create_scanner_plan(&mut scanner, eligibility.dataset.schema(), &query) + .await + .map_err(|e| DataFusionError::External(Box::new(e)))?; + execute_stream(plan, context) + }) + .try_flatten(); + Ok(Box::pin(RecordBatchStreamAdapter::new( + self.schema(), + stream, + ))) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use std::{ + sync::atomic::{AtomicUsize, Ordering}, + time::Duration, + }; + + use arrow_array::{ + ArrayRef, FixedSizeListArray, Int32Array, RecordBatch, StringArray, UInt64Array, + types::Float32Type, + }; + use lance_core::ROW_ID_FIELD; + use lance_datafusion::exec::OneShotExec; + use lance_index::scalar::FullTextSearchQuery; + use lance_namespace::models::CreateNamespaceRequest; + + use crate::{ + Table, + connection::{NamespaceClientPushdownOperation, connect_namespace}, + query::{ExecutableQuery, HasQuery, QueryBase, QueryExecutionOptions}, + }; + + const ELIGIBLE: &str = "id IN (SELECT id FROM acl)"; + + async fn fixture() -> (crate::Connection, Table, tempfile::TempDir) { + let dir = tempfile::tempdir().unwrap(); + let db = connect_namespace( + "dir", + HashMap::from([("root".to_string(), dir.path().display().to_string())]), + ) + .execute() + .await + .unwrap(); + let team = vec!["team".into()]; + db.create_namespace(CreateNamespaceRequest { + id: Some(team.clone()), + ..Default::default() + }) + .await + .unwrap(); + + let table = RecordBatch::try_from_iter([ + ( + "id", + Arc::new(Int32Array::from(vec![1, 2, 3, 4])) as ArrayRef, + ), + ( + "tenantId", + Arc::new(Int32Array::from(vec![0, 1, 0, 1])) as ArrayRef, + ), + ( + "tenantid", + Arc::new(Int32Array::from(vec![1, 0, 1, 0])) as ArrayRef, + ), + ( + "text", + Arc::new(StringArray::from(vec!["alpha", "alpha", "alpha", "beta"])) as ArrayRef, + ), + ( + "vector", + Arc::new( + FixedSizeListArray::from_iter_primitive::( + [0., 1., 2., 3.].map(|x| Some(vec![Some(x), Some(x)])), + 2, + ), + ) as ArrayRef, + ), + ]) + .unwrap(); + let table = db + .create_table("chunks", vec![table]) + .namespace(team.clone()) + .execute() + .await + .unwrap(); + let keys = |ids| { + RecordBatch::try_from_iter([("id", Arc::new(Int32Array::from(ids)) as ArrayRef)]) + .unwrap() + }; + db.create_table("acl", vec![keys(vec![2, 3, 4])]) + .namespace(team) + .execute() + .await + .unwrap(); + db.create_table("acl", vec![keys(vec![1])]) + .execute() + .await + .unwrap(); + (db, table, dir) + } + + async fn top_id(table: &Table, filter: &str) -> Vec { + let batches: Vec<_> = table + .query() + .nearest_to(&[0.0_f32, 0.0]) + .unwrap() + .only_if(filter) + .limit(1) + .execute() + .await + .unwrap() + .try_collect() + .await + .unwrap(); + batches + .iter() + .flat_map(|batch| { + batch + .column_by_name("id") + .unwrap() + .as_primitive::() + .values() + .to_vec() + }) + .collect() + } + + #[tokio::test] + async fn preserves_outer_case_and_lance_functions() { + let (_, table, _dir) = fixture().await; + // Opposing values distinguish exact bindings from lowercasing; id 4 is + // eligible on membership and tenant alone but fails contains_tokens. + let ordinary = "tenantId = 1 AND contains_tokens(text, 'alpha')"; + assert_eq!(top_id(&table, ordinary).await, vec![2]); + assert_eq!( + top_id(&table, &format!("{ordinary} AND {ELIGIBLE}")).await, + vec![2] + ); + assert_eq!( + top_id(&table, "tenantid = 1 AND id IN (SELECT id FROM acl)").await, + vec![3], + ); + assert_eq!( + top_id( + &table, + &format!("contains_tokens(text, 'beta') AND {ELIGIBLE}") + ) + .await, + vec![4], + ); + assert_eq!( + top_id( + &table, + "(tenantID = 1 OR id = 999) AND (id IN (SELECT id FROM acl))" + ) + .await, + vec![2], + ); + assert_eq!( + top_id( + &table, + "tenantId = 1 AND id NOT IN (2, 3) AND id IN (SELECT id FROM acl)" + ) + .await, + vec![4], + ); + } + + #[tokio::test] + async fn subquery_filter_positive_conjuncts_with_nullable_keys() { + let db = crate::connect("memory://").execute().await.unwrap(); + let batch = RecordBatch::try_from_iter([ + ("id", Arc::new(Int32Array::from(vec![1, 2, 3])) as ArrayRef), + ( + "key", + Arc::new(Int32Array::from(vec![Some(10), Some(20), None])) as ArrayRef, + ), + ( + "vector", + Arc::new( + FixedSizeListArray::from_iter_primitive::( + [0., 1., 2.].map(|x| Some(vec![Some(x), Some(x)])), + 2, + ), + ) as ArrayRef, + ), + ]) + .unwrap(); + let table = db.create_table("chunks", batch).execute().await.unwrap(); + let keys = RecordBatch::try_from_iter([( + "key", + Arc::new(Int32Array::from(vec![Some(20), None])) as ArrayRef, + )]) + .unwrap(); + db.create_table("acl", keys).execute().await.unwrap(); + + let membership = "key IN (SELECT key FROM acl)"; + assert_eq!(top_id(&table, membership).await, vec![2]); + assert_eq!( + top_id( + &table, + &format!("({membership}) AND (id = 2 OR id = 3) AND {membership}") + ) + .await, + vec![2] + ); + for additional_condition in ["id = 1", "id = 3"] { + assert!( + top_id(&table, &format!("{membership} AND {additional_condition}")) + .await + .is_empty() + ); + } + assert!( + top_id(&table, "key IN (SELECT key FROM acl WHERE key = 999)") + .await + .is_empty() + ); + assert_eq!( + top_id(&table, "id IN (2, 3) AND id NOT IN (2)").await, + vec![3] + ); + + for filter in [ + "key NOT IN (SELECT key FROM acl)", + "key NOT IN (SELECT key FROM acl) OR id = 3", + "(key IN (SELECT key FROM acl)) IS NULL", + "NOT (key IN (SELECT key FROM acl))", + "(key IN (SELECT key FROM acl) OR id = 3)", + "key IN (SELECT key FROM acl WHERE key NOT IN (SELECT key FROM acl))", + ] { + let result = table + .query() + .nearest_to(&[0.0_f32, 0.0]) + .unwrap() + .only_if(filter) + .execute() + .await; + assert!( + matches!(&result, Err(Error::NotSupported { message }) + if message.contains("positive IN")), + "expected an unsupported subquery filter: {filter}" + ); + } + } + + #[tokio::test] + async fn subquery_filter_preserves_cosine_bounds_for_appended_rows() { + use crate::index::{Index, vector::IvfPqIndexBuilder}; + + let db = crate::connect("memory://").execute().await.unwrap(); + let batch = |ids: Vec, vectors: Vec>>| { + RecordBatch::try_from_iter([ + ("id", Arc::new(Int32Array::from(ids)) as ArrayRef), + ( + "vector", + Arc::new( + FixedSizeListArray::from_iter_primitive::( + vectors.into_iter().map(Some), + 8, + ), + ) as ArrayRef, + ), + ]) + .unwrap() + }; + let mut state = 42_u64; + let vectors = (0..256) + .map(|_| { + let vector = (0..8) + .map(|_| { + state = state + .wrapping_mul(6_364_136_223_846_793_005) + .wrapping_add(1); + (state >> 32) as u32 as f32 / u32::MAX as f32 - 0.5 + }) + .collect::>(); + let norm = vector.iter().map(|v| v * v).sum::().sqrt(); + vector.into_iter().map(|v| Some(v / norm)).collect() + }) + .collect(); + let table = db + .create_table("chunks", batch((0..256).collect(), vectors)) + .execute() + .await + .unwrap(); + table + .create_index( + &["vector"], + Index::IvfPq( + IvfPqIndexBuilder::default() + .distance_type(crate::DistanceType::Cosine) + .num_partitions(1) + .num_sub_vectors(1), + ), + ) + .execute() + .await + .unwrap(); + // The appended row lives outside the index. Its exact cosine + // distance from [1, 0, ...] is 0.75 on the public scale. + let mut appended = vec![Some(0.); 8]; + appended[0] = Some(0.25); + appended[1] = Some((1.0_f32 - 0.25_f32.powi(2)).sqrt()); + table + .add(batch(vec![256], vec![appended])) + .execute() + .await + .unwrap(); + let keys = + RecordBatch::try_from_iter([("id", Arc::new(Int32Array::from(vec![256])) as ArrayRef)]) + .unwrap(); + db.create_table("acl", keys).execute().await.unwrap(); + + let mut mismatches = Vec::new(); + for (lower, upper, expected) in [(None, Some(0.5), vec![]), (Some(0.6), None, vec![256])] { + for filter in ["id = 256", ELIGIBLE] { + let batches = table + .query() + .nearest_to(&[1.0_f32, 0., 0., 0., 0., 0., 0., 0.]) + .unwrap() + .distance_type(crate::DistanceType::Cosine) + .distance_range(lower, upper) + .only_if(filter) + .limit(1) + .execute() + .await + .unwrap() + .try_collect::>() + .await + .unwrap(); + let ids = batches + .iter() + .flat_map(|b| { + b["id"] + .as_primitive::() + .values() + .iter() + .copied() + }) + .collect::>(); + if ids != expected { + mismatches.push(format!( + "{filter}, range ({lower:?}, {upper:?}): expected {expected:?}, got {ids:?}" + )); + } + } + } + assert!(mismatches.is_empty(), "{mismatches:#?}"); + } + + #[tokio::test] + async fn subquery_filter_bypasses_namespace_pushdown() { + let (_, table, dir) = fixture().await; + table + .create_index(&["text"], crate::index::Index::FTS(Default::default())) + .execute() + .await + .unwrap(); + let pushed = connect_namespace( + "dir", + HashMap::from([("root".to_string(), dir.path().display().to_string())]), + ) + .pushdown_operations([NamespaceClientPushdownOperation::QueryTable]) + .execute() + .await + .unwrap() + .open_table("chunks") + .namespace(vec!["team".into()]) + .execute() + .await + .unwrap(); + let query = table + .query() + .nearest_to(&[0.0_f32, 0.0]) + .unwrap() + .only_if(ELIGIBLE) + .limit(1); + let request = super::super::AnyQuery::VectorQuery(query.current_request().clone()); + for table in [&table, &pushed] { + let batches = super::super::execute_query( + table.as_native().unwrap(), + &request, + QueryExecutionOptions::default(), + ) + .await + .unwrap() + .try_collect::>() + .await + .unwrap(); + assert_eq!(batches.len(), 1); + let ids = batches[0] + .column_by_name("id") + .unwrap() + .as_primitive::(); + assert_eq!(ids.values(), &[2]); + let batches = table + .query() + .full_text_search(FullTextSearchQuery::new("alpha".into())) + .only_if("id IN (SELECT id FROM acl WHERE id = 2)") + .limit(1) + .execute() + .await + .unwrap() + .try_collect::>() + .await + .unwrap(); + assert_eq!( + batches[0] + .column_by_name("id") + .unwrap() + .as_primitive::() + .values(), + &[2] + ); + } + } + + #[tokio::test] + async fn planning_never_polls_eligibility_and_timeout_covers_execution() { + let (_, table, _dir) = fixture().await; + let mut query = table + .query() + .nearest_to(&[0.0_f32, 0.0]) + .unwrap() + .only_if(ELIGIBLE) + .limit(1); + let polled = Arc::new(AtomicUsize::new(0)); + let count = polled.clone(); + let schema = Arc::new(Schema::new(vec![ROW_ID_FIELD.clone()])); + let eligibility = stream::once(async move { + count.fetch_add(1, Ordering::SeqCst); + std::future::pending::>().await + }); + let eligibility = + OneShotExec::new(Box::pin(RecordBatchStreamAdapter::new(schema, eligibility))); + let dataset = table.as_native().unwrap().dataset.get().await.unwrap(); + query.mut_query().prepared_subquery = Some(Arc::new(PreparedSubquery { + dataset, + plan: Arc::new(eligibility), + context: SessionContext::new().task_ctx(), + shared_mask: None, + })); + + assert!( + query + .explain_plan(false) + .await + .unwrap() + .contains("SubqueryPrefilterExec") + ); + assert!( + query + .output_schema() + .await + .unwrap() + .field_with_name("id") + .is_ok() + ); + assert_eq!(polled.load(Ordering::SeqCst), 0); + let stream = query + .execute_with_options(QueryExecutionOptions { + timeout: Some(Duration::from_millis(50)), + ..Default::default() + }) + .await + .unwrap(); + assert_eq!(polled.load(Ordering::SeqCst), 0); + let err = stream.try_collect::>().await.unwrap_err(); + assert!(err.to_string().contains("Query timeout")); + assert_eq!(polled.load(Ordering::SeqCst), 1); + } + + #[tokio::test] + async fn hybrid_legs_share_mask_materialization() { + let (_, table, _dir) = fixture().await; + let schema = Arc::new(Schema::new(vec![ROW_ID_FIELD.clone()])); + let batch = + RecordBatch::try_new(schema, vec![Arc::new(UInt64Array::from(vec![1]))]).unwrap(); + let eligibility = PreparedSubquery { + dataset: table.as_native().unwrap().dataset.get().await.unwrap(), + // This source errors if executed a second time. + plan: Arc::new(OneShotExec::from_batch(batch)), + context: SessionContext::new().task_ctx(), + shared_mask: Some(OnceCell::new()), + }; + let (left, right) = + tokio::try_join!(eligibility.row_mask(), eligibility.row_mask()).unwrap(); + assert!(Arc::ptr_eq(&left, &right)); + } +}