Repository navigation
[test](lance) Add indexed coverage for cosine, dot and non-Float32 element types - #67039
Conversation
|
Thank you for your contribution to Apache Doris. Please clearly describe your PR:
|
af9fa35 to
54b999f
Compare
54b999f to
75e20b8
Compare
|
@zhangstar333 @Gabriel39 PTAL |
|
run buildall |
|
@FANNG1 failed one test in test_lance_vector_search_indexed_element_types |
|
@zhangstar333 Thanks for running it. I can't read the failure myself — the TeamCity instance asks for a login — so could you paste the assertion block from the log? The part I need is: The tag name alone would probably be enough to pin it down. For context on where I'd expect trouble: that suite covers three tables, and only the Float16 one records values that are not exactly representable.
Both are exact integers on any platform. The Float16 blocks are different — they record float32 cosine distances printed to 7-8 significant digits ( I regenerated the goldens on macOS/arm64 after rebuilding the fixture. If the failing tag is If it is a different tag, that guess is wrong and I will dig into it from the log. |
Exception: @FANNG1 seems everyone could login as guest for TeamCity. no need admin account. u could have a try |
Got it, thanks! |
…e and metric The Lance vector suites were all Float32 + L2. Doris only plans an indexed split when the query metric equals the metric the index was built with (LanceScanNode.metricMatches), so the cosine and dot branches of that comparison had never run against a real index, and no indexed table existed for any element type other than Float32. Two tiers now cover the whole matrix. Twelve tables carry it in depth: all six algorithms on Float32 + L2, plus cosine and dot, plus Float64, Float16 and UInt8. Each has goldens, a closed-form distance ladder where the data shape allows one, and a discriminator that proves the search parameter reached the index rather than falling back to a scan. Their data shape is per metric, because one shape cannot serve all of them - the collinear ladder is degenerate under cosine (directions converge, the top distances collapse to zero) and under dot (the answer ignores the query), so those tables use a directional shape, and UInt8 uses a thermometer code that makes hamming an exact ladder. One table, doris.vs_index_matrix, carries the remaining 44 cells at 64 rows, one vector column per cell. One column per cell rather than several indexes on one column, because only the first index built on a column is reachable - Lance answers the others with a silent brute-force scan, and Doris gets there by another route, since selectIndexSegments keeps only the segments of the first index it finds for the column's field id. Each cell is asserted to plan an indexed split with no fragment left scanned unindexed, to answer differently at nprobes=1 than at nprobes=4 (a scan has no partitions, so this is what distinguishes a real indexed search from a fallback), and to return what an exhaustive scan returns once its candidates are reranked. No goldens, so a fixture rebuild leaves it untouched. The generator's self-check is the whole contract for a fixture whose bytes are not reproducible, so it now pins a digest of every profile's vectors, reads rows back from each table, asserts the metric each index was actually built with (read from stats["indices"][*]["metric_type"], not searched for - a cosine IVF_PQ reports l2 on its sub-index), keeps the indexed-vs-flat comparison bit-exact for the integer ladders, and enforces the pylance and lance-namespace pins before building or verifying. Discriminator margins are reported and warned on when thin, and --repin lets a rebuild complete so those rows can be re-measured against the fixture that was actually promoted. buildable_Budugs() is a claim about Lance, so it was checked against Lance: all 96 cells of the matrix were built one per subprocess, 56 succeeded, and those 56 are exactly what it yields. The 40 failures are documented next to it and deliberately not attempted at build time - eighteen are Rust panics, and this script writes the fixture that gets committed. Finally, the fixture is published with `mc mirror --remove` instead of `mc cp -r`. The __manifest version is a commit count that a rebuild can lower, and Lance names version files u64::MAX - version so a listing resolves newest first; a stale higher-versioned manifest left in the bucket therefore wins over the one just published. The MinIO in a live test environment had accumulated three. Claude-Session: https://claude.ai/code/session_01J55jh5bX3t1DvTqbWx1qEN
75e20b8 to
2c329df
Compare
|
Thanks — that log made it clear, and the guest login works, so I can read TeamCity myself from now on. The cause is narrower than the digit drift I guessed at. Cosine distance is That is why the framework's 1e-6 relative tolerance did not absorb it: the rows below it passed, but relative error is meaningless around zero, and Two things confirm the diagnosis:
FixThe Float16 table is the one table in this suite whose data has no closed-form expected distance — Float64 records the L2 ladder The magnitude is still worth pinning — a backend that widened Float16 to Float32 before comparing, or lost the query vector's precision, would move it off one ulp — so it is now an assertion on the absolute value with a tolerance, rather than a literal whose sign a golden cannot avoid recording: assertTrue(Math.abs(f16SelfDistance) < 1e-5, ...)I also checked the rest of Full |
|
run buildall |
get it. let's test again in TeamCity. @FANNG1 |
…y matrix (#4082) Documents the Lance vector index compatibility matrix requested in [apache/doris#66495](apache/doris#66495), whose completion criteria include "User documentation contains a supported algorithm compatibility matrix". Follows up on the [review comment on apache/doris#66512](apache/doris#66512 (comment)) asking for the integration capability matrix to be added to this page. Companion code PR: [apache/doris#67039](apache/doris#67039), which adds the regression coverage for the combinations documented here. Both `docs/` and the `zh-CN` translation are updated together. ## What is added **A vector element type x distance metric matrix** under "Supported Vector Index Types", describing which combinations can serve an index-backed search with the embedded Lance version, with footnotes for: - the Float16 L2 index-build limitation (and that Flat Search over Float16 is fine); - UInt8 being hamming-only, and available only for `IVF_FLAT` and `IVF_HNSW_FLAT`; - Int8 having no complete index build path, plus the nullable-Int8 crash and the upstream fix it is waiting on. **A "The Query Metric Must Match the Index Metric" section**, because it is the most likely user-visible surprise: Doris selects a vector index only when the requested `metric` equals the metric the index was built with, and otherwise runs Flat Search. `EXPLAIN` reports this as `lanceSearchIndexSegments=0`. It also notes that only one index per vector column is considered. ## Two corrections to existing text 1. **Version binding.** The page said the BE data reader is bound to Lance `9.1.0-beta.3` at commit `e934cc2c`. That is the `lance-java` version the **FE** uses (`fe/pom.xml`). The BE reader is `lance-c v0.1.6`, which pins the Lance Rust crates at **`7.0.0-beta.7`**, Lance commit **`e0e977a6`**. Both are now stated separately. The `data_storage_version` table below it stays correct: `rust/lance-encoding/src/version.rs` at `e0e977a6` has default `V2_1`, `Stable -> V2_1`, `Next -> V2_3`, and `2.2` stable but not default, which is what the table already describes. 2. **Default `metric`.** The `metric` parameter row and the paragraph after the parameter table both said that omitting `metric` makes Doris use the metric the index was created with. `LanceScanNode.metricMatches` maps an unset metric to `l2`, so on a cosine-indexed table an omitted `metric` plans a Flat Search instead. The documented behavior now matches the code, and says to pass `metric` explicitly for a non-L2 index.
|
PR approved by anyone and no changes requested. |
|
PR approved by at least one committer and no changes requested. |
Issue Number: close apache#67117 Related PR: apache#67039 Problem Summary: LanceScanNode previously committed to the first logical index returned for a vector field before checking its metric. A query whose requested metric matched a later same-column index therefore fell back to Flat Search. Group segments by logical index name, inspect groups in stable lexical name order, and select the first metric-compatible group that can safely produce indexed splits. Legacy or invisible groups no longer prevent a later safe candidate from being used. Vector searches can use a later same-column Lance index when it matches the requested metric instead of unnecessarily falling back to Flat Search. - Test: Maven validate -pl fe-core -am -DskipTests (passed); LanceScanNodeTest added. Targeted ./run-fe-ut.sh --run org.apache.doris.datasource.lance.source.LanceScanNodeTest was blocked before fe-core by generated Thrift source incompatibility from the local prebuilt thirdparty package. - Behavior changed: Yes (metric-compatible same-column indexes are now selected deterministically) - Does this need documentation: Yes (follow up in apache/doris-website#4082)
### What problem does this PR solve? Issue Number: close apache#67117 Related PR: apache#67039 Problem Summary: The same-column vector index selection tests used the pre-full-text-search LanceIndexSegmentInfo constructor and no longer compiled after IndexType became required. They also exercised only injected FE metadata, leaving the real fixture, metadata loader, scan-range serialization, and backend index path untested. Supply IndexType.VECTOR to every affected fixture and add a two-index same-column Lance dataset with L2 created before cosine. The regression verifies that a cosine query plans indexed segments and that nprobes changes the result relative to Flat Search. ### Release note None ### Check List (For Author) - Test: Python syntax check passed for lance_build_preinstalled_catalog.py; git diff --check passed; targeted ./run-fe-ut.sh --run org.apache.doris.datasource.lance.source.LanceScanNodeTest blocked before fe-core because thirdparty/installed/bin/protoc is missing - Behavior changed: No - Does this need documentation: Yes (follow-up website documentation update required)
### What problem does this PR solve? Issue Number: close apache#67117 Related PR: apache#67039 Problem Summary: External Regression provisions its Lance warehouse from a prebuilt fixture rather than rebuilding lance_build_preinstalled_catalog.py from the PR checkout. The newly added same-column multi-index table was therefore absent in CI, causing test_lance_vector_search_metrics to fail before it could exercise index selection. Remove the unavailable external fixture and its dependent assertions. Keep the same-column selection coverage in LanceScanNodeTest, whose metadata fixtures are built in the FE test process, and clarify that the external matrix intentionally uses one index per column. ### Release note None ### Check List (For Author) - Test: git diff --check; python3 -m py_compile docker/thirdparties/docker-compose/iceberg/scripts/lance_build_preinstalled_catalog.py - Behavior changed: No - Does this need documentation: No
Issue Number: close apache#67117 Related PR: apache#67039 Problem Summary: LanceScanNode previously committed to the first logical index returned for a vector field before checking its metric. A query whose requested metric matched a later same-column index therefore fell back to Flat Search. Group segments by logical index name, inspect groups in stable lexical name order, and select the first metric-compatible group that can safely produce indexed splits. Legacy or invisible groups no longer prevent a later safe candidate from being used. Vector searches can use a later same-column Lance index when it matches the requested metric instead of unnecessarily falling back to Flat Search. - Test: Maven validate -pl fe-core -am -DskipTests (passed); LanceScanNodeTest added. Targeted ./run-fe-ut.sh --run org.apache.doris.datasource.lance.source.LanceScanNodeTest was blocked before fe-core by generated Thrift source incompatibility from the local prebuilt thirdparty package. - Behavior changed: Yes (metric-compatible same-column indexes are now selected deterministically) - Does this need documentation: Yes (follow up in apache/doris-website#4082)
### What problem does this PR solve? Issue Number: close apache#67117 Related PR: apache#67039 Problem Summary: The same-column vector index selection tests used the pre-full-text-search LanceIndexSegmentInfo constructor and no longer compiled after IndexType became required. They also exercised only injected FE metadata, leaving the real fixture, metadata loader, scan-range serialization, and backend index path untested. Supply IndexType.VECTOR to every affected fixture and add a two-index same-column Lance dataset with L2 created before cosine. The regression verifies that a cosine query plans indexed segments and that nprobes changes the result relative to Flat Search. ### Release note None ### Check List (For Author) - Test: Python syntax check passed for lance_build_preinstalled_catalog.py; git diff --check passed; targeted ./run-fe-ut.sh --run org.apache.doris.datasource.lance.source.LanceScanNodeTest blocked before fe-core because thirdparty/installed/bin/protoc is missing - Behavior changed: No - Does this need documentation: Yes (follow-up website documentation update required)
### What problem does this PR solve? Issue Number: close apache#67117 Related PR: apache#67039 Problem Summary: External Regression provisions its Lance warehouse from a prebuilt fixture rather than rebuilding lance_build_preinstalled_catalog.py from the PR checkout. The newly added same-column multi-index table was therefore absent in CI, causing test_lance_vector_search_metrics to fail before it could exercise index selection. Remove the unavailable external fixture and its dependent assertions. Keep the same-column selection coverage in LanceScanNodeTest, whose metadata fixtures are built in the FE test process, and clarify that the external matrix intentionally uses one index per column. ### Release note None ### Check List (For Author) - Test: git diff --check; python3 -m py_compile docker/thirdparties/docker-compose/iceberg/scripts/lance_build_preinstalled_catalog.py - Behavior changed: No - Does this need documentation: No
…talogs ### Background Lance datasets carry vector indexes (IVF_FLAT, IVF_PQ, IVF_SQ, IVF_HNSW_*) and full-text indexes. branch-4.1 and branch-4.2 expose them through two table functions, `vector_search(...)` and `full_text_search(...)`: each reads a table of a `lance` catalog and returns its columns plus `_distance` or `_score`; every index segment and every unindexed fragment becomes one scan range, and a Doris TopN merges the ranges' candidates. On master, Lance is a connector plugin (apache#70680), fe-core holds no Lance code, and the BE already executes these searches. ### What problem does this PR solve? Issue Number: close apache#70970 Related PR: apache#65730, apache#66512, apache#66841, apache#67039, apache#67289, apache#68028, apache#68162, apache#68813, apache#68815 (the branch-4.x implementation this ports), apache#70680 (builds on: the Lance connector plugin) PR Type: Feature Problem Summary: Users of `lance` catalogs lose vector and full-text search on master: both functions fail with `Can not found function 'vector_search'`. They come back with branch-4.2's arguments, defaults, limits, errors and EXPLAIN keys, through a new optional connector SPI: fe-core owns the two functions and the plan rules, the connector parses the arguments and plans the search. Two 4.x problems are fixed on the way: filters other than the function's own WHERE crossed the merge, so rows depended on the select list, and row policies, masks and column privileges did not apply. 60% of the diff is tests. Existing statements are unaffected; connector plugins move to API 38.0. ```sql SELECT row_id, category, label, _distance FROM vector_search("table" = "lance_ctl.doris.vs_ivf_pq_f32", "column" = "embedding", "query_vector" = "[0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15]", "top_k" = "5", "metric" = "l2", "nprobes" = "4", "refine_factor" = "10") ORDER BY _distance, row_id; ``` | | Result | |---|---| | master | `Can not found function 'vector_search'` | | this PR (same as branch-4.2) | `1 even item-0001 0.0`, `2 odd item-0002 16.0`, `3 even item-0003 64.0`, `4 odd item-0004 144.0`, `5 even item-0005 256.0` | ### Details - **Change map:** 126 files, +7,321 / -59: production code +2,911 (40%), tests with their generated `.out` +4,397 (60%), docs and build +13. Production code by part, one commit each: 1. Connector search SPI (+344): `ConnectorSearchOps`, the request, function and result types, the `applyTopnLazyMaterialization` overload with lazy column names, API 37.0 -> 38.0 and its surface baselines. 2. Engine (+874: fe-core 865, fe-common 4, BE 5): the two functions, routing and the privilege and policy checks (`ExternalSearchTableValuedFunction`); binding with the merge TopN and PREPARE / EXECUTE parameters (`BindExpression`, `LogicalPlanBuilder`, `UnboundTVFRelation`); the WHERE placement (`PushDownWhereThroughSearchTopN`, an analysis rule); lazy materialization admission and hand-off (`MaterializeProbeVisitor`, `LazyMaterializeTopN`, the translator, `PluginDrivenScanNode`); `enable_lance_lazy_materialization`; BE exec version 20. 3. Lance plugin (+1,693): argument parsing and vector encoding (`LanceSearchArguments`, `LanceVectorQuery`, 865), search planning over index segments and fragments (`LanceScanPlanner`, `LanceSearchPlan`, index metrics, about 470), the search handle, metadata and scan properties (about 360), with its unit tests. 4. fe-core unit tests. 5. Regression suites, three small fixtures copied from branch-4.2 and their registration. - **Scope:** `vector_search` over fixed-size-list vector columns of float16, float32, float64, uint8 and int8, with the `l2`, `cosine`, `dot` and `hamming` metrics, index or flat search (`use_index`, `nprobes`, `refine_factor`, `ef`, `query_parallelism`), a Lance `filter` with `prefilter`, and `distance_lower_bound` / `distance_upper_bound`; `full_text_search` with match and phrase queries and the `STRICT` / `INDEX_ONLY` coverage modes; server-side PREPARE with `?` for `vector_search`'s `query_vector`, `top_k`, `offset`, `filter` and both distance bounds. Not supported: `approx_mode` (apache#69852, which master's BE does not read yet), searching earlier versions, tags or branches (apache#68707), `?` in `full_text_search` (refused: `full_text_search properties must be constant in a prepared statement`), and catalogs whose connector does not implement the SPI (refused: `Catalog 'x' does not support vector_search()`). Modules: fe-connector-spi, fe-core, fe-common, fe-connector-lance, and one constant in the BE. - **Design:** The engine keeps the two function names and routes by the catalog of the `table` argument to `ConnectorSearchOps#prepareSearch`, an optional interface of the connector metadata (implementing it is the declaration, as for `ConnectorFileSourceOps`). The request carries the function, every argument except `table` under its lower-case name, and the names a PREPARE defers; the connector answers with the scan handle, the columns ending with the result column, `top_k`, `offset`, and whether the engine may fetch top-level columns after the merge. The engine owns the result column, the merge order (`_distance` ascending, `_score` descending) and which WHERE filters the candidates. Rejected: plugin-registered function names (one name could belong to one plugin only, while branch-4.2's apache#69493 lets Paimon serve `vector_search` too) and engine-parsed common arguments (Lance and Paimon differ in ranges and in what `filter` means). Proposed in apache#70970, opened with this PR; not discussed yet. - **Usage:** ```sql SELECT row_id, _score FROM full_text_search("table" = "lance_ctl.doris.full_text_search", "column" = "body", "query" = "lance", "top_k" = "4") ORDER BY _score DESC, row_id; -- the WHERE written on the function filters the candidates of each range before the merge SELECT row_id, _distance FROM vector_search("table" = "lance_ctl.doris.vs_ivf_pq_f32", "column" = "embedding", "query_vector" = "[0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15]", "top_k" = "3") v WHERE v.category = 'odd'; -- as a server-side prepared statement (JDBC with useServerPrepStmts=true), each EXECUTE binding the values SELECT row_id, _distance FROM vector_search("table" = "lance_ctl.doris.vs_ivf_pq_f32", "column" = "embedding", "query_vector" = ?, "top_k" = ?, "offset" = ?, "filter" = ?) ORDER BY _distance, row_id; ``` - **Default behavior:** Available on every `lance` catalog. `top_k` 10, `offset` 0, `prefilter` false, and the metric Lance's default (L2), as on branch-4.2. Two-phase fetch is on (`enable_lance_lazy_materialization` = true) once every BE reports exec version 20, and `topn_lazy_materialization_threshold` does not limit a search's TopN. - **Compatibility:** A rolling upgrade with BEs below exec version 20 plans no row-location fetch and keeps the plain TopN, with the same rows. No Thrift or Protobuf change: the request fields already exist on master and branch-4.2. Nothing is persisted. Connector plugins built against earlier API majors are refused by the version gate, as after every SPI surface change. - **Behavior change:** Two differences for users coming from 4.1 or 4.2. On 4.x, any filter that reaches the merge TopN with no column pruning in between moves below it, so rows depend on the select list: `SELECT v.*, w.row_id AS w_row_id FROM vector_search(... "top_k" = "3", "use_index" = "false") v JOIN lance_ctl.doris.vs_ivf_pq_f32 w ON v.row_id = w.row_id WHERE w.row_id > 2` returns rows 3, 513 and 514 there (the inferred `v.row_id > 2` filtered the candidates), and row 3 with three columns of `v`. Here only the WHERE written on the function (`FROM vector_search(...) [alias] WHERE ...`) filters the candidates; outer WHEREs, CTE consumer filters, a WHERE over a join and inferred predicates apply to the result, so the query returns row 3. Second, the privilege rules below. - **Security and privileges:** SELECT on the table is checked before the connector is called, as on 4.2; then SELECT on every column, since the arguments (the searched column, a `filter`) may read any. A search is refused while a row policy or a data mask applies to the user (`vector_search() is not supported on table '<table>' while row policies apply to it for the current user`), since it can apply neither; `root` and `admin` are exempt, as from row policies on scans. No new outbound host. - **Follow-up plan:** A second PR ports branch-4.2's coverage suites that need the large fixtures (index types, IVF_FLAT, the index matrix, indexed element types, metrics, multivector) together with the generators of those fixtures; apache#68707 and apache#69852 come after it. ### Testing All local, on a Mac (arm64), on the head unless noted. - fe-core, 185 tests in 20 classes: the search classes, including `SearchWherePlacementTest`, which plans SQL through the whole analyzer and rewriter against a mocked connector; the lazy-materialization classes; and the analysis and CTE classes that meet the changed analyzer. Lance plugin, 317 tests; connector SPI, 172 (before the last javadoc-only change). - 32 single-point mutations of this PR's decisions, in three rounds, each turning only its target tests red; putting the WHERE rule back into the rewriter, as on 4.x, fails the CTE, join and outer-LIMIT cases. - One FE and one BE built from this branch (the BE from an earlier commit with the same BE change), a read-only S3 server standing in for MinIO: all 17 suites in `external_table_p0/lance` pass, including the six ported suites, whose `.out` files match branch-4.2's, and `test_lance_search_where_and_policy`, which tests the policy as a non-root user. On an FE with the 4.x rule, the suite's outer-LIMIT and CTE queries and the join query above return the 4.x rows, and a user reads rows their row policy hides. - Rolling upgrade: at `be_exec_version` 19 the search plans no `VMaterializeNode` and returns the same rows as at 20. ### Notes for Reviewers - The WHERE is placed at analysis because only there is a filter right above the merge TopN surely the WHERE written on the function; later `MergeTopNs`, `RewriteCteChildren`, `InferJoinNotNull` and `InferPredicates` put other filters in the same place. Join runtime filters and TopN filters already stop at a TopN. - Exec version 20 rather than 19: master BEs built before the Lance row-location reader landed already report 19. - `LazyMaterializeTopN` now runs at every `topn_lazy_materialization_threshold`, as on 4.2, because the connector decides for a search; tables still follow the threshold (`TopnLazyMaterializeTest`). - Unlike 4.2: Jackson parses the query vector, stricter than 4.2's Gson (`[1;2]` and comments are refused); an invalid property is named in lower case, as the SPI passes it; SELECT is checked on the table found, not on the name as written. - Unchanged from 4.2: a search's columns can be fetched late at a TopN that is not its merge TopN (`ORDER BY t.x LIMIT 100000` over a join), outside `topn_lazy_materialization_threshold`; results are right. ### Release note `vector_search` and `full_text_search` work on `lance` catalogs, served by the Lance connector plugin. Unlike 4.1 and 4.2, only the WHERE written on the function filters the search's candidates; other filters apply to its result, so rows no longer depend on the select list. A search needs SELECT on every column and is refused while a row policy or a data mask applies to the user. `approx_mode` and searching earlier versions, tags or branches are not supported yet. ### Check List (For Author) - Behavior changed: Yes (see Details) - Does this need documentation: Yes (the doris-website pages of both functions for the dev version, including the WHERE and privilege rules; to follow) - Pre-submission status: Partially verified: the suites ran against a local S3 stand-in, not the External pipeline's MinIO; PREPARE forwarded through a follower FE, data masks and column denials from an authorization plugin, and cloud mode were not run (masks and column denials are covered by unit tests) ### AI Disclosure - Tool: Claude Code (Claude Opus 5.5) - Generated: the code, the tests, the fixture registration and this description - Human review: not stated - Prompts: 1. Port branch-4.2's `vector_search` / `full_text_search` to master as the next Lance task; show the generic SPI design first. 2. The design as approved: the 4.2 snapshot plus distance bounds and `prefilter`; the SPI shape as proposed; a new BE exec version 20 as the lazy-fetch fence; two PRs, small fixtures first. 3. Fix the three problems the self-review found that 4.x also has (filters crossing the merge TopN; row policies, masks and column privileges not applied) in this PR before publishing it. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…talogs ### Background Lance datasets carry vector indexes (IVF_FLAT, IVF_PQ, IVF_SQ, IVF_HNSW_*) and full-text indexes. branch-4.1 and branch-4.2 expose them through two table functions, `vector_search(...)` and `full_text_search(...)`: each reads a table of a `lance` catalog and returns its columns plus `_distance` or `_score`; every index segment and every unindexed fragment becomes one scan range, and a Doris TopN merges the ranges' candidates. On master, Lance is a connector plugin (apache#70680), fe-core holds no Lance code, and the BE already executes these searches. ### What problem does this PR solve? Issue Number: close apache#70970 Related PR: apache#65730, apache#66512, apache#66841, apache#67039, apache#67289, apache#68028, apache#68162, apache#68813, apache#68815 (the branch-4.x implementation this ports), apache#70680 (builds on: the Lance connector plugin) PR Type: Feature Problem Summary: Users of `lance` catalogs lose vector and full-text search on master: both functions fail with `Can not found function 'vector_search'`. They come back with branch-4.2's arguments, defaults, limits, errors and EXPLAIN keys, through a new optional connector SPI: fe-core owns the two functions and the plan rules, the connector parses the arguments and plans the search. Two 4.x problems are fixed on the way: filters other than the function's own WHERE crossed the merge, so rows depended on the select list, and row policies, masks and column privileges did not apply. 60% of the diff is tests. Existing statements are unaffected; connector plugins move to API 38.0. ```sql SELECT row_id, category, label, _distance FROM vector_search("table" = "lance_ctl.doris.vs_ivf_pq_f32", "column" = "embedding", "query_vector" = "[0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15]", "top_k" = "5", "metric" = "l2", "nprobes" = "4", "refine_factor" = "10") ORDER BY _distance, row_id; ``` | | Result | |---|---| | master | `Can not found function 'vector_search'` | | this PR (same as branch-4.2) | `1 even item-0001 0.0`, `2 odd item-0002 16.0`, `3 even item-0003 64.0`, `4 odd item-0004 144.0`, `5 even item-0005 256.0` | ### Details - **Change map:** 126 files, +7,321 / -59: production code +2,911 (40%), tests with their generated `.out` +4,397 (60%), docs and build +13. Production code by part, one commit each: 1. Connector search SPI (+344): `ConnectorSearchOps`, the request, function and result types, the `applyTopnLazyMaterialization` overload with lazy column names, API 37.0 -> 38.0 and its surface baselines. 2. Engine (+874: fe-core 865, fe-common 4, BE 5): the two functions, routing and the privilege and policy checks (`ExternalSearchTableValuedFunction`); binding with the merge TopN and PREPARE / EXECUTE parameters (`BindExpression`, `LogicalPlanBuilder`, `UnboundTVFRelation`); the WHERE placement (`PushDownWhereThroughSearchTopN`, an analysis rule); lazy materialization admission and hand-off (`MaterializeProbeVisitor`, `LazyMaterializeTopN`, the translator, `PluginDrivenScanNode`); `enable_lance_lazy_materialization`; BE exec version 20. 3. Lance plugin (+1,693): argument parsing and vector encoding (`LanceSearchArguments`, `LanceVectorQuery`, 865), search planning over index segments and fragments (`LanceScanPlanner`, `LanceSearchPlan`, index metrics, about 470), the search handle, metadata and scan properties (about 360), with its unit tests. 4. fe-core unit tests. 5. Regression suites, three small fixtures copied from branch-4.2 and their registration. - **Scope:** `vector_search` over fixed-size-list vector columns of float16, float32, float64, uint8 and int8, with the `l2`, `cosine`, `dot` and `hamming` metrics, index or flat search (`use_index`, `nprobes`, `refine_factor`, `ef`, `query_parallelism`), a Lance `filter` with `prefilter`, and `distance_lower_bound` / `distance_upper_bound`; `full_text_search` with match and phrase queries and the `STRICT` / `INDEX_ONLY` coverage modes; server-side PREPARE with `?` for `vector_search`'s `query_vector`, `top_k`, `offset`, `filter` and both distance bounds. Not supported: `approx_mode` (apache#69852, which master's BE does not read yet), searching earlier versions, tags or branches (apache#68707), `?` in `full_text_search` (refused: `full_text_search properties must be constant in a prepared statement`), and catalogs whose connector does not implement the SPI (refused: `Catalog 'x' does not support vector_search()`). Modules: fe-connector-spi, fe-core, fe-common, fe-connector-lance, and one constant in the BE. - **Design:** The engine keeps the two function names and routes by the catalog of the `table` argument to `ConnectorSearchOps#prepareSearch`, an optional interface of the connector metadata (implementing it is the declaration, as for `ConnectorFileSourceOps`). The request carries the function, every argument except `table` under its lower-case name, and the names a PREPARE defers; the connector answers with the scan handle, the columns ending with the result column, `top_k`, `offset`, and whether the engine may fetch top-level columns after the merge. The engine owns the result column, the merge order (`_distance` ascending, `_score` descending) and which WHERE filters the candidates. Rejected: plugin-registered function names (one name could belong to one plugin only, while branch-4.2's apache#69493 lets Paimon serve `vector_search` too) and engine-parsed common arguments (Lance and Paimon differ in ranges and in what `filter` means). Proposed in apache#70970, opened with this PR; not discussed yet. - **Usage:** ```sql SELECT row_id, _score FROM full_text_search("table" = "lance_ctl.doris.full_text_search", "column" = "body", "query" = "lance", "top_k" = "4") ORDER BY _score DESC, row_id; -- the WHERE written on the function filters the candidates of each range before the merge SELECT row_id, _distance FROM vector_search("table" = "lance_ctl.doris.vs_ivf_pq_f32", "column" = "embedding", "query_vector" = "[0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15]", "top_k" = "3") v WHERE v.category = 'odd'; -- as a server-side prepared statement (JDBC with useServerPrepStmts=true), each EXECUTE binding the values SELECT row_id, _distance FROM vector_search("table" = "lance_ctl.doris.vs_ivf_pq_f32", "column" = "embedding", "query_vector" = ?, "top_k" = ?, "offset" = ?, "filter" = ?) ORDER BY _distance, row_id; ``` - **Default behavior:** Available on every `lance` catalog. `top_k` 10, `offset` 0, `prefilter` false, and the metric Lance's default (L2), as on branch-4.2. Two-phase fetch is on (`enable_lance_lazy_materialization` = true) once every BE reports exec version 20, and `topn_lazy_materialization_threshold` does not limit a search's TopN. - **Compatibility:** A rolling upgrade with BEs below exec version 20 plans no row-location fetch and keeps the plain TopN, with the same rows. No Thrift or Protobuf change: the request fields already exist on master and branch-4.2. Nothing is persisted. Connector plugins built against earlier API majors are refused by the version gate, as after every SPI surface change. - **Behavior change:** Two differences for users coming from 4.1 or 4.2. On 4.x, any filter that reaches the merge TopN with no column pruning in between moves below it, so rows depend on the select list: `SELECT v.*, w.row_id AS w_row_id FROM vector_search(... "top_k" = "3", "use_index" = "false") v JOIN lance_ctl.doris.vs_ivf_pq_f32 w ON v.row_id = w.row_id WHERE w.row_id > 2` returns rows 3, 513 and 514 there (the inferred `v.row_id > 2` filtered the candidates), and row 3 with three columns of `v`. Here only the WHERE written on the function (`FROM vector_search(...) [alias] WHERE ...`) filters the candidates; outer WHEREs, CTE consumer filters, a WHERE over a join and inferred predicates apply to the result, so the query returns row 3. Second, the privilege rules below. - **Security and privileges:** SELECT on the table is checked before the connector is called, as on 4.2; then SELECT on every column, since the arguments (the searched column, a `filter`) may read any. A search is refused while a row policy or a data mask applies to the user (`vector_search() is not supported on table '<table>' while row policies apply to it for the current user`), since it can apply neither; `root` and `admin` are exempt, as from row policies on scans. No new outbound host. - **Follow-up plan:** A second PR ports branch-4.2's coverage suites that need the large fixtures (index types, IVF_FLAT, the index matrix, indexed element types, metrics, multivector) together with the generators of those fixtures; apache#68707 and apache#69852 come after it. ### Testing All local, on a Mac (arm64), on the head unless noted. - fe-core, 185 tests in 20 classes: the search classes, including `SearchWherePlacementTest`, which plans SQL through the whole analyzer and rewriter against a mocked connector; the lazy-materialization classes; and the analysis and CTE classes that meet the changed analyzer. Lance plugin, 317 tests; connector SPI, 172 (before the last javadoc-only change). - 32 single-point mutations of this PR's decisions, in three rounds, each turning only its target tests red; putting the WHERE rule back into the rewriter, as on 4.x, fails the CTE, join and outer-LIMIT cases. - One FE and one BE built from this branch (the BE from an earlier commit with the same BE change), a read-only S3 server standing in for MinIO: all 17 suites in `external_table_p0/lance` pass, including the six ported suites, whose `.out` files match branch-4.2's, and `test_lance_search_where_and_policy`, which tests the policy as a non-root user. On an FE with the 4.x rule, the suite's outer-LIMIT and CTE queries and the join query above return the 4.x rows, and a user reads rows their row policy hides. - Rolling upgrade: at `be_exec_version` 19 the search plans no `VMaterializeNode` and returns the same rows as at 20. ### Notes for Reviewers - The WHERE is placed at analysis because only there is a filter right above the merge TopN surely the WHERE written on the function; later `MergeTopNs`, `RewriteCteChildren`, `InferJoinNotNull` and `InferPredicates` put other filters in the same place. Join runtime filters and TopN filters already stop at a TopN. - Exec version 20 rather than 19: master BEs built before the Lance row-location reader landed already report 19. - `LazyMaterializeTopN` now runs at every `topn_lazy_materialization_threshold`, as on 4.2, because the connector decides for a search; tables still follow the threshold (`TopnLazyMaterializeTest`). - Unlike 4.2: Jackson parses the query vector, stricter than 4.2's Gson (`[1;2]` and comments are refused); an invalid property is named in lower case, as the SPI passes it; SELECT is checked on the table found, not on the name as written. - Unchanged from 4.2: a search's columns can be fetched late at a TopN that is not its merge TopN (`ORDER BY t.x LIMIT 100000` over a join), outside `topn_lazy_materialization_threshold`; results are right. ### Release note `vector_search` and `full_text_search` work on `lance` catalogs, served by the Lance connector plugin. Unlike 4.1 and 4.2, only the WHERE written on the function filters the search's candidates; other filters apply to its result, so rows no longer depend on the select list. A search needs SELECT on every column and is refused while a row policy or a data mask applies to the user. `approx_mode` and searching earlier versions, tags or branches are not supported yet. ### Check List (For Author) - Behavior changed: Yes (see Details) - Does this need documentation: Yes (the doris-website pages of both functions for the dev version, including the WHERE and privilege rules; to follow) - Pre-submission status: Partially verified: the suites ran against a local S3 stand-in, not the External pipeline's MinIO; PREPARE forwarded through a follower FE, data masks and column denials from an authorization plugin, and cloud mode were not run (masks and column denials are covered by unit tests) ### AI Disclosure - Tool: Claude Code (Claude Opus 5.5) - Generated: the code, the tests, the fixture registration and this description - Human review: not stated - Prompts: 1. Port branch-4.2's `vector_search` / `full_text_search` to master as the next Lance task; show the generic SPI design first. 2. The design as approved: the 4.2 snapshot plus distance bounds and `prefilter`; the SPI shape as proposed; a new BE exec version 20 as the lazy-fetch fence; two PRs, small fixtures first. 3. Fix the three problems the self-review found that 4.x also has (filters crossing the merge TopN; row policies, masks and column privileges not applied) in this PR before publishing it. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
What problem does this PR solve?
Issue Number: Part of #66495
Problem Summary:
Companion documentation PR: apache/doris-website#4082.
#66512 gave
vector_search()end-to-end coverage for all six Lance ANN algorithms, but onlywith Float32 + L2. Reviewer feedback there was to merge it and follow up with the other
element types, which is what this PR does.
The gap is not only a dependency-compatibility one. #66841 made the FE metric-aware: Doris
plans an indexed split only when the requested metric equals the metric the index was built
with (
LanceScanNode.metricMatches), and otherwise plans flat splits rather than lettingLance fall back to brute force silently. Until now the cosine and dot branches of that
comparison had never run against a real index, because no non-L2 index existed anywhere in
the fixture. This PR covers them, in both directions.
What is changed?
There is no FE or BE production-code change.
The matrix is now covered in full, in two tiers
The support matrix has 96 cells (4 element types x 4 metrics x 6 algorithms). All 96 were
built against the embedded Lance generation, one per subprocess: 56 build and answer a
search, 40 do not, and the 40 fall into three groups — a float type with
hamming(IVFtraining rejects it),
uint8with a non-hamming metric (it is read as a binary vector), anduint8under a quantizing builder.buildable_Budugs()in the generator yields exactlythose 56; the measurement and the three failure groups are recorded next to it.
All 56 are covered:
Float64, Float16 and UInt8. Committed goldens, a closed-form distance ladder where the
data shape has one, and a discriminator per table. Data shape is per metric, because one
shape cannot serve them all: the collinear ladder is degenerate under cosine (directions
converge and the top distances collapse to zero) and under dot (the answer stops depending
on the query), so those tables use a directional shape, and UInt8 uses a thermometer code
that makes hamming an exact ladder.
doris.vs_index_matrix, at 64 rows with one vector column percell. One column per cell rather than several indexes on one column, because only the
first index built on a column is reachable — Lance answers the others with a brute-force
scan, and Doris arrives at the same place by another route, since
selectIndexSegmentskeeps only the segments of the first index it finds for a field id.
vs_index_matrixasserts three things per cell, and no goldens, so a fixture rebuild leavesit untouched:
lanceSearchUnindexedFragments=0— the only check thatwould catch an index reaching one of the two fragments.
nprobes=1answers differently fromnprobes=4. A flat scan has no partitions and cannot,so this is what separates a real indexed search from a silent fallback. Four query rows are
tried and the first that discriminates is enough.
refine_factor, the indexed search returns exactly the rows an exhaustivescan returns.
Recall is not measured, and (3) compares two paths inside the same backend, so it does not pin
absolute distances — that is what the 12 depth tables' closed-form ladders do.
Fixture self-check
The self-check is the whole contract for a fixture whose bytes are not reproducible, so it now
also pins a digest of every profile's vectors and reads rows back from each table; asserts the
metric each index was actually built with, read from
stats["indices"][*]["metric_type"]rather than searched for, because a cosine IVF_PQ reports
l2on its sub-index; keeps theindexed-vs-flat comparison bit-exact for the integer ladders; and enforces the
pylanceandlance-namespacepins before building or verifying. Discriminator margins are reported andwarned on when thin.
--repindowngrades a stale discriminator row to a warning so a rebuildcan complete and the row can then be re-measured against the fixture that was promoted.
Fixture publishing
iceberg.yaml.tplnow usesmc mirror --overwrite --removeinstead ofmc cp -r. The__manifestversion is a commit count that a rebuild can lower, and Lance names version filesu64::MAX - versionso a listing resolves newest first; a stale higher-versioned manifest leftin the bucket therefore wins over the one just published. A live test environment's MinIO had
accumulated several.
Also removes two
entrypoint.shfiles that agit add -Ahad picked up — they are renderedfrom the
.tplbeside them byrun-thirdparties-docker.sh— and adds the.gitignorerulethat was missing for them.
Release note
None
Check List (For Author)
Test
Behavior changed:
Does this need documentation?
[doc](lance) Document the vector element type and metric compatibility matrix doris-website#4082
Check List (For Reviewer who merge this PR)