frankvicky commented on code in PR #23864:
URL: https://github.com/apache/kafka/pull/23864#discussion_r4554574830


##########
streams/integration-tests/src/test/java/org/apache/kafka/streams/integration/IQv1HeadersStoreIntegrationTest.java:
##########
@@ -0,0 +1,1178 @@
+/*
+ * 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.integration;
+
+import org.apache.kafka.clients.consumer.ConsumerConfig;
+import org.apache.kafka.clients.producer.KafkaProducer;
+import org.apache.kafka.clients.producer.ProducerRecord;
+import org.apache.kafka.common.TopicPartition;
+import org.apache.kafka.common.header.Headers;
+import org.apache.kafka.common.header.internals.RecordHeaders;
+import org.apache.kafka.common.serialization.Serdes;
+import org.apache.kafka.common.serialization.StringSerializer;
+import org.apache.kafka.common.utils.Bytes;
+import org.apache.kafka.streams.CloseOptions;
+import org.apache.kafka.streams.CloseOptions.GroupMembershipOperation;
+import org.apache.kafka.streams.KafkaStreams;
+import org.apache.kafka.streams.KafkaStreams.State;
+import org.apache.kafka.streams.KeyQueryMetadata;
+import org.apache.kafka.streams.KeyValue;
+import org.apache.kafka.streams.StoreQueryParameters;
+import org.apache.kafka.streams.StreamsBuilder;
+import org.apache.kafka.streams.StreamsConfig;
+import org.apache.kafka.streams.errors.InvalidStateStoreException;
+import org.apache.kafka.streams.integration.utils.EmbeddedKafkaCluster;
+import 
org.apache.kafka.streams.integration.utils.IntegrationTestUtils.TrackingStateRestoreListener;
+import org.apache.kafka.streams.kstream.Consumed;
+import org.apache.kafka.streams.kstream.Materialized;
+import org.apache.kafka.streams.kstream.SessionWindows;
+import org.apache.kafka.streams.kstream.TimeWindows;
+import org.apache.kafka.streams.kstream.Windowed;
+import org.apache.kafka.streams.kstream.internals.SessionWindow;
+import org.apache.kafka.streams.kstream.internals.TimeWindow;
+import org.apache.kafka.streams.processor.StateRestoreListener;
+import org.apache.kafka.streams.processor.api.Processor;
+import org.apache.kafka.streams.processor.api.ProcessorContext;
+import org.apache.kafka.streams.processor.api.Record;
+import org.apache.kafka.streams.state.AggregationWithHeaders;
+import org.apache.kafka.streams.state.KeyValueStore;
+import org.apache.kafka.streams.state.QueryableStoreType;
+import org.apache.kafka.streams.state.QueryableStoreTypes;
+import org.apache.kafka.streams.state.ReadOnlyKeyValueStore;
+import org.apache.kafka.streams.state.ReadOnlySessionStore;
+import org.apache.kafka.streams.state.ReadOnlyWindowStore;
+import org.apache.kafka.streams.state.SessionStore;
+import org.apache.kafka.streams.state.SessionStoreWithHeaders;
+import org.apache.kafka.streams.state.StoreBuilder;
+import org.apache.kafka.streams.state.Stores;
+import org.apache.kafka.streams.state.TimestampedKeyValueStoreWithHeaders;
+import org.apache.kafka.streams.state.TimestampedWindowStoreWithHeaders;
+import org.apache.kafka.streams.state.ValueAndTimestamp;
+import org.apache.kafka.streams.state.ValueTimestampHeaders;
+import org.apache.kafka.streams.state.WindowStore;
+import org.apache.kafka.test.TestUtils;
+
+import org.junit.jupiter.api.AfterAll;
+import org.junit.jupiter.api.BeforeAll;
+import org.junit.jupiter.api.Tag;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.TestInfo;
+import org.junit.jupiter.api.Timeout;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.ValueSource;
+
+import java.io.IOException;
+import java.nio.charset.StandardCharsets;
+import java.time.Instant;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.Comparator;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Properties;
+import java.util.Set;
+import java.util.TreeMap;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.TimeUnit;
+import java.util.stream.Collectors;
+
+import static java.time.Duration.ofDays;
+import static java.time.Duration.ofMillis;
+import static java.time.Duration.ofMinutes;
+import static java.time.Duration.ofSeconds;
+import static java.time.Instant.ofEpochMilli;
+import static org.apache.kafka.common.utils.Utils.mkEntry;
+import static org.apache.kafka.common.utils.Utils.mkMap;
+import static org.apache.kafka.common.utils.Utils.mkProperties;
+import static org.apache.kafka.streams.StoreQueryParameters.fromNameAndType;
+import static 
org.apache.kafka.streams.integration.utils.IntegrationTestUtils.getRunningStreams;
+import static 
org.apache.kafka.streams.integration.utils.IntegrationTestUtils.startApplicationAndWaitUntilRunning;
+import static org.apache.kafka.streams.state.QueryableStoreTypes.keyValueStore;
+import static org.apache.kafka.streams.state.QueryableStoreTypes.sessionStore;
+import static org.apache.kafka.streams.utils.TestUtils.safeUniqueTestName;
+import static org.apache.kafka.streams.utils.TestUtils.waitForApplicationState;
+import static org.apache.kafka.test.StreamsTestUtils.toListAndCloseIterator;
+import static org.apache.kafka.test.TestUtils.retryOnExceptionWithTimeout;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertNull;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+/**
+ * Integration tests that verify IQv1 works with the headers-aware state 
stores of KIP-1271 and KIP-1285.
+ *
+ * <p>The DSL tests create the stores either from a {@code 
Stores.*WithHeaders} supplier or from
+ * {@code dsl.store.format=HEADERS}. DSL operators write empty headers to 
their stores (see the KIP-1285
+ * current limitations), so these tests produce records with headers and 
assert that the queried headers are
+ * empty. The Processor API tests write the record headers into the stores, 
and assert that IQv1 returns them.
+ *
+ * <p>IQv2 on headers-aware stores is covered by {@link 
IQv2HeadersStoreIntegrationTest}.
+ */
+@Timeout(600)
+@Tag("integration")
+public class IQv1HeadersStoreIntegrationTest {
+    private static final long DEFAULT_TIMEOUT_MS = 120 * 1000;
+    private static final int NUM_BROKERS = 1;
+    private static final int NUM_PARTITIONS = 2;
+
+    // stores of the Processor API topology built by topology()
+    private static final String HEADERS_KV_STORE = "headers-kv-store";
+    private static final String HEADERS_WINDOW_STORE = "headers-window-store";
+    private static final String HEADERS_SESSION_STORE = 
"headers-session-store";
+    private static final long HEADERS_WINDOW_SIZE_MS = 10_000L;
+
+    public static final EmbeddedKafkaCluster CLUSTER = new 
EmbeddedKafkaCluster(NUM_BROKERS);
+
+    @BeforeAll
+    public static void startCluster() throws IOException {
+        CLUSTER.start();
+    }
+
+    @AfterAll
+    public static void closeCluster() {
+        CLUSTER.stop();
+    }
+
+    @ParameterizedTest
+    @ValueSource(booleans = {false, true})
+    public void shouldQueryHeadersAwareKeyValueStore(final boolean 
viaDslConfig, final TestInfo testInfo) throws Exception {
+        final String uniqueTestName = safeUniqueTestName(testInfo);
+        final String inputTopic = uniqueTestName + "-input";
+        final String storeName = uniqueTestName + "-store";
+
+        CLUSTER.createTopic(inputTopic);
+
+        final StreamsBuilder builder = new StreamsBuilder();
+        builder.table(
+            inputTopic,
+            Consumed.with(Serdes.String(), Serdes.String()),
+            // without caching, approximateNumEntries() counts every record as 
soon as it is processed
+            keyValueMaterialized(storeName, viaDslConfig).withCachingDisabled()
+        );
+
+        try (final KafkaStreams streams = 
getRunningStreams(streamsProperties(uniqueTestName, viaDslConfig), builder, 
true)) {
+            final List<KeyValue<String, String>> records = Arrays.asList(
+                new KeyValue<>("alpha", "a1"),
+                new KeyValue<>("beta", "b1"),
+                new KeyValue<>("gamma", "g1"),
+                new KeyValue<>("delta", "d1"),
+                new KeyValue<>("epsilon", "e1")
+            );
+            final long timestamp = System.currentTimeMillis();
+            produceSynchronously(records.stream()
+                .map(record -> new ProducerRecord<>(inputTopic, null, 
timestamp, record.key, record.value, dslInputHeaders()))
+                .collect(Collectors.toList()));
+
+            // sorted by key: "alpha", "beta", "delta", "epsilon", "gamma"
+            final List<KeyValue<String, String>> sortedRecords = 
records.stream()
+                .sorted(Comparator.comparing(record -> record.key))
+                .collect(Collectors.toList());
+            final List<KeyValue<String, ValueTimestampHeaders<String>>> 
entries = sortedRecords.stream()
+                .map(record -> KeyValue.pair(record.key, 
ValueTimestampHeaders.make(record.value, timestamp, new RecordHeaders())))
+                .collect(Collectors.toList());
+
+            retryOnExceptionWithTimeout(30_000, () -> {
+                final ReadOnlyKeyValueStore<String, 
ValueTimestampHeaders<String>> store =
+                    streams.store(fromNameAndType(storeName, 
QueryableStoreTypes.timestampedKeyValueStoreWithHeaders()));
+                assertNotNull(store);
+
+                assertEquals(entries.get(0).value, store.get("alpha"));
+                assertNull(store.get("nonexistent"));
+                // exact, since all keys are distinct and none was deleted
+                assertEquals(5L, store.approximateNumEntries());
+
+                assertEquals(entries, toListAndCloseIterator(store.all()));
+                assertEquals(reversed(entries), 
toListAndCloseIterator(store.reverseAll()));
+                assertEquals(entries.subList(1, 4), 
toListAndCloseIterator(store.range("beta", "epsilon")));
+                assertEquals(reversed(entries.subList(1, 4)), 
toListAndCloseIterator(store.reverseRange("beta", "epsilon")));
+                assertEquals(entries.subList(2, 3), 
toListAndCloseIterator(store.prefixScan("de", new StringSerializer())));
+
+                final ReadOnlyKeyValueStore<String, ValueAndTimestamp<String>> 
tsStore =
+                    streams.store(fromNameAndType(storeName, 
QueryableStoreTypes.timestampedKeyValueStore()));
+                assertEquals(ValueAndTimestamp.make("b1", timestamp), 
tsStore.get("beta"));
+
+                final ReadOnlyKeyValueStore<String, String> plainStore = 
streams.store(fromNameAndType(storeName, keyValueStore()));
+                assertEquals("b1", plainStore.get("beta"));
+                assertEquals(sortedRecords, 
toListAndCloseIterator(plainStore.all()));
+            });
+        }
+    }
+
+    @ParameterizedTest
+    @ValueSource(booleans = {false, true})
+    public void shouldQueryHeadersAwareGlobalStore(final boolean viaDslConfig, 
final TestInfo testInfo) throws Exception {
+        final String uniqueTestName = safeUniqueTestName(testInfo);
+        final String inputTopic = uniqueTestName + "-input";
+        final String storeName = uniqueTestName + "-global-store";
+
+        CLUSTER.createTopic(inputTopic);
+
+        final StreamsBuilder builder = new StreamsBuilder();
+        builder.globalTable(
+            inputTopic,
+            Consumed.with(Serdes.String(), Serdes.String()),
+            keyValueMaterialized(storeName, viaDslConfig)
+        );
+
+        try (final KafkaStreams streams = 
getRunningStreams(streamsProperties(uniqueTestName, viaDslConfig), builder, 
true)) {
+            final List<KeyValue<String, String>> records = Arrays.asList(
+                new KeyValue<>("alpha", "a1"),
+                new KeyValue<>("beta", "b1")
+            );
+            final long timestamp = System.currentTimeMillis();
+            produceSynchronously(records.stream()
+                .map(record -> new ProducerRecord<>(inputTopic, null, 
timestamp, record.key, record.value, dslInputHeaders()))
+                .collect(Collectors.toList()));
+
+            final List<KeyValue<String, ValueTimestampHeaders<String>>> 
entries = records.stream()
+                .map(record -> KeyValue.pair(record.key, 
ValueTimestampHeaders.make(record.value, timestamp, new RecordHeaders())))
+                .collect(Collectors.toList());
+
+            retryOnExceptionWithTimeout(30_000, () -> {
+                final ReadOnlyKeyValueStore<String, 
ValueTimestampHeaders<String>> store =
+                    streams.store(fromNameAndType(storeName, 
QueryableStoreTypes.timestampedKeyValueStoreWithHeaders()));
+                assertEquals(entries, toListAndCloseIterator(store.all()));
+                assertEquals(entries.get(1).value, store.get("beta"));
+
+                final ReadOnlyKeyValueStore<String, ValueAndTimestamp<String>> 
tsStore =
+                    streams.store(fromNameAndType(storeName, 
QueryableStoreTypes.timestampedKeyValueStore()));
+                assertEquals(ValueAndTimestamp.make("b1", timestamp), 
tsStore.get("beta"));
+
+                final ReadOnlyKeyValueStore<String, String> plainStore = 
streams.store(fromNameAndType(storeName, keyValueStore()));
+                assertEquals(records, 
toListAndCloseIterator(plainStore.all()));
+            });
+        }
+    }
+
+    @ParameterizedTest
+    @ValueSource(booleans = {false, true})
+    public void 
shouldQueryHeadersAwareWindowStoreAcrossMultipleAndOverlappingWindows(final 
boolean viaDslConfig,
+                                                                               
     final TestInfo testInfo) throws Exception {
+        final String uniqueTestName = safeUniqueTestName(testInfo);
+        final String inputTopic = uniqueTestName + "-input";
+        final String storeName = uniqueTestName + "-window-store";
+        final long windowSize = 10_000L;
+        final long advance = 5_000L;
+
+        CLUSTER.createTopic(inputTopic);
+
+        final StreamsBuilder builder = new StreamsBuilder();
+        builder.stream(inputTopic, Consumed.with(Serdes.String(), 
Serdes.String()))
+            .groupByKey()
+            // hopping windows, so that every record is counted in two 
overlapping windows
+            
.windowedBy(TimeWindows.ofSizeWithNoGrace(ofMillis(windowSize)).advanceBy(ofMillis(advance)))
+            .count(windowMaterialized(storeName, windowSize, viaDslConfig));
+
+        try (final KafkaStreams streams = 
getRunningStreams(streamsProperties(uniqueTestName, viaDslConfig), builder, 
true)) {
+            // aligned to the advance, so that a window starts at t
+            final long t = System.currentTimeMillis() / advance * advance;
+            produceSynchronously(Arrays.asList(
+                new ProducerRecord<>(inputTopic, null, t, "wa", "v1", 
dslInputHeaders()),
+                new ProducerRecord<>(inputTopic, null, t + advance, "wa", 
"v2", dslInputHeaders()),
+                new ProducerRecord<>(inputTopic, null, t + 4 * advance, "wb", 
"v3", dslInputHeaders())
+            ));
+
+            final List<KeyValue<Windowed<String>, 
ValueTimestampHeaders<Long>>> windows = Arrays.asList(
+                windowedCount("wa", t - advance, t - advance + windowSize, 1L, 
t),
+                windowedCount("wa", t, t + windowSize, 2L, t + advance),
+                windowedCount("wa", t + advance, t + advance + windowSize, 1L, 
t + advance),
+                windowedCount("wb", t + 3 * advance, t + 3 * advance + 
windowSize, 1L, t + 4 * advance),
+                windowedCount("wb", t + 4 * advance, t + 4 * advance + 
windowSize, 1L, t + 4 * advance)
+            );
+            final List<KeyValue<Long, ValueTimestampHeaders<Long>>> waWindows 
= windows.subList(0, 3).stream()
+                .map(window -> KeyValue.pair(window.key.window().start(), 
window.value))
+                .collect(Collectors.toList());
+            final Instant timeFrom = ofEpochMilli(t - advance);
+            final Instant timeTo = ofEpochMilli(t + 4 * advance);
+
+            retryOnExceptionWithTimeout(30_000, () -> {
+                final ReadOnlyWindowStore<String, ValueTimestampHeaders<Long>> 
store =
+                    streams.store(fromNameAndType(storeName, 
QueryableStoreTypes.timestampedWindowStoreWithHeaders()));
+                assertNotNull(store);
+
+                assertEquals(waWindows, 
toListAndCloseIterator(store.fetch("wa", timeFrom, timeTo)));
+                assertEquals(reversed(waWindows), 
toListAndCloseIterator(store.backwardFetch("wa", timeFrom, timeTo)));
+                // the time range bounds the start time of the windows
+                assertEquals(waWindows.subList(1, 2), 
toListAndCloseIterator(store.fetch("wa", ofEpochMilli(t), ofEpochMilli(t))));
+                assertEquals(waWindows.get(1).value, store.fetch("wa", t));
+
+                final List<KeyValue<Windowed<String>, 
ValueTimestampHeaders<Long>>> fetchedAll =
+                    toListAndCloseIterator(store.fetchAll(timeFrom, timeTo));
+                assertSameEntries(windows, fetchedAll);
+                assertEquals(reversed(fetchedAll), 
toListAndCloseIterator(store.backwardFetchAll(timeFrom, timeTo)));
+
+                final List<KeyValue<Windowed<String>, 
ValueTimestampHeaders<Long>>> all = toListAndCloseIterator(store.all());
+                assertSameEntries(windows, all);
+                assertEquals(reversed(all), 
toListAndCloseIterator(store.backwardAll()));
+
+                final List<KeyValue<Windowed<String>, 
ValueTimestampHeaders<Long>>> keyRange =
+                    toListAndCloseIterator(store.fetch("wa", "wb", timeFrom, 
timeTo));
+                assertSameEntries(windows, keyRange);
+                assertEquals(reversed(keyRange), 
toListAndCloseIterator(store.backwardFetch("wa", "wb", timeFrom, timeTo)));
+
+                final ReadOnlyWindowStore<String, ValueAndTimestamp<Long>> 
tsStore =
+                    streams.store(fromNameAndType(storeName, 
QueryableStoreTypes.timestampedWindowStore()));
+                assertEquals(
+                    waWindows.stream()
+                        .map(window -> KeyValue.pair(window.key, 
ValueAndTimestamp.make(window.value.value(), window.value.timestamp())))
+                        .collect(Collectors.toList()),
+                    toListAndCloseIterator(tsStore.fetch("wa", timeFrom, 
timeTo)));
+
+                final ReadOnlyWindowStore<String, Long> plainStore =
+                    streams.store(fromNameAndType(storeName, 
QueryableStoreTypes.windowStore()));
+                assertEquals(
+                    waWindows.stream().map(window -> KeyValue.pair(window.key, 
window.value.value())).collect(Collectors.toList()),
+                    toListAndCloseIterator(plainStore.fetch("wa", timeFrom, 
timeTo)));
+            });
+        }
+    }
+
+    @ParameterizedTest
+    @ValueSource(booleans = {false, true})
+    public void 
shouldQueryHeadersAwareSessionStoreWithMultipleAndMergedSessions(final boolean 
viaDslConfig,
+                                                                               
final TestInfo testInfo) throws Exception {
+        final String uniqueTestName = safeUniqueTestName(testInfo);
+        final String inputTopic = uniqueTestName + "-input";
+        final String storeName = uniqueTestName + "-session-store";
+        final long inactivityGap = 5_000L;
+
+        CLUSTER.createTopic(inputTopic);
+
+        final StreamsBuilder builder = new StreamsBuilder();
+        builder.stream(inputTopic, Consumed.with(Serdes.String(), 
Serdes.String()))
+            .groupByKey()
+            
.windowedBy(SessionWindows.ofInactivityGapAndGrace(ofMillis(inactivityGap), 
ofMinutes(1)))
+            .count(sessionMaterialized(storeName, viaDslConfig));
+
+        try (final KafkaStreams streams = 
getRunningStreams(streamsProperties(uniqueTestName, viaDslConfig), builder, 
true)) {
+            final long t = System.currentTimeMillis();
+            // the records of "sa" are further apart than the inactivity gap, 
so they are in two sessions
+            produceSynchronously(Arrays.asList(
+                new ProducerRecord<>(inputTopic, null, t, "sa", "v1", 
dslInputHeaders()),
+                new ProducerRecord<>(inputTopic, null, t, "sb", "v2", 
dslInputHeaders()),
+                new ProducerRecord<>(inputTopic, null, t + 2 * inactivityGap, 
"sa", "v3", dslInputHeaders())
+            ));
+
+            final KeyValue<Windowed<String>, AggregationWithHeaders<Long>> 
firstSession = sessionCount("sa", t, t, 1L);
+            final KeyValue<Windowed<String>, AggregationWithHeaders<Long>> 
secondSession =
+                sessionCount("sa", t + 2 * inactivityGap, t + 2 * 
inactivityGap, 1L);
+            final KeyValue<Windowed<String>, AggregationWithHeaders<Long>> 
otherKeySession = sessionCount("sb", t, t, 1L);
+
+            retryOnExceptionWithTimeout(30_000, () -> {
+                final ReadOnlySessionStore<String, 
AggregationWithHeaders<Long>> store =
+                    streams.store(fromNameAndType(storeName, 
QueryableStoreTypes.sessionStoreWithHeaders()));
+                assertNotNull(store);
+
+                assertEquals(Arrays.asList(firstSession, secondSession), 
toListAndCloseIterator(store.fetch("sa")));
+                assertEquals(Arrays.asList(secondSession, firstSession), 
toListAndCloseIterator(store.backwardFetch("sa")));
+                // only the second session ends after t
+                assertEquals(
+                    Collections.singletonList(secondSession),
+                    toListAndCloseIterator(store.findSessions("sa", t + 1, t + 
2 * inactivityGap)));
+                // only the first session starts at or before t
+                assertEquals(
+                    Collections.singletonList(firstSession),
+                    toListAndCloseIterator(store.backwardFindSessions("sa", t, 
t)));
+
+                final List<KeyValue<Windowed<String>, 
AggregationWithHeaders<Long>>> keyRange =
+                    toListAndCloseIterator(store.fetch("sa", "sb"));
+                assertSameEntries(Arrays.asList(firstSession, secondSession, 
otherKeySession), keyRange);
+                assertEquals(reversed(keyRange), 
toListAndCloseIterator(store.backwardFetch("sa", "sb")));
+
+                final ReadOnlySessionStore<String, Long> plainStore = 
streams.store(fromNameAndType(storeName, sessionStore()));
+                assertEquals(
+                    Arrays.asList(KeyValue.pair(firstSession.key, 1L), 
KeyValue.pair(secondSession.key, 1L)),
+                    toListAndCloseIterator(plainStore.fetch("sa")));
+            });
+
+            // a record within the inactivity gap of both sessions merges them 
into one
+            produceSynchronously(Collections.singletonList(
+                new ProducerRecord<>(inputTopic, null, t + inactivityGap, 
"sa", "v4", dslInputHeaders())));
+
+            final KeyValue<Windowed<String>, AggregationWithHeaders<Long>> 
mergedSession =
+                sessionCount("sa", t, t + 2 * inactivityGap, 3L);
+
+            retryOnExceptionWithTimeout(30_000, () -> {
+                final ReadOnlySessionStore<String, 
AggregationWithHeaders<Long>> store =
+                    streams.store(fromNameAndType(storeName, 
QueryableStoreTypes.sessionStoreWithHeaders()));
+
+                assertEquals(Collections.singletonList(mergedSession), 
toListAndCloseIterator(store.fetch("sa")));
+                assertEquals(Collections.singletonList(mergedSession), 
toListAndCloseIterator(store.findSessions("sa", t, t)));
+            });
+        }
+    }
+
+    @Test
+    public void 
shouldQueryHeadersAwareKeyValueStoreAfterUpdateAndTombstone(final TestInfo 
testInfo) throws Exception {
+        final String uniqueTestName = safeUniqueTestName(testInfo);
+        final String inputTopic = uniqueTestName + "-input";
+        final String storeName = uniqueTestName + "-store";
+
+        CLUSTER.createTopic(inputTopic);
+
+        final StreamsBuilder builder = new StreamsBuilder();
+        builder.table(
+            inputTopic,
+            Consumed.with(Serdes.String(), Serdes.String()),
+            keyValueMaterialized(storeName, false)
+        );
+
+        try (final KafkaStreams streams = 
getRunningStreams(streamsProperties(uniqueTestName, false), builder, true)) {
+            final long t = System.currentTimeMillis();
+            produceSynchronously(Collections.singletonList(
+                new ProducerRecord<>(inputTopic, null, t, "key", "v1", 
dslInputHeaders())));
+
+            retryOnExceptionWithTimeout(30_000, () -> {
+                final ReadOnlyKeyValueStore<String, 
ValueTimestampHeaders<String>> store =
+                    streams.store(fromNameAndType(storeName, 
QueryableStoreTypes.timestampedKeyValueStoreWithHeaders()));
+                assertEquals(ValueTimestampHeaders.make("v1", t, new 
RecordHeaders()), store.get("key"));
+            });
+
+            produceSynchronously(Collections.singletonList(
+                new ProducerRecord<>(inputTopic, null, t + 1, "key", "v2", 
dslInputHeaders())));
+
+            retryOnExceptionWithTimeout(30_000, () -> {
+                final ReadOnlyKeyValueStore<String, 
ValueTimestampHeaders<String>> store =
+                    streams.store(fromNameAndType(storeName, 
QueryableStoreTypes.timestampedKeyValueStoreWithHeaders()));
+                final ValueTimestampHeaders<String> expected = 
ValueTimestampHeaders.make("v2", t + 1, new RecordHeaders());
+                assertEquals(expected, store.get("key"));
+                assertEquals(Collections.singletonList(KeyValue.pair("key", 
expected)), toListAndCloseIterator(store.all()));
+            });
+
+            produceSynchronously(Collections.singletonList(
+                new ProducerRecord<>(inputTopic, null, t + 2, "key", null, 
dslInputHeaders())));
+
+            retryOnExceptionWithTimeout(30_000, () -> {
+                final ReadOnlyKeyValueStore<String, 
ValueTimestampHeaders<String>> store =
+                    streams.store(fromNameAndType(storeName, 
QueryableStoreTypes.timestampedKeyValueStoreWithHeaders()));
+                assertNull(store.get("key"));
+                assertEquals(Collections.emptyList(), 
toListAndCloseIterator(store.all()));
+            });
+        }
+    }
+
+    @ParameterizedTest
+    @ValueSource(booleans = {true, false})
+    public void shouldReturnRecordHeadersFromHeadersAwareStores(final boolean 
cachingEnabled, final TestInfo testInfo) throws Exception {

Review Comment:
   Could we also query these stores through `keyValueStore()` / 
`timestampedKeyValueStore()` (and the window/session equivalents) here? 
   The DSL tests do that but only with empty headers, so the facade is never 
exercised with real headers.



##########
streams/integration-tests/src/test/java/org/apache/kafka/streams/integration/IQv1HeadersStoreIntegrationTest.java:
##########
@@ -0,0 +1,1178 @@
+/*
+ * 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.integration;
+
+import org.apache.kafka.clients.consumer.ConsumerConfig;
+import org.apache.kafka.clients.producer.KafkaProducer;
+import org.apache.kafka.clients.producer.ProducerRecord;
+import org.apache.kafka.common.TopicPartition;
+import org.apache.kafka.common.header.Headers;
+import org.apache.kafka.common.header.internals.RecordHeaders;
+import org.apache.kafka.common.serialization.Serdes;
+import org.apache.kafka.common.serialization.StringSerializer;
+import org.apache.kafka.common.utils.Bytes;
+import org.apache.kafka.streams.CloseOptions;
+import org.apache.kafka.streams.CloseOptions.GroupMembershipOperation;
+import org.apache.kafka.streams.KafkaStreams;
+import org.apache.kafka.streams.KafkaStreams.State;
+import org.apache.kafka.streams.KeyQueryMetadata;
+import org.apache.kafka.streams.KeyValue;
+import org.apache.kafka.streams.StoreQueryParameters;
+import org.apache.kafka.streams.StreamsBuilder;
+import org.apache.kafka.streams.StreamsConfig;
+import org.apache.kafka.streams.errors.InvalidStateStoreException;
+import org.apache.kafka.streams.integration.utils.EmbeddedKafkaCluster;
+import 
org.apache.kafka.streams.integration.utils.IntegrationTestUtils.TrackingStateRestoreListener;
+import org.apache.kafka.streams.kstream.Consumed;
+import org.apache.kafka.streams.kstream.Materialized;
+import org.apache.kafka.streams.kstream.SessionWindows;
+import org.apache.kafka.streams.kstream.TimeWindows;
+import org.apache.kafka.streams.kstream.Windowed;
+import org.apache.kafka.streams.kstream.internals.SessionWindow;
+import org.apache.kafka.streams.kstream.internals.TimeWindow;
+import org.apache.kafka.streams.processor.StateRestoreListener;
+import org.apache.kafka.streams.processor.api.Processor;
+import org.apache.kafka.streams.processor.api.ProcessorContext;
+import org.apache.kafka.streams.processor.api.Record;
+import org.apache.kafka.streams.state.AggregationWithHeaders;
+import org.apache.kafka.streams.state.KeyValueStore;
+import org.apache.kafka.streams.state.QueryableStoreType;
+import org.apache.kafka.streams.state.QueryableStoreTypes;
+import org.apache.kafka.streams.state.ReadOnlyKeyValueStore;
+import org.apache.kafka.streams.state.ReadOnlySessionStore;
+import org.apache.kafka.streams.state.ReadOnlyWindowStore;
+import org.apache.kafka.streams.state.SessionStore;
+import org.apache.kafka.streams.state.SessionStoreWithHeaders;
+import org.apache.kafka.streams.state.StoreBuilder;
+import org.apache.kafka.streams.state.Stores;
+import org.apache.kafka.streams.state.TimestampedKeyValueStoreWithHeaders;
+import org.apache.kafka.streams.state.TimestampedWindowStoreWithHeaders;
+import org.apache.kafka.streams.state.ValueAndTimestamp;
+import org.apache.kafka.streams.state.ValueTimestampHeaders;
+import org.apache.kafka.streams.state.WindowStore;
+import org.apache.kafka.test.TestUtils;
+
+import org.junit.jupiter.api.AfterAll;
+import org.junit.jupiter.api.BeforeAll;
+import org.junit.jupiter.api.Tag;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.TestInfo;
+import org.junit.jupiter.api.Timeout;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.ValueSource;
+
+import java.io.IOException;
+import java.nio.charset.StandardCharsets;
+import java.time.Instant;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.Comparator;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Properties;
+import java.util.Set;
+import java.util.TreeMap;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.TimeUnit;
+import java.util.stream.Collectors;
+
+import static java.time.Duration.ofDays;
+import static java.time.Duration.ofMillis;
+import static java.time.Duration.ofMinutes;
+import static java.time.Duration.ofSeconds;
+import static java.time.Instant.ofEpochMilli;
+import static org.apache.kafka.common.utils.Utils.mkEntry;
+import static org.apache.kafka.common.utils.Utils.mkMap;
+import static org.apache.kafka.common.utils.Utils.mkProperties;
+import static org.apache.kafka.streams.StoreQueryParameters.fromNameAndType;
+import static 
org.apache.kafka.streams.integration.utils.IntegrationTestUtils.getRunningStreams;
+import static 
org.apache.kafka.streams.integration.utils.IntegrationTestUtils.startApplicationAndWaitUntilRunning;
+import static org.apache.kafka.streams.state.QueryableStoreTypes.keyValueStore;
+import static org.apache.kafka.streams.state.QueryableStoreTypes.sessionStore;
+import static org.apache.kafka.streams.utils.TestUtils.safeUniqueTestName;
+import static org.apache.kafka.streams.utils.TestUtils.waitForApplicationState;
+import static org.apache.kafka.test.StreamsTestUtils.toListAndCloseIterator;
+import static org.apache.kafka.test.TestUtils.retryOnExceptionWithTimeout;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertNull;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+/**
+ * Integration tests that verify IQv1 works with the headers-aware state 
stores of KIP-1271 and KIP-1285.
+ *
+ * <p>The DSL tests create the stores either from a {@code 
Stores.*WithHeaders} supplier or from
+ * {@code dsl.store.format=HEADERS}. DSL operators write empty headers to 
their stores (see the KIP-1285
+ * current limitations), so these tests produce records with headers and 
assert that the queried headers are
+ * empty. The Processor API tests write the record headers into the stores, 
and assert that IQv1 returns them.
+ *
+ * <p>IQv2 on headers-aware stores is covered by {@link 
IQv2HeadersStoreIntegrationTest}.
+ */
+@Timeout(600)
+@Tag("integration")
+public class IQv1HeadersStoreIntegrationTest {
+    private static final long DEFAULT_TIMEOUT_MS = 120 * 1000;
+    private static final int NUM_BROKERS = 1;
+    private static final int NUM_PARTITIONS = 2;
+
+    // stores of the Processor API topology built by topology()
+    private static final String HEADERS_KV_STORE = "headers-kv-store";
+    private static final String HEADERS_WINDOW_STORE = "headers-window-store";
+    private static final String HEADERS_SESSION_STORE = 
"headers-session-store";
+    private static final long HEADERS_WINDOW_SIZE_MS = 10_000L;
+
+    public static final EmbeddedKafkaCluster CLUSTER = new 
EmbeddedKafkaCluster(NUM_BROKERS);
+
+    @BeforeAll
+    public static void startCluster() throws IOException {
+        CLUSTER.start();
+    }
+
+    @AfterAll
+    public static void closeCluster() {
+        CLUSTER.stop();
+    }
+
+    @ParameterizedTest
+    @ValueSource(booleans = {false, true})
+    public void shouldQueryHeadersAwareKeyValueStore(final boolean 
viaDslConfig, final TestInfo testInfo) throws Exception {
+        final String uniqueTestName = safeUniqueTestName(testInfo);
+        final String inputTopic = uniqueTestName + "-input";
+        final String storeName = uniqueTestName + "-store";
+
+        CLUSTER.createTopic(inputTopic);
+
+        final StreamsBuilder builder = new StreamsBuilder();
+        builder.table(
+            inputTopic,
+            Consumed.with(Serdes.String(), Serdes.String()),
+            // without caching, approximateNumEntries() counts every record as 
soon as it is processed
+            keyValueMaterialized(storeName, viaDslConfig).withCachingDisabled()
+        );
+
+        try (final KafkaStreams streams = 
getRunningStreams(streamsProperties(uniqueTestName, viaDslConfig), builder, 
true)) {
+            final List<KeyValue<String, String>> records = Arrays.asList(
+                new KeyValue<>("alpha", "a1"),
+                new KeyValue<>("beta", "b1"),
+                new KeyValue<>("gamma", "g1"),
+                new KeyValue<>("delta", "d1"),
+                new KeyValue<>("epsilon", "e1")
+            );
+            final long timestamp = System.currentTimeMillis();
+            produceSynchronously(records.stream()
+                .map(record -> new ProducerRecord<>(inputTopic, null, 
timestamp, record.key, record.value, dslInputHeaders()))
+                .collect(Collectors.toList()));
+
+            // sorted by key: "alpha", "beta", "delta", "epsilon", "gamma"
+            final List<KeyValue<String, String>> sortedRecords = 
records.stream()
+                .sorted(Comparator.comparing(record -> record.key))
+                .collect(Collectors.toList());
+            final List<KeyValue<String, ValueTimestampHeaders<String>>> 
entries = sortedRecords.stream()
+                .map(record -> KeyValue.pair(record.key, 
ValueTimestampHeaders.make(record.value, timestamp, new RecordHeaders())))
+                .collect(Collectors.toList());
+
+            retryOnExceptionWithTimeout(30_000, () -> {
+                final ReadOnlyKeyValueStore<String, 
ValueTimestampHeaders<String>> store =
+                    streams.store(fromNameAndType(storeName, 
QueryableStoreTypes.timestampedKeyValueStoreWithHeaders()));
+                assertNotNull(store);
+
+                assertEquals(entries.get(0).value, store.get("alpha"));
+                assertNull(store.get("nonexistent"));
+                // exact, since all keys are distinct and none was deleted
+                assertEquals(5L, store.approximateNumEntries());
+
+                assertEquals(entries, toListAndCloseIterator(store.all()));
+                assertEquals(reversed(entries), 
toListAndCloseIterator(store.reverseAll()));
+                assertEquals(entries.subList(1, 4), 
toListAndCloseIterator(store.range("beta", "epsilon")));
+                assertEquals(reversed(entries.subList(1, 4)), 
toListAndCloseIterator(store.reverseRange("beta", "epsilon")));
+                assertEquals(entries.subList(2, 3), 
toListAndCloseIterator(store.prefixScan("de", new StringSerializer())));
+
+                final ReadOnlyKeyValueStore<String, ValueAndTimestamp<String>> 
tsStore =
+                    streams.store(fromNameAndType(storeName, 
QueryableStoreTypes.timestampedKeyValueStore()));
+                assertEquals(ValueAndTimestamp.make("b1", timestamp), 
tsStore.get("beta"));
+
+                final ReadOnlyKeyValueStore<String, String> plainStore = 
streams.store(fromNameAndType(storeName, keyValueStore()));
+                assertEquals("b1", plainStore.get("beta"));
+                assertEquals(sortedRecords, 
toListAndCloseIterator(plainStore.all()));
+            });
+        }
+    }
+
+    @ParameterizedTest
+    @ValueSource(booleans = {false, true})
+    public void shouldQueryHeadersAwareGlobalStore(final boolean viaDslConfig, 
final TestInfo testInfo) throws Exception {

Review Comment:
   after a restore from the source topic this store no longer holds empty 
headers. Is that expected?
   I restarted this test with a fresh state dir. Live the store returns `[]`, 
after the restore it returns `[source=dsl-input]`. 
   `KTableSource` writes empty headers, but the restore goes through 
`RecordConverters.rawValueToHeadersValue()` which copies `record.headers()`. A 
source `KTable` with `topology.optimization=all` behaves the same, with a 
dedicated changelog it stays `[]`.
   I am not sure which side is right, since a header-aware serde may need the 
source record headers to read the restored bytes. 
   Could we add the restart step here to pin down the current behavior, and 
discuss the semantics ?



##########
streams/integration-tests/src/test/java/org/apache/kafka/streams/integration/IQv1HeadersStoreIntegrationTest.java:
##########
@@ -0,0 +1,1178 @@
+/*
+ * 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.integration;
+
+import org.apache.kafka.clients.consumer.ConsumerConfig;
+import org.apache.kafka.clients.producer.KafkaProducer;
+import org.apache.kafka.clients.producer.ProducerRecord;
+import org.apache.kafka.common.TopicPartition;
+import org.apache.kafka.common.header.Headers;
+import org.apache.kafka.common.header.internals.RecordHeaders;
+import org.apache.kafka.common.serialization.Serdes;
+import org.apache.kafka.common.serialization.StringSerializer;
+import org.apache.kafka.common.utils.Bytes;
+import org.apache.kafka.streams.CloseOptions;
+import org.apache.kafka.streams.CloseOptions.GroupMembershipOperation;
+import org.apache.kafka.streams.KafkaStreams;
+import org.apache.kafka.streams.KafkaStreams.State;
+import org.apache.kafka.streams.KeyQueryMetadata;
+import org.apache.kafka.streams.KeyValue;
+import org.apache.kafka.streams.StoreQueryParameters;
+import org.apache.kafka.streams.StreamsBuilder;
+import org.apache.kafka.streams.StreamsConfig;
+import org.apache.kafka.streams.errors.InvalidStateStoreException;
+import org.apache.kafka.streams.integration.utils.EmbeddedKafkaCluster;
+import 
org.apache.kafka.streams.integration.utils.IntegrationTestUtils.TrackingStateRestoreListener;
+import org.apache.kafka.streams.kstream.Consumed;
+import org.apache.kafka.streams.kstream.Materialized;
+import org.apache.kafka.streams.kstream.SessionWindows;
+import org.apache.kafka.streams.kstream.TimeWindows;
+import org.apache.kafka.streams.kstream.Windowed;
+import org.apache.kafka.streams.kstream.internals.SessionWindow;
+import org.apache.kafka.streams.kstream.internals.TimeWindow;
+import org.apache.kafka.streams.processor.StateRestoreListener;
+import org.apache.kafka.streams.processor.api.Processor;
+import org.apache.kafka.streams.processor.api.ProcessorContext;
+import org.apache.kafka.streams.processor.api.Record;
+import org.apache.kafka.streams.state.AggregationWithHeaders;
+import org.apache.kafka.streams.state.KeyValueStore;
+import org.apache.kafka.streams.state.QueryableStoreType;
+import org.apache.kafka.streams.state.QueryableStoreTypes;
+import org.apache.kafka.streams.state.ReadOnlyKeyValueStore;
+import org.apache.kafka.streams.state.ReadOnlySessionStore;
+import org.apache.kafka.streams.state.ReadOnlyWindowStore;
+import org.apache.kafka.streams.state.SessionStore;
+import org.apache.kafka.streams.state.SessionStoreWithHeaders;
+import org.apache.kafka.streams.state.StoreBuilder;
+import org.apache.kafka.streams.state.Stores;
+import org.apache.kafka.streams.state.TimestampedKeyValueStoreWithHeaders;
+import org.apache.kafka.streams.state.TimestampedWindowStoreWithHeaders;
+import org.apache.kafka.streams.state.ValueAndTimestamp;
+import org.apache.kafka.streams.state.ValueTimestampHeaders;
+import org.apache.kafka.streams.state.WindowStore;
+import org.apache.kafka.test.TestUtils;
+
+import org.junit.jupiter.api.AfterAll;
+import org.junit.jupiter.api.BeforeAll;
+import org.junit.jupiter.api.Tag;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.TestInfo;
+import org.junit.jupiter.api.Timeout;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.ValueSource;
+
+import java.io.IOException;
+import java.nio.charset.StandardCharsets;
+import java.time.Instant;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.Comparator;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Properties;
+import java.util.Set;
+import java.util.TreeMap;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.TimeUnit;
+import java.util.stream.Collectors;
+
+import static java.time.Duration.ofDays;
+import static java.time.Duration.ofMillis;
+import static java.time.Duration.ofMinutes;
+import static java.time.Duration.ofSeconds;
+import static java.time.Instant.ofEpochMilli;
+import static org.apache.kafka.common.utils.Utils.mkEntry;
+import static org.apache.kafka.common.utils.Utils.mkMap;
+import static org.apache.kafka.common.utils.Utils.mkProperties;
+import static org.apache.kafka.streams.StoreQueryParameters.fromNameAndType;
+import static 
org.apache.kafka.streams.integration.utils.IntegrationTestUtils.getRunningStreams;
+import static 
org.apache.kafka.streams.integration.utils.IntegrationTestUtils.startApplicationAndWaitUntilRunning;
+import static org.apache.kafka.streams.state.QueryableStoreTypes.keyValueStore;
+import static org.apache.kafka.streams.state.QueryableStoreTypes.sessionStore;
+import static org.apache.kafka.streams.utils.TestUtils.safeUniqueTestName;
+import static org.apache.kafka.streams.utils.TestUtils.waitForApplicationState;
+import static org.apache.kafka.test.StreamsTestUtils.toListAndCloseIterator;
+import static org.apache.kafka.test.TestUtils.retryOnExceptionWithTimeout;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertNull;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+/**
+ * Integration tests that verify IQv1 works with the headers-aware state 
stores of KIP-1271 and KIP-1285.
+ *
+ * <p>The DSL tests create the stores either from a {@code 
Stores.*WithHeaders} supplier or from
+ * {@code dsl.store.format=HEADERS}. DSL operators write empty headers to 
their stores (see the KIP-1285
+ * current limitations), so these tests produce records with headers and 
assert that the queried headers are
+ * empty. The Processor API tests write the record headers into the stores, 
and assert that IQv1 returns them.
+ *
+ * <p>IQv2 on headers-aware stores is covered by {@link 
IQv2HeadersStoreIntegrationTest}.
+ */
+@Timeout(600)
+@Tag("integration")
+public class IQv1HeadersStoreIntegrationTest {
+    private static final long DEFAULT_TIMEOUT_MS = 120 * 1000;
+    private static final int NUM_BROKERS = 1;
+    private static final int NUM_PARTITIONS = 2;
+
+    // stores of the Processor API topology built by topology()
+    private static final String HEADERS_KV_STORE = "headers-kv-store";
+    private static final String HEADERS_WINDOW_STORE = "headers-window-store";
+    private static final String HEADERS_SESSION_STORE = 
"headers-session-store";
+    private static final long HEADERS_WINDOW_SIZE_MS = 10_000L;
+
+    public static final EmbeddedKafkaCluster CLUSTER = new 
EmbeddedKafkaCluster(NUM_BROKERS);
+
+    @BeforeAll
+    public static void startCluster() throws IOException {
+        CLUSTER.start();
+    }
+
+    @AfterAll
+    public static void closeCluster() {
+        CLUSTER.stop();
+    }
+
+    @ParameterizedTest
+    @ValueSource(booleans = {false, true})
+    public void shouldQueryHeadersAwareKeyValueStore(final boolean 
viaDslConfig, final TestInfo testInfo) throws Exception {
+        final String uniqueTestName = safeUniqueTestName(testInfo);
+        final String inputTopic = uniqueTestName + "-input";
+        final String storeName = uniqueTestName + "-store";
+
+        CLUSTER.createTopic(inputTopic);
+
+        final StreamsBuilder builder = new StreamsBuilder();
+        builder.table(
+            inputTopic,
+            Consumed.with(Serdes.String(), Serdes.String()),
+            // without caching, approximateNumEntries() counts every record as 
soon as it is processed
+            keyValueMaterialized(storeName, viaDslConfig).withCachingDisabled()
+        );
+
+        try (final KafkaStreams streams = 
getRunningStreams(streamsProperties(uniqueTestName, viaDslConfig), builder, 
true)) {
+            final List<KeyValue<String, String>> records = Arrays.asList(
+                new KeyValue<>("alpha", "a1"),
+                new KeyValue<>("beta", "b1"),
+                new KeyValue<>("gamma", "g1"),
+                new KeyValue<>("delta", "d1"),
+                new KeyValue<>("epsilon", "e1")
+            );
+            final long timestamp = System.currentTimeMillis();
+            produceSynchronously(records.stream()
+                .map(record -> new ProducerRecord<>(inputTopic, null, 
timestamp, record.key, record.value, dslInputHeaders()))
+                .collect(Collectors.toList()));
+
+            // sorted by key: "alpha", "beta", "delta", "epsilon", "gamma"
+            final List<KeyValue<String, String>> sortedRecords = 
records.stream()
+                .sorted(Comparator.comparing(record -> record.key))
+                .collect(Collectors.toList());
+            final List<KeyValue<String, ValueTimestampHeaders<String>>> 
entries = sortedRecords.stream()
+                .map(record -> KeyValue.pair(record.key, 
ValueTimestampHeaders.make(record.value, timestamp, new RecordHeaders())))
+                .collect(Collectors.toList());
+
+            retryOnExceptionWithTimeout(30_000, () -> {
+                final ReadOnlyKeyValueStore<String, 
ValueTimestampHeaders<String>> store =
+                    streams.store(fromNameAndType(storeName, 
QueryableStoreTypes.timestampedKeyValueStoreWithHeaders()));
+                assertNotNull(store);
+
+                assertEquals(entries.get(0).value, store.get("alpha"));
+                assertNull(store.get("nonexistent"));
+                // exact, since all keys are distinct and none was deleted
+                assertEquals(5L, store.approximateNumEntries());
+
+                assertEquals(entries, toListAndCloseIterator(store.all()));
+                assertEquals(reversed(entries), 
toListAndCloseIterator(store.reverseAll()));
+                assertEquals(entries.subList(1, 4), 
toListAndCloseIterator(store.range("beta", "epsilon")));
+                assertEquals(reversed(entries.subList(1, 4)), 
toListAndCloseIterator(store.reverseRange("beta", "epsilon")));
+                assertEquals(entries.subList(2, 3), 
toListAndCloseIterator(store.prefixScan("de", new StringSerializer())));
+
+                final ReadOnlyKeyValueStore<String, ValueAndTimestamp<String>> 
tsStore =
+                    streams.store(fromNameAndType(storeName, 
QueryableStoreTypes.timestampedKeyValueStore()));
+                assertEquals(ValueAndTimestamp.make("b1", timestamp), 
tsStore.get("beta"));
+
+                final ReadOnlyKeyValueStore<String, String> plainStore = 
streams.store(fromNameAndType(storeName, keyValueStore()));
+                assertEquals("b1", plainStore.get("beta"));
+                assertEquals(sortedRecords, 
toListAndCloseIterator(plainStore.all()));
+            });
+        }
+    }
+
+    @ParameterizedTest
+    @ValueSource(booleans = {false, true})
+    public void shouldQueryHeadersAwareGlobalStore(final boolean viaDslConfig, 
final TestInfo testInfo) throws Exception {
+        final String uniqueTestName = safeUniqueTestName(testInfo);
+        final String inputTopic = uniqueTestName + "-input";
+        final String storeName = uniqueTestName + "-global-store";
+
+        CLUSTER.createTopic(inputTopic);
+
+        final StreamsBuilder builder = new StreamsBuilder();
+        builder.globalTable(
+            inputTopic,
+            Consumed.with(Serdes.String(), Serdes.String()),
+            keyValueMaterialized(storeName, viaDslConfig)
+        );
+
+        try (final KafkaStreams streams = 
getRunningStreams(streamsProperties(uniqueTestName, viaDslConfig), builder, 
true)) {
+            final List<KeyValue<String, String>> records = Arrays.asList(
+                new KeyValue<>("alpha", "a1"),
+                new KeyValue<>("beta", "b1")
+            );
+            final long timestamp = System.currentTimeMillis();
+            produceSynchronously(records.stream()
+                .map(record -> new ProducerRecord<>(inputTopic, null, 
timestamp, record.key, record.value, dslInputHeaders()))
+                .collect(Collectors.toList()));
+
+            final List<KeyValue<String, ValueTimestampHeaders<String>>> 
entries = records.stream()
+                .map(record -> KeyValue.pair(record.key, 
ValueTimestampHeaders.make(record.value, timestamp, new RecordHeaders())))
+                .collect(Collectors.toList());
+
+            retryOnExceptionWithTimeout(30_000, () -> {
+                final ReadOnlyKeyValueStore<String, 
ValueTimestampHeaders<String>> store =
+                    streams.store(fromNameAndType(storeName, 
QueryableStoreTypes.timestampedKeyValueStoreWithHeaders()));
+                assertEquals(entries, toListAndCloseIterator(store.all()));
+                assertEquals(entries.get(1).value, store.get("beta"));
+
+                final ReadOnlyKeyValueStore<String, ValueAndTimestamp<String>> 
tsStore =
+                    streams.store(fromNameAndType(storeName, 
QueryableStoreTypes.timestampedKeyValueStore()));
+                assertEquals(ValueAndTimestamp.make("b1", timestamp), 
tsStore.get("beta"));
+
+                final ReadOnlyKeyValueStore<String, String> plainStore = 
streams.store(fromNameAndType(storeName, keyValueStore()));
+                assertEquals(records, 
toListAndCloseIterator(plainStore.all()));
+            });
+        }
+    }
+
+    @ParameterizedTest
+    @ValueSource(booleans = {false, true})
+    public void 
shouldQueryHeadersAwareWindowStoreAcrossMultipleAndOverlappingWindows(final 
boolean viaDslConfig,
+                                                                               
     final TestInfo testInfo) throws Exception {
+        final String uniqueTestName = safeUniqueTestName(testInfo);
+        final String inputTopic = uniqueTestName + "-input";
+        final String storeName = uniqueTestName + "-window-store";
+        final long windowSize = 10_000L;
+        final long advance = 5_000L;
+
+        CLUSTER.createTopic(inputTopic);
+
+        final StreamsBuilder builder = new StreamsBuilder();
+        builder.stream(inputTopic, Consumed.with(Serdes.String(), 
Serdes.String()))
+            .groupByKey()
+            // hopping windows, so that every record is counted in two 
overlapping windows
+            
.windowedBy(TimeWindows.ofSizeWithNoGrace(ofMillis(windowSize)).advanceBy(ofMillis(advance)))
+            .count(windowMaterialized(storeName, windowSize, viaDslConfig));
+
+        try (final KafkaStreams streams = 
getRunningStreams(streamsProperties(uniqueTestName, viaDslConfig), builder, 
true)) {
+            // aligned to the advance, so that a window starts at t
+            final long t = System.currentTimeMillis() / advance * advance;
+            produceSynchronously(Arrays.asList(
+                new ProducerRecord<>(inputTopic, null, t, "wa", "v1", 
dslInputHeaders()),
+                new ProducerRecord<>(inputTopic, null, t + advance, "wa", 
"v2", dslInputHeaders()),
+                new ProducerRecord<>(inputTopic, null, t + 4 * advance, "wb", 
"v3", dslInputHeaders())
+            ));
+
+            final List<KeyValue<Windowed<String>, 
ValueTimestampHeaders<Long>>> windows = Arrays.asList(
+                windowedCount("wa", t - advance, t - advance + windowSize, 1L, 
t),
+                windowedCount("wa", t, t + windowSize, 2L, t + advance),
+                windowedCount("wa", t + advance, t + advance + windowSize, 1L, 
t + advance),
+                windowedCount("wb", t + 3 * advance, t + 3 * advance + 
windowSize, 1L, t + 4 * advance),
+                windowedCount("wb", t + 4 * advance, t + 4 * advance + 
windowSize, 1L, t + 4 * advance)
+            );
+            final List<KeyValue<Long, ValueTimestampHeaders<Long>>> waWindows 
= windows.subList(0, 3).stream()
+                .map(window -> KeyValue.pair(window.key.window().start(), 
window.value))
+                .collect(Collectors.toList());
+            final Instant timeFrom = ofEpochMilli(t - advance);
+            final Instant timeTo = ofEpochMilli(t + 4 * advance);
+
+            retryOnExceptionWithTimeout(30_000, () -> {
+                final ReadOnlyWindowStore<String, ValueTimestampHeaders<Long>> 
store =
+                    streams.store(fromNameAndType(storeName, 
QueryableStoreTypes.timestampedWindowStoreWithHeaders()));
+                assertNotNull(store);
+
+                assertEquals(waWindows, 
toListAndCloseIterator(store.fetch("wa", timeFrom, timeTo)));
+                assertEquals(reversed(waWindows), 
toListAndCloseIterator(store.backwardFetch("wa", timeFrom, timeTo)));
+                // the time range bounds the start time of the windows
+                assertEquals(waWindows.subList(1, 2), 
toListAndCloseIterator(store.fetch("wa", ofEpochMilli(t), ofEpochMilli(t))));
+                assertEquals(waWindows.get(1).value, store.fetch("wa", t));
+
+                final List<KeyValue<Windowed<String>, 
ValueTimestampHeaders<Long>>> fetchedAll =
+                    toListAndCloseIterator(store.fetchAll(timeFrom, timeTo));
+                assertSameEntries(windows, fetchedAll);
+                assertEquals(reversed(fetchedAll), 
toListAndCloseIterator(store.backwardFetchAll(timeFrom, timeTo)));
+
+                final List<KeyValue<Windowed<String>, 
ValueTimestampHeaders<Long>>> all = toListAndCloseIterator(store.all());
+                assertSameEntries(windows, all);
+                assertEquals(reversed(all), 
toListAndCloseIterator(store.backwardAll()));
+
+                final List<KeyValue<Windowed<String>, 
ValueTimestampHeaders<Long>>> keyRange =
+                    toListAndCloseIterator(store.fetch("wa", "wb", timeFrom, 
timeTo));
+                assertSameEntries(windows, keyRange);
+                assertEquals(reversed(keyRange), 
toListAndCloseIterator(store.backwardFetch("wa", "wb", timeFrom, timeTo)));
+
+                final ReadOnlyWindowStore<String, ValueAndTimestamp<Long>> 
tsStore =
+                    streams.store(fromNameAndType(storeName, 
QueryableStoreTypes.timestampedWindowStore()));
+                assertEquals(
+                    waWindows.stream()
+                        .map(window -> KeyValue.pair(window.key, 
ValueAndTimestamp.make(window.value.value(), window.value.timestamp())))
+                        .collect(Collectors.toList()),
+                    toListAndCloseIterator(tsStore.fetch("wa", timeFrom, 
timeTo)));
+
+                final ReadOnlyWindowStore<String, Long> plainStore =
+                    streams.store(fromNameAndType(storeName, 
QueryableStoreTypes.windowStore()));
+                assertEquals(
+                    waWindows.stream().map(window -> KeyValue.pair(window.key, 
window.value.value())).collect(Collectors.toList()),
+                    toListAndCloseIterator(plainStore.fetch("wa", timeFrom, 
timeTo)));
+            });
+        }
+    }
+
+    @ParameterizedTest
+    @ValueSource(booleans = {false, true})
+    public void 
shouldQueryHeadersAwareSessionStoreWithMultipleAndMergedSessions(final boolean 
viaDslConfig,
+                                                                               
final TestInfo testInfo) throws Exception {
+        final String uniqueTestName = safeUniqueTestName(testInfo);
+        final String inputTopic = uniqueTestName + "-input";
+        final String storeName = uniqueTestName + "-session-store";
+        final long inactivityGap = 5_000L;
+
+        CLUSTER.createTopic(inputTopic);
+
+        final StreamsBuilder builder = new StreamsBuilder();
+        builder.stream(inputTopic, Consumed.with(Serdes.String(), 
Serdes.String()))
+            .groupByKey()
+            
.windowedBy(SessionWindows.ofInactivityGapAndGrace(ofMillis(inactivityGap), 
ofMinutes(1)))
+            .count(sessionMaterialized(storeName, viaDslConfig));
+
+        try (final KafkaStreams streams = 
getRunningStreams(streamsProperties(uniqueTestName, viaDslConfig), builder, 
true)) {
+            final long t = System.currentTimeMillis();
+            // the records of "sa" are further apart than the inactivity gap, 
so they are in two sessions
+            produceSynchronously(Arrays.asList(
+                new ProducerRecord<>(inputTopic, null, t, "sa", "v1", 
dslInputHeaders()),
+                new ProducerRecord<>(inputTopic, null, t, "sb", "v2", 
dslInputHeaders()),
+                new ProducerRecord<>(inputTopic, null, t + 2 * inactivityGap, 
"sa", "v3", dslInputHeaders())
+            ));
+
+            final KeyValue<Windowed<String>, AggregationWithHeaders<Long>> 
firstSession = sessionCount("sa", t, t, 1L);
+            final KeyValue<Windowed<String>, AggregationWithHeaders<Long>> 
secondSession =
+                sessionCount("sa", t + 2 * inactivityGap, t + 2 * 
inactivityGap, 1L);
+            final KeyValue<Windowed<String>, AggregationWithHeaders<Long>> 
otherKeySession = sessionCount("sb", t, t, 1L);
+
+            retryOnExceptionWithTimeout(30_000, () -> {
+                final ReadOnlySessionStore<String, 
AggregationWithHeaders<Long>> store =
+                    streams.store(fromNameAndType(storeName, 
QueryableStoreTypes.sessionStoreWithHeaders()));
+                assertNotNull(store);
+
+                assertEquals(Arrays.asList(firstSession, secondSession), 
toListAndCloseIterator(store.fetch("sa")));
+                assertEquals(Arrays.asList(secondSession, firstSession), 
toListAndCloseIterator(store.backwardFetch("sa")));
+                // only the second session ends after t
+                assertEquals(
+                    Collections.singletonList(secondSession),
+                    toListAndCloseIterator(store.findSessions("sa", t + 1, t + 
2 * inactivityGap)));
+                // only the first session starts at or before t
+                assertEquals(
+                    Collections.singletonList(firstSession),
+                    toListAndCloseIterator(store.backwardFindSessions("sa", t, 
t)));
+
+                final List<KeyValue<Windowed<String>, 
AggregationWithHeaders<Long>>> keyRange =
+                    toListAndCloseIterator(store.fetch("sa", "sb"));
+                assertSameEntries(Arrays.asList(firstSession, secondSession, 
otherKeySession), keyRange);
+                assertEquals(reversed(keyRange), 
toListAndCloseIterator(store.backwardFetch("sa", "sb")));
+
+                final ReadOnlySessionStore<String, Long> plainStore = 
streams.store(fromNameAndType(storeName, sessionStore()));
+                assertEquals(
+                    Arrays.asList(KeyValue.pair(firstSession.key, 1L), 
KeyValue.pair(secondSession.key, 1L)),
+                    toListAndCloseIterator(plainStore.fetch("sa")));
+            });
+
+            // a record within the inactivity gap of both sessions merges them 
into one
+            produceSynchronously(Collections.singletonList(
+                new ProducerRecord<>(inputTopic, null, t + inactivityGap, 
"sa", "v4", dslInputHeaders())));
+
+            final KeyValue<Windowed<String>, AggregationWithHeaders<Long>> 
mergedSession =
+                sessionCount("sa", t, t + 2 * inactivityGap, 3L);
+
+            retryOnExceptionWithTimeout(30_000, () -> {
+                final ReadOnlySessionStore<String, 
AggregationWithHeaders<Long>> store =
+                    streams.store(fromNameAndType(storeName, 
QueryableStoreTypes.sessionStoreWithHeaders()));
+
+                assertEquals(Collections.singletonList(mergedSession), 
toListAndCloseIterator(store.fetch("sa")));
+                assertEquals(Collections.singletonList(mergedSession), 
toListAndCloseIterator(store.findSessions("sa", t, t)));
+            });
+        }
+    }
+
+    @Test
+    public void 
shouldQueryHeadersAwareKeyValueStoreAfterUpdateAndTombstone(final TestInfo 
testInfo) throws Exception {
+        final String uniqueTestName = safeUniqueTestName(testInfo);
+        final String inputTopic = uniqueTestName + "-input";
+        final String storeName = uniqueTestName + "-store";
+
+        CLUSTER.createTopic(inputTopic);
+
+        final StreamsBuilder builder = new StreamsBuilder();
+        builder.table(
+            inputTopic,
+            Consumed.with(Serdes.String(), Serdes.String()),
+            keyValueMaterialized(storeName, false)
+        );
+
+        try (final KafkaStreams streams = 
getRunningStreams(streamsProperties(uniqueTestName, false), builder, true)) {
+            final long t = System.currentTimeMillis();
+            produceSynchronously(Collections.singletonList(
+                new ProducerRecord<>(inputTopic, null, t, "key", "v1", 
dslInputHeaders())));
+
+            retryOnExceptionWithTimeout(30_000, () -> {
+                final ReadOnlyKeyValueStore<String, 
ValueTimestampHeaders<String>> store =
+                    streams.store(fromNameAndType(storeName, 
QueryableStoreTypes.timestampedKeyValueStoreWithHeaders()));
+                assertEquals(ValueTimestampHeaders.make("v1", t, new 
RecordHeaders()), store.get("key"));
+            });
+
+            produceSynchronously(Collections.singletonList(
+                new ProducerRecord<>(inputTopic, null, t + 1, "key", "v2", 
dslInputHeaders())));
+
+            retryOnExceptionWithTimeout(30_000, () -> {
+                final ReadOnlyKeyValueStore<String, 
ValueTimestampHeaders<String>> store =
+                    streams.store(fromNameAndType(storeName, 
QueryableStoreTypes.timestampedKeyValueStoreWithHeaders()));
+                final ValueTimestampHeaders<String> expected = 
ValueTimestampHeaders.make("v2", t + 1, new RecordHeaders());
+                assertEquals(expected, store.get("key"));
+                assertEquals(Collections.singletonList(KeyValue.pair("key", 
expected)), toListAndCloseIterator(store.all()));
+            });
+
+            produceSynchronously(Collections.singletonList(
+                new ProducerRecord<>(inputTopic, null, t + 2, "key", null, 
dslInputHeaders())));
+
+            retryOnExceptionWithTimeout(30_000, () -> {
+                final ReadOnlyKeyValueStore<String, 
ValueTimestampHeaders<String>> store =
+                    streams.store(fromNameAndType(storeName, 
QueryableStoreTypes.timestampedKeyValueStoreWithHeaders()));
+                assertNull(store.get("key"));
+                assertEquals(Collections.emptyList(), 
toListAndCloseIterator(store.all()));
+            });
+        }
+    }
+
+    @ParameterizedTest
+    @ValueSource(booleans = {true, false})
+    public void shouldReturnRecordHeadersFromHeadersAwareStores(final boolean 
cachingEnabled, final TestInfo testInfo) throws Exception {
+        final String uniqueTestName = safeUniqueTestName(testInfo);
+        final String inputTopic = uniqueTestName + "-input";
+
+        CLUSTER.createTopic(inputTopic);
+
+        try (final KafkaStreams streams = getRunningStreams(
+                streamsProperties(uniqueTestName, false), topology(inputTopic, 
cachingEnabled), true)) {
+            final List<ProducerRecord<String, String>> records = 
recordsWithHeaders(inputTopic);
+            produceSynchronously(records);
+
+            // sorted by key: "duplicate", "multi", "none", "single"
+            final List<KeyValue<String, ValueTimestampHeaders<String>>> 
latestValues = latestValuesByKey(records);
+            final ProducerRecord<String, String> firstRecord = records.get(0);
+            final ProducerRecord<String, String> lastRecord = 
records.get(records.size() - 1);
+            final Instant timeFrom = 
ofEpochMilli(windowStart(firstRecord.timestamp()));
+            final Instant timeTo = 
ofEpochMilli(windowStart(lastRecord.timestamp()));
+
+            retryOnExceptionWithTimeout(30_000, () -> {
+                for (final KeyValue<String, ValueTimestampHeaders<String>> 
latestValue : latestValues) {
+                    verifyForKey(streams, null, false, latestValue.key, 
records);
+                }
+
+                final ReadOnlyKeyValueStore<String, 
ValueTimestampHeaders<String>> kvStore =
+                    store(streams, HEADERS_KV_STORE, 
QueryableStoreTypes.timestampedKeyValueStoreWithHeaders(), null, false);
+                assertEquals(latestValues, 
toListAndCloseIterator(kvStore.all()));
+                assertEquals(reversed(latestValues), 
toListAndCloseIterator(kvStore.reverseAll()));
+                assertEquals(latestValues.subList(1, 3), 
toListAndCloseIterator(kvStore.range("multi", "none")));
+                assertEquals(reversed(latestValues.subList(1, 3)), 
toListAndCloseIterator(kvStore.reverseRange("multi", "none")));
+                assertEquals(latestValues.subList(3, 4), 
toListAndCloseIterator(kvStore.prefixScan("si", new StringSerializer())));
+
+                final ReadOnlyWindowStore<String, 
ValueTimestampHeaders<String>> windowStore =
+                    store(streams, HEADERS_WINDOW_STORE, 
QueryableStoreTypes.timestampedWindowStoreWithHeaders(), null, false);
+                final List<KeyValue<Windowed<String>, 
ValueTimestampHeaders<String>>> windows =
+                    
records.stream().map(IQv1HeadersStoreIntegrationTest::window).collect(Collectors.toList());
+                final List<KeyValue<Windowed<String>, 
ValueTimestampHeaders<String>>> allWindows =
+                    toListAndCloseIterator(windowStore.all());
+                assertSameEntries(windows, allWindows);
+                assertEquals(reversed(allWindows), 
toListAndCloseIterator(windowStore.backwardAll()));
+                final List<KeyValue<Windowed<String>, 
ValueTimestampHeaders<String>>> fetchedWindows =
+                    toListAndCloseIterator(windowStore.fetchAll(timeFrom, 
timeTo));
+                assertSameEntries(windows, fetchedWindows);
+                assertEquals(reversed(fetchedWindows), 
toListAndCloseIterator(windowStore.backwardFetchAll(timeFrom, timeTo)));
+                // only the last record is in the later window
+                assertEquals(
+                    Collections.singletonList(window(lastRecord)),
+                    toListAndCloseIterator(windowStore.fetch("duplicate", 
"single", timeTo, timeTo)));
+                assertEquals(valueTimestampHeaders(firstRecord), 
windowStore.fetch("multi", timeFrom.toEpochMilli()));
+                // the two records of "multi" are in two windows
+                final List<KeyValue<Long, ValueTimestampHeaders<String>>> 
multiWindows = Arrays.asList(
+                    KeyValue.pair(timeFrom.toEpochMilli(), 
valueTimestampHeaders(firstRecord)),
+                    KeyValue.pair(timeTo.toEpochMilli(), 
valueTimestampHeaders(lastRecord)));
+                assertEquals(reversed(multiWindows), 
toListAndCloseIterator(windowStore.backwardFetch("multi", timeFrom, timeTo)));
+
+                final ReadOnlySessionStore<String, 
AggregationWithHeaders<String>> sessionStore =
+                    store(streams, HEADERS_SESSION_STORE, 
QueryableStoreTypes.sessionStoreWithHeaders(), null, false);
+                final List<KeyValue<Windowed<String>, 
AggregationWithHeaders<String>>> sessions =
+                    
records.stream().map(IQv1HeadersStoreIntegrationTest::session).collect(Collectors.toList());
+                final List<KeyValue<Windowed<String>, 
AggregationWithHeaders<String>>> fetchedSessions =
+                    toListAndCloseIterator(sessionStore.fetch("duplicate", 
"single"));
+                assertSameEntries(sessions, fetchedSessions);
+                assertEquals(reversed(fetchedSessions), 
toListAndCloseIterator(sessionStore.backwardFetch("duplicate", "single")));
+                // null bounds fetch the sessions of all keys
+                final List<KeyValue<Windowed<String>, 
AggregationWithHeaders<String>>> allSessions =
+                    toListAndCloseIterator(sessionStore.fetch(null, null));
+                assertSameEntries(sessions, allSessions);
+                assertEquals(reversed(allSessions), 
toListAndCloseIterator(sessionStore.backwardFetch(null, null)));
+                // only the session of the last record ends after the first 
record
+                assertEquals(
+                    Collections.singletonList(session(lastRecord)),
+                    toListAndCloseIterator(sessionStore.findSessions("multi", 
firstRecord.timestamp() + 1, lastRecord.timestamp())));
+                assertEquals(
+                    Collections.singletonList(session(firstRecord)),
+                    
toListAndCloseIterator(sessionStore.backwardFindSessions("multi", 
firstRecord.timestamp(), firstRecord.timestamp())));
+                assertEquals(
+                    session(firstRecord).value,
+                    sessionStore.fetchSession("multi", 
firstRecord.timestamp(), firstRecord.timestamp()));
+            });
+        }
+    }
+
+    @ParameterizedTest
+    @ValueSource(booleans = {true, false})
+    public void shouldHandleNullKeysAndNullBoundsOfHeadersAwareStores(final 
boolean cachingEnabled,
+                                                                       final 
TestInfo testInfo) throws Exception {
+        final String uniqueTestName = safeUniqueTestName(testInfo);
+        final String inputTopic = uniqueTestName + "-input";
+
+        CLUSTER.createTopic(inputTopic);
+
+        try (final KafkaStreams streams = getRunningStreams(
+                streamsProperties(uniqueTestName, false), topology(inputTopic, 
cachingEnabled), true)) {
+            final List<ProducerRecord<String, String>> records = 
recordsWithHeaders(inputTopic);
+            produceSynchronously(records);
+
+            // sorted by key: "duplicate", "multi", "none", "single"
+            final List<KeyValue<String, ValueTimestampHeaders<String>>> 
latestValues = latestValuesByKey(records);
+            final List<KeyValue<Windowed<String>, 
ValueTimestampHeaders<String>>> windows =
+                
records.stream().map(IQv1HeadersStoreIntegrationTest::window).collect(Collectors.toList());
+            final List<KeyValue<Windowed<String>, 
AggregationWithHeaders<String>>> sessions =
+                
records.stream().map(IQv1HeadersStoreIntegrationTest::session).collect(Collectors.toList());
+            final long firstTimestamp = records.get(0).timestamp();
+            final long lastTimestamp = records.get(records.size() - 
1).timestamp();
+            final Instant timeFrom = ofEpochMilli(windowStart(firstTimestamp));
+            final Instant timeTo = ofEpochMilli(windowStart(lastTimestamp));
+
+            retryOnExceptionWithTimeout(30_000, () -> {
+                // a null key is rejected by the store, while a null bound of 
a range means that the range is unbounded
+                final ReadOnlyKeyValueStore<String, 
ValueTimestampHeaders<String>> kvStore =
+                    store(streams, HEADERS_KV_STORE, 
QueryableStoreTypes.timestampedKeyValueStoreWithHeaders(), null, false);
+                assertEquals(latestValues, 
toListAndCloseIterator(kvStore.range(null, null)));
+                assertEquals(reversed(latestValues), 
toListAndCloseIterator(kvStore.reverseRange(null, null)));
+                assertEquals(latestValues.subList(0, 2), 
toListAndCloseIterator(kvStore.range(null, "multi")));
+                assertEquals(reversed(latestValues.subList(2, 4)), 
toListAndCloseIterator(kvStore.reverseRange("none", null)));
+                assertThrows(NullPointerException.class, () -> 
kvStore.get(null));
+
+                final ReadOnlyWindowStore<String, 
ValueTimestampHeaders<String>> windowStore =
+                    store(streams, HEADERS_WINDOW_STORE, 
QueryableStoreTypes.timestampedWindowStoreWithHeaders(), null, false);
+                final List<KeyValue<Windowed<String>, 
ValueTimestampHeaders<String>>> fetchedWindows =
+                    toListAndCloseIterator(windowStore.fetch(null, null, 
timeFrom, timeTo));
+                assertSameEntries(windows, fetchedWindows);
+                assertEquals(reversed(fetchedWindows), 
toListAndCloseIterator(windowStore.backwardFetch(null, null, timeFrom, 
timeTo)));
+                assertSameEntries(
+                    windows.stream().filter(window -> 
window.key.key().compareTo("multi") <= 0).collect(Collectors.toList()),
+                    toListAndCloseIterator(windowStore.fetch(null, "multi", 
timeFrom, timeTo)));
+                assertThrows(NullPointerException.class, () -> 
windowStore.fetch(null, timeFrom.toEpochMilli()));
+                assertThrows(NullPointerException.class, () -> 
windowStore.fetch(null, timeFrom, timeTo));
+                assertThrows(NullPointerException.class, () -> 
windowStore.backwardFetch(null, timeFrom, timeTo));
+
+                final ReadOnlySessionStore<String, 
AggregationWithHeaders<String>> sessionStore =
+                    store(streams, HEADERS_SESSION_STORE, 
QueryableStoreTypes.sessionStoreWithHeaders(), null, false);
+                final List<KeyValue<Windowed<String>, 
AggregationWithHeaders<String>>> foundSessions =
+                    toListAndCloseIterator(sessionStore.findSessions(null, 
null, firstTimestamp, lastTimestamp));
+                assertSameEntries(sessions, foundSessions);
+                assertEquals(
+                    reversed(foundSessions),
+                    
toListAndCloseIterator(sessionStore.backwardFindSessions(null, null, 
firstTimestamp, lastTimestamp)));
+                assertSameEntries(
+                    sessions.stream().filter(session -> 
session.key.key().compareTo("none") >= 0).collect(Collectors.toList()),
+                    toListAndCloseIterator(sessionStore.fetch("none", null)));
+                assertThrows(NullPointerException.class, () -> 
sessionStore.fetch(null));
+                assertThrows(NullPointerException.class, () -> 
sessionStore.backwardFetch(null));
+                assertThrows(NullPointerException.class, () -> 
sessionStore.findSessions(null, firstTimestamp, lastTimestamp));
+                assertThrows(NullPointerException.class, () -> 
sessionStore.fetchSession(null, firstTimestamp, firstTimestamp));
+            });
+        }
+    }
+
+    @Test
+    public void 
shouldReturnRecordHeadersFromHeadersAwareGlobalStoreBeforeAndAfterRestoration(final
 TestInfo testInfo) throws Exception {
+        final String uniqueTestName = safeUniqueTestName(testInfo);
+        final String inputTopic = uniqueTestName + "-input";
+        final String storeName = uniqueTestName + "-global-store";
+
+        CLUSTER.createTopic(inputTopic);
+
+        final List<ProducerRecord<String, String>> records = 
recordsWithHeaders(inputTopic);
+        final List<KeyValue<String, ValueTimestampHeaders<String>>> 
latestValues = latestValuesByKey(records);
+        final Properties properties = streamsProperties(uniqueTestName, false);
+
+        // the global store is updated by the processor while the application 
runs
+        try (final KafkaStreams streams = getRunningStreams(properties, 
globalTopology(inputTopic, storeName), true)) {
+            produceSynchronously(records);
+            retryOnExceptionWithTimeout(30_000, () -> 
verifyGlobalStore(streams, storeName, latestValues));
+        }
+
+        // With an empty state directory, the global store is restored from 
its source topic. The restored records
+        // bypass the processor, so it is the restore path that must keep the 
headers of the records.

Review Comment:
   this comment is not accurate. 
   `StreamsBuilder.addGlobalStore` sets `reprocessOnRestore=true`, so the 
restore replays every record through `GlobalWriter`. 
   I counted 5 `process()` calls during restore with a fresh state dir. The 
test passes but does not cover the converter restore path.



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