pnowojski commented on code in PR #30190:
URL: https://github.com/apache/flink/pull/30190#discussion_r4736634065
##########
flink-state-backends/flink-statebackend-rocksdb/src/main/java/org/apache/flink/state/rocksdb/RocksDBOperationUtils.java:
##########
@@ -129,6 +130,9 @@ public static RocksIteratorWrapper getRocksIterator(
* caller's options are not modified. If the prefix has no exclusive upper
bound (see {@code
* getPrefixEnd}), the caller's options are used as they are and the
iterator is unbounded: no
* key outside such a prefix can follow it, so nothing extra is visited.
+ *
+ * <p>Code that creates an iterator per state access can use a {@link
+ * PrefixBoundedIteratorFactory} to reuse the native upper-bound slice.
*/
static RocksIteratorWrapper getRocksIteratorBoundedByPrefix(
Review Comment:
Should this be moved to the factory now? 🤔 I presume it's only used there
now, isn't it?
##########
flink-state-backends/flink-statebackend-rocksdb/src/main/java/org/apache/flink/state/rocksdb/RocksDBOperationUtils.java:
##########
@@ -143,8 +147,26 @@ static RocksIteratorWrapper
getRocksIteratorBoundedByPrefix(
final Slice upperBound = new Slice(prefixEnd);
ReadOptions boundedReadOptions = null;
try {
- boundedReadOptions = new ReadOptions(readOptions);
- boundedReadOptions.setIterateUpperBound(upperBound);
+ boundedReadOptions = copyForPrefixBoundedIterators(readOptions,
upperBound);
+ return new RocksIteratorWrapper(
+ db.newIterator(columnFamilyHandle, boundedReadOptions),
+ boundedReadOptions,
+ upperBound);
+ } catch (RuntimeException | Error e) {
+ IOUtils.closeQuietly(boundedReadOptions);
+ IOUtils.closeQuietly(upperBound);
+ throw e;
+ }
+ }
+
+ /**
+ * Copies {@code readOptions} for an iterator bounded by a key prefix. The
caller owns both the
+ * copy and the upper bound.
+ */
+ static ReadOptions copyForPrefixBoundedIterators(
Review Comment:
nit: for the future, it would be easier for readers to read/review the code
if this extraction of `copyForPrefixBoundedIterators` was a separate `hotfix`
refactor commit, to highlight that nothing functionlly has changed. I've spent
a couple of minutes reding and comparring this code line by line.
##########
flink-state-backends/flink-statebackend-rocksdb/src/main/java/org/apache/flink/state/rocksdb/PrefixBoundedIteratorFactory.java:
##########
@@ -0,0 +1,175 @@
+/*
+ * 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.flink.state.rocksdb;
+
+import org.apache.flink.annotation.VisibleForTesting;
+import org.apache.flink.util.ExceptionUtils;
+import org.apache.flink.util.IOUtils;
+import org.apache.flink.util.Preconditions;
+
+import org.rocksdb.ColumnFamilyHandle;
+import org.rocksdb.DirectSlice;
+import org.rocksdb.ReadOptions;
+import org.rocksdb.RocksDB;
+import org.rocksdb.RocksIterator;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import javax.annotation.Nullable;
+
+import java.nio.ByteBuffer;
+import java.util.function.IntFunction;
+
+/**
+ * Creates prefix-bounded iterators for MapState scans. RocksDB borrows a
pointer to the upper bound
+ * for the lifetime of the iterator. Once that iterator closes, the next scan
can reuse its slice.
+ * Overlapping iterators and bounds that exceed the buffer capacity get a
slice of their own.
+ *
+ * <p>The factory is not thread-safe. Only the thread that accesses the state
may use it.
+ */
+final class PrefixBoundedIteratorFactory implements AutoCloseable {
+
+ private static final Logger LOG =
LoggerFactory.getLogger(PrefixBoundedIteratorFactory.class);
+
+ @VisibleForTesting static final int MAX_REUSED_BOUND_LENGTH = 256;
+
+ private final ReadOptions readOptions;
+ private final IntFunction<ByteBuffer> boundAllocator;
+ @Nullable private ByteBuffer reusedBound;
+ @Nullable private DirectSlice reusedBoundSlice;
+ @Nullable private ReusedBoundIterator boundOwner;
+ private boolean directMemoryUnavailable;
+ private boolean closed;
+
+ PrefixBoundedIteratorFactory(ReadOptions readOptions) {
+ this(readOptions, ByteBuffer::allocateDirect);
+ }
+
+ @VisibleForTesting
+ PrefixBoundedIteratorFactory(ReadOptions readOptions,
IntFunction<ByteBuffer> boundAllocator) {
+ this.readOptions = readOptions;
+ this.boundAllocator = boundAllocator;
+ }
+
+ RocksIteratorWrapper newIterator(
+ RocksDB db, ColumnFamilyHandle columnFamilyHandle, byte[] prefix) {
+ Preconditions.checkState(!closed, "The iterator factory is closed.");
+ final int length = RocksDBOperationUtils.getPrefixEndLength(prefix);
+ if (length == 0
+ || boundOwner != null
+ || length > MAX_REUSED_BOUND_LENGTH
+ || !ensureReusedBound(length)) {
+ return RocksDBOperationUtils.getRocksIteratorBoundedByPrefix(
+ db, columnFamilyHandle, readOptions, prefix);
+ }
Review Comment:
Does this branch handle the case when we are re-using things, or is it a
short-circuit in case we can't re-use something? -> either add a comment or
even better, extract the whole if's conditions into a named method that would
self explain itself (`if (somethingSomethingCanBeReused(...))` or `if
(somethingSomethingCanNotBeReused(...))`?)
##########
flink-state-backends/flink-statebackend-rocksdb/src/main/java/org/apache/flink/state/rocksdb/RocksDBOperationUtils.java:
##########
@@ -182,14 +201,25 @@ static RocksIteratorWrapper
getRocksIteratorBoundedByPrefix(
@Nullable
@VisibleForTesting
static byte[] getPrefixEnd(byte[] prefix) {
- for (int i = prefix.length - 1; i >= 0; --i) {
- if (prefix[i] != (byte) 0xFF) {
- final byte[] prefixEnd = Arrays.copyOf(prefix, i + 1);
- ++prefixEnd[i];
- return prefixEnd;
- }
Review Comment:
Probably this comment should have been part of the previous review, but here
it is:
I' struggling a bit to understand how this method works and what does it to.
Could you:
1. clarify the java doc a bit?
2. Add unit tests for that method alone to among other things, showcase what
does it do?
##########
flink-state-backends/flink-statebackend-rocksdb/src/main/java/org/apache/flink/state/rocksdb/PrefixBoundedIteratorFactory.java:
##########
@@ -0,0 +1,175 @@
+/*
+ * 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.flink.state.rocksdb;
+
+import org.apache.flink.annotation.VisibleForTesting;
+import org.apache.flink.util.ExceptionUtils;
+import org.apache.flink.util.IOUtils;
+import org.apache.flink.util.Preconditions;
+
+import org.rocksdb.ColumnFamilyHandle;
+import org.rocksdb.DirectSlice;
+import org.rocksdb.ReadOptions;
+import org.rocksdb.RocksDB;
+import org.rocksdb.RocksIterator;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import javax.annotation.Nullable;
+
+import java.nio.ByteBuffer;
+import java.util.function.IntFunction;
+
+/**
+ * Creates prefix-bounded iterators for MapState scans. RocksDB borrows a
pointer to the upper bound
+ * for the lifetime of the iterator. Once that iterator closes, the next scan
can reuse its slice.
+ * Overlapping iterators and bounds that exceed the buffer capacity get a
slice of their own.
+ *
+ * <p>The factory is not thread-safe. Only the thread that accesses the state
may use it.
+ */
Review Comment:
I'm lacking a bit more explanation what are we actually re-using here, what
fields are used for what and why
##########
flink-state-backends/flink-statebackend-rocksdb/src/main/java/org/apache/flink/state/rocksdb/RocksDBOperationUtils.java:
##########
@@ -182,14 +201,25 @@ static RocksIteratorWrapper
getRocksIteratorBoundedByPrefix(
@Nullable
@VisibleForTesting
static byte[] getPrefixEnd(byte[] prefix) {
- for (int i = prefix.length - 1; i >= 0; --i) {
- if (prefix[i] != (byte) 0xFF) {
- final byte[] prefixEnd = Arrays.copyOf(prefix, i + 1);
- ++prefixEnd[i];
- return prefixEnd;
- }
+ final int length = getPrefixEndLength(prefix);
+ if (length == 0) {
+ return null;
+ }
+ final byte[] prefixEnd = Arrays.copyOf(prefix, length);
+ ++prefixEnd[length - 1];
+ return prefixEnd;
+ }
+
+ /**
+ * Returns the length of the key that {@link #getPrefixEnd} returns, or
zero if there is none.
+ * That key is the prefix cut to this length, with its last byte
incremented.
+ */
Review Comment:
nit: add mention `set #getPrefixEnd for more information`.
##########
flink-state-backends/flink-statebackend-rocksdb/src/main/java/org/apache/flink/state/rocksdb/PrefixBoundedIteratorFactory.java:
##########
@@ -0,0 +1,175 @@
+/*
+ * 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.flink.state.rocksdb;
+
+import org.apache.flink.annotation.VisibleForTesting;
+import org.apache.flink.util.ExceptionUtils;
+import org.apache.flink.util.IOUtils;
+import org.apache.flink.util.Preconditions;
+
+import org.rocksdb.ColumnFamilyHandle;
+import org.rocksdb.DirectSlice;
+import org.rocksdb.ReadOptions;
+import org.rocksdb.RocksDB;
+import org.rocksdb.RocksIterator;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import javax.annotation.Nullable;
+
+import java.nio.ByteBuffer;
+import java.util.function.IntFunction;
+
+/**
+ * Creates prefix-bounded iterators for MapState scans. RocksDB borrows a
pointer to the upper bound
+ * for the lifetime of the iterator. Once that iterator closes, the next scan
can reuse its slice.
+ * Overlapping iterators and bounds that exceed the buffer capacity get a
slice of their own.
+ *
+ * <p>The factory is not thread-safe. Only the thread that accesses the state
may use it.
+ */
+final class PrefixBoundedIteratorFactory implements AutoCloseable {
+
+ private static final Logger LOG =
LoggerFactory.getLogger(PrefixBoundedIteratorFactory.class);
+
+ @VisibleForTesting static final int MAX_REUSED_BOUND_LENGTH = 256;
+
+ private final ReadOptions readOptions;
+ private final IntFunction<ByteBuffer> boundAllocator;
+ @Nullable private ByteBuffer reusedBound;
+ @Nullable private DirectSlice reusedBoundSlice;
+ @Nullable private ReusedBoundIterator boundOwner;
+ private boolean directMemoryUnavailable;
+ private boolean closed;
+
+ PrefixBoundedIteratorFactory(ReadOptions readOptions) {
+ this(readOptions, ByteBuffer::allocateDirect);
+ }
+
+ @VisibleForTesting
+ PrefixBoundedIteratorFactory(ReadOptions readOptions,
IntFunction<ByteBuffer> boundAllocator) {
+ this.readOptions = readOptions;
+ this.boundAllocator = boundAllocator;
+ }
+
+ RocksIteratorWrapper newIterator(
+ RocksDB db, ColumnFamilyHandle columnFamilyHandle, byte[] prefix) {
+ Preconditions.checkState(!closed, "The iterator factory is closed.");
+ final int length = RocksDBOperationUtils.getPrefixEndLength(prefix);
+ if (length == 0
+ || boundOwner != null
+ || length > MAX_REUSED_BOUND_LENGTH
+ || !ensureReusedBound(length)) {
+ return RocksDBOperationUtils.getRocksIteratorBoundedByPrefix(
+ db, columnFamilyHandle, readOptions, prefix);
+ }
+
+ if (length != reusedBound.limit()) {
+ reusedBoundSlice.setLength(length);
+ reusedBound.limit(length);
+ }
+ reusedBound.rewind();
+ reusedBound.put(prefix, 0, length - 1);
+ reusedBound.put((byte) (prefix[length - 1] + 1));
+
+ final ReadOptions options =
+
RocksDBOperationUtils.copyForPrefixBoundedIterators(readOptions,
reusedBoundSlice);
+ try {
+ boundOwner =
+ new ReusedBoundIterator(db.newIterator(columnFamilyHandle,
options), options);
+ return boundOwner;
+ } catch (RuntimeException | Error e) {
+ IOUtils.closeQuietly(options);
+ throw e;
+ }
+ }
+
+ private boolean ensureReusedBound(int length) {
+ if (reusedBound != null) {
+ return true;
+ }
+ if (directMemoryUnavailable) {
+ return false;
+ }
+ final ByteBuffer buffer;
+ try {
+ buffer = boundAllocator.apply(MAX_REUSED_BOUND_LENGTH);
+ } catch (OutOfMemoryError e) {
+ if (!ExceptionUtils.isDirectOutOfMemoryError(e)) {
+ throw e;
+ }
+ // A private RocksDB slice does not use the JVM's direct-buffer
allowance.
+ directMemoryUnavailable = true;
+ LOG.warn(
+ "No direct memory is left for the reused upper bound of
MapState scans."
+ + " Every scan of this backend allocates its own
bound instead.");
+ return false;
+ }
+ buffer.limit(length);
+ reusedBoundSlice = new DirectSlice(buffer, length);
+ reusedBound = buffer;
+ return true;
+ }
+
+ @VisibleForTesting
+ boolean isReusedBoundInUse() {
+ return boundOwner != null;
+ }
+
+ @VisibleForTesting
+ @Nullable
+ DirectSlice getReusedBoundSlice() {
+ return reusedBoundSlice;
+ }
+
+ /**
+ * Closes the factory. An iterator that still owns the reused bound keeps
it until that iterator
+ * is closed.
+ */
+ @Override
+ public void close() {
+ closed = true;
+ if (boundOwner == null) {
+ IOUtils.closeQuietly(reusedBoundSlice);
+ reusedBoundSlice = null;
+ reusedBound = null;
+ }
+ }
+
+ private final class ReusedBoundIterator extends RocksIteratorWrapper {
Review Comment:
Add a small java doc explaining why do we need this class?
```
RocksIteratorWrapper that tracks how long is the given iterator re-using the
factory's `#reusedBound` and `#reusedBoundSlice`
```
?
##########
flink-state-backends/flink-statebackend-rocksdb/src/main/java/org/apache/flink/state/rocksdb/PrefixBoundedIteratorFactory.java:
##########
@@ -0,0 +1,175 @@
+/*
+ * 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.flink.state.rocksdb;
+
+import org.apache.flink.annotation.VisibleForTesting;
+import org.apache.flink.util.ExceptionUtils;
+import org.apache.flink.util.IOUtils;
+import org.apache.flink.util.Preconditions;
+
+import org.rocksdb.ColumnFamilyHandle;
+import org.rocksdb.DirectSlice;
+import org.rocksdb.ReadOptions;
+import org.rocksdb.RocksDB;
+import org.rocksdb.RocksIterator;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import javax.annotation.Nullable;
+
+import java.nio.ByteBuffer;
+import java.util.function.IntFunction;
+
+/**
+ * Creates prefix-bounded iterators for MapState scans. RocksDB borrows a
pointer to the upper bound
+ * for the lifetime of the iterator. Once that iterator closes, the next scan
can reuse its slice.
+ * Overlapping iterators and bounds that exceed the buffer capacity get a
slice of their own.
+ *
+ * <p>The factory is not thread-safe. Only the thread that accesses the state
may use it.
+ */
+final class PrefixBoundedIteratorFactory implements AutoCloseable {
+
+ private static final Logger LOG =
LoggerFactory.getLogger(PrefixBoundedIteratorFactory.class);
+
+ @VisibleForTesting static final int MAX_REUSED_BOUND_LENGTH = 256;
+
+ private final ReadOptions readOptions;
+ private final IntFunction<ByteBuffer> boundAllocator;
+ @Nullable private ByteBuffer reusedBound;
+ @Nullable private DirectSlice reusedBoundSlice;
+ @Nullable private ReusedBoundIterator boundOwner;
+ private boolean directMemoryUnavailable;
+ private boolean closed;
+
+ PrefixBoundedIteratorFactory(ReadOptions readOptions) {
+ this(readOptions, ByteBuffer::allocateDirect);
+ }
+
+ @VisibleForTesting
+ PrefixBoundedIteratorFactory(ReadOptions readOptions,
IntFunction<ByteBuffer> boundAllocator) {
+ this.readOptions = readOptions;
+ this.boundAllocator = boundAllocator;
+ }
+
+ RocksIteratorWrapper newIterator(
+ RocksDB db, ColumnFamilyHandle columnFamilyHandle, byte[] prefix) {
+ Preconditions.checkState(!closed, "The iterator factory is closed.");
+ final int length = RocksDBOperationUtils.getPrefixEndLength(prefix);
+ if (length == 0
+ || boundOwner != null
+ || length > MAX_REUSED_BOUND_LENGTH
+ || !ensureReusedBound(length)) {
+ return RocksDBOperationUtils.getRocksIteratorBoundedByPrefix(
+ db, columnFamilyHandle, readOptions, prefix);
+ }
+
+ if (length != reusedBound.limit()) {
+ reusedBoundSlice.setLength(length);
+ reusedBound.limit(length);
+ }
+ reusedBound.rewind();
+ reusedBound.put(prefix, 0, length - 1);
+ reusedBound.put((byte) (prefix[length - 1] + 1));
+
+ final ReadOptions options =
+
RocksDBOperationUtils.copyForPrefixBoundedIterators(readOptions,
reusedBoundSlice);
+ try {
+ boundOwner =
+ new ReusedBoundIterator(db.newIterator(columnFamilyHandle,
options), options);
+ return boundOwner;
+ } catch (RuntimeException | Error e) {
+ IOUtils.closeQuietly(options);
+ throw e;
+ }
+ }
+
+ private boolean ensureReusedBound(int length) {
Review Comment:
This name seems strange and doesn't explain to me what does this method do 🤔
--
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]