You are viewing a plain text version of this content. The canonical link for it is here.
Posted to jira@kafka.apache.org by "nicktelford (via GitHub)" <gi...@apache.org> on 2026/05/19 08:44:02 UTC

[PR] KAFKA-20490: Add transaction buffer framework [kafka]

nicktelford opened a new pull request, #22323:
URL: https://github.com/apache/kafka/pull/22323

   Introduces the core building blocks for transactional state stores:
   TransactionBuffer, AbstractTransactionBuffer, and StagedMergeIterator.
   
   TransactionBuffer defines the staging interface for buffering writes
   before a transaction commits. AbstractTransactionBuffer provides a
   ConcurrentSkipListMap-backed implementation. Reads on the owner thread
   (the stream thread driving the task) take a lock-free fast path directly
   against the staged map; reads on non-owner threads, such as interactive
   query, snapshot the staged entries at iteration start for a consistent
   view without blocking writers.
   
   StagedMergeIterator is a ManagedKeyValueIterator that merges the staged
   overlay with a base store iterator, respecting point-delete tombstones
   for entries deleted within the transaction. It registers with the store's
   open-iterator tracking so RocksDB can defer compactions while it is live.
   
   The abstract base is tombstone-agnostic: point deletes are handled
   uniformly by all implementations. All types are generic over the key
   type so that window and session stores can reuse the same framework with
   composite keys.
   


-- 
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: jira-unsubscribe@kafka.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] KAFKA-20490: Add transaction buffer framework [kafka]

Posted by "nicktelford (via GitHub)" <gi...@apache.org>.
nicktelford commented on code in PR #22323:
URL: https://github.com/apache/kafka/pull/22323#discussion_r3347072889


##########
streams/src/main/java/org/apache/kafka/streams/state/internals/StagedMergeIterator.java:
##########
@@ -0,0 +1,172 @@
+/*
+ * 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.kafka.streams.state.internals;
+
+import org.apache.kafka.streams.KeyValue;
+import org.apache.kafka.streams.state.KeyValueIterator;
+
+import java.util.Iterator;
+import java.util.Map;
+import java.util.NavigableMap;
+import java.util.NoSuchElementException;
+import java.util.Optional;
+
+/**
+ * A merge iterator that overlays staged writes (from a {@link NavigableMap}) on top of
+ * a base store iterator. Staging entries take precedence over base entries for the same key.
+ * Tombstones ({@link Optional#empty()}) in the staging map cause the corresponding key
+ * to be skipped in the merged output.
+ * <p>
+ * Supports both forward and reverse iteration. When iterating in reverse, the staging
+ * map is traversed in descending order and the merge comparison is inverted so that
+ * the largest key is emitted first.
+ *
+ * @param <K> the key type, must be {@link Comparable}
+ * @param <V> the value type
+ */
+class StagedMergeIterator<K extends Comparable<K>, V> implements ManagedKeyValueIterator<K, V> {
+
+    private final Iterator<Map.Entry<K, Optional<V>>> stagingIterator;
+    private final KeyValueIterator<K, V> baseIterator;
+    private final boolean forward;
+
+    private Map.Entry<K, Optional<V>> nextStaging;
+    private KeyValue<K, V> nextBase;
+    private KeyValue<K, V> prefetched;
+    private boolean closed = false;
+    private Runnable closeCallback;
+
+    StagedMergeIterator(final NavigableMap<K, Optional<V>> staging,
+                        final KeyValueIterator<K, V> baseIterator) {
+        this(staging, baseIterator, true);
+    }
+
+    StagedMergeIterator(final NavigableMap<K, Optional<V>> staging,
+                        final KeyValueIterator<K, V> baseIterator,
+                        final boolean forward) {
+        this.forward = forward;
+        final NavigableMap<K, Optional<V>> orderedStaging = forward ? staging : staging.descendingMap();
+        this.stagingIterator = orderedStaging.entrySet().iterator();
+        this.baseIterator = baseIterator;
+        advanceStaging();
+        advanceBase();
+    }
+
+    private void advanceStaging() {
+        nextStaging = stagingIterator.hasNext() ? stagingIterator.next() : null;
+    }
+
+    private void advanceBase() {
+        nextBase = baseIterator.hasNext() ? baseIterator.next() : null;
+    }
+
+    @Override
+    public boolean hasNext() {
+        if (closed) {
+            throw new IllegalStateException("Iterator has already been closed.");
+        }
+        if (prefetched != null) {
+            return true;
+        }
+        prefetched = computeNext();
+        return prefetched != null;
+    }
+
+    @Override
+    public KeyValue<K, V> next() {
+        if (!hasNext()) {
+            throw new NoSuchElementException();
+        }
+        final KeyValue<K, V> result = prefetched;
+        prefetched = null;
+        return result;
+    }
+
+    @Override
+    public K peekNextKey() {
+        if (!hasNext()) {
+            throw new NoSuchElementException();
+        }
+        return prefetched.key;
+    }
+
+    @Override
+    public void onClose(final Runnable closeCallback) {
+        this.closeCallback = closeCallback;
+    }
+
+    @Override
+    public void close() {
+        closed = true;

Review Comment:
   Can do. It's notable that none of the other existing ManagedKeyValueIterators do that though (`RocksDbIterator`, `RocksDBDualCFIterator`, `KeyValueToTimestampedKeyValueAdapterIterator`).



-- 
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: jira-unsubscribe@kafka.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] KAFKA-20490: Add transaction buffer framework [kafka]

Posted by "nicktelford (via GitHub)" <gi...@apache.org>.
nicktelford commented on code in PR #22323:
URL: https://github.com/apache/kafka/pull/22323#discussion_r3347078853


##########
streams/src/main/java/org/apache/kafka/streams/state/internals/StagedMergeIterator.java:
##########
@@ -0,0 +1,172 @@
+/*
+ * 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.kafka.streams.state.internals;
+
+import org.apache.kafka.streams.KeyValue;
+import org.apache.kafka.streams.state.KeyValueIterator;
+
+import java.util.Iterator;
+import java.util.Map;
+import java.util.NavigableMap;
+import java.util.NoSuchElementException;
+import java.util.Optional;
+
+/**
+ * A merge iterator that overlays staged writes (from a {@link NavigableMap}) on top of
+ * a base store iterator. Staging entries take precedence over base entries for the same key.
+ * Tombstones ({@link Optional#empty()}) in the staging map cause the corresponding key
+ * to be skipped in the merged output.
+ * <p>
+ * Supports both forward and reverse iteration. When iterating in reverse, the staging
+ * map is traversed in descending order and the merge comparison is inverted so that
+ * the largest key is emitted first.
+ *
+ * @param <K> the key type, must be {@link Comparable}
+ * @param <V> the value type
+ */
+class StagedMergeIterator<K extends Comparable<K>, V> implements ManagedKeyValueIterator<K, V> {
+
+    private final Iterator<Map.Entry<K, Optional<V>>> stagingIterator;
+    private final KeyValueIterator<K, V> baseIterator;
+    private final boolean forward;
+
+    private Map.Entry<K, Optional<V>> nextStaging;
+    private KeyValue<K, V> nextBase;
+    private KeyValue<K, V> prefetched;
+    private boolean closed = false;
+    private Runnable closeCallback;
+
+    StagedMergeIterator(final NavigableMap<K, Optional<V>> staging,
+                        final KeyValueIterator<K, V> baseIterator) {
+        this(staging, baseIterator, true);
+    }
+
+    StagedMergeIterator(final NavigableMap<K, Optional<V>> staging,
+                        final KeyValueIterator<K, V> baseIterator,
+                        final boolean forward) {
+        this.forward = forward;
+        final NavigableMap<K, Optional<V>> orderedStaging = forward ? staging : staging.descendingMap();
+        this.stagingIterator = orderedStaging.entrySet().iterator();
+        this.baseIterator = baseIterator;
+        advanceStaging();
+        advanceBase();
+    }
+
+    private void advanceStaging() {
+        nextStaging = stagingIterator.hasNext() ? stagingIterator.next() : null;
+    }
+
+    private void advanceBase() {
+        nextBase = baseIterator.hasNext() ? baseIterator.next() : null;
+    }
+
+    @Override
+    public boolean hasNext() {
+        if (closed) {
+            throw new IllegalStateException("Iterator has already been closed.");
+        }
+        if (prefetched != null) {
+            return true;
+        }
+        prefetched = computeNext();
+        return prefetched != null;
+    }
+
+    @Override
+    public KeyValue<K, V> next() {
+        if (!hasNext()) {
+            throw new NoSuchElementException();
+        }
+        final KeyValue<K, V> result = prefetched;
+        prefetched = null;
+        return result;
+    }
+
+    @Override
+    public K peekNextKey() {
+        if (!hasNext()) {
+            throw new NoSuchElementException();
+        }
+        return prefetched.key;
+    }
+
+    @Override
+    public void onClose(final Runnable closeCallback) {
+        this.closeCallback = closeCallback;

Review Comment:
   You're right, but this is consistent with all existing `ManagedKeyValueIterator` implementations (`RocksDbIterator`, `RocksDBDualCFIterator`, `KeyValueToTimestampedKeyValueAdapterIterator`); I guess that means in practice, this method is not repeatedly called?



##########
streams/src/test/java/org/apache/kafka/streams/state/internals/StagedMergeIteratorTest.java:
##########
@@ -0,0 +1,285 @@
+/*
+ * 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.kafka.streams.state.internals;
+
+import org.apache.kafka.common.utils.Bytes;
+import org.apache.kafka.streams.KeyValue;
+import org.apache.kafka.streams.state.KeyValueIterator;
+
+import org.junit.jupiter.api.Test;
+
+import java.nio.charset.StandardCharsets;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.NavigableMap;
+import java.util.NoSuchElementException;
+import java.util.Optional;
+import java.util.TreeMap;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+public class StagedMergeIteratorTest {

Review Comment:
   Good point! Done.



-- 
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: jira-unsubscribe@kafka.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] KAFKA-20490: Add transaction buffer framework [kafka]

Posted by "bbejeck (via GitHub)" <gi...@apache.org>.
bbejeck commented on code in PR #22323:
URL: https://github.com/apache/kafka/pull/22323#discussion_r3345062964


##########
streams/src/main/java/org/apache/kafka/streams/state/internals/StagedMergeIterator.java:
##########
@@ -0,0 +1,172 @@
+/*
+ * 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.kafka.streams.state.internals;
+
+import org.apache.kafka.streams.KeyValue;
+import org.apache.kafka.streams.state.KeyValueIterator;
+
+import java.util.Iterator;
+import java.util.Map;
+import java.util.NavigableMap;
+import java.util.NoSuchElementException;
+import java.util.Optional;
+
+/**
+ * A merge iterator that overlays staged writes (from a {@link NavigableMap}) on top of
+ * a base store iterator. Staging entries take precedence over base entries for the same key.
+ * Tombstones ({@link Optional#empty()}) in the staging map cause the corresponding key
+ * to be skipped in the merged output.
+ * <p>
+ * Supports both forward and reverse iteration. When iterating in reverse, the staging
+ * map is traversed in descending order and the merge comparison is inverted so that
+ * the largest key is emitted first.
+ *
+ * @param <K> the key type, must be {@link Comparable}
+ * @param <V> the value type
+ */
+class StagedMergeIterator<K extends Comparable<K>, V> implements ManagedKeyValueIterator<K, V> {
+
+    private final Iterator<Map.Entry<K, Optional<V>>> stagingIterator;
+    private final KeyValueIterator<K, V> baseIterator;
+    private final boolean forward;
+
+    private Map.Entry<K, Optional<V>> nextStaging;
+    private KeyValue<K, V> nextBase;
+    private KeyValue<K, V> prefetched;
+    private boolean closed = false;
+    private Runnable closeCallback;
+
+    StagedMergeIterator(final NavigableMap<K, Optional<V>> staging,
+                        final KeyValueIterator<K, V> baseIterator) {
+        this(staging, baseIterator, true);
+    }
+
+    StagedMergeIterator(final NavigableMap<K, Optional<V>> staging,
+                        final KeyValueIterator<K, V> baseIterator,
+                        final boolean forward) {
+        this.forward = forward;
+        final NavigableMap<K, Optional<V>> orderedStaging = forward ? staging : staging.descendingMap();
+        this.stagingIterator = orderedStaging.entrySet().iterator();
+        this.baseIterator = baseIterator;
+        advanceStaging();
+        advanceBase();
+    }
+
+    private void advanceStaging() {
+        nextStaging = stagingIterator.hasNext() ? stagingIterator.next() : null;
+    }
+
+    private void advanceBase() {
+        nextBase = baseIterator.hasNext() ? baseIterator.next() : null;
+    }
+
+    @Override
+    public boolean hasNext() {
+        if (closed) {
+            throw new IllegalStateException("Iterator has already been closed.");
+        }
+        if (prefetched != null) {
+            return true;
+        }
+        prefetched = computeNext();
+        return prefetched != null;
+    }
+
+    @Override
+    public KeyValue<K, V> next() {
+        if (!hasNext()) {
+            throw new NoSuchElementException();
+        }
+        final KeyValue<K, V> result = prefetched;
+        prefetched = null;
+        return result;
+    }
+
+    @Override
+    public K peekNextKey() {
+        if (!hasNext()) {
+            throw new NoSuchElementException();
+        }
+        return prefetched.key;
+    }
+
+    @Override
+    public void onClose(final Runnable closeCallback) {
+        this.closeCallback = closeCallback;
+    }
+
+    @Override
+    public void close() {
+        closed = true;

Review Comment:
   maybe check here if close has already been called 
   `if (closed) return`?



##########
streams/src/main/java/org/apache/kafka/streams/state/internals/StagedMergeIterator.java:
##########
@@ -0,0 +1,172 @@
+/*
+ * 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.kafka.streams.state.internals;
+
+import org.apache.kafka.streams.KeyValue;
+import org.apache.kafka.streams.state.KeyValueIterator;
+
+import java.util.Iterator;
+import java.util.Map;
+import java.util.NavigableMap;
+import java.util.NoSuchElementException;
+import java.util.Optional;
+
+/**
+ * A merge iterator that overlays staged writes (from a {@link NavigableMap}) on top of
+ * a base store iterator. Staging entries take precedence over base entries for the same key.
+ * Tombstones ({@link Optional#empty()}) in the staging map cause the corresponding key
+ * to be skipped in the merged output.
+ * <p>
+ * Supports both forward and reverse iteration. When iterating in reverse, the staging
+ * map is traversed in descending order and the merge comparison is inverted so that
+ * the largest key is emitted first.
+ *
+ * @param <K> the key type, must be {@link Comparable}
+ * @param <V> the value type
+ */
+class StagedMergeIterator<K extends Comparable<K>, V> implements ManagedKeyValueIterator<K, V> {
+
+    private final Iterator<Map.Entry<K, Optional<V>>> stagingIterator;
+    private final KeyValueIterator<K, V> baseIterator;
+    private final boolean forward;
+
+    private Map.Entry<K, Optional<V>> nextStaging;
+    private KeyValue<K, V> nextBase;
+    private KeyValue<K, V> prefetched;
+    private boolean closed = false;
+    private Runnable closeCallback;
+
+    StagedMergeIterator(final NavigableMap<K, Optional<V>> staging,
+                        final KeyValueIterator<K, V> baseIterator) {
+        this(staging, baseIterator, true);
+    }
+
+    StagedMergeIterator(final NavigableMap<K, Optional<V>> staging,
+                        final KeyValueIterator<K, V> baseIterator,
+                        final boolean forward) {
+        this.forward = forward;
+        final NavigableMap<K, Optional<V>> orderedStaging = forward ? staging : staging.descendingMap();
+        this.stagingIterator = orderedStaging.entrySet().iterator();
+        this.baseIterator = baseIterator;
+        advanceStaging();
+        advanceBase();
+    }
+
+    private void advanceStaging() {
+        nextStaging = stagingIterator.hasNext() ? stagingIterator.next() : null;
+    }
+
+    private void advanceBase() {
+        nextBase = baseIterator.hasNext() ? baseIterator.next() : null;
+    }
+
+    @Override
+    public boolean hasNext() {
+        if (closed) {
+            throw new IllegalStateException("Iterator has already been closed.");
+        }
+        if (prefetched != null) {
+            return true;
+        }
+        prefetched = computeNext();
+        return prefetched != null;
+    }
+
+    @Override
+    public KeyValue<K, V> next() {
+        if (!hasNext()) {
+            throw new NoSuchElementException();
+        }
+        final KeyValue<K, V> result = prefetched;
+        prefetched = null;
+        return result;
+    }
+
+    @Override
+    public K peekNextKey() {
+        if (!hasNext()) {
+            throw new NoSuchElementException();
+        }
+        return prefetched.key;
+    }
+
+    @Override
+    public void onClose(final Runnable closeCallback) {
+        this.closeCallback = closeCallback;

Review Comment:
   If implementors call this method twice the original `closeCallback` get overwritten - maybe we should guard against that?



##########
streams/src/test/java/org/apache/kafka/streams/state/internals/StagedMergeIteratorTest.java:
##########
@@ -0,0 +1,285 @@
+/*
+ * 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.kafka.streams.state.internals;
+
+import org.apache.kafka.common.utils.Bytes;
+import org.apache.kafka.streams.KeyValue;
+import org.apache.kafka.streams.state.KeyValueIterator;
+
+import org.junit.jupiter.api.Test;
+
+import java.nio.charset.StandardCharsets;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.NavigableMap;
+import java.util.NoSuchElementException;
+import java.util.Optional;
+import java.util.TreeMap;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+public class StagedMergeIteratorTest {

Review Comment:
   There are no reverse iteration tests - we don't need as many for the forward-iteration but 1-2 would be a good idea.



-- 
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: jira-unsubscribe@kafka.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] KAFKA-20490: Add transaction buffer framework [kafka]

Posted by "nicktelford (via GitHub)" <gi...@apache.org>.
nicktelford commented on PR #22323:
URL: https://github.com/apache/kafka/pull/22323#issuecomment-4689627780

   @bbejeck I've added the tests as requested. Regarding your other comments: this is consistent with existing Iterator implementations. We can make StagedMergeIterator more defensive, as requested, but it would be a deviation from the other implementations, which I'm not sure is a good idea.
   
   Maybe all of the Iterator implementations should have this addressed together, perhaps in a separate PR?
   
   What would you like to 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: jira-unsubscribe@kafka.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] KAFKA-20490: Add transaction buffer framework [kafka]

Posted by "bbejeck (via GitHub)" <gi...@apache.org>.
bbejeck commented on code in PR #22323:
URL: https://github.com/apache/kafka/pull/22323#discussion_r3352238601


##########
streams/src/main/java/org/apache/kafka/streams/state/internals/AbstractTransactionBuffer.java:
##########
@@ -0,0 +1,172 @@
+/*
+ * 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.kafka.streams.state.internals;
+
+import java.util.NavigableMap;
+import java.util.Optional;
+import java.util.TreeMap;
+import java.util.concurrent.ConcurrentSkipListMap;
+import java.util.concurrent.locks.ReentrantReadWriteLock;
+
+/**
+ * Base class for {@link TransactionBuffer} implementations. Provides the shared two-layer
+ * staging design: a thread-safe {@link ConcurrentSkipListMap} for reads (any thread) and
+ * backend-specific write accumulation for atomic commit.
+ * <p>
+ * Point lookups ({@link #get(Comparable)}) are lock-free. Scan methods automatically detect the
+ * owner thread and use a lock-free fast path; non-owner threads acquire a read lock to
+ * snapshot the staging map atomically with base iterator creation.
+ *
+ * @param <K> the key type, must be {@link Comparable}
+ */
+abstract class AbstractTransactionBuffer<K extends Comparable<K>> implements TransactionBuffer<K> {

Review Comment:
   Could we get some tests for the concrete methods in this class? I realize it's an `abstract` class - but not a blocker as long as we get coverage with testing in subsequent PRs



-- 
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: jira-unsubscribe@kafka.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] KAFKA-20490: Add transaction buffer framework [kafka]

Posted by "bbejeck (via GitHub)" <gi...@apache.org>.
bbejeck commented on PR #22323:
URL: https://github.com/apache/kafka/pull/22323#issuecomment-4722911116

   Merged #22323 into trunk


-- 
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: jira-unsubscribe@kafka.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] KAFKA-20490: Add transaction buffer framework [kafka]

Posted by "bbejeck (via GitHub)" <gi...@apache.org>.
bbejeck merged PR #22323:
URL: https://github.com/apache/kafka/pull/22323


-- 
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: jira-unsubscribe@kafka.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] KAFKA-20490: Add transaction buffer framework [kafka]

Posted by "github-actions[bot] (via GitHub)" <gi...@apache.org>.
github-actions[bot] commented on PR #22323:
URL: https://github.com/apache/kafka/pull/22323#issuecomment-4551334877

   A label of 'needs-attention' was automatically added to this PR in order to raise the
   attention of the committers. Once this issue has been triaged, the `triage` label
   should be removed to prevent this automation from happening again.


-- 
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: jira-unsubscribe@kafka.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] KAFKA-20490: Add transaction buffer framework [kafka]

Posted by "nicktelford (via GitHub)" <gi...@apache.org>.
nicktelford commented on PR #22323:
URL: https://github.com/apache/kafka/pull/22323#issuecomment-4485987155

   @bbejeck 


-- 
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: jira-unsubscribe@kafka.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] KAFKA-20490: Add transaction buffer framework [kafka]

Posted by "bbejeck (via GitHub)" <gi...@apache.org>.
bbejeck commented on code in PR #22323:
URL: https://github.com/apache/kafka/pull/22323#discussion_r3422582356


##########
streams/src/main/java/org/apache/kafka/streams/state/internals/AbstractTransactionBuffer.java:
##########
@@ -0,0 +1,172 @@
+/*
+ * 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.kafka.streams.state.internals;
+
+import java.util.NavigableMap;
+import java.util.Optional;
+import java.util.TreeMap;
+import java.util.concurrent.ConcurrentSkipListMap;
+import java.util.concurrent.locks.ReentrantReadWriteLock;
+
+/**
+ * Base class for {@link TransactionBuffer} implementations. Provides the shared two-layer
+ * staging design: a thread-safe {@link ConcurrentSkipListMap} for reads (any thread) and
+ * backend-specific write accumulation for atomic commit.
+ * <p>
+ * Point lookups ({@link #get(Comparable)}) are lock-free. Scan methods automatically detect the
+ * owner thread and use a lock-free fast path; non-owner threads acquire a read lock to
+ * snapshot the staging map atomically with base iterator creation.
+ *
+ * @param <K> the key type, must be {@link Comparable}
+ */
+abstract class AbstractTransactionBuffer<K extends Comparable<K>> implements TransactionBuffer<K> {
+
+    final ConcurrentSkipListMap<K, Optional<byte[]>> pendingWrites = new ConcurrentSkipListMap<>();
+    final ReentrantReadWriteLock snapshotLock = new ReentrantReadWriteLock();
+    final Thread ownerThread;
+    long pendingWritesBytes;
+
+    AbstractTransactionBuffer() {
+        this.ownerThread = Thread.currentThread();
+    }
+
+    // -- Abstract methods to be implemented by backend-specific subclasses --
+
+    /** Append the write to the backend-specific batch (e.g. WriteBatch for RocksDB). */
+    abstract void stageToBackend(K key, byte[] value);
+
+    /** Create a base store iterator for the given range. Upper bound is inclusive. Forward direction. */
+    abstract ManagedKeyValueIterator<K, byte[]> newBaseIterator(K from, K to);
+
+    /** Create a base store iterator with configurable direction and upper bound inclusiveness. */
+    ManagedKeyValueIterator<K, byte[]> newBaseIterator(final K from, final K to,
+                                                       final boolean forward, final boolean toInclusive) {
+        return newBaseIterator(from, to);
+    }
+
+    /** Atomically apply the accumulated writes to the base store. */
+    abstract void flushToBase();
+
+    /** Discard the backend-specific pending batch without applying it. */
+    abstract void discardPendingBatch();
+
+    /** Estimate the byte size of a key, for uncommitted bytes tracking. */
+    abstract int estimateKeySize(K key);
+
+    // -- TransactionBuffer implementation --
+
+    @Override
+    public void stage(final K key, final byte[] value) {
+        pendingWrites.put(key, Optional.ofNullable(value));
+        pendingWritesBytes += estimateKeySize(key) + (value != null ? value.length : 0);
+        stageToBackend(key, value);
+    }
+
+    @Override
+    public Optional<byte[]> get(final K key) {
+        return pendingWrites.get(key);
+    }
+
+    @Override
+    public ManagedKeyValueIterator<K, byte[]> all(final boolean forward) {
+        if (Thread.currentThread() == ownerThread) {
+            final ManagedKeyValueIterator<K, byte[]> baseIter = newBaseIterator(null, null, forward, true);
+            return new StagedMergeIterator<>(pendingWrites, baseIter, forward);
+        }
+        return snapshotScan(null, null, forward, true);
+    }
+
+    @Override
+    public ManagedKeyValueIterator<K, byte[]> range(final K from, final K to, final boolean forward, final boolean toInclusive) {
+        if (Thread.currentThread() == ownerThread) {
+            final ManagedKeyValueIterator<K, byte[]> baseIter = newBaseIterator(from, to, forward, toInclusive);
+            final NavigableMap<K, Optional<byte[]>> stagingView = boundStaging(from, to, toInclusive);

Review Comment:
   nit: If `forward == true` and `from` > `to` will throw an `IllegalArguemntException` and a new RocksDB iterator created above at line 96 could turn into a leak.  Let's swap the order of creation here and add a Javadoc comment about forward means from < to.



-- 
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: jira-unsubscribe@kafka.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org