pnowojski commented on code in PR #30190: URL: https://github.com/apache/flink/pull/30190#discussion_r4737141027
########## 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) { Review Comment: Part of the suggestion in `newIterator`: the cached options, and the rule they depend on. ```suggestion @Nullable private DirectSlice reusedBoundSlice; /** * Bounded copy of {@link #readOptions} for the iterators that use {@link #reusedBoundSlice}. * RocksDB copies the read options when it creates an iterator, so only the upper-bound pointer * refers back to the slice afterwards. */ @Nullable private ReadOptions reusedReadOptions; @Nullable private ReusedBoundIterator boundOwner; private boolean directMemoryUnavailable; private boolean closed; /** * Creates a factory whose iterators read with a bounded copy of {@code readOptions}. The copy * for the reused bound is made once, on the first scan, so {@code readOptions} must not change * after that. In particular, they must not carry a snapshot, because the copy would keep * pointing at it after the snapshot is released. */ PrefixBoundedIteratorFactory(ReadOptions readOptions) { ``` ########## 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); Review Comment: Part of the suggestion in `newIterator`: create the copy together with the slice. ```suggestion final DirectSlice slice = new DirectSlice(buffer, length); try { reusedReadOptions = RocksDBOperationUtils.copyForPrefixBoundedIterators(readOptions, slice); } catch (RuntimeException | Error e) { IOUtils.closeQuietly(slice); throw e; } reusedBoundSlice = slice; ``` ########## 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 { + private ReusedBoundIterator(RocksIterator iterator, ReadOptions options) { + super(iterator, options, null); Review Comment: Part of the suggestion in `newIterator`: the iterator no longer owns its options. ```suggestion /** The factory owns the read options and the bound of this iterator. */ private ReusedBoundIterator(RocksIterator iterator) { super(iterator, null, null); ``` ########## 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); Review Comment: Part of the suggestion in `newIterator`: release the options together with the slice. ```suggestion if (boundOwner == null) { IOUtils.closeQuietly(reusedReadOptions); IOUtils.closeQuietly(reusedBoundSlice); reusedReadOptions = null; ``` ########## 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; + } Review Comment: If I count correctly, this removes 2 of the ~8 JNI calls and 1 of the 2 native allocations per scan listed in FLINK-41519: creating and disposing the `Slice`. Everything that's left is the `ReadOptions` copy: the copy itself, four setters and the close. That matches your measurements, where about 40% of the `isEmpty` overhead remains (97 of 237 ns). So I'd expect the dashboard to still show part of the 4–6% regression. I'm not convinced we need a fresh copy per iterator. Nothing in the main code changes the backend's `ReadOptions` after the backend is created. `RocksDBResourceContainer#getReadOptions()` returns a new object on every call, and the options factory has already been applied to it by then. Only tests change it afterwards: `RocksDBMapStateTest#setUp`, the new `testBoundedIteratorObservesUpdatedSkipLimit` and `KeyGroupPartitionedPriorityQueueWithRocksDBStoreTest`. How about creating one bounded `ReadOptions` together with the slice and reusing it? As far as I know, RocksDB copies the `ReadOptions` into the iterator in `NewIterator`. After that, only the upper-bound pointer still refers to our memory, so the rule that only one open iterator may use the slice covers the options too. The suggestions in this file do that: the factory owns and closes both, and `ReusedBoundIterator` owns neither. The price is a new rule: the read options must not change after the first scan, and they must not carry a snapshot, because the cached copy would keep pointing at it after it is released. Both hold in production today. `setUp` sets the skip limit before the first scan, so it keeps working. `testBoundedIteratorObservesUpdatedSkipLimit` (with the three imports only it uses) and `testFactoryUsesCurrentSnapshotForEachIterator` would have to go. One side note: with variable-length keys such as strings, the bound length changes on most scans, so `setLength` adds one JNI call back. `MapStateBenchmark` uses `Long` keys, so it doesn't show this. ```suggestion boundOwner = new ReusedBoundIterator(db.newIterator(columnFamilyHandle, reusedReadOptions)); return boundOwner; ``` ########## 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: This is fine on master. But I don't think it can be backported to `release-2.4` as is, and a backport is the obvious next step, since FLINK-41519 is a regression from FLINK-40584, which shipped in 2.4.0. `release-2.4` still has Queryable State. There, `RocksDBMapState#getSerializedValue` runs on the queryable state server thread. It builds its prefix with its own `SerializedCompositeKeyBuilder` instead of the shared one, and then iterates a `RocksDBMapIterator`. With this change, that iterator's `loadCache()` would go through the shared factory. The task thread and the server thread could then both see `boundOwner == null` and write into the same buffer, which both native iterators read their upper bound from. If the task thread's bound is overwritten with a smaller key, its scan ends early without any error: - `isEmpty()` returns `true` for a non-empty map, - `clear()` leaves entries behind, - iteration stops early. A race on the buffer's position and limit can also throw a `BufferOverflowException`. So the argument in the description, that every scan already uses the shared key builder, holds on master only because FLINK-36244 removed the one scan that doesn't. Could you: - set the fix version of FLINK-41519 to 2.5.0 only, and note in the ticket that the fix can't be backported as is (on 2.4, `getSerializedValue` would have to keep calling `getRocksIteratorBoundedByPrefix` directly), and - add a note to this Javadoc, so that anyone cherry-picking it sees it? For example: ```suggestion * <p>The factory is not thread-safe. Only the thread that accesses the state may use it. This * relies on Queryable State having been removed, because its server threads scanned MapState * concurrently with the task thread. A branch that still has Queryable State must keep those scans * out of this factory. ``` -- 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]
