Copilot commented on code in PR #7330:
URL: https://github.com/apache/paimon/pull/7330#discussion_r2937919617


##########
pom.xml:
##########
@@ -72,6 +72,7 @@ under the License.
         <module>paimon-arrow</module>
         <module>tools/ci/paimon-ci-tools</module>
         <module>paimon-api</module>
+        <module>paimon-lumina</module>
     </modules>
 

Review Comment:
   Adding `paimon-lumina` as a default top-level Maven module means every full 
reactor build now requires resolving `lumina-jni` from the external `lumina` 
repository. This can break contributor/CI builds in environments without access 
to that repository; consider gating the module behind a Maven profile (opt-in) 
or otherwise ensuring the dependency is available from the same repos used for 
normal builds.
   



##########
paimon-lumina/src/main/java/org/apache/paimon/lumina/index/LuminaVectorGlobalIndexWriter.java:
##########
@@ -0,0 +1,362 @@
+/*
+ * 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.paimon.lumina.index;
+
+import org.apache.paimon.data.InternalArray;
+import org.apache.paimon.fs.PositionOutputStream;
+import org.apache.paimon.globalindex.GlobalIndexSingletonWriter;
+import org.apache.paimon.globalindex.ResultEntry;
+import org.apache.paimon.globalindex.io.GlobalIndexFileWriter;
+import org.apache.paimon.types.ArrayType;
+import org.apache.paimon.types.DataType;
+import org.apache.paimon.types.FloatType;
+
+import org.aliyun.lumina.LuminaDataset;
+import org.aliyun.lumina.LuminaFileOutput;
+
+import java.io.Closeable;
+import java.io.File;
+import java.io.IOException;
+import java.io.RandomAccessFile;
+import java.lang.reflect.Field;
+import java.nio.ByteBuffer;
+import java.nio.ByteOrder;
+import java.nio.channels.FileChannel;
+import java.util.Collections;
+import java.util.List;
+import java.util.Map;
+
+/**
+ * Vector global index writer using Lumina. Builds a single index file per 
shard.
+ *
+ * <p>Vectors are spilled to a temporary file on disk as they arrive via 
{@link #write(Object)},
+ * keeping Java heap usage constant (~8 MB buffer) regardless of dataset size. 
During index build,
+ * the Lumina builder streams vectors from the temp file via the {@link 
LuminaDataset} callback API.
+ *
+ * <p><b>Thread safety:</b> This class is <b>not</b> thread-safe. The 
underlying {@code
+ * LuminaBuilder} must be used from a single thread or the caller must provide 
external
+ * synchronization. The internal Lumina executor thread pool size is 
controlled globally by the
+ * {@code LUMINA_EXECUTOR_THREAD_COUNT} environment variable and cannot be 
configured per-instance.
+ */
+public class LuminaVectorGlobalIndexWriter implements 
GlobalIndexSingletonWriter, Closeable {
+
+    private static final String FILE_NAME_PREFIX = "lumina";
+
+    /** I/O buffer size for reading/writing the temp vector file (~8 MB). */
+    private static final int IO_BUFFER_SIZE = 8 * 1024 * 1024;
+
+    private final GlobalIndexFileWriter fileWriter;
+    private final LuminaVectorIndexOptions options;
+    private final int dim;
+
+    /** Temporary file storing vectors as raw native-order floats. */
+    private File tempVectorFile;
+
+    private FileChannel writeChannel;
+    private ByteBuffer writeBuf;
+
+    private int count;
+    private boolean closed;
+
+    public LuminaVectorGlobalIndexWriter(
+            GlobalIndexFileWriter fileWriter,
+            DataType fieldType,
+            LuminaVectorIndexOptions options) {
+        this.fileWriter = fileWriter;
+        this.options = options;
+        this.dim = options.dimension();
+        this.count = 0;
+        this.closed = false;
+
+        validateFieldType(fieldType);
+
+        try {
+            this.tempVectorFile = File.createTempFile("lumina-vectors-", 
".bin");
+            this.tempVectorFile.deleteOnExit();
+            @SuppressWarnings("resource")
+            RandomAccessFile raf = new RandomAccessFile(tempVectorFile, "rw");
+            this.writeChannel = raf.getChannel();
+            this.writeBuf = ByteBuffer.allocateDirect(IO_BUFFER_SIZE);
+            this.writeBuf.order(ByteOrder.nativeOrder());
+        } catch (IOException e) {
+            throw new RuntimeException("Failed to create temp vector file", e);
+        }
+    }
+
+    private void validateFieldType(DataType dataType) {
+        if (!(dataType instanceof ArrayType)) {
+            throw new IllegalArgumentException(
+                    "Lumina vector index requires ArrayType, but got: " + 
dataType);
+        }
+        DataType elementType = ((ArrayType) dataType).getElementType();
+        if (!(elementType instanceof FloatType)) {
+            throw new IllegalArgumentException(
+                    "Lumina vector index requires float array, but got: " + 
elementType);
+        }
+    }
+
+    @Override
+    public void write(Object fieldData) {
+        float[] vector;
+        if (fieldData == null) {
+            throw new IllegalArgumentException("Field data must not be null");
+        }
+        if (fieldData instanceof float[]) {
+            vector = (float[]) fieldData;
+        } else if (fieldData instanceof InternalArray) {
+            vector = ((InternalArray) fieldData).toFloatArray();
+        } else {
+            throw new RuntimeException(
+                    "Unsupported vector type: " + 
fieldData.getClass().getName());
+        }
+        checkDimension(vector);
+
+        int bytesNeeded = dim * Float.BYTES;
+        if (writeBuf.remaining() < bytesNeeded) {
+            flushWriteBuffer();
+        }
+        for (int i = 0; i < dim; i++) {
+            writeBuf.putFloat(vector[i]);
+        }
+        count++;
+    }
+
+    private void flushWriteBuffer() {
+        try {
+            writeBuf.flip();
+            while (writeBuf.hasRemaining()) {
+                writeChannel.write(writeBuf);
+            }
+            writeBuf.clear();
+        } catch (IOException e) {
+            throw new RuntimeException("Failed to flush vector buffer to 
disk", e);
+        }
+    }
+
+    @Override
+    public List<ResultEntry> finish() {
+        try {
+            if (count == 0) {
+                return Collections.emptyList();
+            }
+            // Flush remaining data and close the write channel
+            flushWriteBuffer();
+            writeChannel.close();
+            writeChannel = null;
+            writeBuf = null;
+            return Collections.singletonList(buildIndex());
+        } catch (IOException e) {
+            throw new RuntimeException("Failed to write Lumina vector global 
index", e);
+        } finally {
+            // Delete the temp file eagerly so index builds don't exhaust disk.
+            // Production callers (e.g. DefaultGlobalIndexBuilder) call 
finish()
+            // but never close(), so we must clean up here.
+            if (tempVectorFile != null) {
+                tempVectorFile.delete();
+                tempVectorFile = null;
+            }
+        }
+    }
+
+    private ResultEntry buildIndex() throws IOException {
+        configureExecutorThreadCount();
+        try (LuminaIndex index =
+                LuminaIndex.createForBuild(dim, options.metric(), 
options.toLuminaOptions())) {
+
+            // Pretrain and insert via streaming file-backed Dataset API
+            try (FileBackedDataset ds = new FileBackedDataset(tempVectorFile, 
dim, count)) {
+                index.pretrainFrom(ds);
+            }
+            try (FileBackedDataset ds = new FileBackedDataset(tempVectorFile, 
dim, count)) {
+                index.insertFrom(ds);
+            }
+
+            String fileName = fileWriter.newFileName(FILE_NAME_PREFIX);
+            try (PositionOutputStream out = 
fileWriter.newOutputStream(fileName)) {
+                index.dump(new OutputStreamFileOutput(out));
+                out.flush();
+            }
+
+            LuminaIndexMeta meta = new 
LuminaIndexMeta(options.toLuminaOptions());
+            return new ResultEntry(fileName, count, meta.serialize());
+        }
+    }
+
+    /**
+     * Sets the {@code LUMINA_EXECUTOR_THREAD_COUNT} environment variable from 
the {@link
+     * LuminaVectorIndexOptions#DISKANN_BUILD_THREAD_COUNT} option so the 
native Lumina executor
+     * thread pool is sized correctly before the builder is created.
+     */
+    private void configureExecutorThreadCount() {
+        Map<String, String> luminaOpts = options.toLuminaOptions();
+        String threadCountKey =
+                LuminaVectorIndexOptions.toLuminaKey(
+                        LuminaVectorIndexOptions.DISKANN_BUILD_THREAD_COUNT);
+        String threadCount = luminaOpts.get(threadCountKey);
+        if (threadCount != null && !threadCount.isEmpty()) {
+            setEnv("LUMINA_EXECUTOR_THREAD_COUNT", threadCount);
+        }
+    }
+
+    /**
+     * Best-effort attempt to set an environment variable in the current 
process. Uses reflection to
+     * modify the JVM's process environment map. This is necessary because 
Lumina's native executor
+     * thread pool reads {@code LUMINA_EXECUTOR_THREAD_COUNT} from the OS 
environment.
+     */
+    @SuppressWarnings("unchecked")
+    private static void setEnv(String key, String value) {
+        try {
+            Map<String, String> env = System.getenv();
+            Field field = env.getClass().getDeclaredField("m");
+            field.setAccessible(true);
+            ((Map<String, String>) field.get(env)).put(key, value);
+        } catch (Exception e) {
+        }
+    }

Review Comment:
   `setEnv` silently swallows all exceptions. If updating the process 
environment fails (common on newer JDKs / different `System.getenv()` 
implementations), the build thread-count tuning won’t take effect and it will 
be very hard to diagnose. At minimum, surface this failure via logging (or an 
explicit warning) so misconfiguration isn’t silent.



##########
paimon-lumina/src/main/java/org/apache/paimon/lumina/index/LuminaVectorGlobalIndexReader.java:
##########
@@ -0,0 +1,528 @@
+/*
+ * 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.paimon.lumina.index;
+
+import org.apache.paimon.fs.SeekableInputStream;
+import org.apache.paimon.globalindex.GlobalIndexIOMeta;
+import org.apache.paimon.globalindex.GlobalIndexReader;
+import org.apache.paimon.globalindex.GlobalIndexResult;
+import org.apache.paimon.globalindex.io.GlobalIndexFileReader;
+import org.apache.paimon.predicate.FieldRef;
+import org.apache.paimon.predicate.VectorSearch;
+import org.apache.paimon.types.ArrayType;
+import org.apache.paimon.types.DataType;
+import org.apache.paimon.types.FloatType;
+import org.apache.paimon.utils.IOUtils;
+import org.apache.paimon.utils.RoaringNavigableMap64;
+
+import org.aliyun.lumina.LuminaFileInput;
+
+import java.io.IOException;
+import java.util.Comparator;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
+import java.util.PriorityQueue;
+
+import static org.apache.paimon.utils.Preconditions.checkArgument;
+
+/**
+ * Vector global index reader using Lumina.
+ *
+ * <p>Each shard has exactly one Lumina index file. This reader loads the 
single index and performs
+ * vector similarity search.
+ */
+public class LuminaVectorGlobalIndexReader implements GlobalIndexReader {
+
+    /**
+     * Sets {@code diskann.search.list_size} when not explicitly configured. 
The list size is set to
+     * at least {@code MIN_SEARCH_LIST_SIZE} to ensure sufficient recall for 
DiskANN, even when topK
+     * is very small.
+     */
+    private static final int MIN_SEARCH_LIST_SIZE = 16;
+
+    private final GlobalIndexIOMeta ioMeta;
+    private final GlobalIndexFileReader fileReader;
+    private final DataType fieldType;
+    private final LuminaVectorIndexOptions options;
+
+    private volatile LuminaIndexMeta indexMeta;
+    private volatile LuminaIndex index;
+    private SeekableInputStream openStream;
+    private InputStreamFileInput inputStreamFileInput;
+
+    public LuminaVectorGlobalIndexReader(
+            GlobalIndexFileReader fileReader,
+            List<GlobalIndexIOMeta> ioMetas,
+            DataType fieldType,
+            LuminaVectorIndexOptions options) {
+        checkArgument(ioMetas.size() == 1, "Expected exactly one index file 
per shard");
+        this.fileReader = fileReader;
+        this.ioMeta = ioMetas.get(0);
+        this.fieldType = fieldType;
+        this.options = options;
+    }
+
+    @Override
+    public Optional<GlobalIndexResult> visitVectorSearch(VectorSearch 
vectorSearch) {
+        try {
+            ensureLoaded();
+            return Optional.ofNullable(search(vectorSearch));
+        } catch (IOException e) {
+            throw new RuntimeException(
+                    String.format(
+                            "Failed to search Lumina vector index with 
fieldName=%s, limit=%d",
+                            vectorSearch.fieldName(), vectorSearch.limit()),
+                    e);
+        }
+    }
+
+    private GlobalIndexResult search(VectorSearch vectorSearch) throws 
IOException {
+        validateSearchVector(vectorSearch.vector());
+        float[] queryVector = ((float[]) vectorSearch.vector()).clone();
+        int limit = vectorSearch.limit();
+        LuminaVectorMetric indexMetric = indexMeta.metric();
+
+        int effectiveK = (int) Math.min(limit, index.size());
+        if (effectiveK <= 0) {
+            return null;
+        }
+
+        RoaringNavigableMap64 includeRowIds = vectorSearch.includeRowIds();
+        float[] distances;
+        long[] labels;
+
+        if (includeRowIds != null) {
+            long cardinality = includeRowIds.getLongCardinality();
+            if (cardinality > Integer.MAX_VALUE) {
+                throw new IllegalArgumentException(
+                        "includeRowIds cardinality ("
+                                + cardinality
+                                + ") exceeds Integer.MAX_VALUE");
+            }
+            long[] scopedIds = new long[(int) cardinality];
+            Iterator<Long> iter = includeRowIds.iterator();
+            for (int i = 0; i < scopedIds.length; i++) {
+                scopedIds[i] = iter.next();
+            }
+            if (scopedIds.length == 0) {
+                return null;
+            }
+            effectiveK = Math.min(effectiveK, scopedIds.length);
+            distances = new float[effectiveK];
+            labels = new long[effectiveK];
+            Map<String, String> searchOptions = options.toLuminaOptions();
+            searchOptions.putAll(indexMeta.options());
+            searchOptions.put("search.thread_safe_filter", "true");
+            ensureSearchListSize(searchOptions, effectiveK);
+            index.searchWithFilter(
+                    queryVector, 1, effectiveK, distances, labels, scopedIds, 
searchOptions);
+        } else {
+            distances = new float[effectiveK];
+            labels = new long[effectiveK];
+            Map<String, String> searchOptions = options.toLuminaOptions();
+            searchOptions.putAll(indexMeta.options());
+            ensureSearchListSize(searchOptions, effectiveK);
+            index.search(queryVector, 1, effectiveK, distances, labels, 
searchOptions);
+        }
+
+        // Min-heap: smallest score at head, so we can evict the weakest 
candidate efficiently.
+        PriorityQueue<ScoredRow> topK =
+                new PriorityQueue<>(limit + 1, Comparator.comparingDouble(s -> 
s.score));
+        collectResults(distances, labels, effectiveK, limit, topK, 
indexMetric);

Review Comment:
   `PriorityQueue` is initialized with `limit + 1` capacity. If a query uses a 
very large `limit`, this eagerly allocates a large backing array even though 
the actual result count is capped by `effectiveK`. Consider initializing the 
heap with `effectiveK + 1` (or `Math.min(limit, effectiveK) + 1`) and also 
using the capped limit in `collectResults(...)`.
   



##########
paimon-lumina/src/main/java/org/apache/paimon/lumina/index/LuminaIndex.java:
##########
@@ -0,0 +1,226 @@
+/*
+ * 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.paimon.lumina.index;
+
+import org.aliyun.lumina.LuminaBuilder;
+import org.aliyun.lumina.LuminaDataset;
+import org.aliyun.lumina.LuminaFileInput;
+import org.aliyun.lumina.LuminaFileOutput;
+import org.aliyun.lumina.LuminaSearcher;
+import org.aliyun.lumina.MetricType;
+
+import java.io.Closeable;
+import java.util.LinkedHashMap;
+import java.util.Map;
+
+/**
+ * A high-level wrapper for Lumina index operations (build and search).
+ *
+ * <p>This class provides a safe Java API for building and searching Lumina 
vector indices. It
+ * manages the lifecycle of native LuminaBuilder and LuminaSearcher objects.
+ */
+public class LuminaIndex implements Closeable {
+
+    private LuminaBuilder builder;
+    private LuminaSearcher searcher;
+    private final int dimension;
+    private final LuminaVectorMetric metric;
+    private volatile boolean closed = false;
+
+    private LuminaIndex(int dimension, LuminaVectorMetric metric) {
+        this.dimension = dimension;
+        this.metric = metric;
+    }
+
+    /** Create a new index for building. */
+    public static LuminaIndex createForBuild(
+            int dimension, LuminaVectorMetric metric, Map<String, String> 
extraOptions) {
+        LuminaIndex index = new LuminaIndex(dimension, metric);
+
+        Map<String, String> opts = new LinkedHashMap<>(extraOptions);
+        index.builder =
+                LuminaBuilder.create(
+                        LuminaVectorIndexOptions.INDEX_TYPE.defaultValue(),
+                        dimension,
+                        toMetricType(metric),
+                        opts);
+        return index;

Review Comment:
   `lumina.index.type` is exposed as a configurable option, but 
`LuminaBuilder.create(...)` is always passed 
`LuminaVectorIndexOptions.INDEX_TYPE.defaultValue()` ("diskann"). This makes 
the option ineffective and could lead to confusing behavior if additional index 
types are added/used. Use the resolved index type from options/metadata instead 
of the default constant when creating the builder/searcher.



##########
paimon-lumina/src/main/java/org/apache/paimon/lumina/index/LuminaVectorGlobalIndexWriter.java:
##########
@@ -0,0 +1,362 @@
+/*
+ * 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.paimon.lumina.index;
+
+import org.apache.paimon.data.InternalArray;
+import org.apache.paimon.fs.PositionOutputStream;
+import org.apache.paimon.globalindex.GlobalIndexSingletonWriter;
+import org.apache.paimon.globalindex.ResultEntry;
+import org.apache.paimon.globalindex.io.GlobalIndexFileWriter;
+import org.apache.paimon.types.ArrayType;
+import org.apache.paimon.types.DataType;
+import org.apache.paimon.types.FloatType;
+
+import org.aliyun.lumina.LuminaDataset;
+import org.aliyun.lumina.LuminaFileOutput;
+
+import java.io.Closeable;
+import java.io.File;
+import java.io.IOException;
+import java.io.RandomAccessFile;
+import java.lang.reflect.Field;
+import java.nio.ByteBuffer;
+import java.nio.ByteOrder;
+import java.nio.channels.FileChannel;
+import java.util.Collections;
+import java.util.List;
+import java.util.Map;
+
+/**
+ * Vector global index writer using Lumina. Builds a single index file per 
shard.
+ *
+ * <p>Vectors are spilled to a temporary file on disk as they arrive via 
{@link #write(Object)},
+ * keeping Java heap usage constant (~8 MB buffer) regardless of dataset size. 
During index build,
+ * the Lumina builder streams vectors from the temp file via the {@link 
LuminaDataset} callback API.
+ *
+ * <p><b>Thread safety:</b> This class is <b>not</b> thread-safe. The 
underlying {@code
+ * LuminaBuilder} must be used from a single thread or the caller must provide 
external
+ * synchronization. The internal Lumina executor thread pool size is 
controlled globally by the
+ * {@code LUMINA_EXECUTOR_THREAD_COUNT} environment variable and cannot be 
configured per-instance.
+ */
+public class LuminaVectorGlobalIndexWriter implements 
GlobalIndexSingletonWriter, Closeable {
+
+    private static final String FILE_NAME_PREFIX = "lumina";
+
+    /** I/O buffer size for reading/writing the temp vector file (~8 MB). */
+    private static final int IO_BUFFER_SIZE = 8 * 1024 * 1024;
+
+    private final GlobalIndexFileWriter fileWriter;
+    private final LuminaVectorIndexOptions options;
+    private final int dim;
+
+    /** Temporary file storing vectors as raw native-order floats. */
+    private File tempVectorFile;
+
+    private FileChannel writeChannel;
+    private ByteBuffer writeBuf;
+
+    private int count;
+    private boolean closed;
+
+    public LuminaVectorGlobalIndexWriter(
+            GlobalIndexFileWriter fileWriter,
+            DataType fieldType,
+            LuminaVectorIndexOptions options) {
+        this.fileWriter = fileWriter;
+        this.options = options;
+        this.dim = options.dimension();
+        this.count = 0;
+        this.closed = false;
+
+        validateFieldType(fieldType);
+
+        try {
+            this.tempVectorFile = File.createTempFile("lumina-vectors-", 
".bin");
+            this.tempVectorFile.deleteOnExit();
+            @SuppressWarnings("resource")
+            RandomAccessFile raf = new RandomAccessFile(tempVectorFile, "rw");
+            this.writeChannel = raf.getChannel();
+            this.writeBuf = ByteBuffer.allocateDirect(IO_BUFFER_SIZE);
+            this.writeBuf.order(ByteOrder.nativeOrder());
+        } catch (IOException e) {
+            throw new RuntimeException("Failed to create temp vector file", e);
+        }
+    }
+
+    private void validateFieldType(DataType dataType) {
+        if (!(dataType instanceof ArrayType)) {
+            throw new IllegalArgumentException(
+                    "Lumina vector index requires ArrayType, but got: " + 
dataType);
+        }
+        DataType elementType = ((ArrayType) dataType).getElementType();
+        if (!(elementType instanceof FloatType)) {
+            throw new IllegalArgumentException(
+                    "Lumina vector index requires float array, but got: " + 
elementType);
+        }
+    }
+
+    @Override
+    public void write(Object fieldData) {
+        float[] vector;
+        if (fieldData == null) {
+            throw new IllegalArgumentException("Field data must not be null");
+        }
+        if (fieldData instanceof float[]) {
+            vector = (float[]) fieldData;
+        } else if (fieldData instanceof InternalArray) {
+            vector = ((InternalArray) fieldData).toFloatArray();
+        } else {
+            throw new RuntimeException(
+                    "Unsupported vector type: " + 
fieldData.getClass().getName());
+        }
+        checkDimension(vector);
+
+        int bytesNeeded = dim * Float.BYTES;
+        if (writeBuf.remaining() < bytesNeeded) {
+            flushWriteBuffer();
+        }
+        for (int i = 0; i < dim; i++) {
+            writeBuf.putFloat(vector[i]);
+        }
+        count++;
+    }
+
+    private void flushWriteBuffer() {
+        try {
+            writeBuf.flip();
+            while (writeBuf.hasRemaining()) {
+                writeChannel.write(writeBuf);
+            }
+            writeBuf.clear();
+        } catch (IOException e) {
+            throw new RuntimeException("Failed to flush vector buffer to 
disk", e);
+        }
+    }
+
+    @Override
+    public List<ResultEntry> finish() {
+        try {
+            if (count == 0) {
+                return Collections.emptyList();
+            }
+            // Flush remaining data and close the write channel
+            flushWriteBuffer();
+            writeChannel.close();
+            writeChannel = null;
+            writeBuf = null;
+            return Collections.singletonList(buildIndex());
+        } catch (IOException e) {
+            throw new RuntimeException("Failed to write Lumina vector global 
index", e);
+        } finally {
+            // Delete the temp file eagerly so index builds don't exhaust disk.
+            // Production callers (e.g. DefaultGlobalIndexBuilder) call 
finish()
+            // but never close(), so we must clean up here.
+            if (tempVectorFile != null) {
+                tempVectorFile.delete();
+                tempVectorFile = null;
+            }
+        }
+    }
+
+    private ResultEntry buildIndex() throws IOException {
+        configureExecutorThreadCount();
+        try (LuminaIndex index =
+                LuminaIndex.createForBuild(dim, options.metric(), 
options.toLuminaOptions())) {
+
+            // Pretrain and insert via streaming file-backed Dataset API
+            try (FileBackedDataset ds = new FileBackedDataset(tempVectorFile, 
dim, count)) {
+                index.pretrainFrom(ds);
+            }
+            try (FileBackedDataset ds = new FileBackedDataset(tempVectorFile, 
dim, count)) {
+                index.insertFrom(ds);
+            }
+
+            String fileName = fileWriter.newFileName(FILE_NAME_PREFIX);
+            try (PositionOutputStream out = 
fileWriter.newOutputStream(fileName)) {
+                index.dump(new OutputStreamFileOutput(out));
+                out.flush();
+            }
+
+            LuminaIndexMeta meta = new 
LuminaIndexMeta(options.toLuminaOptions());
+            return new ResultEntry(fileName, count, meta.serialize());
+        }
+    }
+
+    /**
+     * Sets the {@code LUMINA_EXECUTOR_THREAD_COUNT} environment variable from 
the {@link
+     * LuminaVectorIndexOptions#DISKANN_BUILD_THREAD_COUNT} option so the 
native Lumina executor
+     * thread pool is sized correctly before the builder is created.
+     */
+    private void configureExecutorThreadCount() {
+        Map<String, String> luminaOpts = options.toLuminaOptions();
+        String threadCountKey =
+                LuminaVectorIndexOptions.toLuminaKey(
+                        LuminaVectorIndexOptions.DISKANN_BUILD_THREAD_COUNT);
+        String threadCount = luminaOpts.get(threadCountKey);
+        if (threadCount != null && !threadCount.isEmpty()) {
+            setEnv("LUMINA_EXECUTOR_THREAD_COUNT", threadCount);
+        }
+    }
+
+    /**
+     * Best-effort attempt to set an environment variable in the current 
process. Uses reflection to
+     * modify the JVM's process environment map. This is necessary because 
Lumina's native executor
+     * thread pool reads {@code LUMINA_EXECUTOR_THREAD_COUNT} from the OS 
environment.
+     */
+    @SuppressWarnings("unchecked")
+    private static void setEnv(String key, String value) {
+        try {
+            Map<String, String> env = System.getenv();
+            Field field = env.getClass().getDeclaredField("m");
+            field.setAccessible(true);
+            ((Map<String, String>) field.get(env)).put(key, value);
+        } catch (Exception e) {
+        }
+    }
+
+    private void checkDimension(float[] vector) {
+        if (vector.length != dim) {
+            throw new IllegalArgumentException(
+                    String.format(
+                            "Vector dimension mismatch: expected %d, but got 
%d",
+                            dim, vector.length));
+        }
+    }
+
+    @Override
+    public void close() {
+        if (!closed) {
+            closed = true;
+            try {
+                if (writeChannel != null) {
+                    writeChannel.close();
+                }
+            } catch (IOException ignored) {
+            }
+            writeBuf = null;
+            if (tempVectorFile != null) {
+                tempVectorFile.delete();
+                tempVectorFile = null;
+            }
+        }
+    }
+
+    /**
+     * A {@link LuminaDataset} that streams vectors from a temporary file. 
Reads are sequential and
+     * buffered for efficiency. Each instance reads the file from the 
beginning independently.
+     */
+    static class FileBackedDataset implements LuminaDataset, Closeable {
+        private final RandomAccessFile raf;
+        private final FileChannel channel;
+        private final int dim;
+        private final int totalCount;
+        private int cursor;
+        private final ByteBuffer readBuf;
+
+        FileBackedDataset(File file, int dim, int totalCount) throws 
IOException {
+            this.raf = new RandomAccessFile(file, "r");
+            this.channel = raf.getChannel();
+            this.dim = dim;
+            this.totalCount = totalCount;
+            this.cursor = 0;
+            this.readBuf = ByteBuffer.allocateDirect(IO_BUFFER_SIZE);
+            this.readBuf.order(ByteOrder.nativeOrder());
+            this.readBuf.limit(0); // empty initially
+        }
+
+        @Override
+        public int dim() {
+            return dim;
+        }
+
+        @Override
+        public long totalSize() {
+            return totalCount;
+        }
+
+        @Override
+        public long getNextBatch(float[] vectorBuf, long[] idBuf) {
+            if (cursor >= totalCount) {
+                return 0;
+            }
+            int remaining = totalCount - cursor;
+            int maxByVectorBuf = vectorBuf.length / dim;
+            int batchSize = Math.min(Math.min(maxByVectorBuf, idBuf.length), 
remaining);
+
+            int floatsNeeded = batchSize * dim;
+            int destOffset = 0;
+            try {
+                while (destOffset < floatsNeeded) {
+                    if (readBuf.remaining() < Float.BYTES) {
+                        // Compact any partial float bytes and refill
+                        readBuf.compact();
+                        channel.read(readBuf);
+                        readBuf.flip();
+                    }
+                    int availableFloats = readBuf.remaining() / Float.BYTES;
+                    int toRead = Math.min(availableFloats, floatsNeeded - 
destOffset);
+                    readBuf.asFloatBuffer().get(vectorBuf, destOffset, toRead);
+                    readBuf.position(readBuf.position() + toRead * 
Float.BYTES);
+                    destOffset += toRead;
+                }

Review Comment:
   `FileBackedDataset.getNextBatch` refills the read buffer with 
`channel.read(readBuf)` but doesn’t handle EOF (`-1`). If the temp file is 
truncated/corrupted (or an unexpected short read happens), `availableFloats` 
can stay 0 and the loop may never make progress, effectively hanging. Check the 
return value from `channel.read(...)` and fail fast (or break) when EOF is 
reached before the requested floats are read.



##########
paimon-lumina/src/main/java/org/apache/paimon/lumina/index/LuminaIndex.java:
##########
@@ -0,0 +1,226 @@
+/*
+ * 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.paimon.lumina.index;
+
+import org.aliyun.lumina.LuminaBuilder;
+import org.aliyun.lumina.LuminaDataset;
+import org.aliyun.lumina.LuminaFileInput;
+import org.aliyun.lumina.LuminaFileOutput;
+import org.aliyun.lumina.LuminaSearcher;
+import org.aliyun.lumina.MetricType;
+
+import java.io.Closeable;
+import java.util.LinkedHashMap;
+import java.util.Map;
+
+/**
+ * A high-level wrapper for Lumina index operations (build and search).
+ *
+ * <p>This class provides a safe Java API for building and searching Lumina 
vector indices. It
+ * manages the lifecycle of native LuminaBuilder and LuminaSearcher objects.
+ */
+public class LuminaIndex implements Closeable {
+
+    private LuminaBuilder builder;
+    private LuminaSearcher searcher;
+    private final int dimension;
+    private final LuminaVectorMetric metric;
+    private volatile boolean closed = false;
+
+    private LuminaIndex(int dimension, LuminaVectorMetric metric) {
+        this.dimension = dimension;
+        this.metric = metric;
+    }
+
+    /** Create a new index for building. */
+    public static LuminaIndex createForBuild(
+            int dimension, LuminaVectorMetric metric, Map<String, String> 
extraOptions) {
+        LuminaIndex index = new LuminaIndex(dimension, metric);
+
+        Map<String, String> opts = new LinkedHashMap<>(extraOptions);
+        index.builder =
+                LuminaBuilder.create(
+                        LuminaVectorIndexOptions.INDEX_TYPE.defaultValue(),
+                        dimension,
+                        toMetricType(metric),
+                        opts);
+        return index;
+    }
+
+    /**
+     * Open an existing index from a streaming file input for searching.
+     *
+     * <p>The native searcher reads on-demand from the provided input. The 
caller must keep the
+     * underlying stream open until this index is closed.
+     */
+    public static LuminaIndex fromStream(
+            LuminaFileInput fileInput,
+            long fileSize,
+            int dimension,
+            LuminaVectorMetric metric,
+            Map<String, String> extraOptions) {
+        LuminaIndex index = new LuminaIndex(dimension, metric);
+        index.searcher =
+                LuminaSearcher.create(
+                        LuminaVectorIndexOptions.INDEX_TYPE.defaultValue(),
+                        dimension,
+                        toMetricType(metric),
+                        extraOptions);
+        index.searcher.open(fileInput, fileSize);
+        return index;

Review Comment:
   Same issue as builder creation: `LuminaSearcher.create(...)` is always 
called with `LuminaVectorIndexOptions.INDEX_TYPE.defaultValue()` rather than 
the configured/metadata index type. This prevents reading/searching indexes 
built with a non-default index type.



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


Reply via email to