Copilot commented on code in PR #24260:
URL: https://github.com/apache/kafka/pull/24260#discussion_r4589318965


##########
streams/src/main/java/org/apache/kafka/streams/state/internals/InMemoryTimeOrderedKeyValueChangeBuffer.java:
##########
@@ -441,93 +443,96 @@ private void restoreBatch(final 
Collection<ConsumerRecord<byte[], byte[]>> batch
     @Override
     public void evictWhile(final Supplier<Boolean> predicate,
                            final Consumer<Eviction<K, Change<V>>> callback) {
-        final Iterator<Map.Entry<BufferKey, BufferValue>> delegate = 
sortedMap.entrySet().iterator();
-        int evictions = 0;
-
-        if (predicate.get()) {
-            Map.Entry<BufferKey, BufferValue> next = null;
-            if (delegate.hasNext()) {
-                next = delegate.next();
-            }
+        final Iterator<Map.Entry<BufferKey, BufferValue>> iterator = 
sortedMap.entrySet().iterator();
+        // The callback may re-enter this buffer, so it must not run while we 
iterate over sortedMap. We therefore
+        // only deserialize and remove the entries (through the iterator) 
inside the loop, and invoke the callback
+        // afterwards. Deserializing before removing means an entry that fails 
to deserialize stays buffered.
+        final List<Eviction<K, Change<V>>> evictions = new ArrayList<>();
+
+        try {
+            while (iterator.hasNext()) {
+                if (!predicate.get()) {
+                    break;
+                }
 
-            // predicate being true means we read one record, call the 
callback, and then remove it
-            while (next != null && predicate.get()) {
-                if (next.getKey().time() != minTimestamp) {
+                final Map.Entry<BufferKey, BufferValue> next = iterator.next();
+                if (evictions.isEmpty() && next.getKey().time() != 
minTimestamp) {
                     throw new IllegalStateException(
                         "minTimestamp [" + minTimestamp + "] did not match the 
actual min timestamp [" +
                             next.getKey().time() + "]"
                     );
                 }
+                final Bytes serializedKey = next.getKey().key();
                 final BufferValue bufferValue = next.getValue();
-                final ProcessorRecordContext bufferedContext = 
bufferValue.context();
-
-                final K key;
-                final Change<V> value;
-                final ProcessorRecordContext evictionContext;
-                if (storeHeaders) {
-                    // Each value part was stored as a ValueTimestampHeaders 
blob carrying the headers of
-                    // the record it originated from, so take them from the 
value rather than from the
-                    // buffered context: the old value came from an earlier 
record than the new one, and
-                    // deserializing it with the new record's headers would 
hand the serde the wrong ones.
-                    // (ValueTimestampHeadersDeserializer feeds each part's 
own headers to the inner
-                    // value deserializer.)
-                    final ValueTimestampHeaders<V> newPart = 
deserializeValueTimestampHeaders(bufferValue.newValue());
-                    final ValueTimestampHeaders<V> oldPart = 
deserializeValueTimestampHeaders(bufferValue.oldValue());
-                    // A tombstone has no new value to take headers from; fall 
back to the buffered context.
-                    // That fallback is not a second-best guess: the buffered 
context and the new value's
-                    // embedded headers always agree. put() hands the very 
same record.headers() instance to
-                    // both, and ValueTimestampHeadersSerializer snapshots the 
headers only AFTER running the
-                    // inner value serializer, so even a serde that writes 
into the headers it is given (a
-                    // Schema Registry serde recording the schema id, say) is 
reflected in both. Restoring
-                    // preserves the equality, because toInMemoryEncoding 
rebuilds the new part from that
-                    // same context. Only the old and prior parts can differ 
from the context, which is why
-                    // they are the ones read from the value here.
-                    final Headers newHeaders = newPart == null ? 
bufferedContext.headers() : newPart.headers();
-                    key = keySerde.deserializer().deserialize(changelogTopic, 
newHeaders, next.getKey().key().get());
-                    value = new Change<>(
-                        ValueTimestampHeaders.getValueOrNull(newPart),
-                        ValueTimestampHeaders.getValueOrNull(oldPart)
-                    );
-                    // The emitted record carries the new value's headers, so 
hand them to the callback
-                    // via the eviction's context (which is what the suppress 
processor forwards).
-                    evictionContext = withHeaders(bufferedContext, newHeaders);
-                } else {
-                    // Plain values store no headers of their own; the 
buffered context is the only
-                    // carrier, exactly as before.
-                    final Headers headers = bufferedContext.headers();
-                    key = keySerde.deserializer().deserialize(changelogTopic, 
headers, next.getKey().key().get());
-                    value = new Change<>(
-                        deserializeValue(bufferValue.newValue(), headers),
-                        deserializeValue(bufferValue.oldValue(), headers)
-                    );
-                    evictionContext = bufferedContext;
-                }
-                callback.accept(new Eviction<K, Change<V>>(key, value, 
evictionContext));
-
-                delegate.remove();
-                index.remove(next.getKey().key());
+                evictions.add(toEviction(serializedKey, bufferValue));
 
                 if (loggingEnabled) {
-                    dirtyKeys.add(next.getKey().key());
+                    dirtyKeys.add(serializedKey);
                 }
 
-                memBufferSize -= computeRecordSize(next.getKey().key(), 
bufferValue);
-
-                // peek at the next record so we can update the minTimestamp
-                if (delegate.hasNext()) {
-                    next = delegate.next();
-                    minTimestamp = next == null ? Long.MAX_VALUE : 
next.getKey().time();
-                } else {
-                    next = null;
-                    minTimestamp = Long.MAX_VALUE;
-                }
+                memBufferSize -= computeRecordSize(serializedKey, bufferValue);
 
-                evictions++;
+                iterator.remove();
+                index.remove(serializedKey);
+                // the predicate (e.g. minTimestamp() or bufferSize()) is 
re-evaluated on the next iteration
+                minTimestamp = sortedMap.isEmpty() ? Long.MAX_VALUE : 
sortedMap.firstKey().time();
+            }
+        } finally {
+            // also hand over what was already removed if a later entry 
failed, so no evicted record is lost
+            if (!evictions.isEmpty()) {
+                updateBufferMetrics();
+            }
+            for (final Eviction<K, Change<V>> eviction : evictions) {
+                callback.accept(eviction);
             }

Review Comment:
   With callbacks executed after removals, a callback that throws will leave 
the buffer already mutated (entries removed and `memBufferSize` decremented), 
and will also prevent later callbacks from running. Previously, callback 
execution happened before `remove()`, so an exception could prevent removal of 
the current entry. Consider guarding callback execution so that one failing 
callback doesn’t suppress subsequent callbacks (e.g., catch, store the first 
exception, continue invoking remaining callbacks, then rethrow), and 
document/align the intended semantics regarding whether evictions are applied 
if the callback fails.



##########
streams/src/main/java/org/apache/kafka/streams/state/internals/InMemoryTimeOrderedKeyValueChangeBuffer.java:
##########
@@ -441,93 +443,96 @@ private void restoreBatch(final 
Collection<ConsumerRecord<byte[], byte[]>> batch
     @Override
     public void evictWhile(final Supplier<Boolean> predicate,
                            final Consumer<Eviction<K, Change<V>>> callback) {
-        final Iterator<Map.Entry<BufferKey, BufferValue>> delegate = 
sortedMap.entrySet().iterator();
-        int evictions = 0;
-
-        if (predicate.get()) {
-            Map.Entry<BufferKey, BufferValue> next = null;
-            if (delegate.hasNext()) {
-                next = delegate.next();
-            }
+        final Iterator<Map.Entry<BufferKey, BufferValue>> iterator = 
sortedMap.entrySet().iterator();
+        // The callback may re-enter this buffer, so it must not run while we 
iterate over sortedMap. We therefore
+        // only deserialize and remove the entries (through the iterator) 
inside the loop, and invoke the callback
+        // afterwards. Deserializing before removing means an entry that fails 
to deserialize stays buffered.
+        final List<Eviction<K, Change<V>>> evictions = new ArrayList<>();
+
+        try {
+            while (iterator.hasNext()) {
+                if (!predicate.get()) {
+                    break;
+                }
 
-            // predicate being true means we read one record, call the 
callback, and then remove it
-            while (next != null && predicate.get()) {
-                if (next.getKey().time() != minTimestamp) {
+                final Map.Entry<BufferKey, BufferValue> next = iterator.next();
+                if (evictions.isEmpty() && next.getKey().time() != 
minTimestamp) {
                     throw new IllegalStateException(
                         "minTimestamp [" + minTimestamp + "] did not match the 
actual min timestamp [" +
                             next.getKey().time() + "]"
                     );
                 }

Review Comment:
   The `minTimestamp` invariant check was previously performed for each evicted 
record, but is now only checked for the first eviction (`evictions.isEmpty()`). 
This weakens an internal consistency check and could make future regressions 
harder to diagnose. Consider restoring the check on every iteration (or adding 
an equivalent assertion) so inconsistencies are caught as early as before.



##########
streams/src/main/java/org/apache/kafka/streams/state/internals/InMemoryTimeOrderedKeyValueChangeBuffer.java:
##########
@@ -441,93 +443,96 @@ private void restoreBatch(final 
Collection<ConsumerRecord<byte[], byte[]>> batch
     @Override
     public void evictWhile(final Supplier<Boolean> predicate,
                            final Consumer<Eviction<K, Change<V>>> callback) {
-        final Iterator<Map.Entry<BufferKey, BufferValue>> delegate = 
sortedMap.entrySet().iterator();
-        int evictions = 0;
-
-        if (predicate.get()) {
-            Map.Entry<BufferKey, BufferValue> next = null;
-            if (delegate.hasNext()) {
-                next = delegate.next();
-            }
+        final Iterator<Map.Entry<BufferKey, BufferValue>> iterator = 
sortedMap.entrySet().iterator();
+        // The callback may re-enter this buffer, so it must not run while we 
iterate over sortedMap. We therefore
+        // only deserialize and remove the entries (through the iterator) 
inside the loop, and invoke the callback
+        // afterwards. Deserializing before removing means an entry that fails 
to deserialize stays buffered.
+        final List<Eviction<K, Change<V>>> evictions = new ArrayList<>();
+
+        try {
+            while (iterator.hasNext()) {
+                if (!predicate.get()) {
+                    break;
+                }
 
-            // predicate being true means we read one record, call the 
callback, and then remove it
-            while (next != null && predicate.get()) {
-                if (next.getKey().time() != minTimestamp) {
+                final Map.Entry<BufferKey, BufferValue> next = iterator.next();
+                if (evictions.isEmpty() && next.getKey().time() != 
minTimestamp) {
                     throw new IllegalStateException(
                         "minTimestamp [" + minTimestamp + "] did not match the 
actual min timestamp [" +
                             next.getKey().time() + "]"
                     );
                 }
+                final Bytes serializedKey = next.getKey().key();
                 final BufferValue bufferValue = next.getValue();
-                final ProcessorRecordContext bufferedContext = 
bufferValue.context();
-
-                final K key;
-                final Change<V> value;
-                final ProcessorRecordContext evictionContext;
-                if (storeHeaders) {
-                    // Each value part was stored as a ValueTimestampHeaders 
blob carrying the headers of
-                    // the record it originated from, so take them from the 
value rather than from the
-                    // buffered context: the old value came from an earlier 
record than the new one, and
-                    // deserializing it with the new record's headers would 
hand the serde the wrong ones.
-                    // (ValueTimestampHeadersDeserializer feeds each part's 
own headers to the inner
-                    // value deserializer.)
-                    final ValueTimestampHeaders<V> newPart = 
deserializeValueTimestampHeaders(bufferValue.newValue());
-                    final ValueTimestampHeaders<V> oldPart = 
deserializeValueTimestampHeaders(bufferValue.oldValue());
-                    // A tombstone has no new value to take headers from; fall 
back to the buffered context.
-                    // That fallback is not a second-best guess: the buffered 
context and the new value's
-                    // embedded headers always agree. put() hands the very 
same record.headers() instance to
-                    // both, and ValueTimestampHeadersSerializer snapshots the 
headers only AFTER running the
-                    // inner value serializer, so even a serde that writes 
into the headers it is given (a
-                    // Schema Registry serde recording the schema id, say) is 
reflected in both. Restoring
-                    // preserves the equality, because toInMemoryEncoding 
rebuilds the new part from that
-                    // same context. Only the old and prior parts can differ 
from the context, which is why
-                    // they are the ones read from the value here.
-                    final Headers newHeaders = newPart == null ? 
bufferedContext.headers() : newPart.headers();
-                    key = keySerde.deserializer().deserialize(changelogTopic, 
newHeaders, next.getKey().key().get());
-                    value = new Change<>(
-                        ValueTimestampHeaders.getValueOrNull(newPart),
-                        ValueTimestampHeaders.getValueOrNull(oldPart)
-                    );
-                    // The emitted record carries the new value's headers, so 
hand them to the callback
-                    // via the eviction's context (which is what the suppress 
processor forwards).
-                    evictionContext = withHeaders(bufferedContext, newHeaders);
-                } else {
-                    // Plain values store no headers of their own; the 
buffered context is the only
-                    // carrier, exactly as before.
-                    final Headers headers = bufferedContext.headers();
-                    key = keySerde.deserializer().deserialize(changelogTopic, 
headers, next.getKey().key().get());
-                    value = new Change<>(
-                        deserializeValue(bufferValue.newValue(), headers),
-                        deserializeValue(bufferValue.oldValue(), headers)
-                    );
-                    evictionContext = bufferedContext;
-                }
-                callback.accept(new Eviction<K, Change<V>>(key, value, 
evictionContext));
-
-                delegate.remove();
-                index.remove(next.getKey().key());
+                evictions.add(toEviction(serializedKey, bufferValue));
 
                 if (loggingEnabled) {
-                    dirtyKeys.add(next.getKey().key());
+                    dirtyKeys.add(serializedKey);
                 }
 
-                memBufferSize -= computeRecordSize(next.getKey().key(), 
bufferValue);
-
-                // peek at the next record so we can update the minTimestamp
-                if (delegate.hasNext()) {
-                    next = delegate.next();
-                    minTimestamp = next == null ? Long.MAX_VALUE : 
next.getKey().time();
-                } else {
-                    next = null;
-                    minTimestamp = Long.MAX_VALUE;
-                }
+                memBufferSize -= computeRecordSize(serializedKey, bufferValue);
 
-                evictions++;
+                iterator.remove();
+                index.remove(serializedKey);
+                // the predicate (e.g. minTimestamp() or bufferSize()) is 
re-evaluated on the next iteration
+                minTimestamp = sortedMap.isEmpty() ? Long.MAX_VALUE : 
sortedMap.firstKey().time();
+            }

Review Comment:
   `minTimestamp` is recomputed each iteration via `sortedMap.firstKey()`, 
which is typically O(log N) on `TreeMap`-like structures. In large evictions, 
this adds avoidable overhead. Consider restructuring the loop to maintain/peek 
the next entry’s timestamp without performing a map lookup each time (similar 
to the previous implementation that advanced/peeked the iterator), while still 
keeping callbacks deferred.



-- 
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]

Reply via email to