aliehsaeedii commented on code in PR #22992: URL: https://github.com/apache/kafka/pull/22992#discussion_r4566859135
########## streams/src/test/java/org/apache/kafka/streams/state/internals/TimestampedToHeadersWindowStoreAdapterDelegationTest.java: ########## @@ -0,0 +1,178 @@ +/* + * 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.kstream.Windowed; +import org.apache.kafka.streams.kstream.internals.TimeWindow; +import org.apache.kafka.streams.state.KeyValueIterator; +import org.apache.kafka.streams.state.TimestampedBytesStore; +import org.apache.kafka.streams.state.WindowStore; +import org.apache.kafka.streams.state.WindowStoreIterator; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Named; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; +import org.mockito.junit.jupiter.MockitoSettings; +import org.mockito.quality.Strictness; + +import java.time.Instant; +import java.util.function.Function; +import java.util.stream.Stream; + +import static org.apache.kafka.streams.state.HeadersBytesStore.convertToHeaderFormat; +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +/** + * Method-level coverage of {@link TimestampedToHeadersWindowStoreAdapter} over a mocked inner store: reads + * convert/wrap, put strips headers. Strict stubs make a call to the wrong inner overload fail the test + * instead of returning {@code null}. See {@link TimestampedToHeadersWindowStoreAdapterCompletenessTest} + * for the completeness guard and {@link TimestampedToHeadersWindowStoreAdapterTest} for coverage against a + * real RocksDB store. + */ +@ExtendWith(MockitoExtension.class) +@MockitoSettings(strictness = Strictness.STRICT_STUBS) +public class TimestampedToHeadersWindowStoreAdapterDelegationTest { + + private static final Bytes KEY = Bytes.wrap("key".getBytes()); + private static final Bytes KEY_TO = Bytes.wrap("key-to".getBytes()); + private static final Windowed<Bytes> WINDOWED_KEY = new Windowed<>(KEY, new TimeWindow(0L, 10L)); + private static final long WINDOW_START = 5L; + // [8-byte timestamp][value], the format of the timestamped inner store + private static final byte[] RAW_VALUE = new byte[] {0, 0, 0, 0, 0, 0, 0, 42, 'v', 'a', 'l'}; + private static final Instant T_FROM = Instant.ofEpochMilli(0L); + private static final Instant T_TO = Instant.ofEpochMilli(10L); + + @Mock(extraInterfaces = TimestampedBytesStore.class) + private WindowStore<Bytes, byte[]> inner; + + private TimestampedToHeadersWindowStoreAdapter adapter; + + @BeforeEach + public void setUp() { + when(inner.persistent()).thenReturn(true); + adapter = new TimestampedToHeadersWindowStoreAdapter(inner); + } + + @Test + public void shouldStripHeadersOnPut() { + adapter.put(KEY, convertToHeaderFormat(RAW_VALUE), WINDOW_START); + verify(inner).put(KEY, RAW_VALUE, WINDOW_START); + } + + @Test + public void shouldConvertFetchByKeyAndTimestampToHeaderFormat() { + when(inner.fetch(KEY, WINDOW_START)).thenReturn(RAW_VALUE); + assertArrayEquals(convertToHeaderFormat(RAW_VALUE), adapter.fetch(KEY, WINDOW_START)); + } + + @Test + public void shouldReturnNullWhenFetchByKeyAndTimestampReturnsNull() { + when(inner.fetch(KEY, WINDOW_START)).thenReturn(null); + assertNull(adapter.fetch(KEY, WINDOW_START)); + } + + // Each call is applied to the inner store to stub it and to the adapter to exercise it, so the + // adapter must forward to the same overload with the same arguments. + private static Stream<Arguments> windowStoreIteratorCalls() { + return Stream.of( + call("fetch(key, long, long)", s -> s.fetch(KEY, 0L, 10L)), + call("fetch(key, Instant, Instant)", s -> s.fetch(KEY, T_FROM, T_TO)), + call("backwardFetch(key, long, long)", s -> s.backwardFetch(KEY, 0L, 10L)), + call("backwardFetch(key, Instant, Instant)", s -> s.backwardFetch(KEY, T_FROM, T_TO)) + ); + } + + @ParameterizedTest(name = "{0}") + @MethodSource("windowStoreIteratorCalls") + public void shouldConvertWindowStoreIteratorValues( + final Function<WindowStore<Bytes, byte[]>, WindowStoreIterator<byte[]>> call) { + @SuppressWarnings("unchecked") + final WindowStoreIterator<byte[]> innerIterator = mock(WindowStoreIterator.class); + when(innerIterator.next()).thenReturn(KeyValue.pair(WINDOW_START, RAW_VALUE)); + when(call.apply(inner)).thenReturn(innerIterator); + + final KeyValue<Long, byte[]> next = call.apply(adapter).next(); + + assertEquals(WINDOW_START, next.key); + assertArrayEquals(convertToHeaderFormat(RAW_VALUE), next.value); + } + + private static Stream<Arguments> keyValueIteratorCalls() { + return Stream.of( + call("fetch(keyFrom, keyTo, long, long)", s -> s.fetch(KEY, KEY_TO, 0L, 10L)), + call("fetch(keyFrom, keyTo, Instant, Instant)", s -> s.fetch(KEY, KEY_TO, T_FROM, T_TO)), + call("backwardFetch(keyFrom, keyTo, long, long)", s -> s.backwardFetch(KEY, KEY_TO, 0L, 10L)), + call("backwardFetch(keyFrom, keyTo, Instant, Instant)", s -> s.backwardFetch(KEY, KEY_TO, T_FROM, T_TO)), + call("fetchAll(long, long)", s -> s.fetchAll(0L, 10L)), + call("fetchAll(Instant, Instant)", s -> s.fetchAll(T_FROM, T_TO)), + call("backwardFetchAll(long, long)", s -> s.backwardFetchAll(0L, 10L)), + call("backwardFetchAll(Instant, Instant)", s -> s.backwardFetchAll(T_FROM, T_TO)), + call("all()", WindowStore::all), + call("backwardAll()", WindowStore::backwardAll) + ); + } + + @ParameterizedTest(name = "{0}") + @MethodSource("keyValueIteratorCalls") + public void shouldConvertKeyValueIteratorValues( + final Function<WindowStore<Bytes, byte[]>, KeyValueIterator<Windowed<Bytes>, byte[]>> call) { + @SuppressWarnings("unchecked") + final KeyValueIterator<Windowed<Bytes>, byte[]> innerIterator = mock(KeyValueIterator.class); + when(innerIterator.next()).thenReturn(KeyValue.pair(WINDOWED_KEY, RAW_VALUE)); + when(call.apply(inner)).thenReturn(innerIterator); + + final KeyValue<Windowed<Bytes>, byte[]> next = call.apply(adapter).next(); + + assertEquals(WINDOWED_KEY, next.key); + assertArrayEquals(convertToHeaderFormat(RAW_VALUE), next.value); + } + + @Test + public void shouldDelegateName() { Review Comment: Essential: `commit`, `managesOffsets`, `committedOffset`, `approximateNumUncommittedBytes`, `getPosition` and `close` have no test for this adapter, so an override that stops delegating (e.g. an empty `commit`) still passes everything. Please add a delegation check for each. `SessionToHeadersStoreAdapterTest` has the same gap for the first five. ########## streams/src/test/java/org/apache/kafka/streams/state/internals/TimestampedToHeadersWindowStoreAdapterCompletenessTest.java: ########## @@ -0,0 +1,141 @@ +/* + * 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.state.WindowStore; + +import org.junit.jupiter.api.Test; + +import java.lang.reflect.Method; +import java.lang.reflect.Modifier; +import java.util.Arrays; +import java.util.Set; +import java.util.TreeSet; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +import static org.junit.jupiter.api.Assertions.assertTrue; + +/** + * Requires every {@link WindowStore} method to be classified into a contract group, and every non-special + * method to be overridden by {@link TimestampedToHeadersWindowStoreAdapter}, so a header-aware override + * that is silently dropped (returning raw bytes) fails this test rather than escaping to manual testing + * (KAFKA-20328). Behavioral assertions live in {@link TimestampedToHeadersWindowStoreAdapterDelegationTest} + * and {@link TimestampedToHeadersWindowStoreAdapterTest}. + * <p> + * Signatures use erased parameter types, so a key ({@code K}) or value ({@code V}) appears as {@code Object}. + */ +public class TimestampedToHeadersWindowStoreAdapterCompletenessTest { + + private static final Set<String> VALUE_CONVERTING = Set.of( + "fetch(Object,long)" + ); + + private static final Set<String> ITERATOR_WRAPPING = Set.of( + "fetch(Object,long,long)", + "fetch(Object,Instant,Instant)", + "backwardFetch(Object,long,long)", + "backwardFetch(Object,Instant,Instant)", + "fetch(Object,Object,long,long)", + "fetch(Object,Object,Instant,Instant)", + "backwardFetch(Object,Object,long,long)", + "backwardFetch(Object,Object,Instant,Instant)", + "fetchAll(long,long)", + "fetchAll(Instant,Instant)", + "backwardFetchAll(long,long)", + "backwardFetchAll(Instant,Instant)", + "all()", + "backwardAll()" + ); + + private static final Set<String> HEADER_STRIPPING = Set.of( + "put(Object,Object,long)" + ); + + private static final Set<String> DELEGATING = Set.of( + "name()", + "init(StateStoreContext,StateStore)", + "commit(Map)", + "managesOffsets()", + "committedOffset(TopicPartition)", + "approximateNumUncommittedBytes()", + "close()", + "persistent()", + "isOpen()", + "getPosition()" + ); + + // query has bespoke iterator wrapping; flush is a deprecated no-op; readOnly returns `this`. + private static final Set<String> SPECIAL = Set.of( + "query(Query,PositionBound,QueryConfig)", + "flush()", + "readOnly(IsolationLevel)" Review Comment: Essential: `readOnly` is not a harmless default here. `RocksDBWindowStore` overrides it so that READ_COMMITTED hides staged writes, but this adapter inherits the default that returns `this`, so a READ_COMMITTED read through the adapter still sees uncommitted data. The same applies to `SessionToHeadersStoreAdapter` vs `RocksDBSessionStore`. I opened [KAFKA-21505](https://issues.apache.org/jira/browse/KAFKA-21505) for it. Could you reference it in the `SPECIAL` comment here (and in the session test), so `readOnly` is dropped from `SPECIAL` once it's fixed? ########## streams/src/test/java/org/apache/kafka/streams/state/internals/TimestampedToHeadersWindowStoreAdapterCompletenessTest.java: ########## @@ -0,0 +1,141 @@ +/* + * 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.state.WindowStore; + +import org.junit.jupiter.api.Test; + +import java.lang.reflect.Method; +import java.lang.reflect.Modifier; +import java.util.Arrays; +import java.util.Set; +import java.util.TreeSet; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +import static org.junit.jupiter.api.Assertions.assertTrue; + +/** + * Requires every {@link WindowStore} method to be classified into a contract group, and every non-special + * method to be overridden by {@link TimestampedToHeadersWindowStoreAdapter}, so a header-aware override + * that is silently dropped (returning raw bytes) fails this test rather than escaping to manual testing + * (KAFKA-20328). Behavioral assertions live in {@link TimestampedToHeadersWindowStoreAdapterDelegationTest} + * and {@link TimestampedToHeadersWindowStoreAdapterTest}. + * <p> + * Signatures use erased parameter types, so a key ({@code K}) or value ({@code V}) appears as {@code Object}. + */ +public class TimestampedToHeadersWindowStoreAdapterCompletenessTest { + + private static final Set<String> VALUE_CONVERTING = Set.of( + "fetch(Object,long)" + ); + + private static final Set<String> ITERATOR_WRAPPING = Set.of( + "fetch(Object,long,long)", + "fetch(Object,Instant,Instant)", + "backwardFetch(Object,long,long)", + "backwardFetch(Object,Instant,Instant)", + "fetch(Object,Object,long,long)", + "fetch(Object,Object,Instant,Instant)", + "backwardFetch(Object,Object,long,long)", + "backwardFetch(Object,Object,Instant,Instant)", + "fetchAll(long,long)", + "fetchAll(Instant,Instant)", + "backwardFetchAll(long,long)", + "backwardFetchAll(Instant,Instant)", + "all()", + "backwardAll()" + ); + + private static final Set<String> HEADER_STRIPPING = Set.of( + "put(Object,Object,long)" + ); + + private static final Set<String> DELEGATING = Set.of( + "name()", + "init(StateStoreContext,StateStore)", + "commit(Map)", + "managesOffsets()", + "committedOffset(TopicPartition)", + "approximateNumUncommittedBytes()", + "close()", + "persistent()", + "isOpen()", + "getPosition()" + ); + + // query has bespoke iterator wrapping; flush is a deprecated no-op; readOnly returns `this`. + private static final Set<String> SPECIAL = Set.of( + "query(Query,PositionBound,QueryConfig)", + "flush()", + "readOnly(IsolationLevel)" + ); + + @Test + public void everyWindowStoreMethodMustBeClassified() { + final Set<String> classified = Stream.of( + VALUE_CONVERTING, ITERATOR_WRAPPING, HEADER_STRIPPING, DELEGATING, SPECIAL) + .flatMap(Set::stream) + .collect(Collectors.toSet()); + + final Set<String> unclassified = Arrays.stream(WindowStore.class.getMethods()) + .filter(m -> !m.isSynthetic()) + .filter(m -> !Modifier.isStatic(m.getModifiers())) + .map(TimestampedToHeadersWindowStoreAdapterCompletenessTest::signature) + .filter(sig -> !classified.contains(sig)) + .collect(Collectors.toCollection(TreeSet::new)); + + assertTrue(unclassified.isEmpty(), + "Unclassified WindowStore method(s): " + unclassified + ". Add each to a contract group in " + + "this test AND cover it with a behavioral test in TimestampedToHeadersWindowStoreAdapterDelegationTest, " + + "so a forgotten header conversion cannot leak raw bytes silently."); + } + + @Test + public void everyNonSpecialMethodMustBeOverriddenByAdapter() { + final Set<String> notOverridden = Arrays.stream(WindowStore.class.getMethods()) + .filter(m -> !m.isSynthetic()) + .filter(m -> !Modifier.isStatic(m.getModifiers())) + .filter(m -> !SPECIAL.contains(signature(m))) + .filter(m -> !isOverriddenByAdapter(m)) + .map(TimestampedToHeadersWindowStoreAdapterCompletenessTest::signature) + .collect(Collectors.toCollection(TreeSet::new)); + + assertTrue(notOverridden.isEmpty(), + "WindowStore method(s) not overridden by TimestampedToHeadersWindowStoreAdapter: " + notOverridden + + ". The inherited default would return the inner store's raw bytes without header conversion."); Review Comment: Nice-to-have: a dropped override can't leak raw bytes, because an interface default can't reach the inner store. It either throws `UnsupportedOperationException` (the `backward*` methods) or silently stops delegating (e.g. `commit` turns into a no-op). Please reword this message and the class javadoc, here and in the session test. ########## streams/src/test/java/org/apache/kafka/streams/processor/internals/AbstractReadOnlyDecoratorTest.java: ########## @@ -0,0 +1,115 @@ +/* + * 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.processor.internals; + +import org.apache.kafka.streams.processor.StateStore; +import org.apache.kafka.streams.processor.internals.AbstractReadOnlyDecorator.KeyValueStoreReadOnlyDecorator; +import org.apache.kafka.streams.processor.internals.AbstractReadOnlyDecorator.SessionStoreReadOnlyDecorator; +import org.apache.kafka.streams.processor.internals.AbstractReadOnlyDecorator.TimestampedKeyValueStoreReadOnlyDecorator; +import org.apache.kafka.streams.processor.internals.AbstractReadOnlyDecorator.TimestampedKeyValueStoreReadOnlyDecoratorWithHeaders; +import org.apache.kafka.streams.processor.internals.AbstractReadOnlyDecorator.TimestampedWindowStoreReadOnlyDecorator; +import org.apache.kafka.streams.processor.internals.AbstractReadOnlyDecorator.VersionedKeyValueStoreReadOnlyDecorator; +import org.apache.kafka.streams.processor.internals.AbstractReadOnlyDecorator.WindowStoreReadOnlyDecorator; +import org.apache.kafka.streams.state.KeyValueStore; +import org.apache.kafka.streams.state.SessionStore; +import org.apache.kafka.streams.state.SessionStoreWithHeaders; +import org.apache.kafka.streams.state.TimestampedKeyValueStore; +import org.apache.kafka.streams.state.TimestampedKeyValueStoreWithHeaders; +import org.apache.kafka.streams.state.TimestampedWindowStore; +import org.apache.kafka.streams.state.TimestampedWindowStoreWithHeaders; +import org.apache.kafka.streams.state.VersionedKeyValueStore; +import org.apache.kafka.streams.state.WindowStore; + +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; +import org.mockito.junit.jupiter.MockitoExtension; +import org.mockito.junit.jupiter.MockitoSettings; +import org.mockito.quality.Strictness; + +import java.util.stream.Stream; + +import static org.apache.kafka.streams.processor.internals.AbstractReadOnlyDecorator.getReadOnlyStore; +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.assertThrows; +import static org.mockito.Mockito.mock; + +@ExtendWith(MockitoExtension.class) +@MockitoSettings(strictness = Strictness.STRICT_STUBS) +public class AbstractReadOnlyDecoratorTest { + + // Dispatch tests pin getReadOnlyStore to the exact decorator per store type. Because the + // *WithHeaders interfaces extend their base store interface, a reordered/removed instanceof check + // would silently fall through to the base decorator; asserting the exact class catches that. + private static Stream<Arguments> storeTypes() { + return Stream.of( + Arguments.of(TimestampedKeyValueStoreWithHeaders.class, TimestampedKeyValueStoreReadOnlyDecoratorWithHeaders.class), + Arguments.of(TimestampedKeyValueStore.class, TimestampedKeyValueStoreReadOnlyDecorator.class), + Arguments.of(VersionedKeyValueStore.class, VersionedKeyValueStoreReadOnlyDecorator.class), + Arguments.of(KeyValueStore.class, KeyValueStoreReadOnlyDecorator.class), + Arguments.of(TimestampedWindowStore.class, TimestampedWindowStoreReadOnlyDecorator.class), + Arguments.of(WindowStore.class, WindowStoreReadOnlyDecorator.class), + Arguments.of(SessionStore.class, SessionStoreReadOnlyDecorator.class) + ); + } + + @ParameterizedTest(name = "{0} -> {1}") + @MethodSource("storeTypes") + public void shouldWrapWithMatchingDecorator(final Class<? extends StateStore> storeType, + final Class<? extends StateStore> expectedDecorator) { + assertEquals(expectedDecorator, getReadOnlyStore(mock(storeType)).getClass()); + } + + // Pins current behavior: unlike wrapWithReadWriteStore, getReadOnlyStore has no branch for the Review Comment: Nice-to-have: Since you said this gap wasn't intentional, it shouldn't stay pinned as expected behavior with no pointer to a fix. Please open a JIRA for the missing read-only window/session headers decorators and reference it in this comment. Fixing it in a separate PR is fine. ########## streams/src/test/java/org/apache/kafka/streams/state/internals/SessionToHeadersStoreAdapterTest.java: ########## @@ -306,4 +308,21 @@ public void shouldReportRetentionPeriodOfUnderlyingStore() { assertInstanceOf(WithRetentionPeriod.class, store); assertEquals(retentionMs, ((WithRetentionPeriod) store).retentionPeriod()); } + + // Instant overloads delegate to the long-based overloads; verify conversion still happens. Review Comment: Nice-to-have: The PR description still mentions a new `findSessions(long,long)` case and a `TimestampedToHeadersIteratorAdapter` test, but neither is in the diff anymore. Please update the description, since it becomes the commit message. -- 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]
