Skip to content

[feature](lance) Support prepared vector search on branch-4.1 - #68162

Merged
yiguolei merged 3 commits into
apache:branch-4.1from
Gabriel39:dev/lance-prepared-statement-branch-4.1
Sep 20, 2026
Merged

yiguolei merged 3 commits into
apache:branch-4.1from
Gabriel39:dev/lance-prepared-statement-branch-4.1

Conversation

@Gabriel39

@Gabriel39 Gabriel39 commented Sep 18, 2026 •

Copy link
Copy Markdown
Contributor

What problem does this PR solve?

vector_search("query_vector"=?, "top_k"=?) currently converts the placeholders into the literal string ?, so server-side prepared Lance vector queries fail during analysis.

Preserve placeholders for query_vector, top_k, offset, and filter, and bind fresh property values on every EXECUTE. PREPARE resolves the output schema without requiring a query vector. Table, column, and search configuration remain constant. Each execution performs normal analysis and planning and resolves Lance metadata again; the retained statement never caches a bound vector or snapshot.

This supports both indexed and flat searches and reuses the parsed statement. Forwarded executions preserve cached parameter types when the client omits the type table on repeated executions; the forwarding request includes the types needed by a fresh master-side PREPARE. It does not introduce an execution-plan cache or bypass the optimizer.

Example with MySQL Connector/J and useServerPrepStmts=true:

try (PreparedStatement statement = connection.prepareStatement(
        "SELECT id, _distance FROM vector_search("
        + "'table'='catalog.db.items', 'column'='embedding', "
        + "'query_vector'=?, 'top_k'=?, 'offset'=?, 'filter'=?)")) {
    for (String vector : vectors) {
        statement.setString(1, vector); // JSON array matching the vector column dimension.
        statement.setInt(2, 10);
        statement.setInt(3, 0);
        statement.setString(4, "id > 0");
        try (ResultSet rows = statement.executeQuery()) {
            // Consume the result before executing the next vector.
        }
    }
}

Release note

Support server-side prepared parameters for Lance vector_search query vectors, top-k, offsets, and filters.

Validation

  • Proxy PREPARE tests reproduce the stale planner context in both search modes before the fix; PREPARE now synchronizes the executor with the parser-created context before parameter decoding.
  • Parser and analyzer tests cover parameter retention, quoted question marks, case-insensitive properties, constant-only property rejection, repeated execution with different vectors and snapshots, mixed constants/parameters, and invalid or missing parameters.
  • A JDBC regression reuses one ServerPreparedStatement with A/B/A parameter changes and compares results with literal SQL for both indexed and flat searches. On live non-master FEs, it also prepares locally and forces repeated executions to the master.
  • A protocol test exercises five executions through the follower decoder, RPC request construction, Thrift serialization, and a fresh proxy decoder. It covers omitted type tables, unsigned values, NULL parameters across two bitmap bytes, and later parameter type changes. Local execution retains the original payload without copying it.
  • PREPARE and EXECUTE share single-vector and multi-vector schema validation. Tests cover schema-only PREPARE, multi-vector binding, and rejection of invalid dimensions and excessive candidate budgets at EXECUTE. The four CI FE UT failures caused by unbound-vector validation were reproduced before the fix.
  • Local verification: all 154 tests passed via run-fe-ut.sh across MysqlPreparedStatementForwardingTest, MysqlConnectProcessorCursorFetchTest, FEOpExecutorMysqlProtocolTest, LancePreparedSearchTest, LancePreparedStatementTest, LanceVectorQueryTest, VectorSearchTableValuedFunctionTest, FullTextSearchTableValuedFunctionTest, LanceScanNodeTest, PrepareTest, and NereidsParserTest. FE Checkstyle passed. The full external JDBC regression was also executed locally using the current PR FE build, a master FE, an observer FE, one BE, and the MinIO/Lance fixtures: 1 suite passed, 0 failures, 0 skips. It executed 12 real server-prepared queries covering direct and forwarded execution, indexed and flat search, and A/B/A parameter changes. The original script reproduced the CI String.positive() failure before fixing both JDBC URL concatenations.

Check List (For Author)

  • Test
    • Regression test
    • Unit Test
  • Behavior changed:
    • Yes. Supported vector_search property values can be prepared parameters.
  • Does this need documentation?
    • Yes. Usage and the supported parameter scope are documented above.

Check List (For Reviewer who merge this PR)

  • Confirm the release note
  • Confirm test cases
  • Confirm document
  • Add branch pick label

@Gabriel39
Gabriel39 requested a review from yiguolei as a code owner September 18, 2026 06:30
@hello-stephen

Copy link
Copy Markdown
Contributor

Thank you for your contribution to Apache Doris.
Don't know what should be done next? See How to process your PR.

Please clearly describe your PR:

  1. What problem was fixed (it's best to include specific error reporting information). How it was fixed.
  2. Which behaviors were modified. What was the previous behavior, what is it now, why was it modified, and what possible impacts might there be.
  3. What features were added. Why was this function added?
  4. Which code was refactored and why was this part of the code refactored?
  5. Which functions were optimized and what is the difference before and after the optimization?

@Gabriel39

Copy link
Copy Markdown
Contributor Author

run buildall

@Gabriel39

Copy link
Copy Markdown
Contributor Author

/review

@github-actions github-actions Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Static review conclusion: request changes for one P1 correctness issue. A server-prepared SELECT with a parameterized vector_search property fails if it is prepared locally on a readable follower and a later execution is forwarded to the master: reconstructed PREPARE plans with the executor's unmarked StatementContext before the forwarded parameter packet is decoded. The planner context must be synchronized, and this path needs a forced-forward/proxy regression.

Critical checkpoints: the direct PREPARE/EXECUTE path preserves placeholder identity and rebuilds fresh bindings, authorization, Lance metadata, snapshot state, request values, and the global TopN on every execution. Schema-only PREPARE stops before physical translation, so its deferred vector and dummy values cannot reach a scan. Indexed and flat request construction, limit/offset handling, property validation, plan-copy behavior, cache fencing, and FE/BE request checks were traced without finding another defect. The added JDBC regression covers real server-prepared A/B/A reuse for both search modes, but it does not exercise execution forwarding. The expression AGENTS checkpoint is not implicated because no checkLegalityBeforeTypeCoercion overload was added or changed. No user-specific focus points were provided.

This was a static-only review as required; I did not run builds or tests. The PR author's reported FE tests/checkstyle and the fixture-gated external regression were not independently validated here. Two complete review rounds covered all nine changed files and converged on this single non-duplicate finding, with no unresolved candidates.

@Gabriel39

Copy link
Copy Markdown
Contributor Author

run buildall

@Gabriel39

Copy link
Copy Markdown
Contributor Author

/review

@github-actions github-actions Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Static review of head 1364feb56e found one blocking correctness issue.

  • Prepared-property parsing, placeholder ID retention/copying, schema-only PREPARE deferral, and fresh per-EXECUTE vector/top-k/offset/filter/field-ID/snapshot rebuilding are internally consistent.
  • The prior forwarded PREPARE StatementContext issue is fixed at this head and was treated as an existing-thread duplicate fence.
  • Repeated forced forwarding still loses Connector/J's cached parameter types: the second same-typed COM_STMT_EXECUTE omits the type table while the master reconstructs an untyped PREPARE, so the A/B/A path fails before binding. See the inline P1.
  • The expressions review checkpoint is not directly implicated because no checkLegalityBeforeTypeCoercion overload changed.
  • No additional user focus was provided.

Validation status: static inspection only, as required by the runner contract. I did not run builds or tests. The author reports 107 FE tests and FE Checkstyle passed and the Groovy regression compiled; the external multi-FE Lance regression was not run, and static protocol tracing indicates its second forwarded iteration will fail.

@Gabriel39

Copy link
Copy Markdown
Contributor Author

run buildall

@Gabriel39

Copy link
Copy Markdown
Contributor Author

/review

@Gabriel39

Copy link
Copy Markdown
Contributor Author

run buildall

@Gabriel39

Copy link
Copy Markdown
Contributor Author

/review

@Gabriel39

Copy link
Copy Markdown
Contributor Author

Fixed both JDBC URL concatenations in the Lance prepared-search regression. A leading + on a new line was parsed by Groovy as unary plus on a String, causing the runtime String.positive() error even though script compilation succeeded.

Verified locally before committing:

  • Built the current PR FE with build.sh --fe.
  • Ran the original complete suite and reproduced the same String.positive() failure.
  • Ran the fixed complete suite against a master FE, an observer FE, one BE, and MinIO/Lance fixtures: 1 suite passed, 0 failures, 0 skips.
  • All 12 actual ServerPreparedStatement executions passed, covering direct and forwarded execution, indexed and flat search, and repeated A/B/A parameter binding. Both connections retained emulateUnsupportedPstmts=false.

The fix does not weaken any assertions or skip forwarding coverage.

@github-actions

Copy link
Copy Markdown
Contributor

Codex automated review failed and did not complete.

Error: Selected model is at capacity. Please try a different model.
Workflow run: https://github.com/apache/doris/actions/runs/35326619148

Please inspect the workflow logs and rerun the review after the underlying issue is resolved.

@github-actions

Copy link
Copy Markdown
Contributor

Codex automated review failed and did not complete.

Error: Codex completed, but no new pull request review was submitted for the current head SHA.
Workflow run: https://github.com/apache/doris/actions/runs/35323527595

Please inspect the workflow logs and rerun the review after the underlying issue is resolved.

@hello-stephen

Copy link
Copy Markdown
Contributor

FE UT Coverage Report

Increment line coverage 90.09% (100/111) 🎉
Increment coverage report
Complete coverage report

@Gabriel39
Gabriel39 force-pushed the dev/lance-prepared-statement-branch-4.1 branch from d8a1594 to cab91e1 Compare September 20, 2026 01:25
@Gabriel39

Copy link
Copy Markdown
Contributor Author

run buildall

@Gabriel39

Copy link
Copy Markdown
Contributor Author

/review

@github-actions github-actions Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Static review conclusion: no blocking issues found at head cab91e1. Summary-only approval comment; no inline comments.

Critical checkpoints:

  • Prepared vector_search properties are parsed with stable placeholder IDs, restricted to query_vector/top_k/offset/filter, reject dynamic names/duplicates/NULL or non-literal execute values, and are rebound into a fresh property map and VectorSearch/catalog function on every EXECUTE. Retained plans do not reuse a prior Lance vector, metadata snapshot, or catalog-function cache.
  • PREPARE defers only query-value-dependent vector encoding, shape/dimension, multi-vector metric, and candidate-budget checks. Table/catalog authorization, metadata/version, schema, field IDs, static options, filter encoding, and top-k/offset invariants remain enforced; PrepareCommandPlanner stops at analysis, so an unset query vector cannot reach physical scanning.
  • Repeated COM_STMT_EXECUTE forwarding preserves the follower's cached MySQL type codes and unsigned bits when the packet omits its type table, rebuilds the null bitmap/type table in little-endian form, copies values without mutating the client buffer, and retains zero-parameter forwarding behavior. The existing omitted-type forwarding thread is therefore a duplicate fence and is not resubmitted.
  • PrepareCommand now installs the parser-created prepare-stage StatementContext before slot planning and registration. The existing forwarded planner-context thread is fixed at this head and is also a duplicate fence.
  • The required expressions AGENTS checkpoint is not implicated: this PR adds no checkLegalityBeforeTypeCoercion overload or child traversal.
  • No user-specific review focus points were supplied.

The normal full review and the risk-focused forwarding/context review both returned NO_NEW_VALUABLE_FINDINGS after complete changed-file coverage and missed-issue rechecks. This was static-only review as required by the runner; I did not run builds or tests. The author-reported FE tests/checkstyle and fixture-gated external regression were not independently validated here. The repository contained no discoverable code-review SKILL.md, so the mandated review prompt and checked-in AGENTS guide were followed as the operative instructions.

@hello-stephen

Copy link
Copy Markdown
Contributor

FE UT Coverage Report

Increment line coverage 89.91% (98/109) 🎉
Increment coverage report
Complete coverage report

@yiguolei
yiguolei merged commit 66ebcdd into apache:branch-4.1 Sep 20, 2026
31 of 32 checks passed
yiguolei pushed a commit that referenced this pull request Sep 21, 2026
### What problem does this PR solve?

`vector_search("query_vector"=?, "top_k"=?)` currently converts the
placeholders into the literal string `?`, so server-side prepared Lance
vector queries fail during analysis.

Preserve placeholders for `query_vector`, `top_k`, `offset`, and
`filter`, and bind fresh property values on every EXECUTE. PREPARE
resolves the output schema without requiring a query vector. Table,
column, and search configuration remain constant. Each execution
performs normal analysis and planning and resolves Lance metadata again;
the retained statement never caches a bound vector or snapshot.

This supports both indexed and flat searches and reuses the parsed
statement. Forwarded executions preserve cached parameter types when the
client omits the type table on repeated executions; the forwarding
request includes the types needed by a fresh master-side PREPARE. It
does not introduce an execution-plan cache or bypass the optimizer.

Example with MySQL Connector/J and `useServerPrepStmts=true`:

```java
try (PreparedStatement statement = connection.prepareStatement(
        "SELECT id, _distance FROM vector_search("
        + "'table'='catalog.db.items', 'column'='embedding', "
        + "'query_vector'=?, 'top_k'=?, 'offset'=?, 'filter'=?)")) {
    for (String vector : vectors) {
        statement.setString(1, vector); // JSON array matching the vector column dimension.
        statement.setInt(2, 10);
        statement.setInt(3, 0);
        statement.setString(4, "id > 0");
        try (ResultSet rows = statement.executeQuery()) {
            // Consume the result before executing the next vector.
        }
    }
}
```

### Release note

Support server-side prepared parameters for Lance `vector_search` query
vectors, top-k, offsets, and filters.

### Validation

- Proxy PREPARE tests reproduce the stale planner context in both search
modes before the fix; PREPARE now synchronizes the executor with the
parser-created context before parameter decoding.
- Parser and analyzer tests cover parameter retention, quoted question
marks, case-insensitive properties, constant-only property rejection,
repeated execution with different vectors and snapshots, mixed
constants/parameters, and invalid or missing parameters.
- A JDBC regression reuses one `ServerPreparedStatement` with A/B/A
parameter changes and compares results with literal SQL for both indexed
and flat searches. On live non-master FEs, it also prepares locally and
forces repeated executions to the master.
- A protocol test exercises five executions through the follower
decoder, RPC request construction, Thrift serialization, and a fresh
proxy decoder. It covers omitted type tables, unsigned values, NULL
parameters across two bitmap bytes, and later parameter type changes.
Local execution retains the original payload without copying it.
- PREPARE and EXECUTE share single-vector and multi-vector schema
validation. Tests cover schema-only PREPARE, multi-vector binding, and
rejection of invalid dimensions and excessive candidate budgets at
EXECUTE. The four CI FE UT failures caused by unbound-vector validation
were reproduced before the fix.
- Local verification: all 154 tests passed via `run-fe-ut.sh` across
`MysqlPreparedStatementForwardingTest`,
`MysqlConnectProcessorCursorFetchTest`, `FEOpExecutorMysqlProtocolTest`,
`LancePreparedSearchTest`, `LancePreparedStatementTest`,
`LanceVectorQueryTest`, `VectorSearchTableValuedFunctionTest`,
`FullTextSearchTableValuedFunctionTest`, `LanceScanNodeTest`,
`PrepareTest`, and `NereidsParserTest`. FE Checkstyle passed. The full
external JDBC regression was also executed locally using the current PR
FE build, a master FE, an observer FE, one BE, and the MinIO/Lance
fixtures: 1 suite passed, 0 failures, 0 skips. It executed 12 real
server-prepared queries covering direct and forwarded execution, indexed
and flat search, and A/B/A parameter changes. The original script
reproduced the CI String.positive() failure before fixing both JDBC URL
concatenations.

### Check List (For Author)

- Test
    - [x] Regression test
    - [x] Unit Test
- Behavior changed:
- [x] Yes. Supported `vector_search` property values can be prepared
parameters.
- Does this need documentation?
- [x] Yes. Usage and the supported parameter scope are documented above.

### Check List (For Reviewer who merge this PR)

- [ ] Confirm the release note
- [ ] Confirm test cases
- [ ] Confirm document
- [ ] Add branch pick label
morningman added a commit that referenced this pull request Nov 5, 2026
…meter types (#70150)

### What problem does this PR solve?

Issue Number: None

Related PR: #68162, #69314

Problem Summary:

**In short.** This ports `MysqlPreparedStatementForwardingTest` from
branch-4.1 #68162 to master. Master already has the fix the test guards,
through #69314. The port adds what master's own tests do not cover: a
NULL bitmap of two bytes, and the forward request that `FEOpExecutor`
builds and Thrift carries. The PR changes tests only.

**Background.** A client that runs a server-side prepared statement
again may leave out the parameter types (`new_params_bind_flag` = 0) and
have the server reuse the ones it cached. A follower forwards every
COM_STMT_EXECUTE to the master. The master prepares the statement again
for each forwarded execution, so it has no cached types and cannot bind
the parameters. #68162 fixed this on branch-4.1, together with the Lance
prepared vector search it was written for. Master fixed it independently
in #69314: when the client reuses cached types,
`MysqlConnectProcessor.handleExecute` writes the forwarded packet again,
with the NULL bitmap, `new_params_bind_flag` = 1, every type code
including the unsigned flag, and the values. #69314 also has the prepare
stage plan with the context of the re-parsed statement, which is the
other generic part of #68162. Its tests in
`MysqlConnectProcessorLongDataTest` cover cached types, unsigned flags,
changing NULLs, changing types, all-NULL executions and the prepare
context.

**What those tests leave out.** They use at most four parameters, so the
NULL bitmap always fits in one byte. They also give the master the
buffer kept on the follower's context, rather than the request
`FEOpExecutor.buildStmtForwardParams` builds.

**What this PR adds.** The test runs a ten-parameter statement five
times on a follower connection:

- The parameter types are sent with the first and the fourth execution;
the other executions reuse the cached ones.
- One execution has a NULL parameter in each byte of the NULL bitmap.
- An unsigned INT parameter becomes a BIGINT in the fourth execution.

After each execution, the test builds the forward request with
`FEOpExecutor`, passes it through a Thrift round trip and executes it on
a new proxy context whose placeholders have no types. It then checks
three things: every parameter binds to the same value as on the
follower, the unsigned flag carries over, and the client's packet is
read to its end and left unchanged. The code is the 4.1 test adapted to
master's structure: master's `PrepareCommand`, query id and audit setup,
as in `MysqlConnectProcessorLongDataTest`, and expressions compared
directly. The 4.1 assertion that the follower keeps the client's buffer
was dropped, because master writes a separate buffer for cached types by
design.

**Results.**

| `handleExecute` on master | `MysqlConnectProcessorLongDataTest` (14) |
`MysqlPreparedStatementForwardingTest` (1) |
|---|---|---|
| as is | pass | pass |
| no rewrite of the forwarded packet for cached types (the bug #68162
fixed) | 3 fail | fails: the master binds untyped placeholders (`No
value present`) |
| the rewrite keeps only the first byte of the NULL bitmap | pass |
fails: the master reads the packet one byte off |

Co-authored-by: Gabriel <liwenqiang@selectdb.com>
morningman added a commit to morningman/doris that referenced this pull request Nov 25, 2026
…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>
morningman added a commit to morningman/doris that referenced this pull request Nov 28, 2026
…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>
morningman added a commit that referenced this pull request Nov 29, 2026
…talogs (#70971)

### 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
(#70680), fe-core holds no Lance code, and the BE already executes these
searches.

### What problem does this PR solve?

Issue Number: close #70970
Related PR: #65730, #66512, #66841, #67039, #67289, #68028, #68162,
#68813, #68815 (the branch-4.x implementation this ports), #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,315 / -59: production code +2,911 (40%),
tests with their generated `.out` +4,391 (60%), docs and build +13. The
six commits cover:
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. 6. Nullable INT8 vector-search
regression.
- **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` (#69852, which master's BE
does not read yet), searching earlier versions, tags or branches
(#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 #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 #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; #68707 and #69852 come after it.

### Testing

Initial feature validation ran locally on macOS (arm64) before the
rebase.

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

- Review follow-up: four Lance vector-search regression suites passed
against the local pre-rebase binaries and S3 fixture service. The new
nullable INT8 case returned only row 1 at distance zero. The IVF_PQ
EXPLAIN reported `USED`, one index segment, and coverage of both
fragments.
- After rebasing, 96 targeted FE tests passed (32 FE Core, 12 connector
SPI and 52 Lance connector). Checkstyle passed for all three modules.

### 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.
- Lance-C's pinned Lance revision preserves nulls during INT8
conversion. The Java SDK reports `metric_type` for both committed IVF
fixtures, while `distance_type` is part of the index file.
- 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.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants