924060929 commented on code in PR #70704:
URL: https://github.com/apache/doris/pull/70704#discussion_r4794480180


##########
fe/fe-core/src/main/java/org/apache/doris/tablefunction/ExternalSearchTableValuedFunction.java:
##########
@@ -175,11 +204,68 @@ public final List<Column> getTableColumns() {
 
     @Override
     public final ScanNode getScanNode(PlanNodeId id, TupleDescriptor desc, 
SessionVariable sv) {
-        return new PluginDrivenScanNode(id, desc, false, sv,
+        PluginDrivenScanNode node = new PluginDrivenScanNode(id, desc, false, 
sv,
                 ScanContext.builder().clusterName(sv.resolveCloudClusterName())
                         
.beExecVersion(ConnectContext.get().getStatementContext().getBeExecVersion())
                         .build(),
-                catalog.getConnector(), catalog.buildConnectorSession(), 
search.getScanHandle());
+                catalog.getConnector(), session, search.getScanHandle());
+        search.getVectorSearch().ifPresent(node::setVectorSearch);
+        PlanTranslatorContext translation = new PlanTranslatorContext();
+        List<Expr> predicates = new ArrayList<>();
+        for (Expression expression : boundPrefilter) {
+            for (Slot slot : expression.getInputSlots()) {
+                SlotDescriptor descriptor = desc.getSlots().stream()
+                        .filter(candidate -> 
candidate.getColumn().getName().equalsIgnoreCase(slot.getName()))
+                        .findFirst().orElseThrow(() -> new 
IllegalStateException(
+                                "search prefilter column was pruned: " + 
slot.getName()));
+                translation.addExprIdSlotRefPair(slot.getExprId(), new 
SlotRef(descriptor));
+            }
+            predicates.add(ExpressionTranslator.translate(expression, 
translation));
+        }
+        node.setVectorPrefilter(predicates);
+        return node;
+    }
+
+    public final Optional<ConnectorSearchFilter> getEngineFilter() {
+        return search.getEngineFilter();
+    }
+
+    public final boolean isWhereFiltersCandidates() {
+        return search.isWhereFiltersCandidates();
+    }
+
+    public final List<Slot> getPrefilterSlots() {
+        return boundPrefilter.stream().flatMap(expression -> 
expression.getInputSlots().stream())
+                .distinct().collect(Collectors.toList());
+    }
+
+    public final void bindFilter(LogicalFilter<?> plan, CascadesContext 
context) {

Review Comment:
   [P2] The BEFORE_SEARCH prefilter lives outside the plan tree, as mutable 
state on the bound TVF object (`search` / `boundPrefilter`), which hangs off a 
Nereids `Expression` (memoized `catalogFunction`). It keeps analysis-time 
ExprIds and un-rewritten expressions, and `getScanNode` re-resolves slots by 
column name with a fresh `PlanTranslatorContext`. Because column pruning can't 
see it, `PhysicalPlanTranslator.withVectorSearchPrefilterSlots` has to inject 
descriptor-only slots, e.g.:
   
   ```
   TopN(_distance)
     Filter(id IS NOT NULL)        <- simplified to TRUE and removed when id is 
NOT NULL
       TVFRelation(id, _distance)  <- id pruned, but the native prefilter still 
reads it
   ```
   
   Any path that rebuilds the TVF expression (`withChildren`, deep copy, 
`withDeferredArguments`) re-runs `toCatalogFunction` and gets an object without 
`boundPrefilter`. The `Filter` stays in the plan, but the native prefilter is 
gone, so each bucket takes top-k unfiltered and rows go missing silently. I 
couldn't trigger this today, but it relies on a calling convention.
   
   Suggestion: keep the prefilter in the plan, either as conjuncts carried by 
`LogicalTVFRelation` that take part in `getInputSlots` and column pruning, or 
by deriving it from the scan node's own conjuncts (a Filter directly above the 
scan already becomes scan conjuncts in the translator). Then the translator 
slot injection and the mutable fields can go away.



##########
fe/fe-core/src/main/java/org/apache/doris/nereids/rules/rewrite/PushDownVectorTopNIntoFileScan.java:
##########
@@ -0,0 +1,224 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+package org.apache.doris.nereids.rules.rewrite;
+
+import org.apache.doris.catalog.Column;
+import org.apache.doris.catalog.Type;
+import org.apache.doris.connector.spi.pushdown.ConnectorAnd;
+import org.apache.doris.connector.spi.pushdown.ConnectorExpression;
+import org.apache.doris.connector.spi.scan.ConnectorVectorSearch;
+import 
org.apache.doris.datasource.connector.converter.VectorSearchPredicateConverter;
+import org.apache.doris.datasource.plugin.PluginDrivenExternalTable;
+import org.apache.doris.datasource.scan.ConnectorVectorSearchPlanner;
+import org.apache.doris.nereids.rules.Rule;
+import org.apache.doris.nereids.rules.RuleType;
+import org.apache.doris.nereids.trees.expressions.Alias;
+import org.apache.doris.nereids.trees.expressions.Expression;
+import org.apache.doris.nereids.trees.expressions.NamedExpression;
+import org.apache.doris.nereids.trees.expressions.SlotReference;
+import org.apache.doris.nereids.trees.expressions.StatementScopeIdGenerator;
+import 
org.apache.doris.nereids.trees.expressions.functions.NoneMovableFunction;
+import 
org.apache.doris.nereids.trees.expressions.functions.scalar.InnerProductApproximate;
+import 
org.apache.doris.nereids.trees.expressions.functions.scalar.L2DistanceApproximate;
+import org.apache.doris.nereids.trees.expressions.literal.ArrayLiteral;
+import org.apache.doris.nereids.trees.expressions.literal.Literal;
+import org.apache.doris.nereids.trees.expressions.literal.NullLiteral;
+import org.apache.doris.nereids.trees.plans.Plan;
+import org.apache.doris.nereids.trees.plans.logical.LogicalFileScan;
+import org.apache.doris.nereids.trees.plans.logical.LogicalFilter;
+import org.apache.doris.nereids.trees.plans.logical.LogicalProject;
+import org.apache.doris.nereids.trees.plans.logical.LogicalTopN;
+import org.apache.doris.nereids.util.ExpressionUtils;
+import org.apache.doris.qe.ConnectContext;
+import org.apache.doris.thrift.TExternalSearchQuery;
+import org.apache.doris.thrift.TExternalSearchRequest;
+import org.apache.doris.thrift.TSearchVector;
+import org.apache.doris.thrift.TVectorElementType;
+import org.apache.doris.thrift.TVectorMetric;
+import org.apache.doris.thrift.TVectorSearchParams;
+
+import com.google.common.collect.ImmutableList;
+
+import java.nio.ByteBuffer;
+import java.nio.ByteOrder;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
+import java.util.Set;
+
+/** Preserve the global TopN and let a connector admit bounded search on each 
of its ranges. */
+public class PushDownVectorTopNIntoFileScan implements RewriteRuleFactory {
+    @Override
+    public List<Rule> buildRules() {
+        return ImmutableList.of(
+                logicalTopN(logicalProject(logicalFileScan())).then(top ->
+                        pushDown(top, top.child(), top.child().child(), 
Optional.empty()))
+                        .toRule(RuleType.PUSH_DOWN_VECTOR_TOPN_INTO_FILE_SCAN),
+                
logicalTopN(logicalProject(logicalFilter(logicalFileScan()))).then(top ->
+                        pushDown(top, top.child(), 
top.child().child().child(), Optional.of(top.child().child())))
+                        
.toRule(RuleType.PUSH_DOWN_VECTOR_TOPN_INTO_FILE_SCAN));
+    }
+
+    private Plan pushDown(LogicalTopN<?> top, LogicalProject<?> project,
+            LogicalFileScan scan, Optional<LogicalFilter<?>> filter) {
+        if (!(scan.getTable() instanceof PluginDrivenExternalTable) || 
scan.getVectorSearch().isPresent()
+                || scan.getTableSample().isPresent() || 
top.getOrderKeys().size() != 1 || top.getLimit() <= 0
+                || top.getOffset() > Integer.MAX_VALUE - top.getLimit()
+                || 
!ConnectContext.get().getSessionVariable().enableFileScannerV2
+                || scan.getScanParams().map(params -> 
params.incrementalRead()).orElse(false)) {
+            return null;
+        }
+        Alias key = project.getProjects().stream().filter(expr -> expr 
instanceof Alias
+                && expr.toSlot().equals(top.getOrderKeys().get(0).getExpr()))
+                .map(Alias.class::cast).findFirst().orElse(null);
+        if (key == null) {
+            return null;
+        }
+        Expression distance = key.child();
+        boolean l2 = distance instanceof L2DistanceApproximate;
+        if (!(l2 && top.getOrderKeys().get(0).isAsc())
+                && !(distance instanceof InnerProductApproximate && 
!top.getOrderKeys().get(0).isAsc())) {
+            return null;
+        }
+        if (!(distance.child(0) instanceof SlotReference) || 
!(distance.child(1) instanceof ArrayLiteral)) {
+            return null;
+        }
+        SlotReference vectorColumn = (SlotReference) distance.child(0);
+        List<Literal> query = ((ArrayLiteral) distance.child(1)).getValue();
+        if (query.isEmpty() || query.stream().anyMatch(value -> value 
instanceof NullLiteral
+                || !Float.isFinite((float) value.getDouble()))) {
+            return null;
+        }
+        // Moving a bounded read below assert_true/random-like projections may 
suppress evaluation/errors.
+        for (NamedExpression output : project.getProjects()) {
+            if (output.anyMatch(expr -> expr instanceof NoneMovableFunction
+                    || ((Expression) expr).getDataType().isVariantType()
+                    || ((Expression) expr).getDataType().isTimeStampNsType())) 
{
+                return null;
+            }
+        }
+        if (!complexColumnsRideAsWholeColumns(project, key, distance)) {
+            return null;
+        }
+        List<ConnectorExpression> predicates = new ArrayList<>();
+        if (filter.isPresent()) {
+            for (Expression conjunct : filter.get().getConjuncts()) {
+                ConnectorExpression converted = 
VectorSearchPredicateConverter.convert(conjunct);

Review Comment:
   [P2] FE admission requires an exact conversion of every conjunct, but in the 
SQL path BE builds the native filter from the scanner `_conjuncts` with 
`require_complete = _is_tvf_search()` (paimon_rust_table_reader.cpp L890/L911). 
So BE silently drops any data conjunct it cannot convert. FE and BE use two 
independent converters, and FE converts the rewrite-time Filter, not the 
conjuncts that reach BE. Any mismatch means each bucket picks top-k under a 
looser predicate, and the engine filter then returns fewer than LIMIT rows with 
no error. I found no concrete counterexample with today's type/operator sets, 
but the invariant in `VectorSearchPredicateConverter`'s doc ("must never 
silently lose an AND arm") isn't enforced.
   
   Suggestion: send the admitted prefilter explicitly in the SQL path too (same 
`prefilter` field as the TVF), and require complete conversion for data 
predicates in BE in both paths, handling partition predicates separately.



##########
fe/fe-core/src/main/java/org/apache/doris/nereids/rules/rewrite/PushDownVectorTopNIntoFileScan.java:
##########
@@ -0,0 +1,224 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+package org.apache.doris.nereids.rules.rewrite;
+
+import org.apache.doris.catalog.Column;
+import org.apache.doris.catalog.Type;
+import org.apache.doris.connector.spi.pushdown.ConnectorAnd;
+import org.apache.doris.connector.spi.pushdown.ConnectorExpression;
+import org.apache.doris.connector.spi.scan.ConnectorVectorSearch;
+import 
org.apache.doris.datasource.connector.converter.VectorSearchPredicateConverter;
+import org.apache.doris.datasource.plugin.PluginDrivenExternalTable;
+import org.apache.doris.datasource.scan.ConnectorVectorSearchPlanner;
+import org.apache.doris.nereids.rules.Rule;
+import org.apache.doris.nereids.rules.RuleType;
+import org.apache.doris.nereids.trees.expressions.Alias;
+import org.apache.doris.nereids.trees.expressions.Expression;
+import org.apache.doris.nereids.trees.expressions.NamedExpression;
+import org.apache.doris.nereids.trees.expressions.SlotReference;
+import org.apache.doris.nereids.trees.expressions.StatementScopeIdGenerator;
+import 
org.apache.doris.nereids.trees.expressions.functions.NoneMovableFunction;
+import 
org.apache.doris.nereids.trees.expressions.functions.scalar.InnerProductApproximate;
+import 
org.apache.doris.nereids.trees.expressions.functions.scalar.L2DistanceApproximate;
+import org.apache.doris.nereids.trees.expressions.literal.ArrayLiteral;
+import org.apache.doris.nereids.trees.expressions.literal.Literal;
+import org.apache.doris.nereids.trees.expressions.literal.NullLiteral;
+import org.apache.doris.nereids.trees.plans.Plan;
+import org.apache.doris.nereids.trees.plans.logical.LogicalFileScan;
+import org.apache.doris.nereids.trees.plans.logical.LogicalFilter;
+import org.apache.doris.nereids.trees.plans.logical.LogicalProject;
+import org.apache.doris.nereids.trees.plans.logical.LogicalTopN;
+import org.apache.doris.nereids.util.ExpressionUtils;
+import org.apache.doris.qe.ConnectContext;
+import org.apache.doris.thrift.TExternalSearchQuery;
+import org.apache.doris.thrift.TExternalSearchRequest;
+import org.apache.doris.thrift.TSearchVector;
+import org.apache.doris.thrift.TVectorElementType;
+import org.apache.doris.thrift.TVectorMetric;
+import org.apache.doris.thrift.TVectorSearchParams;
+
+import com.google.common.collect.ImmutableList;
+
+import java.nio.ByteBuffer;
+import java.nio.ByteOrder;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
+import java.util.Set;
+
+/** Preserve the global TopN and let a connector admit bounded search on each 
of its ranges. */
+public class PushDownVectorTopNIntoFileScan implements RewriteRuleFactory {
+    @Override
+    public List<Rule> buildRules() {
+        return ImmutableList.of(
+                logicalTopN(logicalProject(logicalFileScan())).then(top ->
+                        pushDown(top, top.child(), top.child().child(), 
Optional.empty()))
+                        .toRule(RuleType.PUSH_DOWN_VECTOR_TOPN_INTO_FILE_SCAN),
+                
logicalTopN(logicalProject(logicalFilter(logicalFileScan()))).then(top ->
+                        pushDown(top, top.child(), 
top.child().child().child(), Optional.of(top.child().child())))
+                        
.toRule(RuleType.PUSH_DOWN_VECTOR_TOPN_INTO_FILE_SCAN));
+    }
+
+    private Plan pushDown(LogicalTopN<?> top, LogicalProject<?> project,
+            LogicalFileScan scan, Optional<LogicalFilter<?>> filter) {
+        if (!(scan.getTable() instanceof PluginDrivenExternalTable) || 
scan.getVectorSearch().isPresent()
+                || scan.getTableSample().isPresent() || 
top.getOrderKeys().size() != 1 || top.getLimit() <= 0
+                || top.getOffset() > Integer.MAX_VALUE - top.getLimit()

Review Comment:
   [P2] The SQL path has no upper bound on `limit + offset`. The TVF caps 
candidates at `MAX_CANDIDATES = 100_000`, but `ORDER BY 
l2_distance_approximate(...) LIMIT 10000000` is still pushed down, and every 
bucket eagerly materializes 10M rows in the Rust SDK, outside MemTracker. 
Please apply the same cap here and fall back to the scalar scan above it.



##########
fe/fe-core/src/main/java/org/apache/doris/nereids/rules/rewrite/PushDownVectorTopNIntoFileScan.java:
##########
@@ -0,0 +1,224 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+package org.apache.doris.nereids.rules.rewrite;
+
+import org.apache.doris.catalog.Column;
+import org.apache.doris.catalog.Type;
+import org.apache.doris.connector.spi.pushdown.ConnectorAnd;
+import org.apache.doris.connector.spi.pushdown.ConnectorExpression;
+import org.apache.doris.connector.spi.scan.ConnectorVectorSearch;
+import 
org.apache.doris.datasource.connector.converter.VectorSearchPredicateConverter;
+import org.apache.doris.datasource.plugin.PluginDrivenExternalTable;
+import org.apache.doris.datasource.scan.ConnectorVectorSearchPlanner;
+import org.apache.doris.nereids.rules.Rule;
+import org.apache.doris.nereids.rules.RuleType;
+import org.apache.doris.nereids.trees.expressions.Alias;
+import org.apache.doris.nereids.trees.expressions.Expression;
+import org.apache.doris.nereids.trees.expressions.NamedExpression;
+import org.apache.doris.nereids.trees.expressions.SlotReference;
+import org.apache.doris.nereids.trees.expressions.StatementScopeIdGenerator;
+import 
org.apache.doris.nereids.trees.expressions.functions.NoneMovableFunction;
+import 
org.apache.doris.nereids.trees.expressions.functions.scalar.InnerProductApproximate;
+import 
org.apache.doris.nereids.trees.expressions.functions.scalar.L2DistanceApproximate;
+import org.apache.doris.nereids.trees.expressions.literal.ArrayLiteral;
+import org.apache.doris.nereids.trees.expressions.literal.Literal;
+import org.apache.doris.nereids.trees.expressions.literal.NullLiteral;
+import org.apache.doris.nereids.trees.plans.Plan;
+import org.apache.doris.nereids.trees.plans.logical.LogicalFileScan;
+import org.apache.doris.nereids.trees.plans.logical.LogicalFilter;
+import org.apache.doris.nereids.trees.plans.logical.LogicalProject;
+import org.apache.doris.nereids.trees.plans.logical.LogicalTopN;
+import org.apache.doris.nereids.util.ExpressionUtils;
+import org.apache.doris.qe.ConnectContext;
+import org.apache.doris.thrift.TExternalSearchQuery;
+import org.apache.doris.thrift.TExternalSearchRequest;
+import org.apache.doris.thrift.TSearchVector;
+import org.apache.doris.thrift.TVectorElementType;
+import org.apache.doris.thrift.TVectorMetric;
+import org.apache.doris.thrift.TVectorSearchParams;
+
+import com.google.common.collect.ImmutableList;
+
+import java.nio.ByteBuffer;
+import java.nio.ByteOrder;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
+import java.util.Set;
+
+/** Preserve the global TopN and let a connector admit bounded search on each 
of its ranges. */
+public class PushDownVectorTopNIntoFileScan implements RewriteRuleFactory {
+    @Override
+    public List<Rule> buildRules() {
+        return ImmutableList.of(
+                logicalTopN(logicalProject(logicalFileScan())).then(top ->
+                        pushDown(top, top.child(), top.child().child(), 
Optional.empty()))
+                        .toRule(RuleType.PUSH_DOWN_VECTOR_TOPN_INTO_FILE_SCAN),
+                
logicalTopN(logicalProject(logicalFilter(logicalFileScan()))).then(top ->
+                        pushDown(top, top.child(), 
top.child().child().child(), Optional.of(top.child().child())))
+                        
.toRule(RuleType.PUSH_DOWN_VECTOR_TOPN_INTO_FILE_SCAN));
+    }
+
+    private Plan pushDown(LogicalTopN<?> top, LogicalProject<?> project,
+            LogicalFileScan scan, Optional<LogicalFilter<?>> filter) {
+        if (!(scan.getTable() instanceof PluginDrivenExternalTable) || 
scan.getVectorSearch().isPresent()
+                || scan.getTableSample().isPresent() || 
top.getOrderKeys().size() != 1 || top.getLimit() <= 0
+                || top.getOffset() > Integer.MAX_VALUE - top.getLimit()
+                || 
!ConnectContext.get().getSessionVariable().enableFileScannerV2
+                || scan.getScanParams().map(params -> 
params.incrementalRead()).orElse(false)) {
+            return null;
+        }
+        Alias key = project.getProjects().stream().filter(expr -> expr 
instanceof Alias
+                && expr.toSlot().equals(top.getOrderKeys().get(0).getExpr()))
+                .map(Alias.class::cast).findFirst().orElse(null);
+        if (key == null) {
+            return null;
+        }
+        Expression distance = key.child();
+        boolean l2 = distance instanceof L2DistanceApproximate;
+        if (!(l2 && top.getOrderKeys().get(0).isAsc())
+                && !(distance instanceof InnerProductApproximate && 
!top.getOrderKeys().get(0).isAsc())) {
+            return null;
+        }
+        if (!(distance.child(0) instanceof SlotReference) || 
!(distance.child(1) instanceof ArrayLiteral)) {
+            return null;
+        }
+        SlotReference vectorColumn = (SlotReference) distance.child(0);
+        List<Literal> query = ((ArrayLiteral) distance.child(1)).getValue();
+        if (query.isEmpty() || query.stream().anyMatch(value -> value 
instanceof NullLiteral
+                || !Float.isFinite((float) value.getDouble()))) {
+            return null;
+        }
+        // Moving a bounded read below assert_true/random-like projections may 
suppress evaluation/errors.
+        for (NamedExpression output : project.getProjects()) {
+            if (output.anyMatch(expr -> expr instanceof NoneMovableFunction
+                    || ((Expression) expr).getDataType().isVariantType()
+                    || ((Expression) expr).getDataType().isTimeStampNsType())) 
{
+                return null;
+            }
+        }
+        if (!complexColumnsRideAsWholeColumns(project, key, distance)) {
+            return null;
+        }
+        List<ConnectorExpression> predicates = new ArrayList<>();
+        if (filter.isPresent()) {
+            for (Expression conjunct : filter.get().getConjuncts()) {
+                ConnectorExpression converted = 
VectorSearchPredicateConverter.convert(conjunct);
+                if (converted == null) {
+                    return null;
+                }
+                predicates.add(converted);
+            }
+        }
+        Optional<ConnectorExpression> predicate = predicates.isEmpty() ? 
Optional.empty()
+                : Optional.of(predicates.size() == 1 ? predicates.get(0) : new 
ConnectorAnd(predicates));
+        ByteBuffer values = ByteBuffer.allocate(query.size() * 
Float.BYTES).order(ByteOrder.LITTLE_ENDIAN);
+        query.forEach(value -> values.putFloat((float) value.getDouble()));
+        TVectorSearchParams vector = new TVectorSearchParams().setColumn(
+                
vectorColumn.getOriginalColumn().map(Column::getName).orElse(vectorColumn.getName()))
+                .setQueryVector(new 
TSearchVector().setElementType(TVectorElementType.FLOAT32)
+                        .setDimension(query.size()).setValues(values.array()))
+                .setMetric(l2 ? TVectorMetric.L2 : TVectorMetric.DOT_PRODUCT)
+                .setTopK(top.getLimit() + top.getOffset()).setOffset(0);
+        ConnectorVectorSearch requested = new ConnectorVectorSearch(new 
TExternalSearchRequest()
+                
.setSchemaVersion(1).setSearchQuery(TExternalSearchQuery.vector_search(vector)),
+                "", false, predicate);
+        Optional<ConnectorVectorSearch> admitted = 
ConnectorVectorSearchPlanner.prepare(

Review Comment:
   [P2] This rewrite rule does remote connector IO: `resolveTable`, reading 
every historical schema file in `PaimonVectorSearch.prepare`, and bucket 
vector-scan planning (manifests). Elsewhere the planner deliberately avoids 
connector/HMS requests while internal plan read locks are held 
(`hasAnyPlanReadLockTable()` in `PruneFileScanPartition` / 
`PluginDrivenScanNode`). A query that also touches an OLAP table will now do 
object-store IO under those locks. Please skip admission (or use preloaded 
metadata) when plan read locks are held, and memoize the admission result per 
statement.



##########
fe/fe-core/src/main/java/org/apache/doris/nereids/glue/translator/PhysicalPlanTranslator.java:
##########
@@ -853,6 +856,7 @@ public PlanFragment visitPhysicalFileScan(PhysicalFileScan 
fileScan, PlanTransla
                 pluginScanNode.setTopnLazyMaterializedColumns(
                         lazyColumnNames(((PhysicalLazyMaterializeFileScan) 
fileScan).getLazySlots()));
             }
+            
fileScan.getVectorSearch().ifPresent(pluginScanNode::setVectorSearch);

Review Comment:
   [P2] (latent) `PhysicalLazyMaterializeFileScan` uses the old 
`PhysicalFileScan` constructor, which sets `vectorSearch = Optional.empty()`. 
TopN lazy materialization targets exactly `TopN -> Project -> FileScan`, so for 
a connector that supports both lazy materialization and `prepareVectorSearch`, 
this branch would see a scan with the synthesized distance slot but no vector 
search. Paimon doesn't declare `SUPPORTS_TOPN_LAZY_MATERIALIZE` today, but the 
SPI is connector-neutral. Please propagate `vectorSearch` through the lazy 
wrapper, or exclude vector-search scans in `MaterializeProbeVisitor`.



##########
fe/fe-connector/fe-connector-paimon/src/main/java/org/apache/doris/connector/paimon/PaimonVectorSearch.java:
##########
@@ -0,0 +1,211 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+package org.apache.doris.connector.paimon;
+
+import org.apache.doris.connector.spi.pushdown.ConnectorAnd;
+import org.apache.doris.connector.spi.pushdown.ConnectorColumnRef;
+import org.apache.doris.connector.spi.pushdown.ConnectorComparison;
+import org.apache.doris.connector.spi.pushdown.ConnectorExpression;
+import org.apache.doris.connector.spi.pushdown.ConnectorIn;
+import org.apache.doris.connector.spi.pushdown.ConnectorIsNull;
+import org.apache.doris.connector.spi.pushdown.ConnectorLiteral;
+import org.apache.doris.connector.spi.pushdown.ConnectorNot;
+import org.apache.doris.connector.spi.scan.ConnectorVectorSearch;
+import org.apache.doris.thrift.TExternalSearchRequest;
+import org.apache.doris.thrift.TPaimonVectorSearchOptions;
+import org.apache.doris.thrift.TVectorMetric;
+import org.apache.doris.thrift.TVectorSearchParams;
+
+import org.apache.paimon.CoreOptions;
+import org.apache.paimon.index.pk.PrimaryKeyIndexSourcePolicy;
+import org.apache.paimon.index.pkvector.PkVectorBucketIndexState;
+import org.apache.paimon.io.DataFileMeta;
+import org.apache.paimon.schema.TableSchema;
+import org.apache.paimon.table.FileStoreTable;
+import org.apache.paimon.table.source.BucketVectorSearchSplit;
+import org.apache.paimon.types.DataField;
+import org.apache.paimon.types.DataType;
+import org.apache.paimon.types.DataTypeRoot;
+import org.apache.paimon.types.VectorType;
+
+import java.util.Arrays;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Locale;
+import java.util.Map;
+import java.util.Optional;
+import java.util.Set;
+
+/** Paimon-specific admission and wire options for the connector-neutral 
vector search path. */
+final class PaimonVectorSearch {
+    static final String DISTANCE_COLUMN = "__paimon_search_score_to_dis";
+    private static final Set<String> FILTER_TYPES = new 
HashSet<>(Arrays.asList(
+            "BOOLEAN", "TINYINT", "SMALLINT", "INT", "BIGINT", "STRING", 
"DATE", "DATEV2"));
+
+    private PaimonVectorSearch() {
+    }
+
+    static Optional<ConnectorVectorSearch> prepare(FileStoreTable table, 
ConnectorVectorSearch search) {
+        TExternalSearchRequest request = search.getRequest();
+        TVectorSearchParams vector = 
request.getSearchQuery().getVectorSearch();
+        CoreOptions options = table.coreOptions();
+        String column = table.rowType().getFieldNames().stream()
+                .filter(name -> 
name.equalsIgnoreCase(vector.getColumn())).findFirst().orElse(null);
+        if (column == null || !options.primaryKeyVectorIndexEnabled()
+                || !options.primaryKeyVectorIndexColumns().contains(column)) {
+            return Optional.empty();
+        }
+        if 
(!PaimonRustReaderCapabilities.hasRustCompatibleTimestamps(table.schema().fields()))
 {
+            return Optional.empty();
+        }
+        DataType type = 
table.rowType().getTypeAt(table.rowType().getFieldIndex(column));
+        if (!(type instanceof VectorType)
+                || ((VectorType) type).getElementType().getTypeRoot() != 
DataTypeRoot.FLOAT
+                || ((VectorType) type).getLength() != 
vector.getQueryVector().getDimension()
+                || (!search.isTableFunction() && type.isNullable())) {
+            return Optional.empty();
+        }
+        String metric = options.primaryKeyVectorDistanceMetric(column);
+        if (!(vector.getMetric() == TVectorMetric.L2 && "l2".equals(metric))
+                && !(vector.getMetric() == TVectorMetric.DOT_PRODUCT && 
"inner_product".equals(metric))) {
+            return Optional.empty();
+        }
+        for (String name : table.rowType().getFieldNames()) {
+            if (DISTANCE_COLUMN.equalsIgnoreCase(name) || 
"__paimon_search_score".equalsIgnoreCase(name)
+                    || "_PKEY_VECTOR_POSITION".equalsIgnoreCase(name)
+                    || (search.isTableFunction() && 
"_distance".equalsIgnoreCase(name))) {
+                return Optional.empty();
+            }
+        }
+        // Arrow safe casts can silently replace out-of-range historical 
values with NULL. A bounded
+        // search has no JNI fallback; decline schema evolution instead of 
changing the SQL result.
+        for (Long id : table.schemaManager().listAllIds()) {

Review Comment:
   [P2] This reads every historical schema file, so remote reads grow with the 
number of schema versions, plus a schemas x fields x fields scan. It isn't 
memoized, and one query runs it several times: SQL runs it at rewrite admission 
and again in `planVectorScan` -> `prepareVectorSearch`; TVF runs it in 
`prepareSearch`, `applyFilter` and `planScan`. Please cache the result, at 
least per statement and ideally keyed by (table, latest schema id).



##########
fe/fe-connector/fe-connector-paimon/src/main/java/org/apache/doris/connector/paimon/PaimonConnector.java:
##########
@@ -561,6 +561,9 @@ private Catalog createCatalogFromContext(CatalogContext 
catalogContext, String f
                         ? createHmsCatalog(catalogContext, hmsAuth, 
catalogProps.getRaw(),
                                 storageHadoopConfig)
                         : 
CatalogFactory.createUnwrappedCatalog(catalogContext, 
getClass().getClassLoader());
+                // SDK 2.1 removed warehouse ACL enforcement. Check before a 
cache wrapper takes
+                // ownership, while FileIO probes and rejected-catalog cleanup 
remain authenticated.
+                PaimonCatalogCompatibility.requireSupportedPrivileges(catalog);

Review Comment:
   [P2] Unrelated to vector search: this makes catalog creation fail for every 
Paimon warehouse that has legacy `user.sys`/`privilege.sys`, and adds two 
remote `exists` calls per catalog creation. It addresses the SDK 2.1 ACL 
removal, and that SDK bump is already on master. Please move it to a separate 
PR with a release note, to keep this PR focused.



##########
fe/fe-core/src/main/java/org/apache/doris/nereids/rules/analysis/BindExpression.java:
##########
@@ -1999,17 +2001,34 @@ private Plan 
bindTableValuedFunction(MatchingContext<UnboundTVFRelation> ctx) {
         LogicalTVFRelation relation = new LogicalTVFRelation(
                 unboundTVFRelation.getRelationId(), search, 
ImmutableList.of());
         // Each range of the scan returns its own best top_k + offset 
candidates. This TopN keeps the best of all
-        // of them. PushDownWhereThroughSearchTopN moves the WHERE written on 
the function below it, so that the
-        // WHERE filters the candidates as a scan residual, after the 
connector's search and before the merge.
+        // of them. The connector's WHERE policy determines whether 
PushDownWhereThroughSearchTopN moves the
+        // function's outer WHERE below this merge to filter candidates or 
keeps it above the merged results.
         ExternalSearchTableValuedFunction function = 
search.getSearchFunction();
+        Plan input = relation;
+        LogicalFilter<Plan> postfilter = null;
+        if (function.getEngineFilter().isPresent()) {
+            ConnectorSearchFilter filter = function.getEngineFilter().get();
+            Expression predicate = buildSimpleExprAnalyzer(relation, 
ctx.cascadesContext,
+                    ImmutableList.of(relation)).analyze(new 
NereidsParser().parseExpression(filter.getExpression()));

Review Comment:
   [P3] The `filter` argument is parsed as an arbitrary Doris expression. With 
`prefilter=false` it becomes a regular Filter, so subqueries, aggregates or 
window functions may get through here (I haven't verified this). Please 
restrict it to scalar predicates over the search columns and add negative 
tests. Also worth documenting: the same argument is native dialect for Lance 
but Doris SQL for Paimon.



##########
fe/fe-connector/fe-connector-spi/src/main/java/org/apache/doris/connector/spi/scan/ConnectorVectorSearch.java:
##########
@@ -0,0 +1,72 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+package org.apache.doris.connector.spi.scan;
+
+import org.apache.doris.connector.spi.pushdown.ConnectorExpression;
+import org.apache.doris.thrift.TExternalSearchRequest;
+
+import java.util.Objects;
+import java.util.Optional;
+
+/** A bounded vector search admitted by the connector for one pinned scan. */
+public final class ConnectorVectorSearch {
+    private final TExternalSearchRequest request;
+    private final String distanceColumn;
+    private final boolean tableFunction;

Review Comment:
   [P3] `tableFunction` tells the connector who the caller is, and Paimon 
derives several unrelated behaviors from it: distance semantics (squared L2 / 
negative inner product for the TVF vs L2 / inner product for SQL), 
nullable-column acceptance, the index-coverage requirement, and the distance 
column name. Explicit fields (e.g. distance semantics, requireFullCoverage) 
would make the SPI contract clear for other connectors. Also, please document 
that the TVF `_distance` for `l2` is squared L2, unlike 
`l2_distance_approximate`.



##########
fe/fe-connector/fe-connector-paimon/src/main/java/org/apache/doris/connector/paimon/PaimonSearchArguments.java:
##########
@@ -0,0 +1,206 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+package org.apache.doris.connector.paimon;
+
+import org.apache.doris.connector.spi.DorisConnectorException;
+import org.apache.doris.connector.spi.mvcc.ConnectorTimeTravelSpec;
+import org.apache.doris.connector.spi.search.ConnectorSearchFilter;
+import org.apache.doris.connector.spi.search.ConnectorSearchFunction;
+import org.apache.doris.connector.spi.search.ConnectorSearchRequest;
+import org.apache.doris.thrift.TExternalSearchQuery;
+import org.apache.doris.thrift.TExternalSearchRequest;
+import org.apache.doris.thrift.TSearchVector;
+import org.apache.doris.thrift.TVectorElementType;
+import org.apache.doris.thrift.TVectorMetric;
+import org.apache.doris.thrift.TVectorSearchOptions;
+import org.apache.doris.thrift.TVectorSearchParams;
+
+import com.google.common.collect.ImmutableSet;
+import com.google.gson.JsonArray;
+import com.google.gson.JsonElement;
+import com.google.gson.JsonParser;
+
+import java.nio.ByteBuffer;
+import java.nio.ByteOrder;
+import java.nio.charset.StandardCharsets;
+import java.util.Locale;
+import java.util.Map;
+import java.util.Optional;
+import java.util.Set;
+
+/** Paimon's vector-search arguments; the engine only owns the table argument 
and Doris filter binding. */
+final class PaimonSearchArguments {
+    private static final int MAX_CANDIDATES = 100_000;
+    private static final String NAME = "vector_search";
+    private static final Set<String> PROPERTIES = ImmutableSet.of(
+            "column", "query_vector", "top_k", "offset", "metric", "filter", 
"prefilter",
+            "nprobes", "refine_factor", "use_index", "version", "timestamp", 
"tag", "branch");
+    final long topK;
+    final long offset;
+    final Optional<String> filter;
+    final boolean prefilter;
+    final TExternalSearchRequest request;
+    final Optional<ConnectorTimeTravelSpec> timeTravel;
+
+    PaimonSearchArguments(ConnectorSearchRequest search) {
+        if (search.getFunction() != ConnectorSearchFunction.VECTOR_SEARCH) {
+            throw new DorisConnectorException("Paimon supports only 
vector_search");
+        }
+        if (!search.getDeferredArguments().isEmpty()) {
+            throw new DorisConnectorException("Paimon vector_search parameters 
must be constant");
+        }
+        // The shared TVF already normalized names; the connector owns their 
vocabulary and values.
+        Map<String, String> params = search.getArguments();
+        for (String key : params.keySet()) {
+            if (!PROPERTIES.contains(key)) {
+                throw new DorisConnectorException("'" + key + "' is an invalid 
property for vector_search()");
+            }
+        }
+        ConnectorTimeTravelSpec selector = null;
+        for (String key : new String[] {"version", "timestamp", "tag", 
"branch"}) {
+            if (!params.containsKey(key)) {
+                continue;
+            }
+            String value = required(params, key, NAME);
+            if (selector != null) {
+                throw new DorisConnectorException("version, timestamp, tag and 
branch are mutually exclusive");
+            }
+            switch (key) {
+                case "version":
+                    selector = value.matches("[0-9]+") ? 
ConnectorTimeTravelSpec.snapshotId(value)
+                            : ConnectorTimeTravelSpec.versionRef(value);
+                    break;
+                case "timestamp":
+                    selector = ConnectorTimeTravelSpec.timestamp(value, 
value.matches("[0-9]+"));
+                    break;
+                case "tag":
+                    selector = ConnectorTimeTravelSpec.tag(value);
+                    break;
+                case "branch":
+                    selector = ConnectorTimeTravelSpec.branch(value);
+                    break;
+                default:
+                    throw new IllegalStateException(key);
+            }
+        }
+        timeTravel = Optional.ofNullable(selector);
+        topK = parseLong(params.getOrDefault("top_k", "10"), "top_k", 1, 
MAX_CANDIDATES);
+        offset = parseLong(params.getOrDefault("offset", "0"), "offset", 0, 
MAX_CANDIDATES - topK);
+        filter = Optional.ofNullable(params.get("filter"));
+        if (filter.isPresent()) {
+            validateAndEncodeSqlFilter(filter.get());

Review Comment:
   [P3] The return value of `validateAndEncodeSqlFilter` is unused; make it a 
`void` validator.



##########
fe/fe-connector/fe-connector-paimon/src/main/java/org/apache/doris/connector/paimon/PaimonScanRange.java:
##########
@@ -143,6 +150,12 @@ public Optional<String> getPath() {
 
     @Override
     public String getSplitIdentity() {
+        // Vector buckets share a table root and have no Java DataSplit 
payload. Use their
+        // actual bucket payload so two buckets cannot acquire the same split 
identity.
+        String vectorPayload = properties.get("paimon.vector_payload");
+        if (vectorPayload != null) {
+            return vectorPayload;

Review Comment:
   [P3] The split identity is the whole base64 bucket payload, whose size grows 
with the number of row ranges in the bucket. It's only used for consistent 
hashing in `FederationBackendPolicy`; a compact (snapshot, partition, bucket) 
identity is enough.



##########
fe/fe-core/src/main/java/org/apache/doris/connector/ConnectorSessionImpl.java:
##########
@@ -182,6 +184,12 @@ public Map<String, String> getSessionProperties() {
         return sessionProperties;
     }
 
+    @Override
+    public Set<String> getBackendCapabilities() {

Review Comment:
   [P3] `getAllClusterBackends(true)` intersects capabilities across all 
compute groups, so in cloud mode one old BE in an unrelated group makes 
`vector_search` fail with "not supported" for this group 
(`ConnectorVectorSearchPlanner` has the same issue). It also makes 
`connector.ConnectorSessionImpl` depend on 
`datasource.scan.PluginDrivenScanNode`, and `ConnectorScanRequest` already 
carries scan-scoped backend capabilities, so this SPI addition duplicates that.



##########
fe/fe-core/src/main/java/org/apache/doris/datasource/scan/PluginDrivenScanNode.java:
##########
@@ -405,6 +408,17 @@ protected boolean applyColumnDefaultsOnRead() {
      * volatile write of the holder safely publishes the pair to concurrent 
readers (no torn new-key/old-provider
      * view). {@code provider} may be {@code null} for a connector without 
scan capability.
      */
+    private ConnectorVectorSearch vectorSearch;

Review Comment:
   [P3] These fields were inserted between the `ResolvedScanProvider` Javadoc 
and its class, so that Javadoc now documents `vectorSearch`. Please move them 
above the comment. Minor: avoid the fully-qualified 
`org.apache.doris.thrift.TVectorSearchParams` in `getNodeExplainString`.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]


---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]

Reply via email to