This is an automated email from the ASF dual-hosted git repository.

xiangfu0 pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/pinot.git


The following commit(s) were added to refs/heads/master by this push:
     new 794f76e2c85 Read Lucene index files from the index buffer without 
copying (#20071)
794f76e2c85 is described below

commit 794f76e2c852e38c70fa7d85fb9e7251d490631b
Author: RAGHVENDRA KUMAR YADAV <[email protected]>
AuthorDate: Sat Nov 21 18:12:32 2026 -0800

    Read Lucene index files from the index buffer without copying (#20071)
    
    Use Lucene's bulk accessors over shared heap, direct, and mapped views of
    packed text and HNSW index files. The segment owns the backing memory.
    Buffers that require a fetch or copy, and files larger than a single
    ByteBuffer, continue to use bounded on-demand reads.
    
    Validate file offsets and lengths before opening either input. Cover
    both byte orders, both local factories, copying buffers, oversized
    logical files, malformed metadata, term searches, and KNN searches.
---
 .../readers/text/PinotBufferLuceneDirectory.java   |  20 ++-
 .../text/PinotBufferLuceneDirectoryTest.java       | 186 +++++++++++++++++++++
 .../spi/memory/NonNativePinotDataBuffer.java       |   7 +
 .../pinot/segment/spi/memory/PinotByteBuffer.java  |   5 +
 .../pinot/segment/spi/memory/PinotDataBuffer.java  |   8 +
 .../spi/memory/unsafe/UnsafePinotBuffer.java       |   5 +
 6 files changed, 230 insertions(+), 1 deletion(-)

diff --git 
a/pinot-segment-local/src/main/java/org/apache/pinot/segment/local/segment/index/readers/text/PinotBufferLuceneDirectory.java
 
b/pinot-segment-local/src/main/java/org/apache/pinot/segment/local/segment/index/readers/text/PinotBufferLuceneDirectory.java
index 7c8d2a65467..948257b1f11 100644
--- 
a/pinot-segment-local/src/main/java/org/apache/pinot/segment/local/segment/index/readers/text/PinotBufferLuceneDirectory.java
+++ 
b/pinot-segment-local/src/main/java/org/apache/pinot/segment/local/segment/index/readers/text/PinotBufferLuceneDirectory.java
@@ -19,9 +19,14 @@
 package org.apache.pinot.segment.local.segment.index.readers.text;
 
 import java.io.IOException;
+import java.nio.ByteBuffer;
+import java.nio.ByteOrder;
 import java.util.Collection;
+import java.util.List;
 import java.util.Map;
 import java.util.Set;
+import org.apache.lucene.store.ByteBuffersDataInput;
+import org.apache.lucene.store.ByteBuffersIndexInput;
 import org.apache.lucene.store.Directory;
 import org.apache.lucene.store.IOContext;
 import org.apache.lucene.store.IndexInput;
@@ -109,7 +114,20 @@ public class PinotBufferLuceneDirectory extends Directory {
     if (fileInfo == null) {
       throw new IOException("File not found: " + name);
     }
-    return new PinotBufferIndexInput(name, _indexBuffer, fileInfo.getOffset(), 
fileInfo.getSize());
+    long offset = fileInfo.getOffset();
+    long size = fileInfo.getSize();
+    long bufferSize = _indexBuffer.size();
+    if (offset < 0 || size < 0 || offset > bufferSize - size) {
+      throw new IOException("Invalid file range for " + name + ": offset=" + 
offset + ", size=" + size
+          + ", bufferSize=" + bufferSize);
+    }
+    if (size <= Integer.MAX_VALUE) {
+      ByteBuffer view = _indexBuffer.tryViewAsByteBuffer(offset, (int) size, 
ByteOrder.LITTLE_ENDIAN);
+      if (view != null) {
+        return new ByteBuffersIndexInput(new 
ByteBuffersDataInput(List.of(view)), name);
+      }
+    }
+    return new PinotBufferIndexInput(name, _indexBuffer, offset, size);
   }
 
   @Override
diff --git 
a/pinot-segment-local/src/test/java/org/apache/pinot/segment/local/segment/index/readers/text/PinotBufferLuceneDirectoryTest.java
 
b/pinot-segment-local/src/test/java/org/apache/pinot/segment/local/segment/index/readers/text/PinotBufferLuceneDirectoryTest.java
new file mode 100644
index 00000000000..c70e0ad1472
--- /dev/null
+++ 
b/pinot-segment-local/src/test/java/org/apache/pinot/segment/local/segment/index/readers/text/PinotBufferLuceneDirectoryTest.java
@@ -0,0 +1,186 @@
+/**
+ * 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.pinot.segment.local.segment.index.readers.text;
+
+import java.io.IOException;
+import java.nio.ByteBuffer;
+import java.nio.ByteOrder;
+import java.util.Arrays;
+import java.util.HashMap;
+import java.util.Map;
+import org.apache.lucene.analysis.standard.StandardAnalyzer;
+import org.apache.lucene.document.Document;
+import org.apache.lucene.document.Field;
+import org.apache.lucene.document.KnnFloatVectorField;
+import org.apache.lucene.document.TextField;
+import org.apache.lucene.index.DirectoryReader;
+import org.apache.lucene.index.IndexWriter;
+import org.apache.lucene.index.IndexWriterConfig;
+import org.apache.lucene.index.Term;
+import org.apache.lucene.index.VectorSimilarityFunction;
+import org.apache.lucene.search.IndexSearcher;
+import org.apache.lucene.search.KnnFloatVectorQuery;
+import org.apache.lucene.search.TermQuery;
+import org.apache.lucene.search.TopDocs;
+import org.apache.lucene.store.ByteBuffersDirectory;
+import org.apache.lucene.store.ByteBuffersIndexInput;
+import org.apache.lucene.store.IOContext;
+import org.apache.lucene.store.IndexInput;
+import org.apache.pinot.segment.spi.memory.ByteBufferPinotBufferFactory;
+import org.apache.pinot.segment.spi.memory.PinotBufferFactory;
+import org.apache.pinot.segment.spi.memory.PinotByteBuffer;
+import org.apache.pinot.segment.spi.memory.PinotDataBuffer;
+import org.apache.pinot.segment.spi.memory.unsafe.UnsafePinotBufferFactory;
+import org.testng.annotations.DataProvider;
+import org.testng.annotations.Test;
+
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.ArgumentMatchers.anyInt;
+import static org.mockito.ArgumentMatchers.anyLong;
+import static org.mockito.ArgumentMatchers.eq;
+import static org.mockito.Mockito.CALLS_REAL_METHODS;
+import static org.mockito.Mockito.doReturn;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.never;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+import static org.testng.Assert.assertEquals;
+import static org.testng.Assert.assertThrows;
+import static org.testng.Assert.assertTrue;
+
+
+/// Reads a Lucene index packed into a [PinotDataBuffer], as the combined text 
and vector index files are, through
+/// [PinotBufferLuceneDirectory], for both buffer implementations and either 
byte order.
+public class PinotBufferLuceneDirectoryTest {
+  private static final int NUM_DOCS = 500;
+  private static final int PADDING = 13;
+
+  @DataProvider
+  public Object[][] buffers() {
+    // The ByteBuffer factory backs small column files, the Unsafe one backs 
files over 2 GB (or every file when
+    // pinot.offheap.prioritize.bytebuffer=false)
+    PinotBufferFactory byteBuffer = new ByteBufferPinotBufferFactory();
+    PinotBufferFactory unsafe = new UnsafePinotBufferFactory();
+    return new Object[][]{
+        {byteBuffer, ByteOrder.BIG_ENDIAN}, {byteBuffer, 
ByteOrder.LITTLE_ENDIAN},
+        {unsafe, ByteOrder.BIG_ENDIAN}, {unsafe, ByteOrder.LITTLE_ENDIAN}
+    };
+  }
+
+  @Test(dataProvider = "buffers")
+  public void testSearchesIndexPackedInBuffer(PinotBufferFactory factory, 
ByteOrder byteOrder)
+      throws Exception {
+    try (ByteBuffersDirectory source = new ByteBuffersDirectory()) {
+      try (IndexWriter writer = new IndexWriter(source, new 
IndexWriterConfig(new StandardAnalyzer()))) {
+        for (int i = 0; i < NUM_DOCS; i++) {
+          Document document = new Document();
+          document.add(new TextField("text", (i % 2 == 0 ? "even" : "odd") + " 
doc" + i, Field.Store.NO));
+          document.add(new KnnFloatVectorField("vector", new float[]{i, 1, 
-i}, VectorSimilarityFunction.EUCLIDEAN));
+          writer.addDocument(document);
+        }
+        writer.forceMerge(1);
+      }
+
+      // Add padding between files to exercise unaligned offsets.
+      Map<String, LuceneTextIndexHeader.FileInfo> fileMap = new HashMap<>();
+      long size = PADDING;
+      for (String name : source.listAll()) {
+        long length = source.fileLength(name);
+        fileMap.put(name, new LuceneTextIndexHeader.FileInfo(name, size, 
length));
+        size += length + PADDING;
+      }
+      try (PinotDataBuffer buffer = factory.allocateDirect(size, byteOrder)) {
+        for (LuceneTextIndexHeader.FileInfo file : fileMap.values()) {
+          byte[] bytes = new byte[(int) file.getSize()];
+          try (IndexInput input = source.openInput(file.getName(), 
IOContext.READONCE)) {
+            input.readBytes(bytes, 0, bytes.length);
+          }
+          // Byte by byte, not readFrom: readFrom writes through 
toDirectByteBuffer, the method openInput reads
+          // through, so a wrong offset there would shift the write and the 
read alike and go unnoticed
+          for (int i = 0; i < bytes.length; i++) {
+            buffer.putByte(file.getOffset() + i, bytes[i]);
+          }
+        }
+
+        PinotBufferLuceneDirectory directory = new 
PinotBufferLuceneDirectory(buffer, fileMap, "text");
+        for (LuceneTextIndexHeader.FileInfo file : fileMap.values()) {
+          try (IndexInput expected = source.openInput(file.getName(), 
IOContext.READONCE);
+              IndexInput actual = directory.openInput(file.getName(), 
IOContext.READONCE)) {
+            assertTrue(actual instanceof ByteBuffersIndexInput);
+            assertEquals(actual.length(), expected.length());
+            for (long i = 0; i < expected.length(); i++) {
+              assertEquals(actual.readByte(), expected.readByte(), 
file.getName() + " at " + i);
+            }
+          }
+        }
+        try (DirectoryReader reader = DirectoryReader.open(directory)) {
+          IndexSearcher searcher = new IndexSearcher(reader);
+          assertEquals(searcher.count(new TermQuery(new Term("text", 
"even"))), NUM_DOCS / 2);
+          TopDocs nearest = searcher.search(new KnnFloatVectorQuery("vector", 
new float[]{42, 1, -42}, 3), 3);
+          assertEquals(nearest.scoreDocs[0].doc, 42);
+        }
+      }
+    }
+  }
+
+  @Test
+  public void testBufferedFallback()
+      throws IOException {
+    byte[] bytes = new byte[16 * 1024];
+    bytes[0] = 42;
+    long largeSize = 1L + Integer.MAX_VALUE;
+    PinotDataBuffer buffer = mock(PinotDataBuffer.class, CALLS_REAL_METHODS);
+    when(buffer.size()).thenReturn(bytes.length + largeSize);
+    doReturn(buffer).when(buffer).view(0, bytes.length);
+    doReturn(buffer).when(buffer).view(bytes.length, bytes.length + largeSize);
+    when(buffer.toDirectByteBuffer(anyLong(), anyInt(), 
any())).thenAnswer(call -> {
+      int offset = Math.toIntExact(call.<Long>getArgument(0));
+      int size = call.getArgument(1);
+      assertTrue(size < bytes.length, "A buffered read should only copy the 
requested block");
+      return ByteBuffer.wrap(Arrays.copyOfRange(bytes, offset, offset + size));
+    });
+    Map<String, LuceneTextIndexHeader.FileInfo> files = Map.of(
+        "small", new LuceneTextIndexHeader.FileInfo("small", 0, bytes.length),
+        "large", new LuceneTextIndexHeader.FileInfo("large", bytes.length, 
largeSize));
+    try (PinotBufferLuceneDirectory directory = new 
PinotBufferLuceneDirectory(buffer, files, "text");
+        IndexInput small = directory.openInput("small", IOContext.DEFAULT);
+        IndexInput large = directory.openInput("large", IOContext.DEFAULT)) {
+      verify(buffer, never()).toDirectByteBuffer(anyLong(), anyInt(), any());
+      verify(buffer, never()).tryViewAsByteBuffer(eq((long) bytes.length), 
anyInt(), any());
+      assertEquals(small.readByte(), (byte) 42);
+      assertEquals(large.length(), largeSize);
+    }
+  }
+
+  @DataProvider
+  public Object[][] invalidFileRanges() {
+    return new Object[][]{{-1L, 1L}, {0L, -(1L << 32)}, {7L, 2L}, 
{Long.MAX_VALUE, 1L}};
+  }
+
+  @Test(dataProvider = "invalidFileRanges")
+  public void testInvalidFileRange(long offset, long length)
+      throws IOException {
+    Map<String, LuceneTextIndexHeader.FileInfo> files =
+        Map.of("file", new LuceneTextIndexHeader.FileInfo("file", offset, 
length));
+    try (PinotBufferLuceneDirectory directory =
+        new PinotBufferLuceneDirectory(PinotByteBuffer.wrap(new byte[8]), 
files, "text")) {
+      assertThrows(IOException.class, () -> directory.openInput("file", 
IOContext.DEFAULT));
+    }
+  }
+}
diff --git 
a/pinot-segment-spi/src/main/java/org/apache/pinot/segment/spi/memory/NonNativePinotDataBuffer.java
 
b/pinot-segment-spi/src/main/java/org/apache/pinot/segment/spi/memory/NonNativePinotDataBuffer.java
index 3d29cb549ee..0057d75cde7 100644
--- 
a/pinot-segment-spi/src/main/java/org/apache/pinot/segment/spi/memory/NonNativePinotDataBuffer.java
+++ 
b/pinot-segment-spi/src/main/java/org/apache/pinot/segment/spi/memory/NonNativePinotDataBuffer.java
@@ -22,6 +22,7 @@ import java.io.File;
 import java.io.IOException;
 import java.nio.ByteBuffer;
 import java.nio.ByteOrder;
+import javax.annotation.Nullable;
 
 
 public class NonNativePinotDataBuffer extends PinotDataBuffer {
@@ -230,6 +231,12 @@ public class NonNativePinotDataBuffer extends 
PinotDataBuffer {
     _nativeBuffer.readFrom(offset, file, srcOffset, size);
   }
 
+  @Override
+  @Nullable
+  public ByteBuffer tryViewAsByteBuffer(long offset, int size, ByteOrder 
byteOrder) {
+    return _nativeBuffer.tryViewAsByteBuffer(offset, size, byteOrder);
+  }
+
   @Override
   public ByteBuffer toDirectByteBuffer(long offset, int size, ByteOrder 
byteOrder) {
     return _nativeBuffer.toDirectByteBuffer(offset, size, byteOrder);
diff --git 
a/pinot-segment-spi/src/main/java/org/apache/pinot/segment/spi/memory/PinotByteBuffer.java
 
b/pinot-segment-spi/src/main/java/org/apache/pinot/segment/spi/memory/PinotByteBuffer.java
index 53ab8a4bcdd..72a3e880d17 100644
--- 
a/pinot-segment-spi/src/main/java/org/apache/pinot/segment/spi/memory/PinotByteBuffer.java
+++ 
b/pinot-segment-spi/src/main/java/org/apache/pinot/segment/spi/memory/PinotByteBuffer.java
@@ -324,6 +324,11 @@ public class PinotByteBuffer extends PinotDataBuffer {
     return new PinotByteBuffer(buffer, false, false);
   }
 
+  @Override
+  public ByteBuffer tryViewAsByteBuffer(long offset, int size, ByteOrder 
byteOrder) {
+    return toDirectByteBuffer(offset, size, byteOrder);
+  }
+
   @Override
   public ByteBuffer toDirectByteBuffer(long offset, int size, ByteOrder 
byteOrder) {
     assert offset <= Integer.MAX_VALUE;
diff --git 
a/pinot-segment-spi/src/main/java/org/apache/pinot/segment/spi/memory/PinotDataBuffer.java
 
b/pinot-segment-spi/src/main/java/org/apache/pinot/segment/spi/memory/PinotDataBuffer.java
index b929082b965..90ddaff8fc0 100644
--- 
a/pinot-segment-spi/src/main/java/org/apache/pinot/segment/spi/memory/PinotDataBuffer.java
+++ 
b/pinot-segment-spi/src/main/java/org/apache/pinot/segment/spi/memory/PinotDataBuffer.java
@@ -633,6 +633,14 @@ public abstract class PinotDataBuffer implements 
DataBuffer {
   ///                  buffer will be different.
   public abstract ByteBuffer toDirectByteBuffer(long offset, int size, 
ByteOrder byteOrder);
 
+  /// Returns a shared view starting at `offset`, positioned at zero with 
limit `size` and the requested byte order.
+  /// Returns null if the range cannot be exposed without copying or fetching 
data. The caller may retain the view
+  /// until the owning buffer is closed and must not release it.
+  @Nullable
+  public ByteBuffer tryViewAsByteBuffer(long offset, int size, ByteOrder 
byteOrder) {
+    return null;
+  }
+
   /// Returns an ByteBuffer with the same content of this buffer.
   ///
   /// This receiver object and the returned ByteBuffer share the same memory 
address, but the receiver conserves the
diff --git 
a/pinot-segment-spi/src/main/java/org/apache/pinot/segment/spi/memory/unsafe/UnsafePinotBuffer.java
 
b/pinot-segment-spi/src/main/java/org/apache/pinot/segment/spi/memory/unsafe/UnsafePinotBuffer.java
index 2f83cb0b825..73c9cbb8b16 100644
--- 
a/pinot-segment-spi/src/main/java/org/apache/pinot/segment/spi/memory/unsafe/UnsafePinotBuffer.java
+++ 
b/pinot-segment-spi/src/main/java/org/apache/pinot/segment/spi/memory/unsafe/UnsafePinotBuffer.java
@@ -161,6 +161,11 @@ public class UnsafePinotBuffer extends PinotDataBuffer {
     }
   }
 
+  @Override
+  public ByteBuffer tryViewAsByteBuffer(long offset, int size, ByteOrder 
byteOrder) {
+    return toDirectByteBuffer(offset, size, byteOrder);
+  }
+
   @Override
   public ByteBuffer toDirectByteBuffer(long offset, int size, ByteOrder 
byteOrder) {
     checkOffset(offset, size);


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

Reply via email to