Gabriel39 commented on code in PR #67289:
URL: https://github.com/apache/doris/pull/67289#discussion_r3963962288


##########
fe/fe-core/src/main/java/org/apache/doris/tablefunction/LanceExternalSearchTableValuedFunction.java:
##########
@@ -0,0 +1,360 @@
+// 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.tablefunction;
+
+import org.apache.doris.analysis.TableName;
+import org.apache.doris.analysis.TupleDescriptor;
+import org.apache.doris.catalog.Column;
+import org.apache.doris.catalog.Env;
+import org.apache.doris.catalog.TableIf;
+import org.apache.doris.catalog.Type;
+import org.apache.doris.common.AnalysisException;
+import org.apache.doris.common.ErrorCode;
+import org.apache.doris.common.ErrorReport;
+import org.apache.doris.datasource.CatalogIf;
+import org.apache.doris.datasource.lance.LanceExternalCatalog;
+import org.apache.doris.datasource.lance.LanceExternalTable;
+import org.apache.doris.datasource.lance.LanceTableMetadata;
+import org.apache.doris.datasource.lance.LanceTypeConverter;
+import org.apache.doris.datasource.lance.source.LanceScanNode;
+import org.apache.doris.mysql.privilege.PrivPredicate;
+import org.apache.doris.nereids.analyzer.UnboundSlot;
+import org.apache.doris.nereids.exceptions.ParseException;
+import org.apache.doris.nereids.parser.NereidsParser;
+import org.apache.doris.nereids.trees.expressions.Expression;
+import org.apache.doris.planner.PlanNodeId;
+import org.apache.doris.planner.ScanNode;
+import org.apache.doris.qe.ConnectContext;
+import org.apache.doris.qe.SessionVariable;
+import org.apache.doris.thrift.TExternalSearchRequest;
+import org.apache.doris.thrift.TSearchFilter;
+import org.apache.doris.thrift.TSearchFilterFormat;
+
+import org.apache.arrow.vector.types.pojo.Field;
+
+import java.nio.charset.StandardCharsets;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.List;
+import java.util.Locale;
+import java.util.Map;
+import java.util.OptionalInt;
+import java.util.Set;
+import java.util.TreeMap;
+import java.util.TreeSet;
+
+/** Common immutable planning state and validation for Lance external-search 
relation TVFs. */
+abstract class LanceExternalSearchTableValuedFunction extends 
TableValuedFunctionIf {
+    protected static final String TABLE = "table";
+    protected static final String COLUMN = "column";
+    protected static final String TOP_K = "top_k";
+    protected static final String OFFSET = "offset";
+    protected static final String FILTER = "filter";
+
+    private static final String FULLY_QUALIFIED_TABLE_NAME_ERROR =
+            "'table' must be a fully qualified catalog.database.table name";
+    private static final long UINT32_MAX = 0xFFFF_FFFFL;
+
+    private final String displayName;
+    private final TableName sourceTableName;
+    private final LanceExternalTable sourceTable;
+    private final LanceTableMetadata metadata;
+    private final int fieldId;
+    private final TExternalSearchRequest searchRequest;
+    private final List<Column> columns;
+    private final long topK;
+    private final long offset;
+
+    protected LanceExternalSearchTableValuedFunction(PreparedSearch prepared) {
+        CommonSearch common = prepared.common;
+        this.displayName = common.displayName;
+        this.sourceTableName = common.sourceTableName;
+        this.sourceTable = common.sourceTable;
+        this.metadata = common.metadata;
+        this.fieldId = prepared.fieldId;
+        this.searchRequest = prepared.searchRequest.deepCopy();
+        this.columns = Collections.unmodifiableList(new 
ArrayList<>(prepared.columns));
+        this.topK = common.topK;
+        this.offset = common.offset;
+    }
+
+    public final LanceExternalTable getSourceTable() {
+        return sourceTable;
+    }
+
+    public final LanceTableMetadata getMetadata() {
+        return metadata;
+    }
+
+    public final TExternalSearchRequest getSearchRequest() {
+        return searchRequest.deepCopy();
+    }
+
+    public final long getTopK() {
+        return topK;
+    }
+
+    public final long getOffset() {
+        return offset;
+    }
+
+    @Override
+    public final String getTableName() {
+        return displayName + "<" + sourceTableName + ">";
+    }
+
+    @Override
+    public final List<Column> getTableColumns() {
+        return columns;
+    }
+
+    @Override
+    public final ScanNode getScanNode(PlanNodeId id, TupleDescriptor desc, 
SessionVariable sv) {
+        return LanceScanNode.forExternalSearch(
+                id, desc, sourceTable, metadata, fieldId, searchRequest, sv);
+    }
+
+    protected static Map<String, String> normalizeProperties(Map<String, 
String> properties,
+            Set<String> allowedProperties, String functionName) throws 
AnalysisException {
+        Map<String, String> normalized = new 
TreeMap<>(String.CASE_INSENSITIVE_ORDER);
+        for (Map.Entry<String, String> entry : properties.entrySet()) {
+            String key = entry.getKey().toLowerCase(Locale.ROOT);
+            if (!allowedProperties.contains(key)) {
+                throw new AnalysisException("'" + entry.getKey()
+                        + "' is an invalid property for " + functionName + 
"()");
+            }
+            if (normalized.put(key, entry.getValue()) != null) {
+                throw new AnalysisException(
+                        "Duplicate " + functionName + "() property '" + key + 
"'");
+            }
+        }
+        return normalized;
+    }
+
+    protected static String required(Map<String, String> params, String key, 
String functionName)
+            throws AnalysisException {
+        String value = params.get(key);
+        if (value == null || value.trim().isEmpty()) {
+            throw new AnalysisException(
+                    "Missing required " + functionName + "() property '" + key 
+ "'");
+        }
+        return value.trim();
+    }
+
+    protected static CommonSearch prepareCommon(Map<String, String> params, 
String functionName,
+            String displayName, String searchDescription, boolean 
loadIndexMetadata)
+            throws AnalysisException {
+        TableName sourceTableName = parseTableName(required(params, TABLE, 
functionName));
+        LanceExternalTable sourceTable = 
findLanceExternalTable(sourceTableName);
+        LanceTableMetadata metadata;
+        try {
+            metadata = loadIndexMetadata
+                    ? sourceTable.loadMetadataForSearch() : 
sourceTable.loadMetadata();
+        } catch (RuntimeException e) {
+            throw new AnalysisException("Failed to load Lance metadata for " + 
searchDescription
+                    + " on " + sourceTableName + ": " + e.getMessage(), e);
+        }
+        if (metadata.getVersion() <= 0) {
+            throw new AnalysisException("Lance " + searchDescription
+                    + " requires a fixed positive dataset version");
+        }
+
+        long topK = parseLong(params.getOrDefault(TOP_K, "10"), TOP_K, 1, 
Long.MAX_VALUE);
+        long offset = parseLong(params.getOrDefault(OFFSET, "0"), OFFSET, 0, 
Long.MAX_VALUE);
+        if (offset > UINT32_MAX || topK > UINT32_MAX - offset) {

Review Comment:
   [P1] Bound the FTS candidate allocation well below UINT32_MAX. This 
validation permits top_k + offset up to 4,294,967,295, and LanceTableReader 
passes that value as the limit to every segment scanner. In the pinned Lance 
dependency, both the per-index BM25 search and the cross-segment merge retain a 
BinaryHeap until candidates.len() reaches the requested limit. A broad match 
can therefore retain nearly every hit in each active FileScannerV2, potentially 
outside Doris query memory tracking, and exhaust BE memory. Please introduce a 
practical or configurable FTS candidate cap, validate it again at the BE 
boundary, account the Lance allocation against the query memory limit, and add 
a rejection test near the cap.



##########
be/src/format_v2/table/lance_reader.cpp:
##########
@@ -561,6 +689,41 @@ Status LanceTableReader::_open_dataset(const DatasetKey& 
key) {
     return Status::OK();
 }
 
+Status LanceTableReader::_prepare_fts_query_context() {
+    DORIS_CHECK(_dataset != nullptr);
+    DORIS_CHECK(_fts_query_context == nullptr);
+    DORIS_CHECK(_scan_params != nullptr);
+    const auto& full_text =
+            
_scan_params->lance_scan_params.external_search_request.search_query.full_text_search;
+    if (full_text.__isset.global_statistics) {
+        return Status::NotSupported(
+                "Lance FE-provided FTS global statistics require a lance-c 
consumer API");
+    }
+    const auto coverage_mode = full_text.coverage_mode == 
TFtsCoverageMode::STRICT
+                                       ? LANCE_FTS_COVERAGE_STRICT
+                                       : LANCE_FTS_COVERAGE_INDEX_ONLY;
+    // Keep statistics preparation at the reader/scanner lifetime today. A 
future FE-provided
+    // opaque statistics payload should enter through this boundary and create 
the same context,
+    // leaving segment-scoped scanner execution unchanged.
+    if (full_text.query_type == TFtsQueryType::MATCH) {
+        const auto match_operator = full_text.match_operator == 
TFtsMatchOperator::AND
+                                            ? LANCE_FTS_MATCH_OPERATOR_AND
+                                            : LANCE_FTS_MATCH_OPERATOR_OR;
+        _fts_query_context = lance_dataset_prepare_fts_match_query(

Review Comment:
   One additional correctness case is row-level deletion. A fragment can remain 
visible and fully covered while a deletion file removes some of its rows, so 
STRICT coverage still passes, yet the immutable segment statistics continue to 
include the deleted documents in num_docs, total_tokens, and term document 
frequencies. The output mask removes those rows only after scoring, allowing 
deleted documents to change the ordering of live rows. Please make the scorer 
live-row aware and include a delete-without-fragment-replacement regression in 
addition to the update or rewrite case.



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