aliehsaeedii commented on code in PR #24278:
URL: https://github.com/apache/kafka/pull/24278#discussion_r4601831812


##########
streams/src/test/java/org/apache/kafka/streams/state/internals/RocksDBTimeOrderedKeyValueBufferTest.java:
##########
@@ -112,6 +112,21 @@ public void shouldPutInBufferAndUpdateFields() {
         assertNumSizeAndTimestamp(buffer, 2, 0, 84);
     }
 
+    @Test
+    public void shouldBalanceSizeAfterEvictingRecordWithRawSourceBytes() {

Review Comment:
   This PR no longer changes buffer accounting, so this test (and 
`TimeOrderedKeyValueBufferTest#shouldBalanceSizeWhenEvictionReleasesRawSourceBytes`)
 passes on trunk and covers nothing here. Please drop both.



##########
streams/src/test/java/org/apache/kafka/streams/state/internals/TimeOrderedCachingPersistentWindowStoreTest.java:
##########
@@ -131,6 +133,84 @@ public void closeStore() {
         cachingStore.close();
     }
 
+    @ParameterizedTest
+    @ValueSource(booleans = {true, false})
+    public void 
shouldHandleOversizedRawPayloadReleasedDuringFlushAndSameKeyUpdates(final 
boolean hasIndex) {
+        setUp(hasIndex);
+        final List<byte[]> forwarded = new ArrayList<>();
+        cachingStore.setFlushListener(record -> {
+            forwarded.add(record.value().newValue);
+            context.recordContext().freeRawRecord();
+        }, true);
+        final Bytes key = bytesKey("key");
+        for (int i = 1; i <= 2; i++) {
+            context.setRecordContext(new 
ProcessorRecordContext(DEFAULT_TIMESTAMP, i, 0, TOPIC,
+                new RecordHeaders(), new byte[7], new 
byte[MAX_CACHE_SIZE_BYTES * 4]));
+            cachingStore.put(key, bytesValue("v" + i), DEFAULT_TIMESTAMP);
+            assertArrayEquals(bytesValue("v" + i), cachingStore.fetch(key, 
DEFAULT_TIMESTAMP));
+            assertTrue(cache.sizeBytes() >= 0 && cache.sizeBytes() <= 
MAX_CACHE_SIZE_BYTES);
+        }
+        cachingStore.commit(Map.of());
+        assertArrayEquals(bytesValue("v2"), underlyingStore.fetch(key, 
DEFAULT_TIMESTAMP));
+        assertFalse(forwarded.isEmpty());
+        assertArrayEquals(bytesValue("v2"), forwarded.get(forwarded.size() - 
1));
+        context.setRecordContext(new ProcessorRecordContext(DEFAULT_TIMESTAMP, 
3L, 0, TOPIC,
+            new RecordHeaders(), new byte[7], new byte[MAX_CACHE_SIZE_BYTES * 
4]));
+        cachingStore.put(key, null, DEFAULT_TIMESTAMP);
+        cachingStore.commit(Map.of());
+        assertNull(cachingStore.fetch(key, DEFAULT_TIMESTAMP));
+        assertNull(underlyingStore.fetch(key, DEFAULT_TIMESTAMP));
+        assertNull(forwarded.get(forwarded.size() - 1));
+        assertTrue(cache.evicts() > 0);
+        cachingStore.close();
+        assertEquals(0L, cache.sizeBytes());
+        assertEquals(0L, cache.size());
+    }
+
+    @ParameterizedTest
+    @ValueSource(booleans = {true, false})
+    public void 
shouldPreserveWindowResultsWithRawSourceBytesUnderSmallCacheBudget(final 
boolean hasIndex) {
+        setUp(hasIndex);
+        for (int i = 0; i < 8; i++) {
+            context.setRecordContext(new 
ProcessorRecordContext(DEFAULT_TIMESTAMP, i, 0, TOPIC,
+                new RecordHeaders(), new byte[7], new byte[128]));
+            cachingStore.put(bytesKey("k" + i), bytesValue("v" + i), 
DEFAULT_TIMESTAMP);
+            if (i == 0 && hasIndex) {

Review Comment:
   On your open question about the index entry: its raw bytes are never read, 
because flush looks up and forwards the base entry. So 
`TimeOrderedCachingWindowStore.put` can pass `null` raw key/value for the index 
`emptyEntry`. That removes both the double charge and the extra retention, and 
this assertion would go away.



##########
streams/src/test/java/org/apache/kafka/streams/state/internals/ThreadCacheRawRecordTest.java:
##########
@@ -0,0 +1,131 @@
+/*
+ * 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.header.internals.RecordHeaders;
+import org.apache.kafka.common.metrics.Metrics;
+import org.apache.kafka.common.utils.Bytes;
+import org.apache.kafka.common.utils.internals.LogContext;
+import org.apache.kafka.streams.processor.internals.MockStreamsMetrics;
+
+import org.junit.jupiter.api.Test;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertSame;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+class ThreadCacheRawRecordTest {
+    @Test
+    void shouldCountNullableAndEmptyRawArrays() {
+        final byte[] value = {1};
+        final long baseSize = new LRUCacheEntry(value, new RecordHeaders(), 
true,
+            0L, 0L, 0, "", null, null).size();
+        for (final byte[] rawKey : new byte[][] {null, new byte[0], new 
byte[7]}) {
+            for (final byte[] rawValue : new byte[][] {null, new byte[0], new 
byte[1024]}) {
+                final LRUCacheEntry entry = new LRUCacheEntry(value, new 
RecordHeaders(), true,
+                    0L, 0L, 0, "", rawKey, rawValue);
+                assertEquals(baseSize + (rawKey == null ? 0 : rawKey.length)
+                    + (rawValue == null ? 0 : rawValue.length), entry.size());
+            }
+        }
+    }
+
+    @Test
+    void shouldEvictWhenRawRecordsExceedBudget() {
+        final String namespace = "0.0-raw-record";
+        final long budget = 4096L;
+        try (final Metrics metrics = new Metrics()) {
+            final ThreadCache cache = new ThreadCache(new 
LogContext("testCache "),
+                budget, new MockStreamsMetrics(metrics));
+            cache.addDirtyEntryFlushListener(namespace, entries -> { });
+            for (int i = 0; i < 8; i++) {
+                cache.put(namespace, Bytes.wrap(new byte[] {(byte) i}),
+                    new LRUCacheEntry(new byte[1], new RecordHeaders(), true,
+                        i, i, 0, "", new byte[1], new byte[1024]));
+            }
+            // The transformed values are tiny, but each entry retains the 
source payload.
+            assertTrue(cache.evicts() > 0);
+            assertTrue(cache.sizeBytes() <= budget);
+            cache.close(namespace);
+            assertEquals(0L, cache.sizeBytes());
+        }
+    }
+
+    @Test
+    void 
shouldConservativelyCountSharedArraysAndBalanceReplacementAndDeletion() {
+        final byte[] shared = new byte[1024];
+        final Bytes first = Bytes.wrap(new byte[] {1});
+        final Bytes second = Bytes.wrap(new byte[] {2});
+        final String namespace = "0_0-shared";
+        try (final Metrics metrics = new Metrics()) {
+            final ThreadCache cache = new ThreadCache(new LogContext(), 
100_000L, new MockStreamsMetrics(metrics));
+            final LRUCacheEntry entry = new LRUCacheEntry(shared, new 
RecordHeaders(), true,
+                0L, 0L, 0, "", shared, shared);
+            final LRUCacheEntry withoutRaw = new LRUCacheEntry(shared, new 
RecordHeaders(), true,
+                0L, 0L, 0, "", null, null);
+            assertEquals(withoutRaw.size() + 2L * shared.length, entry.size());
+            cache.put(namespace, first, entry);
+            final long oneEntrySize = cache.sizeBytes();
+            final LRUCacheEntry otherEntry = new LRUCacheEntry(shared, new 
RecordHeaders(), true,
+                0L, 0L, 0, "", shared, shared);
+            cache.put(namespace, second, otherEntry);
+            assertEquals(2L * oneEntrySize, cache.sizeBytes());
+            cache.put(namespace, first, withoutRaw);
+            assertEquals(2L * oneEntrySize - 2L * shared.length, 
cache.sizeBytes());
+            cache.delete(namespace, first);
+            assertEquals(oneEntrySize, cache.sizeBytes());
+            // Accounting is a construction-time snapshot even if the raw 
references are released.
+            entry.context().freeRawRecord();
+            assertSame(shared, otherEntry.context().sourceRawValue());
+            otherEntry.context().freeRawRecord();
+            cache.delete(namespace, second);
+            assertEquals(0L, cache.sizeBytes());
+            cache.close(namespace);
+        }
+    }
+
+    @Test
+    void shouldKeepCleanRawReferencesWhenFlushListenerDoesNotReleaseThem() {
+        final byte[] raw = new byte[1024];
+        final Bytes key = Bytes.wrap(new byte[] {1});
+        final String namespace = "0_0-flush";
+        try (final Metrics metrics = new Metrics()) {
+            final ThreadCache cache = new ThreadCache(new LogContext(), 
100_000L, new MockStreamsMetrics(metrics));
+            final LRUCacheEntry entry = new LRUCacheEntry(new byte[] {7}, new 
RecordHeaders(), true,
+                0L, 0L, 0, "", null, raw);
+            final int[] forwarded = {0};
+            cache.addDirtyEntryFlushListener(namespace, entries -> {
+                forwarded[0] += entries.size();
+                assertSame(raw, 
entries.get(0).entry().context().sourceRawValue());
+            });
+            cache.put(namespace, key, entry);
+            final long beforeFlush = cache.sizeBytes();
+            cache.flush(namespace);
+            assertEquals(1, forwarded[0]);
+            assertFalse(entry.isDirty());
+            assertSame(raw, cache.get(namespace, 
key).context().sourceRawValue());

Review Comment:
   This pins that clean entries keep their raw bytes after flush, which is the 
retention the ticket complains about. I wouldn't lock that in. Keeping only the 
size assertion is enough.



##########
streams/src/test/java/org/apache/kafka/streams/state/internals/ThreadCacheTest.java:
##########
@@ -137,7 +137,7 @@ public void cacheOverheadsLargeValues() {
 
 
     static long memoryCacheEntrySize(final byte[] key, final byte[] value, 
final String topic) {
-        return key.length +
+        return 2 + // source raw key and value in the test fixtures

Review Comment:
   The hardcoded `2` only holds for this class's 1-byte raw fixtures. 
`CachingInMemoryKeyValueStoreTest`, `CachingPersistentWindowStoreTest`, 
`TimeOrderedWindowStoreTest` and `TimeOrderedCachingPersistentWindowStoreTest` 
also call this helper, and their entries have no raw bytes. Could you pass the 
raw lengths in as a parameter?



##########
streams/src/main/java/org/apache/kafka/streams/state/internals/LRUCacheEntry.java:
##########
@@ -61,7 +61,10 @@ class LRUCacheEntry {
 
         this.isDirty = isDirty;
         this.sizeBytes = 1 + // isDirty
-            record.residentMemorySizeEstimate();
+            record.residentMemorySizeEstimate() +
+            // Raw source arrays are retained by cache entries, but are not 
serialized with the context.
+            (rawKey == null ? 0 : rawKey.length) +
+            (rawValue == null ? 0 : rawValue.length);

Review Comment:
   Clean entries are never forwarded again, so they don't need the raw bytes 
after a flush. Could `NamedCache.flush` free them and subtract their size once 
the listener returns? Otherwise, with large inputs, the read cache stays mostly 
charged for dead bytes after every commit. A sink that frees the shared context 
also leaves bytes charged that are already gone.



##########
streams/src/test/java/org/apache/kafka/streams/state/internals/ThreadCacheRawRecordTest.java:
##########
@@ -0,0 +1,131 @@
+/*
+ * 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.header.internals.RecordHeaders;
+import org.apache.kafka.common.metrics.Metrics;
+import org.apache.kafka.common.utils.Bytes;
+import org.apache.kafka.common.utils.internals.LogContext;
+import org.apache.kafka.streams.processor.internals.MockStreamsMetrics;
+
+import org.junit.jupiter.api.Test;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertSame;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+class ThreadCacheRawRecordTest {
+    @Test
+    void shouldCountNullableAndEmptyRawArrays() {
+        final byte[] value = {1};
+        final long baseSize = new LRUCacheEntry(value, new RecordHeaders(), 
true,
+            0L, 0L, 0, "", null, null).size();
+        for (final byte[] rawKey : new byte[][] {null, new byte[0], new 
byte[7]}) {
+            for (final byte[] rawValue : new byte[][] {null, new byte[0], new 
byte[1024]}) {
+                final LRUCacheEntry entry = new LRUCacheEntry(value, new 
RecordHeaders(), true,
+                    0L, 0L, 0, "", rawKey, rawValue);
+                assertEquals(baseSize + (rawKey == null ? 0 : rawKey.length)
+                    + (rawValue == null ? 0 : rawValue.length), entry.size());
+            }
+        }
+    }
+
+    @Test
+    void shouldEvictWhenRawRecordsExceedBudget() {
+        final String namespace = "0.0-raw-record";
+        final long budget = 4096L;
+        try (final Metrics metrics = new Metrics()) {
+            final ThreadCache cache = new ThreadCache(new 
LogContext("testCache "),
+                budget, new MockStreamsMetrics(metrics));
+            cache.addDirtyEntryFlushListener(namespace, entries -> { });
+            for (int i = 0; i < 8; i++) {
+                cache.put(namespace, Bytes.wrap(new byte[] {(byte) i}),
+                    new LRUCacheEntry(new byte[1], new RecordHeaders(), true,
+                        i, i, 0, "", new byte[1], new byte[1024]));
+            }
+            // The transformed values are tiny, but each entry retains the 
source payload.
+            assertTrue(cache.evicts() > 0);
+            assertTrue(cache.sizeBytes() <= budget);
+            cache.close(namespace);
+            assertEquals(0L, cache.sizeBytes());
+        }
+    }
+
+    @Test
+    void 
shouldConservativelyCountSharedArraysAndBalanceReplacementAndDeletion() {
+        final byte[] shared = new byte[1024];
+        final Bytes first = Bytes.wrap(new byte[] {1});
+        final Bytes second = Bytes.wrap(new byte[] {2});
+        final String namespace = "0_0-shared";
+        try (final Metrics metrics = new Metrics()) {
+            final ThreadCache cache = new ThreadCache(new LogContext(), 
100_000L, new MockStreamsMetrics(metrics));
+            final LRUCacheEntry entry = new LRUCacheEntry(shared, new 
RecordHeaders(), true,
+                0L, 0L, 0, "", shared, shared);
+            final LRUCacheEntry withoutRaw = new LRUCacheEntry(shared, new 
RecordHeaders(), true,
+                0L, 0L, 0, "", null, null);
+            assertEquals(withoutRaw.size() + 2L * shared.length, entry.size());
+            cache.put(namespace, first, entry);
+            final long oneEntrySize = cache.sizeBytes();
+            final LRUCacheEntry otherEntry = new LRUCacheEntry(shared, new 
RecordHeaders(), true,
+                0L, 0L, 0, "", shared, shared);
+            cache.put(namespace, second, otherEntry);
+            assertEquals(2L * oneEntrySize, cache.sizeBytes());
+            cache.put(namespace, first, withoutRaw);
+            assertEquals(2L * oneEntrySize - 2L * shared.length, 
cache.sizeBytes());
+            cache.delete(namespace, first);
+            assertEquals(oneEntrySize, cache.sizeBytes());
+            // Accounting is a construction-time snapshot even if the raw 
references are released.
+            entry.context().freeRawRecord();
+            assertSame(shared, otherEntry.context().sourceRawValue());

Review Comment:
   `entry` was already replaced in the cache at line 89, so freeing it here 
doesn't touch the cache, and the `assertSame` only tests 
`ProcessorRecordContext`. Please drop these two lines. The `otherEntry` free 
and delete below are worth keeping.



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