github-actions[bot] commented on code in PR #70971:
URL: https://github.com/apache/doris/pull/70971#discussion_r4689222605


##########
fe/fe-connector/fe-connector-lance/src/main/java/org/apache/doris/connector/lance/LanceIndexMetadata.java:
##########
@@ -27,11 +29,13 @@
 import org.lance.schema.LanceField;
 import org.lance.schema.LanceSchema;
 
+import java.io.IOException;
 import java.util.ArrayList;
 import java.util.Collections;
 import java.util.HashMap;
 import java.util.LinkedHashMap;
 import java.util.List;
+import java.util.Locale;
 import java.util.Map;
 import java.util.OptionalInt;

Review Comment:
   [P2] Parse the Lance index metric from the key present in the committed 
index metadata. The IVF fixtures store `distance_type` (for example, 
{"type":"IVF_FLAT","distance_type":"l2"}), but this code only reads 
`metric_type`, so `metricMatches` rejects every segment and all vector searches 
fall back to flat scans; the added EXPLAIN checks for 
`lanceSearchIndexSegments=1`/`lanceSearchIndexFragments=2` will fail. Accept 
the Lance key (with compatibility handling if multiple SDK versions use 
different names) and add a fixture-backed `USED` assertion.



##########
fe/fe-connector/fe-connector-lance/src/main/java/org/apache/doris/connector/lance/LanceVectorQuery.java:
##########
@@ -0,0 +1,358 @@
+// 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.lance;
+
+import org.apache.doris.connector.spi.DorisConnectorException;
+import org.apache.doris.thrift.TSearchVector;
+import org.apache.doris.thrift.TVectorElementType;
+import org.apache.doris.thrift.TVectorMetric;
+
+import com.fasterxml.jackson.core.JsonProcessingException;
+import com.fasterxml.jackson.databind.DeserializationFeature;
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import org.apache.arrow.memory.util.Float16;
+import org.apache.arrow.vector.types.FloatingPointPrecision;
+import org.apache.arrow.vector.types.pojo.ArrowType;
+import org.apache.arrow.vector.types.pojo.Field;
+
+import java.math.BigDecimal;
+import java.math.BigInteger;
+import java.nio.ByteBuffer;
+import java.nio.ByteOrder;
+import java.util.Locale;
+
+/**
+ * The query vector of a {@code vector_search}: checks that the searched 
column is a vector Lance can search, and
+ * encodes the user's JSON array into the typed little-endian matrix the BE 
hands to lance-c.
+ *
+ * <p>A vector column is {@code 
fixed_size_list<float16|float32|float64|uint8|int8>}; a multi-vector column is
+ * {@code list<fixed_size_list<float16|float32|float64>>} with non-nullable 
subvectors, queried with a matrix of
+ * subvectors. Every element must be representable in the column's element 
type: nothing is rounded into range.
+ */
+final class LanceVectorQuery {
+    // Keep aligned with the BE and Lance-C limits: each subvector expands 
into an ANN branch.
+    static final int MAX_QUERY_VECTORS = 128;
+    static final long MAX_QUERY_VECTOR_CANDIDATES = 100_000;
+
+    private static final String ARROW_EXTENSION_NAME = "ARROW:extension:name";
+    private static final BigDecimal UINT8_MAX = BigDecimal.valueOf(255);
+    private static final BigDecimal INT8_MIN = 
BigDecimal.valueOf(Byte.MIN_VALUE);
+    private static final BigDecimal INT8_MAX = 
BigDecimal.valueOf(Byte.MAX_VALUE);
+    /**
+     * Reads a fraction as the exact decimal written, not as a double: an 
integer element must be an exact integer,
+     * not one a double rounds to. Text after the array is an error, not 
ignored.
+     */
+    private static final ObjectMapper JSON = new ObjectMapper()
+            .enable(DeserializationFeature.USE_BIG_DECIMAL_FOR_FLOATS)
+            .enable(DeserializationFeature.FAIL_ON_TRAILING_TOKENS);
+
+    private LanceVectorQuery() {
+    }
+
+    /**
+     * Encodes {@code json}, a JSON array of numbers (a matrix of them for a 
multi-vector column), for a search of
+     * {@code field}.
+     *
+     * @throws DorisConnectorException when the column cannot be searched, or 
the value does not fit it
+     */
+    static TSearchVector parseAndEncode(Field field, String json) {
+        boolean multiVector = isMultiVector(field);
+        Encoding encoding = analyzeField(field);
+        JsonNode values = parseArray(json, field, multiVector ? -1 : 
encoding.dimension);
+        int numVectors = multiVector ? values.size() : 1;
+        if (multiVector) {
+            if (numVectors > MAX_QUERY_VECTORS) {
+                throw new DorisConnectorException("Multi-vector query exceeds 
" + MAX_QUERY_VECTORS + " subvectors");
+            }
+            // Validate the shape before allocating from the schema dimension, 
even for a short input.
+            for (JsonNode subvector : values) {
+                if (!subvector.isArray() || subvector.size() != 
encoding.dimension) {
+                    throw new DorisConnectorException("Each query subvector 
must be an array of dimension "
+                            + encoding.dimension);
+                }
+            }
+        }
+        long bytesPerVector = (long) encoding.dimension * encoding.byteWidth;
+        if (numVectors == 0 || numVectors > Integer.MAX_VALUE / 
bytesPerVector) {
+            throw new DorisConnectorException("Query vector matrix must be 
non-empty and fit in a binary value");
+        }
+        ByteBuffer buffer = ByteBuffer.allocate((int) (numVectors * 
bytesPerVector)).order(ByteOrder.LITTLE_ENDIAN);
+        if (multiVector) {
+            for (JsonNode subvector : values) {
+                encodeValues(subvector, encoding.elementType, buffer);
+            }
+        } else {
+            encodeValues(values, encoding.elementType, buffer);
+        }
+        TSearchVector query = new TSearchVector()
+                .setElementType(encoding.elementType)
+                .setDimension(encoding.dimension)
+                .setValues(buffer.array());
+        if (multiVector) {
+            query.setNumVectors(numVectors);
+        }
+        return query;
+    }
+
+    /**
+     * Checks that {@code field} is a vector column Lance can search, without 
a query vector: what a prepared
+     * statement can check before its execution supplies the vector.
+     */
+    static void checkSearchable(Field field) {
+        analyzeField(field);
+    }
+
+    /** Whether {@code field} is a multi-vector column, a list of vectors. */
+    static boolean isMultiVector(Field field) {
+        return field.getType().getTypeID() == ArrowType.ArrowTypeID.List;
+    }
+
+    /**
+     * Bounds the work of a multi-vector search: lance-c searches once per 
subvector, each for
+     * {@code refine_factor * (top_k + offset)} candidates.
+     */
+    static void validateMultiVectorBudget(TSearchVector query, long topK, long 
offset, int refineFactor) {
+        if (query.isSetNumVectors() && (query.getNumVectors() <= 0
+                || query.getNumVectors() > MAX_QUERY_VECTORS || topK <= 0 || 
offset < 0
+                || offset > MAX_QUERY_VECTOR_CANDIDATES
+                || topK > MAX_QUERY_VECTOR_CANDIDATES - offset
+                || refineFactor <= 0 || topK + offset > 
MAX_QUERY_VECTOR_CANDIDATES / refineFactor
+                || query.getNumVectors() > MAX_QUERY_VECTOR_CANDIDATES / (topK 
+ offset))) {
+            throw new DorisConnectorException("Multi-vector query exceeds 128 
subvectors or "
+                    + "100000 candidate budget for num_vectors or 
refine_factor times (top_k + offset)");
+        }
+    }
+
+    /** The {@code metric} argument: Lance's metric names, and {@code 
dot_product} for {@code dot}. */
+    static TVectorMetric parseMetric(String value) {
+        switch (value.trim().toLowerCase(Locale.ROOT)) {
+            case "l2":
+                return TVectorMetric.L2;
+            case "cosine":
+                return TVectorMetric.COSINE;
+            case "dot":
+            case "dot_product":
+                return TVectorMetric.DOT_PRODUCT;
+            case "hamming":
+                return TVectorMetric.HAMMING;
+            default:
+                throw new DorisConnectorException("Unsupported vector metric 
'" + value
+                        + "': expected l2, cosine, dot, or hamming");
+        }
+    }
+
+    /** Lance's spelling of a metric, as EXPLAIN shows it; an index records it 
in upper case. */
+    static String metricName(TVectorMetric metric) {
+        switch (metric) {
+            case L2:
+                return "l2";
+            case COSINE:
+                return "cosine";
+            case DOT_PRODUCT:
+                return "dot";
+            case HAMMING:
+                return "hamming";
+            case DEFAULT:
+            default:
+                return "default";
+        }
+    }
+
+    private static Encoding analyzeField(Field field) {
+        boolean multiVector = isMultiVector(field);
+        Field vectorField = field;
+        if (multiVector) {
+            if (hasExtension(field) || field.getDictionary() != null || 
field.getChildren().size() != 1) {
+                throw unsupportedVectorType(field);
+            }
+            vectorField = field.getChildren().get(0);
+            // Lance's multi-vector distance kernels do not consult inner 
validity bitmaps.
+            if (vectorField.isNullable() || vectorField.getChildren().size() 
!= 1) {
+                throw new DorisConnectorException("Lance multi-vector columns 
require non-nullable subvectors");
+            }
+        }
+        Encoding encoding = analyzeVectorField(vectorField);
+        if (multiVector && encoding.elementType != TVectorElementType.FLOAT16
+                && encoding.elementType != TVectorElementType.FLOAT32
+                && encoding.elementType != TVectorElementType.FLOAT64) {
+            throw unsupportedVectorType(field);
+        }
+        return encoding;
+    }
+
+    private static Encoding analyzeVectorField(Field field) {
+        if (hasExtension(field) || field.getDictionary() != null
+                || field.getType().getTypeID() != 
ArrowType.ArrowTypeID.FixedSizeList
+                || field.getChildren().size() != 1) {
+            throw unsupportedVectorType(field);
+        }
+        int dimension = ((ArrowType.FixedSizeList) 
field.getType()).getListSize();
+        if (dimension <= 0) {
+            throw new DorisConnectorException("Lance vector column '" + 
field.getName()
+                    + "' has invalid dimension " + dimension);
+        }
+        Field elementField = field.getChildren().get(0);
+        if (hasExtension(elementField) || elementField.getDictionary() != 
null) {
+            throw unsupportedVectorType(field);
+        }
+        return encodingOf(field, elementField.getType(), dimension);
+    }
+
+    private static Encoding encodingOf(Field vectorField, ArrowType 
elementType, int dimension) {
+        switch (elementType.getTypeID()) {
+            case FloatingPoint:
+                FloatingPointPrecision precision = ((ArrowType.FloatingPoint) 
elementType).getPrecision();
+                switch (precision) {
+                    case HALF:
+                        return new Encoding(dimension, 
TVectorElementType.FLOAT16, Short.BYTES);
+                    case SINGLE:
+                        return new Encoding(dimension, 
TVectorElementType.FLOAT32, Float.BYTES);
+                    case DOUBLE:
+                        return new Encoding(dimension, 
TVectorElementType.FLOAT64, Double.BYTES);
+                    default:
+                        throw unsupportedVectorType(vectorField);
+                }
+            case Int:
+                ArrowType.Int integer = (ArrowType.Int) elementType;
+                if (integer.getBitWidth() == Byte.SIZE) {

Review Comment:
   [P1] Reject nullable INT8 vector columns before they reach Lance-C. 
`analyzeVectorField` admits any 8-bit integer fixed-size-list without checking 
the element/vector nullability, so `vector_search` over the fixture's nullable 
`fixed_size_list_int8_col` is accepted. The new regression suite documents that 
this exact query aborts the BE because Lance-C's INT8 null conversion 
constructs an invalid FixedSizeListArray and panics across FFI. Add a 
schema-level rejection (or disable INT8 until the bundled Lance-C is fixed) and 
a negative test that proves the query fails cleanly.



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