This is an automated email from the ASF dual-hosted git repository.
gortiz 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 df69b9f824f Add a Foreign Function & Memory (Panama) based
PinotDataBuffer implementation (#19021)
df69b9f824f is described below
commit df69b9f824f84d7c7f318cade3aedc5ec4e8fbb2
Author: Gonzalo Ortiz Jaureguizar <[email protected]>
AuthorDate: Wed Nov 25 17:55:46 2026 +0100
Add a Foreign Function & Memory (Panama) based PinotDataBuffer
implementation (#19021)
* Add java.lang.foreign (Panama) PinotDataBuffer implementation
Add an opt-in off-heap buffer implementation backed by the Foreign
Function & Memory API (MemorySegment/Arena) in a new Java 25 module
pinot-segment-spi-foreign, as an alternative to the sun.misc.Unsafe
based buffer. It is selected via the pinot.offheap.buffer.factory
config or the PINOT_BUFFER_LIBRARY environment variable; the default
(Unsafe wrapped in SmallWithFallback) is unchanged.
The code lives in a separate module so that pinot-segment-spi can stay
Java 11 bytecode for the JDBC/Java driver dependency closure
(pinot-jdbc-client -> pinot-java-client -> pinot-common ->
pinot-segment-spi), while the FFM code (which requires Java 21+) is
compiled at Java 25.
Also extend pinot-perf: BenchmarkPinotDataBuffer gains foreign options
and BenchmarkQueriesSSQE gains an opt-in _bufferLibrary parameter to
compare backends end-to-end.
* Address review: rename module to pinot-foreign-buffers, add Cleaner leak
safety net
- Rename module pinot-segment-spi-foreign -> pinot-foreign-buffers and move
the
classes to package org.apache.pinot.segment.memory.foreign, dropping the
misleading "spi" from what is an implementation module.
- Register a java.lang.ref.Cleaner that closes the shared Arena (and logs a
WARN)
if a ForeignPinotBuffer is garbage collected without being closed. This
restores
the leak safety net the Unsafe path provided via finalize(), using the
modern,
non-deprecated mechanism. Explicit close() runs the cleanup eagerly and
de-registers it, so no false warning is emitted on normal close.
* Bump pinot-foreign-buffers parent to 1.7.0-SNAPSHOT
The merge of master moved the root pom to 1.7.0-SNAPSHOT. The new module
still
pointed at the 1.6.0-SNAPSHOT parent, so the reactor could not resolve it.
* Keep the owning ForeignPinotBuffer reachable from its views
ForeignPinotBuffer.view() created a non-owning buffer over a slice of the
segment, with no reference to the owning buffer. If the owner was leaked
(never
closed) and collected while a view was still in use, the Cleaner closed the
shared Arena and the next read through the view threw IllegalStateException.
The Unsafe and ByteBuffer implementations keep the backing memory alive
while a
view is reachable.
A view now holds a reference to the owning buffer (for a view of a view, the
original owner), so the Cleaner of a leaked owner runs only after all its
views
are unreachable. toDirectByteBuffer is unchanged: the PinotDataBuffer
contract
already forbids using its result after the buffer is released.
Add tests for the leak safety net itself and for views (native order,
non-native order and a view of a view) of a leaked owner.
* Fix the ForeignPinotBuffer close semantics in its Javadoc
The class Javadoc said that release() blocks until in-flight accesses
complete. On JDK 25 SharedSession.justClose() never waits: it throws
when an I/O operation still holds a ByteBuffer from toDirectByteBuffer,
and otherwise closes at once, so a concurrent access fails with
IllegalStateException.
---------
Co-authored-by: Gonzalo Ortiz <[email protected]>
---
pinot-bom/pom.xml | 11 +
pinot-foreign-buffers/pom.xml | 67 ++++++
.../segment/memory/foreign/ForeignPinotBuffer.java | 263 +++++++++++++++++++++
.../memory/foreign/ForeignPinotBufferFactory.java | 92 +++++++
.../foreign/ForeignMemoryPinotDataBufferTest.java | 188 +++++++++++++++
pinot-perf/pom.xml | 4 +
.../pinot/perf/BenchmarkPinotDataBuffer.java | 19 +-
.../apache/pinot/perf/BenchmarkQueriesSSQE.java | 50 +++-
pinot-segment-local/pom.xml | 6 +
pom.xml | 1 +
10 files changed, 698 insertions(+), 3 deletions(-)
diff --git a/pinot-bom/pom.xml b/pinot-bom/pom.xml
index 04c5979623e..8051da3a1b8 100644
--- a/pinot-bom/pom.xml
+++ b/pinot-bom/pom.xml
@@ -139,6 +139,11 @@
<artifactId>pinot-segment-spi</artifactId>
<version>${project.version}</version>
</dependency>
+ <dependency>
+ <groupId>org.apache.pinot</groupId>
+ <artifactId>pinot-foreign-buffers</artifactId>
+ <version>${project.version}</version>
+ </dependency>
<dependency>
<groupId>org.apache.pinot</groupId>
<artifactId>pinot-common</artifactId>
@@ -446,6 +451,12 @@
<version>${project.version}</version>
<type>test-jar</type>
</dependency>
+ <dependency>
+ <groupId>org.apache.pinot</groupId>
+ <artifactId>pinot-segment-spi</artifactId>
+ <version>${project.version}</version>
+ <type>test-jar</type>
+ </dependency>
<dependency>
<groupId>org.apache.pinot</groupId>
<artifactId>pinot-common</artifactId>
diff --git a/pinot-foreign-buffers/pom.xml b/pinot-foreign-buffers/pom.xml
new file mode 100644
index 00000000000..a1bf2a303fc
--- /dev/null
+++ b/pinot-foreign-buffers/pom.xml
@@ -0,0 +1,67 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+
+ 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.
+
+-->
+<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
http://maven.apache.org/xsd/maven-4.0.0.xsd">
+ <modelVersion>4.0.0</modelVersion>
+ <parent>
+ <artifactId>pinot</artifactId>
+ <groupId>org.apache.pinot</groupId>
+ <version>1.7.0-SNAPSHOT</version>
+ </parent>
+ <artifactId>pinot-foreign-buffers</artifactId>
+ <name>Pinot Foreign (Panama) Buffers</name>
+ <url>https://pinot.apache.org/</url>
+ <properties>
+ <pinot.root>${basedir}/..</pinot.root>
+ </properties>
+
+ <!--
+ This module provides a java.lang.foreign (Panama FFM) based
PinotDataBuffer implementation. It is kept separate
+ from pinot-segment-spi (which is pinned to Java 11 bytecode for
driver/client consumers) because the Foreign
+ Function & Memory API requires Java 21+. It therefore inherits the
project-wide Java 25 release level and must not
+ be depended on by any Java 11 artifact. The factory is selected at runtime
by class name via the
+ pinot.offheap.buffer.factory config or the PINOT_BUFFER_LIBRARY
environment variable.
+ -->
+
+ <dependencies>
+ <dependency>
+ <groupId>org.apache.pinot</groupId>
+ <artifactId>pinot-segment-spi</artifactId>
+ </dependency>
+
+ <dependency>
+ <groupId>org.apache.pinot</groupId>
+ <artifactId>pinot-segment-spi</artifactId>
+ <type>test-jar</type>
+ <scope>test</scope>
+ </dependency>
+ <dependency>
+ <groupId>commons-io</groupId>
+ <artifactId>commons-io</artifactId>
+ <scope>test</scope>
+ </dependency>
+ <dependency>
+ <groupId>org.testng</groupId>
+ <artifactId>testng</artifactId>
+ <scope>test</scope>
+ </dependency>
+ </dependencies>
+</project>
diff --git
a/pinot-foreign-buffers/src/main/java/org/apache/pinot/segment/memory/foreign/ForeignPinotBuffer.java
b/pinot-foreign-buffers/src/main/java/org/apache/pinot/segment/memory/foreign/ForeignPinotBuffer.java
new file mode 100644
index 00000000000..0b3856a32e0
--- /dev/null
+++
b/pinot-foreign-buffers/src/main/java/org/apache/pinot/segment/memory/foreign/ForeignPinotBuffer.java
@@ -0,0 +1,263 @@
+/**
+ * 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.memory.foreign;
+
+import java.lang.foreign.Arena;
+import java.lang.foreign.MemorySegment;
+import java.lang.foreign.ValueLayout;
+import java.lang.ref.Cleaner;
+import java.nio.ByteBuffer;
+import java.nio.ByteOrder;
+import javax.annotation.Nullable;
+import org.apache.pinot.segment.spi.memory.NonNativePinotDataBuffer;
+import org.apache.pinot.segment.spi.memory.PinotDataBuffer;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+
+/// A [PinotDataBuffer] backed by the Foreign Function & Memory API
([MemorySegment]).
+///
+/// This is the Java 21+ replacement for the `sun.misc.Unsafe` based buffer.
Like the Unsafe implementation it only
+/// reads and writes in [native byte order][ByteOrder#nativeOrder()];
non-native order is provided by wrapping it in a
+/// [NonNativePinotDataBuffer]. Because [MemorySegment] natively supports
`long` indexing, a single implementation
+/// covers buffers larger than [Integer#MAX_VALUE] without any of the manual
pointer arithmetic, page alignment or
+/// reflective `DirectByteBuffer` construction the Unsafe path required.
+///
+/// All accessors use the `*_UNALIGNED` [ValueLayout] constants because
callers read and write at arbitrary byte
+/// offsets. Bounds checking is performed by [MemorySegment] itself (throwing
[IndexOutOfBoundsException]), so this
+/// class does not add its own checks. Access is memory-safe: reads and writes
after the backing [Arena] is closed fail
+/// deterministically instead of corrupting memory.
+///
+/// Thread-safety: instances created through [ForeignPinotBufferFactory] use a
[shared arena][Arena#ofShared()], so the
+/// buffer may be read, written and closed from any thread. As with every
[PinotDataBuffer], closing a buffer while
+/// another thread accesses it is a caller error. Closing does not wait for
other threads, and it stays memory-safe:
+/// a concurrent read or write on this buffer or its views fails with
[IllegalStateException]. If an I/O operation
+/// still uses a [ByteBuffer] from [#toDirectByteBuffer(long, int,
ByteOrder)], [#release()] throws
+/// [IllegalStateException] and the memory stays allocated. The inherited
synchronized [#close()] serialises
+/// concurrent close calls on the same instance.
+public class ForeignPinotBuffer extends PinotDataBuffer {
+
+ private static final Logger LOGGER =
LoggerFactory.getLogger(ForeignPinotBuffer.class);
+ /// Leak safety net for owning buffers. A shared [Arena] is not GC-managed
(unlike [Arena#ofAuto()]), so if a buffer
+ /// is never closed the native memory would leak. This cleaner closes the
arena on collection, mirroring the
+ /// `finalize()` safety net the `Unsafe` implementation used (but without
the deprecated finalizer).
+ private static final Cleaner CLEANER = Cleaner.create();
+
+ // Native-order, byte-aligned (alignment == 1) layouts. Single-byte access
is always aligned.
+ private static final ValueLayout.OfByte BYTE = ValueLayout.JAVA_BYTE;
+ private static final ValueLayout.OfChar CHAR =
ValueLayout.JAVA_CHAR_UNALIGNED;
+ private static final ValueLayout.OfShort SHORT =
ValueLayout.JAVA_SHORT_UNALIGNED;
+ private static final ValueLayout.OfInt INT = ValueLayout.JAVA_INT_UNALIGNED;
+ private static final ValueLayout.OfLong LONG =
ValueLayout.JAVA_LONG_UNALIGNED;
+ private static final ValueLayout.OfFloat FLOAT =
ValueLayout.JAVA_FLOAT_UNALIGNED;
+ private static final ValueLayout.OfDouble DOUBLE =
ValueLayout.JAVA_DOUBLE_UNALIGNED;
+
+ private final MemorySegment _segment;
+ /// The cleanup action registered with the [Cleaner] for owning buffers, or
{@code null} for a non-owning view.
+ @Nullable
+ private final ArenaCleanup _cleanup;
+ /// The handle to the registered cleaning action, used to free eagerly (and
de-register) on explicit close.
+ @Nullable
+ private final Cleaner.Cleanable _cleanable;
+ /// For a view, the owning buffer whose arena backs this view, or {@code
null} for an owning buffer. The field is
+ /// never read. It keeps the owner reachable while the view is reachable, so
the leak safety net of a leaked owner
+ /// cannot close the arena under a view that is still in use. The `Unsafe`
and `ByteBuffer` implementations give
+ /// their views the same guarantee.
+ @SuppressWarnings({"unused", "FieldCanBeLocal"})
+ @Nullable
+ private final ForeignPinotBuffer _owner;
+
+ /// Creates a buffer over the given segment.
+ ///
+ /// @param segment the memory segment this buffer reads and writes. Its
[MemorySegment#byteSize()] is the buffer size.
+ /// @param arena the arena to close when this buffer is released, or {@code
null} for a non-owning view.
+ public ForeignPinotBuffer(MemorySegment segment, @Nullable Arena arena) {
+ this(segment, arena, null);
+ }
+
+ private ForeignPinotBuffer(MemorySegment segment, @Nullable Arena arena,
@Nullable ForeignPinotBuffer owner) {
+ super(arena != null);
+ _segment = segment;
+ _owner = owner;
+ if (arena != null) {
+ _cleanup = new ArenaCleanup(arena, segment.byteSize());
+ // The registered action (ArenaCleanup) must not reference this buffer,
otherwise it would never be collected.
+ _cleanable = CLEANER.register(this, _cleanup);
+ } else {
+ _cleanup = null;
+ _cleanable = null;
+ }
+ }
+
+ @Override
+ public byte getByte(long offset) {
+ return _segment.get(BYTE, offset);
+ }
+
+ @Override
+ public void putByte(long offset, byte value) {
+ _segment.set(BYTE, offset, value);
+ }
+
+ @Override
+ public char getChar(long offset) {
+ return _segment.get(CHAR, offset);
+ }
+
+ @Override
+ public void putChar(long offset, char value) {
+ _segment.set(CHAR, offset, value);
+ }
+
+ @Override
+ public short getShort(long offset) {
+ return _segment.get(SHORT, offset);
+ }
+
+ @Override
+ public void putShort(long offset, short value) {
+ _segment.set(SHORT, offset, value);
+ }
+
+ @Override
+ public int getInt(long offset) {
+ return _segment.get(INT, offset);
+ }
+
+ @Override
+ public void putInt(long offset, int value) {
+ _segment.set(INT, offset, value);
+ }
+
+ @Override
+ public long getLong(long offset) {
+ return _segment.get(LONG, offset);
+ }
+
+ @Override
+ public void putLong(long offset, long value) {
+ _segment.set(LONG, offset, value);
+ }
+
+ @Override
+ public float getFloat(long offset) {
+ return _segment.get(FLOAT, offset);
+ }
+
+ @Override
+ public void putFloat(long offset, float value) {
+ _segment.set(FLOAT, offset, value);
+ }
+
+ @Override
+ public double getDouble(long offset) {
+ return _segment.get(DOUBLE, offset);
+ }
+
+ @Override
+ public void putDouble(long offset, double value) {
+ _segment.set(DOUBLE, offset, value);
+ }
+
+ @Override
+ public void copyTo(long offset, byte[] buffer, int destOffset, int size) {
+ // Direct segment-to-array copy: a bounds-checked, JIT-intrinsified memcpy
with no intermediate ByteBuffer.
+ MemorySegment.copy(_segment, BYTE, offset, buffer, destOffset, size);
+ }
+
+ @Override
+ public void readFrom(long offset, byte[] buffer, int srcOffset, int size) {
+ // Direct array-to-segment copy: a bounds-checked, JIT-intrinsified memcpy
with no intermediate ByteBuffer.
+ MemorySegment.copy(buffer, srcOffset, _segment, BYTE, offset, size);
+ }
+
+ @Override
+ public long size() {
+ return _segment.byteSize();
+ }
+
+ @Override
+ public ByteOrder order() {
+ return ByteOrder.nativeOrder();
+ }
+
+ @Override
+ public PinotDataBuffer view(long start, long end, ByteOrder byteOrder) {
+ // asSlice validates start/size against the segment bounds. The view
references the owning buffer (for a view of a
+ // view, the original owner) so the owner stays reachable while the view
is reachable.
+ ForeignPinotBuffer owner = _cleanable != null ? this : _owner;
+ ForeignPinotBuffer nativeView = new
ForeignPinotBuffer(_segment.asSlice(start, end - start), null, owner);
+ if (byteOrder == ByteOrder.nativeOrder()) {
+ return nativeView;
+ } else {
+ return new NonNativePinotDataBuffer(nativeView);
+ }
+ }
+
+ @Override
+ public ByteBuffer toDirectByteBuffer(long offset, int size, ByteOrder
byteOrder) {
+ // The returned ByteBuffer is a borrowed view over the same native memory
and must not be freed by the caller.
+ // It stays valid for as long as the backing arena is alive.
+ return _segment.asSlice(offset, size).asByteBuffer().order(byteOrder);
+ }
+
+ @Override
+ public void flush() {
+ // force() is only valid on a writable mapped segment; it is a no-op for
anonymous (allocated) memory.
+ if (_segment.isMapped() && !_segment.isReadOnly()) {
+ _segment.force();
+ }
+ }
+
+ @Override
+ public void release() {
+ if (_cleanable != null) {
+ // Explicit close: mark it so the cleaner does not emit a leak warning,
then run the cleanup exactly once
+ // (Cleanable.clean() also de-registers, so it will not run again on GC).
+ _cleanup._closedExplicitly = true;
+ _cleanable.clean();
+ }
+ }
+
+ /// The action registered with the [Cleaner] that frees the native memory of
an owning buffer. It is a static nested
+ /// class so it holds no implicit reference to the enclosing
[ForeignPinotBuffer] (which would keep the buffer
+ /// reachable and defeat the cleaner). It closes the [Arena] on collection,
warning if the buffer was leaked
+ /// (collected without an explicit close).
+ private static final class ArenaCleanup implements Runnable {
+ private final Arena _arena;
+ private final long _size;
+ // Only gates the leak warning (not the freeing, which Cleanable.clean()
makes exactly-once). It is set and read on
+ // the same thread on the explicit-close path; volatile is defensive
belt-and-braces, not required for correctness.
+ private volatile boolean _closedExplicitly;
+
+ ArenaCleanup(Arena arena, long size) {
+ _arena = arena;
+ _size = size;
+ }
+
+ @Override
+ public void run() {
+ if (!_closedExplicitly) {
+ LOGGER.warn("A ForeignPinotBuffer of {} bytes was garbage collected
without being closed; freeing it now. "
+ + "This is a buffer leak that should be fixed.", _size);
+ }
+ _arena.close();
+ }
+ }
+}
diff --git
a/pinot-foreign-buffers/src/main/java/org/apache/pinot/segment/memory/foreign/ForeignPinotBufferFactory.java
b/pinot-foreign-buffers/src/main/java/org/apache/pinot/segment/memory/foreign/ForeignPinotBufferFactory.java
new file mode 100644
index 00000000000..5e205d6f24a
--- /dev/null
+++
b/pinot-foreign-buffers/src/main/java/org/apache/pinot/segment/memory/foreign/ForeignPinotBufferFactory.java
@@ -0,0 +1,92 @@
+/**
+ * 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.memory.foreign;
+
+import java.io.File;
+import java.io.IOException;
+import java.lang.foreign.Arena;
+import java.lang.foreign.MemorySegment;
+import java.nio.ByteOrder;
+import java.nio.channels.FileChannel;
+import java.nio.file.StandardOpenOption;
+import org.apache.pinot.segment.spi.memory.NonNativePinotDataBuffer;
+import org.apache.pinot.segment.spi.memory.PinotBufferFactory;
+import org.apache.pinot.segment.spi.memory.PinotDataBuffer;
+
+
+/// A [PinotBufferFactory] that creates buffers backed by the Foreign Function
& Memory API.
+///
+/// This is the Java 21+ alternative to
+/// [org.apache.pinot.segment.spi.memory.unsafe.UnsafePinotBufferFactory]. It
produces [ForeignPinotBuffer] instances
+/// backed by a [MemorySegment]. Every buffer owns a dedicated [shared
arena][Arena#ofShared()] so that the buffer can
+/// be accessed and closed from any thread; closing the buffer closes the
arena, which frees the native memory or
+/// unmaps the file.
+///
+/// Unlike the Unsafe factory this works on every operating system (including
Windows), needs no reflection, and maps
+/// files larger than [Integer#MAX_VALUE] directly through
[FileChannel#map(FileChannel.MapMode, long, long, Arena)].
+///
+/// To select this factory set the `pinot.offheap.buffer.factory`
configuration (or the `PINOT_BUFFER_LIBRARY`
+/// environment variable) to this class' fully qualified name.
+public class ForeignPinotBufferFactory implements PinotBufferFactory {
+
+ @Override
+ public PinotDataBuffer allocateDirect(long size, ByteOrder byteOrder) {
+ Arena arena = Arena.ofShared();
+ try {
+ MemorySegment segment = arena.allocate(size);
+ return wrap(new ForeignPinotBuffer(segment, arena), byteOrder);
+ } catch (RuntimeException | Error e) {
+ arena.close();
+ throw e;
+ }
+ }
+
+ @Override
+ public PinotDataBuffer mapFile(File file, boolean readOnly, long offset,
long size, ByteOrder byteOrder)
+ throws IOException {
+ FileChannel.MapMode mapMode = readOnly ? FileChannel.MapMode.READ_ONLY :
FileChannel.MapMode.READ_WRITE;
+ // The channel can be closed right after mapping; the mapping outlives it
(as with MappedByteBuffer). The mapping
+ // itself is kept alive by the arena and released when the arena is closed.
+ Arena arena = Arena.ofShared();
+ try (FileChannel channel = openChannel(file, readOnly)) {
+ MemorySegment segment = channel.map(mapMode, offset, size, arena);
+ return wrap(new ForeignPinotBuffer(segment, arena), byteOrder);
+ } catch (RuntimeException | Error | IOException e) {
+ arena.close();
+ throw e;
+ }
+ }
+
+ private static FileChannel openChannel(File file, boolean readOnly)
+ throws IOException {
+ if (readOnly) {
+ return FileChannel.open(file.toPath(), StandardOpenOption.READ);
+ }
+ return FileChannel.open(file.toPath(), StandardOpenOption.READ,
StandardOpenOption.WRITE,
+ StandardOpenOption.CREATE);
+ }
+
+ private static PinotDataBuffer wrap(ForeignPinotBuffer buffer, ByteOrder
byteOrder) {
+ if (byteOrder == ByteOrder.nativeOrder()) {
+ return buffer;
+ } else {
+ return new NonNativePinotDataBuffer(buffer);
+ }
+ }
+}
diff --git
a/pinot-foreign-buffers/src/test/java/org/apache/pinot/segment/memory/foreign/ForeignMemoryPinotDataBufferTest.java
b/pinot-foreign-buffers/src/test/java/org/apache/pinot/segment/memory/foreign/ForeignMemoryPinotDataBufferTest.java
new file mode 100644
index 00000000000..76c40ba9d30
--- /dev/null
+++
b/pinot-foreign-buffers/src/test/java/org/apache/pinot/segment/memory/foreign/ForeignMemoryPinotDataBufferTest.java
@@ -0,0 +1,188 @@
+/**
+ * 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.memory.foreign;
+
+import java.io.RandomAccessFile;
+import java.lang.ref.WeakReference;
+import java.nio.ByteBuffer;
+import java.nio.ByteOrder;
+import org.apache.commons.io.FileUtils;
+import org.apache.pinot.segment.spi.memory.PinotDataBuffer;
+import org.apache.pinot.segment.spi.memory.PinotDataBufferTest;
+import org.testng.Assert;
+import org.testng.annotations.Test;
+
+
+public class ForeignMemoryPinotDataBufferTest extends PinotDataBufferTest {
+ public ForeignMemoryPinotDataBufferTest() {
+ super(new ForeignPinotBufferFactory());
+ }
+
+ @Override
+ protected boolean prioritizeByteBuffer() {
+ return false;
+ }
+
+ /// Verifies that {@link PinotDataBuffer#toDirectByteBuffer} returns a
zero-copy, live view over the same native
+ /// memory (not a copy). This is what lets consumers such as RoaringBitmap
read a buffer region in place (e.g. via
+ /// {@link PinotDataBuffer#viewAsRoaringBitmap}) without materialising a
copy on the query path. The check writes
+ /// through the buffer AFTER the view is obtained and asserts the change is
visible through the view, and vice versa.
+ @Test
+ public void testToDirectByteBufferIsZeroCopyView()
+ throws Exception {
+ try (PinotDataBuffer buffer = _factory.allocateDirect(BUFFER_SIZE,
PinotDataBuffer.NATIVE_ORDER)) {
+ ByteBuffer view = buffer.toDirectByteBuffer(0, BUFFER_SIZE);
+ Assert.assertTrue(view.isDirect(), "view must be a direct ByteBuffer
over native memory");
+ Assert.assertEquals(view.capacity(), BUFFER_SIZE);
+ // Write through the buffer after the view exists -> must be visible
through the view (proves it is not a copy).
+ buffer.putInt(0, 0x0A0B0C0D);
+ Assert.assertEquals(view.getInt(0), 0x0A0B0C0D);
+ // Write through the view -> must be visible through the buffer.
+ view.putInt(Integer.BYTES, 0x01020304);
+ Assert.assertEquals(buffer.getInt(Integer.BYTES), 0x01020304);
+ }
+ }
+
+ /// Verifies the headline memory-safety guarantee: reading or writing after
the backing arena is closed fails
+ /// deterministically with {@link IllegalStateException} instead of
corrupting memory (as the {@code Unsafe}
+ /// implementation would).
+ @Test
+ public void testUseAfterCloseFailsDeterministically() {
+ PinotDataBuffer buffer = _factory.allocateDirect(BUFFER_SIZE,
PinotDataBuffer.NATIVE_ORDER);
+ buffer.putInt(0, 42);
+ Assert.assertEquals(buffer.getInt(0), 42);
+ try {
+ buffer.close();
+ } catch (Exception e) {
+ throw new AssertionError("close() should not throw", e);
+ }
+ Assert.assertThrows(IllegalStateException.class, () -> buffer.getInt(0));
+ Assert.assertThrows(IllegalStateException.class, () -> buffer.putInt(0,
7));
+ }
+
+ /// Verifies that {@code long} offset addressing is correct beyond {@link
Integer#MAX_VALUE}. A narrowing bug in the
+ /// offset arithmetic would silently read/write the wrong location; this
writes distinct values at offsets below, on
+ /// and above the 2^31 boundary and reads them back.
+ @Test
+ public void testLargeOffsetAddressing()
+ throws Exception {
+ // A few bytes beyond Integer.MAX_VALUE so that an 8-byte long can be
addressed strictly above the int range.
+ // Offsets are chosen so that the four written regions do not overlap.
+ long size = Integer.MAX_VALUE + 32L;
+ long lowOffset = 0; // bytes [0, 8)
+ long straddlingOffset = Integer.MAX_VALUE - 3L; // bytes span the 2^31
boundary: [MAX-3, MAX+5)
+ long highOffset = Integer.MAX_VALUE + 8L; // fully above the int
range: [MAX+8, MAX+16)
+ long lastByteOffset = size - 1; // last addressable byte
+
+ try (PinotDataBuffer buffer = _factory.allocateDirect(size,
PinotDataBuffer.NATIVE_ORDER)) {
+ Assert.assertEquals(buffer.size(), size);
+ buffer.putLong(lowOffset, 0x0102030405060708L);
+ buffer.putLong(straddlingOffset, 0x1112131415161718L);
+ buffer.putLong(highOffset, 0x2122232425262728L);
+ buffer.putByte(lastByteOffset, (byte) 0x5A);
+
+ Assert.assertEquals(buffer.getLong(lowOffset), 0x0102030405060708L);
+ Assert.assertEquals(buffer.getLong(straddlingOffset),
0x1112131415161718L);
+ Assert.assertEquals(buffer.getLong(highOffset), 0x2122232425262728L);
+ Assert.assertEquals(buffer.getByte(lastByteOffset), (byte) 0x5A);
+ }
+ }
+
+ /// Verifies that writing to a read-only memory-mapped buffer throws {@link
IllegalArgumentException}. This is an
+ /// intentional improvement over the {@code Unsafe} implementation, where
writing to a {@code PROT_READ} mapping is a
+ /// native SIGSEGV that crashes the JVM.
+ @Test
+ public void testReadOnlyMappedWriteThrows()
+ throws Exception {
+ try (RandomAccessFile randomAccessFile = new RandomAccessFile(TEMP_FILE,
"rw")) {
+ randomAccessFile.setLength(FILE_OFFSET + BUFFER_SIZE);
+ try (PinotDataBuffer buffer =
+ _factory.mapFile(TEMP_FILE, true, FILE_OFFSET, BUFFER_SIZE,
PinotDataBuffer.NATIVE_ORDER)) {
+ Assert.assertThrows(IllegalArgumentException.class, () ->
buffer.putInt(0, 1));
+ }
+ } finally {
+ FileUtils.forceDelete(TEMP_FILE);
+ }
+ }
+
+ /// Verifies the leak safety net: an owning buffer that is never closed has
its arena closed once the buffer is
+ /// garbage collected. The probe is a [ByteBuffer] from
[PinotDataBuffer#toDirectByteBuffer], which does not keep
+ /// the owner reachable, so it fails with [IllegalStateException] once the
arena is closed.
+ @Test
+ public void testLeakedBufferIsFreedOnCollection()
+ throws InterruptedException {
+ PinotDataBuffer buffer = _factory.allocateDirect(BUFFER_SIZE,
PinotDataBuffer.NATIVE_ORDER);
+ ByteBuffer probe = buffer.toDirectByteBuffer(0, Long.BYTES);
+ WeakReference<PinotDataBuffer> ownerRef = new WeakReference<>(buffer);
+ buffer = null;
+
+ long deadline = System.currentTimeMillis() + 10_000;
+ boolean freed = false;
+ while (!freed && System.currentTimeMillis() < deadline) {
+ System.gc();
+ Thread.sleep(10);
+ try {
+ probe.getLong(0);
+ } catch (IllegalStateException e) {
+ freed = true;
+ }
+ }
+ Assert.assertNull(ownerRef.get(), "the leaked buffer must be collected");
+ Assert.assertTrue(freed, "the arena of a leaked buffer must be closed
after the buffer is collected");
+ }
+
+ /// Verifies that a view keeps its owning buffer reachable, as the `Unsafe`
and `ByteBuffer` implementations do. If
+ /// the owner is leaked (never closed) while a view is still in use, the
leak safety net must not close the arena
+ /// under the view. This covers native and non-native order views and a view
of a view.
+ @Test
+ public void testViewKeepsLeakedOwnerAlive()
+ throws Exception {
+ PinotDataBuffer owner = _factory.allocateDirect(BUFFER_SIZE,
PinotDataBuffer.NATIVE_ORDER);
+ owner.putLong(0, 0x1122334455667788L);
+ ByteOrder nonNativeOrder =
+ PinotDataBuffer.NATIVE_ORDER == ByteOrder.BIG_ENDIAN ?
ByteOrder.LITTLE_ENDIAN : ByteOrder.BIG_ENDIAN;
+ PinotDataBuffer nativeView = owner.view(0, Long.BYTES,
PinotDataBuffer.NATIVE_ORDER);
+ PinotDataBuffer nonNativeView = owner.view(0, Long.BYTES, nonNativeOrder);
+ WeakReference<PinotDataBuffer> ownerRef = new WeakReference<>(owner);
+ owner = null;
+
+ forceGc();
+ Assert.assertNotNull(ownerRef.get(), "a reachable view must keep its owner
reachable");
+ Assert.assertEquals(nativeView.getLong(0), 0x1122334455667788L);
+ Assert.assertEquals(nonNativeView.getLong(0),
Long.reverseBytes(0x1122334455667788L));
+
+ // A view of a view must keep the original owner reachable too.
+ PinotDataBuffer nestedView = nativeView.view(0, Long.BYTES,
PinotDataBuffer.NATIVE_ORDER);
+ nativeView = null;
+ nonNativeView = null;
+ forceGc();
+ Assert.assertNotNull(ownerRef.get(), "a view of a view must keep the
original owner reachable");
+ Assert.assertEquals(nestedView.getLong(0), 0x1122334455667788L);
+
+ ownerRef.get().close();
+ }
+
+ private static void forceGc()
+ throws InterruptedException {
+ for (int i = 0; i < 5; i++) {
+ System.gc();
+ Thread.sleep(20);
+ }
+ }
+}
diff --git a/pinot-perf/pom.xml b/pinot-perf/pom.xml
index 9d2f1002a8f..1829570966c 100644
--- a/pinot-perf/pom.xml
+++ b/pinot-perf/pom.xml
@@ -45,6 +45,10 @@
<groupId>org.apache.pinot</groupId>
<artifactId>pinot-segment-local</artifactId>
</dependency>
+ <dependency>
+ <groupId>org.apache.pinot</groupId>
+ <artifactId>pinot-foreign-buffers</artifactId>
+ </dependency>
<dependency>
<groupId>org.apache.pinot</groupId>
<artifactId>pinot-server</artifactId>
diff --git
a/pinot-perf/src/main/java/org/apache/pinot/perf/BenchmarkPinotDataBuffer.java
b/pinot-perf/src/main/java/org/apache/pinot/perf/BenchmarkPinotDataBuffer.java
index 9d01e92a1ea..98ca37c3856 100644
---
a/pinot-perf/src/main/java/org/apache/pinot/perf/BenchmarkPinotDataBuffer.java
+++
b/pinot-perf/src/main/java/org/apache/pinot/perf/BenchmarkPinotDataBuffer.java
@@ -22,6 +22,7 @@ import java.io.IOException;
import java.nio.ByteOrder;
import java.util.Random;
import java.util.concurrent.TimeUnit;
+import org.apache.pinot.segment.memory.foreign.ForeignPinotBufferFactory;
import org.apache.pinot.segment.spi.memory.ByteBufferPinotBufferFactory;
import org.apache.pinot.segment.spi.memory.PinotDataBuffer;
import org.apache.pinot.segment.spi.memory.SmallWithFallbackPinotBufferFactory;
@@ -49,9 +50,16 @@ import org.openjdk.jmh.runner.options.OptionsBuilder;
@OutputTimeUnit(TimeUnit.NANOSECONDS)
@Warmup(iterations = 3, time = 1)
@Measurement(iterations = 3, time = 1)
+// Mirror the --add-opens that the production launcher
(appAssemblerScriptTemplate) and surefire pass on JDK 11+. The
+// Unsafe/Chronicle mmap path (sun.nio.ch) and Netty's zero-copy path require
them; without them the "unsafe" factory
+// fails in the forked JVM.
@Fork(value = 1, jvmArgsPrepend = {
"--add-opens=java.base/java.nio=ALL-UNNAMED",
- "--add-opens=java.base/sun.nio.ch=ALL-UNNAMED"
+ "--add-opens=java.base/sun.nio.ch=ALL-UNNAMED",
+ "--add-opens=java.base/java.lang=ALL-UNNAMED",
+ "--add-opens=java.base/java.util=ALL-UNNAMED",
+ "--add-opens=java.base/java.lang.reflect=ALL-UNNAMED",
+ "--add-opens=java.base/jdk.internal.misc=ALL-UNNAMED"
})
@State(Scope.Benchmark)
public class BenchmarkPinotDataBuffer {
@@ -60,7 +68,7 @@ public class BenchmarkPinotDataBuffer {
@Param({"1", "32", "1024"})
private int _valueLength;
- @Param({"bytebuffer", "unsafe", "wrapper+unsafe"})
+ @Param({"bytebuffer", "unsafe", "wrapper+unsafe", "foreign",
"wrapper+foreign"})
private String _bufferLibrary;
private byte[] _bytes;
private PinotDataBuffer _buffer;
@@ -102,6 +110,13 @@ public class BenchmarkPinotDataBuffer {
PinotDataBuffer.useFactory(new SmallWithFallbackPinotBufferFactory(
new ByteBufferPinotBufferFactory(), new
UnsafePinotBufferFactory()));
break;
+ case "foreign":
+ PinotDataBuffer.useFactory(new ForeignPinotBufferFactory());
+ break;
+ case "wrapper+foreign":
+ PinotDataBuffer.useFactory(new SmallWithFallbackPinotBufferFactory(
+ new ByteBufferPinotBufferFactory(), new
ForeignPinotBufferFactory()));
+ break;
default:
throw new IllegalArgumentException("Unrecognized buffer library \"" +
_bufferLibrary + "\"");
}
diff --git
a/pinot-perf/src/main/java/org/apache/pinot/perf/BenchmarkQueriesSSQE.java
b/pinot-perf/src/main/java/org/apache/pinot/perf/BenchmarkQueriesSSQE.java
index 1eee683cf7f..7834dff51cd 100644
--- a/pinot-perf/src/main/java/org/apache/pinot/perf/BenchmarkQueriesSSQE.java
+++ b/pinot-perf/src/main/java/org/apache/pinot/perf/BenchmarkQueriesSSQE.java
@@ -36,6 +36,7 @@ import org.apache.pinot.segment.spi.AggregationFunctionType;
import org.apache.pinot.segment.spi.IndexSegment;
import org.apache.pinot.segment.spi.creator.SegmentGeneratorConfig;
import
org.apache.pinot.segment.spi.index.startree.AggregationFunctionColumnPair;
+import org.apache.pinot.segment.spi.memory.PinotDataBuffer;
import org.apache.pinot.spi.config.table.FieldConfig;
import org.apache.pinot.spi.config.table.StarTreeIndexConfig;
import org.apache.pinot.spi.config.table.TableConfig;
@@ -44,6 +45,8 @@ import org.apache.pinot.spi.data.FieldSpec;
import org.apache.pinot.spi.data.Schema;
import org.apache.pinot.spi.data.readers.GenericRow;
import org.apache.pinot.spi.data.readers.RecordReader;
+import org.apache.pinot.spi.env.PinotConfiguration;
+import org.apache.pinot.spi.utils.ReadMode;
import org.apache.pinot.spi.utils.builder.TableConfigBuilder;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.BenchmarkMode;
@@ -64,7 +67,17 @@ import org.openjdk.jmh.runner.options.OptionsBuilder;
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.MILLISECONDS)
-@Fork(1)
+// Mirror the --add-opens that the production launcher
(appAssemblerScriptTemplate) and surefire pass on JDK 11+. These
+// are required by the Unsafe/Chronicle mmap path (sun.nio.ch) and Netty's
zero-copy path; without them the "unsafe"
+// _bufferLibrary and other reflective JDK access fail in the forked JVM.
+@Fork(value = 1, jvmArgsPrepend = {
+ "--add-opens=java.base/java.nio=ALL-UNNAMED",
+ "--add-opens=java.base/sun.nio.ch=ALL-UNNAMED",
+ "--add-opens=java.base/java.lang=ALL-UNNAMED",
+ "--add-opens=java.base/java.util=ALL-UNNAMED",
+ "--add-opens=java.base/java.lang.reflect=ALL-UNNAMED",
+ "--add-opens=java.base/jdk.internal.misc=ALL-UNNAMED"
+})
@Warmup(iterations = 5, time = 1)
@Measurement(iterations = 5, time = 1)
@State(Scope.Benchmark)
@@ -230,18 +243,53 @@ public class BenchmarkQueriesSSQE extends BaseQueriesTest
{
FILTERING_ON_TIMESTAMP_QUERY, REGEXP_REPLACE_QUERY, JSON_MATCH_QUERY
})
String _query;
+ // Off-heap buffer backend used for mmap'd segment reads. Defaults to
"default" (the JVM default factory, Unsafe
+ // wrapped in SmallWithFallback) so the standard matrix is unaffected.
Override on the CLI to compare backends, e.g.
+ // -p _bufferLibrary=foreign,bytebuffer,unsafe . The non-default values
force a single factory for ALL buffer sizes
+ // (prioritize.bytebuffer=false) so the query read path is exercised
entirely through that implementation.
+ @Param({"default"})
+ String _bufferLibrary;
private IndexSegment _indexSegment;
private List<IndexSegment> _indexSegments;
private Distribution.DataSupplier _supplier;
+ /// Sets the process-wide default {@link PinotDataBuffer} factory according
to {@link #_bufferLibrary}. Uses
+ /// {@code prioritize.bytebuffer=false} so a single factory backs ALL buffer
sizes (otherwise buffers below 2GB fall
+ /// back to ByteBuffer and the chosen implementation is never exercised).
+ private void configureBufferFactory() {
+ String className;
+ switch (_bufferLibrary) {
+ case "default":
+ return; // keep the JVM default factory (Unsafe wrapped in
SmallWithFallback)
+ case "unsafe":
+ className =
"org.apache.pinot.segment.spi.memory.unsafe.UnsafePinotBufferFactory";
+ break;
+ case "foreign":
+ className =
"org.apache.pinot.segment.memory.foreign.ForeignPinotBufferFactory";
+ break;
+ case "bytebuffer":
+ className =
"org.apache.pinot.segment.spi.memory.ByteBufferPinotBufferFactory";
+ break;
+ default:
+ throw new IllegalArgumentException("Unknown buffer library: " +
_bufferLibrary);
+ }
+ Map<String, String> props = new HashMap<>();
+ props.put("pinot.offheap.buffer.factory", className);
+ props.put("pinot.offheap.prioritize.bytebuffer", "false");
+ PinotDataBuffer.loadDefaultFactory(new PinotConfiguration(props));
+ }
+
@Setup
public void setUp()
throws Exception {
+ configureBufferFactory();
_supplier = Distribution.createSupplier(42, _scenario);
FileUtils.deleteQuietly(INDEX_DIR);
_indexSegments = new ArrayList<>();
IndexLoadingConfig indexLoadingConfig = new
IndexLoadingConfig(TABLE_CONFIG, SCHEMA);
+ // Force mmap so segment reads go through PinotDataBuffer (the configured
off-heap factory), not on-heap.
+ indexLoadingConfig.setReadMode(ReadMode.mmap);
for (int i = 0; i < _numSegments; i++) {
buildSegment(String.format(SEGMENT_NAME_TEMPLATE, i));
_indexSegments.add(ImmutableSegmentLoader.load(new File(INDEX_DIR,
String.format(SEGMENT_NAME_TEMPLATE, i)),
diff --git a/pinot-segment-local/pom.xml b/pinot-segment-local/pom.xml
index 1c47c0e162b..74f023e95c3 100644
--- a/pinot-segment-local/pom.xml
+++ b/pinot-segment-local/pom.xml
@@ -39,6 +39,12 @@
<groupId>org.apache.pinot</groupId>
<artifactId>pinot-common</artifactId>
</dependency>
+ <!-- Java 21+ (Panama FFM) PinotDataBuffer implementation, opt-in via
pinot.offheap.buffer.factory. Kept in its own
+ Java 25 module so pinot-segment-spi can stay Java 11 for
driver/client consumers. -->
+ <dependency>
+ <groupId>org.apache.pinot</groupId>
+ <artifactId>pinot-foreign-buffers</artifactId>
+ </dependency>
<!-- Lucene dependencies -->
<dependency>
diff --git a/pom.xml b/pom.xml
index 708a1008367..cee727887a8 100644
--- a/pom.xml
+++ b/pom.xml
@@ -42,6 +42,7 @@
<module>pinot-dependency-verifier</module>
<module>pinot-spi</module>
<module>pinot-segment-spi</module>
+ <module>pinot-foreign-buffers</module>
<module>pinot-broker</module>
<module>pinot-common</module>
<module>pinot-clients</module>
---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]