You are viewing a plain text version of this content. The canonical link for it is here.
Posted to jira@kafka.apache.org by "hanyuzheng7 (via GitHub)" <gi...@apache.org> on 2023/10/18 06:22:04 UTC

[PR] KAFKA-15629: Proposal to introduce IQv2 Query Types: TimestampKeyQuery and TimestampRangeQuery [kafka]

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

   In the current IQv2 code, there are noticeable differences when interfacing with plain-kv-store and ts-kv-store. Notably, the return type V acts as a simple value for plain-kv-store but evolves into ValueAndTimestamp<V> for ts-kv-store, which presents type safety issues in the API.
   
   Even if IQv2 hasn't gained widespread adoption, an immediate fix might bring compatibility concerns.
   
   This brings us to the essence of our proposal: the introduction of distinct query types. One that returns a plain value, another for values accompanied by timestamps.
   
   While querying a ts-kv-store for a plain value and then extracting it is feasible, it doesn't make sense to query a plain-kv-store for a ValueAndTimestamp<V>.
   
   Our vision is for plain-kv-store to always return V, while ts-kv-store should return ValueAndTimestamp<V>.
   
   ### Committer Checklist (excluded from commit message)
   - [ ] Verify design and implementation 
   - [ ] Verify test coverage and CI build status
   - [ ] Verify documentation (including upgrade notes)
   


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: jira-unsubscribe@kafka.apache.org

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


Re: [PR] KAFKA-15629: Proposal to introduce IQv2 Query Types: TimestampedKeyQuery and TimestampedRangeQuery [kafka]

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


##########
streams/src/main/java/org/apache/kafka/streams/state/internals/MeteredTimestampedKeyValueStore.java:
##########
@@ -102,4 +140,230 @@ static class RawAndDeserializedValue<ValueType> {
             this.value = value;
         }
     }
+
+    @SuppressWarnings("unchecked")
+    @Override
+    public <R> QueryResult<R> query(final Query<R> query,
+                                    final PositionBound positionBound,
+                                    final QueryConfig config) {
+
+        final long start = time.nanoseconds();
+        final QueryResult<R> result;
+
+        final StoreQueryUtils.QueryHandler handler = queryHandlers.get(query.getClass());
+        if (handler == null) {
+            result = wrapped().query(query, positionBound, config);
+            if (config.isCollectExecutionInfo()) {
+                result.addExecutionInfo(
+                        "Handled in " + getClass() + " in " + (time.nanoseconds() - start) + "ns");
+            }
+        } else {
+            result = (QueryResult<R>) handler.apply(
+                    query,
+                    positionBound,
+                    config,
+                    this
+            );
+            if (config.isCollectExecutionInfo()) {
+                result.addExecutionInfo(
+                        "Handled in " + getClass() + " with serdes "
+                                + serdes + " in " + (time.nanoseconds() - start) + "ns");
+            }
+        }
+        return result;
+    }
+
+
+
+    @SuppressWarnings("unchecked")
+    protected <R> QueryResult<R> runTimestampKeyQuery(final Query<R> query,
+                                                      final PositionBound positionBound,
+                                                      final QueryConfig config) {
+        final QueryResult<R> result;
+        final TimestampedKeyQuery<K, V> typedKeyQuery = (TimestampedKeyQuery<K, V>) query;
+        final KeyQuery<Bytes, byte[]> rawKeyQuery =
+                KeyQuery.withKey(keyBytes(typedKeyQuery.getKey()));
+        final QueryResult<byte[]> rawResult =
+                wrapped().query(rawKeyQuery, positionBound, config);
+        if (rawResult.isSuccess()) {
+            final Function<byte[], ValueAndTimestamp<V>> deserializer = getDeserializeValue(serdes, wrapped());
+            final ValueAndTimestamp<V> value = deserializer.apply(rawResult.getResult());
+            final QueryResult<ValueAndTimestamp<V>> typedQueryResult =
+                    InternalQueryResultUtil.copyAndSubstituteDeserializedResult(rawResult, value);
+            result = (QueryResult<R>) typedQueryResult;
+        } else {
+            // the generic type doesn't matter, since failed queries have no result set.
+            result = (QueryResult<R>) rawResult;
+        }
+        return result;
+    }
+
+    @SuppressWarnings("unchecked")
+    protected <R> QueryResult<R> runTimestampRangeQuery(final Query<R> query,
+                                                        final PositionBound positionBound,
+                                                        final QueryConfig config) {
+
+        final QueryResult<R> result;
+        final TimestampedRangeQuery<K, V> typedQuery = (TimestampedRangeQuery<K, V>) query;
+
+        final RangeQuery<Bytes, byte[]> rawRangeQuery;
+        if (typedQuery.getLowerBound().isPresent() && typedQuery.getUpperBound().isPresent()) {
+            rawRangeQuery = RangeQuery.withRange(
+                    keyBytes(typedQuery.getLowerBound().get()),
+                    keyBytes(typedQuery.getUpperBound().get())
+            );
+        } else if (typedQuery.getLowerBound().isPresent()) {
+            rawRangeQuery = RangeQuery.withLowerBound(keyBytes(typedQuery.getLowerBound().get()));
+        } else if (typedQuery.getUpperBound().isPresent()) {
+            rawRangeQuery = RangeQuery.withUpperBound(keyBytes(typedQuery.getUpperBound().get()));
+        } else {
+            rawRangeQuery = RangeQuery.withNoBounds();
+        }
+        final QueryResult<KeyValueIterator<Bytes, byte[]>> rawResult =
+                wrapped().query(rawRangeQuery, positionBound, config);
+        if (rawResult.isSuccess()) {
+            final KeyValueIterator<Bytes, byte[]> iterator = rawResult.getResult();
+            final KeyValueIterator<K, V> resultIterator = new MeteredKeyValueTimestampedIterator(
+                    iterator,
+                    getSensor,
+                    getDeserializeValue(serdes, wrapped()),
+                    false
+            );
+            final QueryResult<KeyValueIterator<K, V>> typedQueryResult =
+                    InternalQueryResultUtil.copyAndSubstituteDeserializedResult(
+                            rawResult,
+                            resultIterator
+                    );
+            result = (QueryResult<R>) typedQueryResult;
+        } else {
+            // the generic type doesn't matter, since failed queries have no result set.
+            result = (QueryResult<R>) rawResult;
+        }
+        return result;
+    }
+
+    @SuppressWarnings("unchecked")
+    protected <R> QueryResult<R> runKeyQuery2(final Query<R> query,

Review Comment:
   solved
   



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: jira-unsubscribe@kafka.apache.org

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


Re: [PR] KAFKA-15629: Proposal to introduce IQv2 Query Types: TimestampedKeyQuery and TimestampedRangeQuery [kafka]

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


##########
streams/src/main/java/org/apache/kafka/streams/query/TimestampedKeyQuery.java:
##########
@@ -0,0 +1,70 @@
+/*
+ * 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.query;
+
+import org.apache.kafka.common.annotation.InterfaceStability.Evolving;
+import org.apache.kafka.streams.state.ValueAndTimestamp;
+
+import java.util.Objects;
+
+/**
+ * Interactive query for retrieving a single record based on its key.
+ */
+@Evolving
+public final class TimestampedKeyQuery<K, V> implements Query<ValueAndTimestamp<V>> {
+
+    private final K key;
+    private final boolean skipCache;
+
+    private TimestampedKeyQuery(final K key, final boolean skipCache) {
+        this.key = Objects.requireNonNull(key);

Review Comment:
   ok, but it seems that `withkey() `use r`eturn new KeyQuery<>(key, false);` to do the check now.



##########
streams/src/main/java/org/apache/kafka/streams/query/TimestampedKeyQuery.java:
##########
@@ -0,0 +1,70 @@
+/*
+ * 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.query;
+
+import org.apache.kafka.common.annotation.InterfaceStability.Evolving;
+import org.apache.kafka.streams.state.ValueAndTimestamp;
+
+import java.util.Objects;
+
+/**
+ * Interactive query for retrieving a single record based on its key.
+ */
+@Evolving
+public final class TimestampedKeyQuery<K, V> implements Query<ValueAndTimestamp<V>> {
+
+    private final K key;
+    private final boolean skipCache;
+
+    private TimestampedKeyQuery(final K key, final boolean skipCache) {
+        this.key = Objects.requireNonNull(key);

Review Comment:
   ok, but it seems that `withkey() `use `return` new KeyQuery<>(key, false);` to do the check now.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: jira-unsubscribe@kafka.apache.org

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


Re: [PR] KAFKA-15629: Proposal to introduce IQv2 Query Types: TimestampedKeyQuery and TimestampedRangeQuery [kafka]

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


##########
streams/src/main/java/org/apache/kafka/streams/state/internals/MeteredTimestampedKeyValueStore.java:
##########
@@ -102,4 +139,232 @@ static class RawAndDeserializedValue<ValueType> {
             this.value = value;
         }
     }
+
+    @SuppressWarnings("unchecked")
+    @Override
+    public <R> QueryResult<R> query(final Query<R> query,
+                                    final PositionBound positionBound,
+                                    final QueryConfig config) {
+
+        final long start = time.nanoseconds();
+        final QueryResult<R> result;
+
+        final StoreQueryUtils.QueryHandler handler = queryHandlers.get(query.getClass());
+        if (handler == null) {
+            result = wrapped().query(query, positionBound, config);
+            if (config.isCollectExecutionInfo()) {
+                result.addExecutionInfo(
+                        "Handled in " + getClass() + " in " + (time.nanoseconds() - start) + "ns");
+            }
+        } else {
+            result = (QueryResult<R>) handler.apply(
+                    query,
+                    positionBound,
+                    config,
+                    this
+            );
+            if (config.isCollectExecutionInfo()) {
+                result.addExecutionInfo(
+                        "Handled in " + getClass() + " with serdes "
+                                + serdes + " in " + (time.nanoseconds() - start) + "ns");
+            }
+        }
+        return result;
+    }
+
+
+
+    @SuppressWarnings("unchecked")
+    protected <R> QueryResult<R> runTimestampedKeyQuery(final Query<R> query,

Review Comment:
   Why is it `protected` in `MeteredKeyValueStore` -- I believe it should be `private` there, too? Can you try it out?



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: jira-unsubscribe@kafka.apache.org

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


Re: [PR] KAFKA-15629: Proposal to introduce IQv2 Query Types: TimestampedKeyQuery and TimestampedRangeQuery [kafka]

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


##########
streams/src/main/java/org/apache/kafka/streams/state/internals/KeyValueToTimestampedKeyValueByteStoreAdapter.java:
##########
@@ -127,14 +131,31 @@ public <R> QueryResult<R> query(
         final QueryConfig config) {
 
 
+
         final long start = config.isCollectExecutionInfo() ? System.nanoTime() : -1L;
-        final QueryResult<R> result = store.query(query, positionBound, config);
+        QueryResult<R> result = store.query(query, positionBound, config);
+        final Position position = result.getPosition();
+
+        if (result.isSuccess()) {
+            if (result.getResult() instanceof byte[]) {
+                final byte[] plainValue = (byte[]) result.getResult();
+                final byte[] valueWithTimestamp = convertToTimestampedFormat(plainValue);
+                result = (QueryResult<R>) QueryResult.forResult(valueWithTimestamp);

Review Comment:
   Should we use `InternalQueryResultUtil.copyAndSubstituteDeserializedResult` instead, to create a copy of the result correctly?



##########
streams/src/main/java/org/apache/kafka/streams/query/TimestampedKeyQuery.java:
##########
@@ -0,0 +1,70 @@
+/*
+ * 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.query;
+
+import org.apache.kafka.common.annotation.InterfaceStability.Evolving;
+import org.apache.kafka.streams.state.ValueAndTimestamp;
+
+import java.util.Objects;
+
+/**
+ * Interactive query for retrieving a single record based on its key.
+ */
+@Evolving
+public final class TimestampedKeyQuery<K, V> implements Query<ValueAndTimestamp<V>> {
+
+    private final K key;
+    private final boolean skipCache;
+
+    private TimestampedKeyQuery(final K key, final boolean skipCache) {
+        this.key = Objects.requireNonNull(key);

Review Comment:
   I think this check should go into `withKey()` -- we should also add an error message
   
   (Might be good to clean this up, inside `KeyQuery`, too)



##########
streams/src/main/java/org/apache/kafka/streams/state/internals/KeyValueToTimestampedKeyValueByteStoreAdapter.java:
##########
@@ -180,5 +201,38 @@ public <PS extends Serializer<P>, P> KeyValueIterator<Bytes, byte[]> prefixScan(
     public long approximateNumEntries() {
         return store.approximateNumEntries();
     }
+}
 
+class WrappedRocksDbIterator extends AbstractIterator implements ManagedKeyValueIterator {

Review Comment:
   Wondering if we should only `implements ManagedKeyValueIterator<Bytes, byte[]>` 🤔 -- what do we gain/need from `AbstractIterator`?
   
   We should for sure set the correct types:
   ```
   ... extends AbstractIterator<KeyValue<Bytes, byte[]>> implements ManagedKeyValueIterator<Bytes, byte[]>
   ```
   to fix the `Object` return type on some methods.
   
   
   
   



##########
streams/src/main/java/org/apache/kafka/streams/state/internals/KeyValueToTimestampedKeyValueByteStoreAdapter.java:
##########
@@ -180,5 +201,38 @@ public <PS extends Serializer<P>, P> KeyValueIterator<Bytes, byte[]> prefixScan(
     public long approximateNumEntries() {
         return store.approximateNumEntries();
     }
+}
 
+class WrappedRocksDbIterator extends AbstractIterator implements ManagedKeyValueIterator {

Review Comment:
   Wondering if we should only `implements ManagedKeyValueIterator<Bytes, byte[]>` 🤔 -- what do we gain/need from `AbstractIterator`?
   
   We should for sure set the correct types:
   ```
   ... extends AbstractIterator<KeyValue<Bytes, byte[]>> implements ManagedKeyValueIterator<Bytes, byte[]>
   ```
   to fix the `Object` return type on some methods.
   
   
   
   



##########
streams/src/main/java/org/apache/kafka/streams/query/TimestampedKeyQuery.java:
##########
@@ -0,0 +1,70 @@
+/*
+ * 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.query;
+
+import org.apache.kafka.common.annotation.InterfaceStability.Evolving;
+import org.apache.kafka.streams.state.ValueAndTimestamp;
+
+import java.util.Objects;
+
+/**
+ * Interactive query for retrieving a single record based on its key.
+ */
+@Evolving
+public final class TimestampedKeyQuery<K, V> implements Query<ValueAndTimestamp<V>> {
+
+    private final K key;
+    private final boolean skipCache;
+
+    private TimestampedKeyQuery(final K key, final boolean skipCache) {
+        this.key = Objects.requireNonNull(key);
+        this.skipCache = skipCache;
+    }
+
+    /**
+     * Creates a query that will retrieve the record identified by {@code key} if it exists
+     * (or {@code null} otherwise).
+     * @param key The key to retrieve
+     * @param <K> The type of the key
+     * @param <V> The type of the value that will be retrieved
+     */
+    public static <K, V> TimestampedKeyQuery<K, V> withKey(final K key) {
+        return new TimestampedKeyQuery<>(key, false);
+    }
+
+    /**
+     * Specifies that the cache should be skipped during query evaluation. This means, that the query will always
+     * get forwarded to the underlying store.
+     */
+    public TimestampedKeyQuery<K, V> skipCache() {
+        return new TimestampedKeyQuery<>(key, true);
+    }
+
+    /**
+     * The key that was specified for this query.
+     */

Review Comment:
   We should add an `@return` annotation (I know, it's somewhat redundant, but still "cleaner" for the JavaDocs that are generated to have it) -- same below.



##########
streams/src/main/java/org/apache/kafka/streams/query/RangeQuery.java:
##########
@@ -34,6 +34,8 @@
  * <p>
  *  Keys' order is based on the serialized byte[] of the keys, not the 'logical' key order.
  * <p>

Review Comment:
   nit: remove unnecessary `<p>` tag



##########
streams/src/main/java/org/apache/kafka/streams/state/internals/KeyValueToTimestampedKeyValueByteStoreAdapter.java:
##########
@@ -180,5 +201,38 @@ public <PS extends Serializer<P>, P> KeyValueIterator<Bytes, byte[]> prefixScan(
     public long approximateNumEntries() {
         return store.approximateNumEntries();
     }
+}
 
+class WrappedRocksDbIterator extends AbstractIterator implements ManagedKeyValueIterator {

Review Comment:
   Can this class be `private` -- also, should we nest it inside the adaptor class?
   
   Would also rename it to `KeyValueToTimestampedKeyValueAdapterIterator` -- "wrapped" is very generic and not descriptive.



##########
streams/src/main/java/org/apache/kafka/streams/state/internals/KeyValueToTimestampedKeyValueByteStoreAdapter.java:
##########
@@ -180,5 +201,38 @@ public <PS extends Serializer<P>, P> KeyValueIterator<Bytes, byte[]> prefixScan(
     public long approximateNumEntries() {
         return store.approximateNumEntries();
     }
+}
 
+class WrappedRocksDbIterator extends AbstractIterator implements ManagedKeyValueIterator {
+    final private RocksDbIterator rocksDbIterator;
+    public WrappedRocksDbIterator(final RocksDbIterator rocksDbIterator) {

Review Comment:
   nit: add empty lines before and after constructor



##########
streams/src/main/java/org/apache/kafka/streams/state/internals/KeyValueToTimestampedKeyValueByteStoreAdapter.java:
##########
@@ -180,5 +201,38 @@ public <PS extends Serializer<P>, P> KeyValueIterator<Bytes, byte[]> prefixScan(
     public long approximateNumEntries() {
         return store.approximateNumEntries();
     }
+}
 
+class WrappedRocksDbIterator extends AbstractIterator implements ManagedKeyValueIterator {
+    final private RocksDbIterator rocksDbIterator;
+    public WrappedRocksDbIterator(final RocksDbIterator rocksDbIterator) {
+        this.rocksDbIterator = rocksDbIterator;
+    }
+    @Override
+    protected Object makeNext() {
+        final KeyValue<Bytes, byte[]> next = rocksDbIterator.makeNext();
+        if (next == null) {
+            allDone();
+            return null;
+        }
+        final Bytes key = next.key;
+        final byte[] value = next.value;
+        final byte[] res = convertToTimestampedFormat(value);
+        return KeyValue.pair(key, res);
+    }
+
+    @Override
+    public void close() {

Review Comment:
   We need to call `rocksDbIterator.close()` here -- same for all other public method -- we need to forward the call the the iterator we wrap.



##########
streams/src/main/java/org/apache/kafka/streams/query/TimestampedRangeQuery.java:
##########
@@ -0,0 +1,131 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+
+package org.apache.kafka.streams.query;
+
+
+import org.apache.kafka.common.annotation.InterfaceStability.Evolving;
+import org.apache.kafka.streams.state.KeyValueIterator;
+import org.apache.kafka.streams.state.ValueAndTimestamp;
+
+
+import java.util.Optional;
+
+/**
+ * Interactive query for issuing range queries and scans over Timestamped
+ * KeyValue stores.
+ * <p>
+ *  A range query retrieves a set of records, specified using an upper and/or lower bound on the keys.
+ * <p>
+ *  A scan query retrieves all records contained in the store.
+ * <p>
+ *  Keys' order is based on the serialized byte[] of the keys, not the 'logical' key order.
+ * <p>

Review Comment:
   nit: remove unnecessary `<p>` tag



##########
streams/src/main/java/org/apache/kafka/streams/state/internals/KeyValueToTimestampedKeyValueByteStoreAdapter.java:
##########
@@ -180,5 +201,38 @@ public <PS extends Serializer<P>, P> KeyValueIterator<Bytes, byte[]> prefixScan(
     public long approximateNumEntries() {
         return store.approximateNumEntries();
     }
+}
 
+class WrappedRocksDbIterator extends AbstractIterator implements ManagedKeyValueIterator {
+    final private RocksDbIterator rocksDbIterator;
+    public WrappedRocksDbIterator(final RocksDbIterator rocksDbIterator) {
+        this.rocksDbIterator = rocksDbIterator;
+    }
+    @Override
+    protected Object makeNext() {
+        final KeyValue<Bytes, byte[]> next = rocksDbIterator.makeNext();
+        if (next == null) {
+            allDone();
+            return null;
+        }
+        final Bytes key = next.key;
+        final byte[] value = next.value;
+        final byte[] res = convertToTimestampedFormat(value);
+        return KeyValue.pair(key, res);

Review Comment:
   Seems we can make this a one-liner:
   ```
   return KeyValue(next.key, convertToTimestampedFormat(next.value));
   ```



##########
streams/src/main/java/org/apache/kafka/streams/state/internals/MeteredTimestampedKeyValueStore.java:
##########
@@ -102,4 +139,232 @@ static class RawAndDeserializedValue<ValueType> {
             this.value = value;
         }
     }
+
+    @SuppressWarnings("unchecked")
+    @Override
+    public <R> QueryResult<R> query(final Query<R> query,
+                                    final PositionBound positionBound,
+                                    final QueryConfig config) {
+
+        final long start = time.nanoseconds();
+        final QueryResult<R> result;
+
+        final StoreQueryUtils.QueryHandler handler = queryHandlers.get(query.getClass());
+        if (handler == null) {
+            result = wrapped().query(query, positionBound, config);
+            if (config.isCollectExecutionInfo()) {
+                result.addExecutionInfo(
+                        "Handled in " + getClass() + " in " + (time.nanoseconds() - start) + "ns");
+            }
+        } else {
+            result = (QueryResult<R>) handler.apply(
+                    query,
+                    positionBound,
+                    config,
+                    this
+            );
+            if (config.isCollectExecutionInfo()) {
+                result.addExecutionInfo(
+                        "Handled in " + getClass() + " with serdes "
+                                + serdes + " in " + (time.nanoseconds() - start) + "ns");
+            }
+        }
+        return result;
+    }
+
+
+
+    @SuppressWarnings("unchecked")
+    protected <R> QueryResult<R> runTimestampedKeyQuery(final Query<R> query,

Review Comment:
   Why do we add this as `protected`? Seems it could be `private`? (same below)



##########
streams/src/main/java/org/apache/kafka/streams/state/internals/MeteredTimestampedKeyValueStore.java:
##########
@@ -102,4 +139,232 @@ static class RawAndDeserializedValue<ValueType> {
             this.value = value;
         }
     }
+
+    @SuppressWarnings("unchecked")
+    @Override
+    public <R> QueryResult<R> query(final Query<R> query,
+                                    final PositionBound positionBound,
+                                    final QueryConfig config) {
+
+        final long start = time.nanoseconds();
+        final QueryResult<R> result;
+
+        final StoreQueryUtils.QueryHandler handler = queryHandlers.get(query.getClass());
+        if (handler == null) {
+            result = wrapped().query(query, positionBound, config);
+            if (config.isCollectExecutionInfo()) {
+                result.addExecutionInfo(
+                        "Handled in " + getClass() + " in " + (time.nanoseconds() - start) + "ns");
+            }
+        } else {
+            result = (QueryResult<R>) handler.apply(
+                    query,
+                    positionBound,
+                    config,
+                    this
+            );
+            if (config.isCollectExecutionInfo()) {
+                result.addExecutionInfo(
+                        "Handled in " + getClass() + " with serdes "
+                                + serdes + " in " + (time.nanoseconds() - start) + "ns");
+            }
+        }
+        return result;
+    }
+
+
+
+    @SuppressWarnings("unchecked")
+    protected <R> QueryResult<R> runTimestampedKeyQuery(final Query<R> query,
+                                                      final PositionBound positionBound,

Review Comment:
   nit: fix intention 



##########
streams/src/main/java/org/apache/kafka/streams/state/internals/MeteredTimestampedKeyValueStore.java:
##########
@@ -102,4 +139,232 @@ static class RawAndDeserializedValue<ValueType> {
             this.value = value;
         }
     }
+
+    @SuppressWarnings("unchecked")
+    @Override
+    public <R> QueryResult<R> query(final Query<R> query,
+                                    final PositionBound positionBound,
+                                    final QueryConfig config) {
+
+        final long start = time.nanoseconds();
+        final QueryResult<R> result;
+
+        final StoreQueryUtils.QueryHandler handler = queryHandlers.get(query.getClass());
+        if (handler == null) {
+            result = wrapped().query(query, positionBound, config);
+            if (config.isCollectExecutionInfo()) {
+                result.addExecutionInfo(
+                        "Handled in " + getClass() + " in " + (time.nanoseconds() - start) + "ns");
+            }
+        } else {
+            result = (QueryResult<R>) handler.apply(
+                    query,
+                    positionBound,
+                    config,
+                    this
+            );
+            if (config.isCollectExecutionInfo()) {
+                result.addExecutionInfo(
+                        "Handled in " + getClass() + " with serdes "
+                                + serdes + " in " + (time.nanoseconds() - start) + "ns");
+            }
+        }
+        return result;
+    }
+
+
+
+    @SuppressWarnings("unchecked")
+    protected <R> QueryResult<R> runTimestampedKeyQuery(final Query<R> query,
+                                                      final PositionBound positionBound,
+                                                      final QueryConfig config) {
+        final QueryResult<R> result;
+        final TimestampedKeyQuery<K, V> typedKeyQuery = (TimestampedKeyQuery<K, V>) query;
+        final KeyQuery<Bytes, byte[]> rawKeyQuery =
+                KeyQuery.withKey(keyBytes(typedKeyQuery.key()));
+        final QueryResult<byte[]> rawResult =
+                wrapped().query(rawKeyQuery, positionBound, config);
+        if (rawResult.isSuccess()) {
+            final Function<byte[], ValueAndTimestamp<V>> deserializer = getDeserializeValue(serdes, wrapped());
+            final ValueAndTimestamp<V> value = deserializer.apply(rawResult.getResult());
+            final QueryResult<ValueAndTimestamp<V>> typedQueryResult =
+                    InternalQueryResultUtil.copyAndSubstituteDeserializedResult(rawResult, value);
+            result = (QueryResult<R>) typedQueryResult;
+        } else {
+            // the generic type doesn't matter, since failed queries have no result set.
+            result = (QueryResult<R>) rawResult;
+        }
+        return result;
+    }
+
+    @SuppressWarnings("unchecked")
+    protected <R> QueryResult<R> runTimestampedRangeQuery(final Query<R> query,
+                                                        final PositionBound positionBound,
+                                                        final QueryConfig config) {
+
+        final QueryResult<R> result;
+        final TimestampedRangeQuery<K, V> typedQuery = (TimestampedRangeQuery<K, V>) query;
+        RangeQuery<Bytes, byte[]> rawRangeQuery;
+        final boolean isKeyAscending = typedQuery.isKeyAscending();
+        if (typedQuery.lowerBound().isPresent() && typedQuery.upperBound().isPresent()) {
+            rawRangeQuery = RangeQuery.withRange(

Review Comment:
   Given that we can pass in `null` for upper and/or lower bound (with semantics "no bound") I am wondering if we can simplify this whole if/else stuff here?
   ```
   rawRangeQuery = RangeQuery.withRange(
       keyBytes(typedQuery.lowerBound().orElse(null)),
       keyBytes(typedQuery.upperBound().orElse(null))
   );
   ```



##########
streams/src/main/java/org/apache/kafka/streams/state/internals/KeyValueToTimestampedKeyValueByteStoreAdapter.java:
##########
@@ -180,5 +201,38 @@ public <PS extends Serializer<P>, P> KeyValueIterator<Bytes, byte[]> prefixScan(
     public long approximateNumEntries() {
         return store.approximateNumEntries();
     }
+}
 
+class WrappedRocksDbIterator extends AbstractIterator implements ManagedKeyValueIterator {
+    final private RocksDbIterator rocksDbIterator;
+    public WrappedRocksDbIterator(final RocksDbIterator rocksDbIterator) {
+        this.rocksDbIterator = rocksDbIterator;
+    }
+    @Override
+    protected Object makeNext() {
+        final KeyValue<Bytes, byte[]> next = rocksDbIterator.makeNext();

Review Comment:
   Given that we _wrap_ `RocksDbIterator` we should not call `makeNext` directly? But instead of public methods only, ie, is `hasNext()` and `next()` instead. 



##########
streams/src/main/java/org/apache/kafka/streams/state/internals/MeteredTimestampedKeyValueStore.java:
##########
@@ -102,4 +139,232 @@ static class RawAndDeserializedValue<ValueType> {
             this.value = value;
         }
     }
+
+    @SuppressWarnings("unchecked")
+    @Override
+    public <R> QueryResult<R> query(final Query<R> query,
+                                    final PositionBound positionBound,
+                                    final QueryConfig config) {
+
+        final long start = time.nanoseconds();
+        final QueryResult<R> result;
+
+        final StoreQueryUtils.QueryHandler handler = queryHandlers.get(query.getClass());
+        if (handler == null) {
+            result = wrapped().query(query, positionBound, config);
+            if (config.isCollectExecutionInfo()) {
+                result.addExecutionInfo(
+                        "Handled in " + getClass() + " in " + (time.nanoseconds() - start) + "ns");
+            }
+        } else {
+            result = (QueryResult<R>) handler.apply(
+                    query,
+                    positionBound,
+                    config,
+                    this
+            );
+            if (config.isCollectExecutionInfo()) {
+                result.addExecutionInfo(
+                        "Handled in " + getClass() + " with serdes "
+                                + serdes + " in " + (time.nanoseconds() - start) + "ns");
+            }
+        }
+        return result;
+    }
+
+
+
+    @SuppressWarnings("unchecked")
+    protected <R> QueryResult<R> runTimestampedKeyQuery(final Query<R> query,
+                                                      final PositionBound positionBound,
+                                                      final QueryConfig config) {
+        final QueryResult<R> result;
+        final TimestampedKeyQuery<K, V> typedKeyQuery = (TimestampedKeyQuery<K, V>) query;
+        final KeyQuery<Bytes, byte[]> rawKeyQuery =
+                KeyQuery.withKey(keyBytes(typedKeyQuery.key()));
+        final QueryResult<byte[]> rawResult =
+                wrapped().query(rawKeyQuery, positionBound, config);
+        if (rawResult.isSuccess()) {
+            final Function<byte[], ValueAndTimestamp<V>> deserializer = getDeserializeValue(serdes, wrapped());
+            final ValueAndTimestamp<V> value = deserializer.apply(rawResult.getResult());

Review Comment:
   nit: `value` -> `valueAndTimestamp`



##########
streams/src/main/java/org/apache/kafka/streams/state/internals/MeteredTimestampedKeyValueStore.java:
##########
@@ -102,4 +139,232 @@ static class RawAndDeserializedValue<ValueType> {
             this.value = value;
         }
     }
+
+    @SuppressWarnings("unchecked")
+    @Override
+    public <R> QueryResult<R> query(final Query<R> query,
+                                    final PositionBound positionBound,
+                                    final QueryConfig config) {
+
+        final long start = time.nanoseconds();
+        final QueryResult<R> result;
+
+        final StoreQueryUtils.QueryHandler handler = queryHandlers.get(query.getClass());
+        if (handler == null) {
+            result = wrapped().query(query, positionBound, config);
+            if (config.isCollectExecutionInfo()) {
+                result.addExecutionInfo(
+                        "Handled in " + getClass() + " in " + (time.nanoseconds() - start) + "ns");
+            }
+        } else {
+            result = (QueryResult<R>) handler.apply(
+                    query,
+                    positionBound,
+                    config,
+                    this
+            );
+            if (config.isCollectExecutionInfo()) {
+                result.addExecutionInfo(
+                        "Handled in " + getClass() + " with serdes "
+                                + serdes + " in " + (time.nanoseconds() - start) + "ns");
+            }
+        }
+        return result;
+    }
+
+
+
+    @SuppressWarnings("unchecked")
+    protected <R> QueryResult<R> runTimestampedKeyQuery(final Query<R> query,
+                                                      final PositionBound positionBound,
+                                                      final QueryConfig config) {
+        final QueryResult<R> result;
+        final TimestampedKeyQuery<K, V> typedKeyQuery = (TimestampedKeyQuery<K, V>) query;
+        final KeyQuery<Bytes, byte[]> rawKeyQuery =
+                KeyQuery.withKey(keyBytes(typedKeyQuery.key()));
+        final QueryResult<byte[]> rawResult =
+                wrapped().query(rawKeyQuery, positionBound, config);
+        if (rawResult.isSuccess()) {
+            final Function<byte[], ValueAndTimestamp<V>> deserializer = getDeserializeValue(serdes, wrapped());
+            final ValueAndTimestamp<V> value = deserializer.apply(rawResult.getResult());
+            final QueryResult<ValueAndTimestamp<V>> typedQueryResult =
+                    InternalQueryResultUtil.copyAndSubstituteDeserializedResult(rawResult, value);
+            result = (QueryResult<R>) typedQueryResult;
+        } else {
+            // the generic type doesn't matter, since failed queries have no result set.
+            result = (QueryResult<R>) rawResult;
+        }
+        return result;
+    }
+
+    @SuppressWarnings("unchecked")
+    protected <R> QueryResult<R> runTimestampedRangeQuery(final Query<R> query,
+                                                        final PositionBound positionBound,
+                                                        final QueryConfig config) {
+
+        final QueryResult<R> result;
+        final TimestampedRangeQuery<K, V> typedQuery = (TimestampedRangeQuery<K, V>) query;
+        RangeQuery<Bytes, byte[]> rawRangeQuery;
+        final boolean isKeyAscending = typedQuery.isKeyAscending();
+        if (typedQuery.lowerBound().isPresent() && typedQuery.upperBound().isPresent()) {
+            rawRangeQuery = RangeQuery.withRange(
+                    keyBytes(typedQuery.lowerBound().get()),
+                    keyBytes(typedQuery.upperBound().get())
+            );
+        } else if (typedQuery.lowerBound().isPresent()) {
+            rawRangeQuery = RangeQuery.withLowerBound(keyBytes(typedQuery.lowerBound().get()));
+        } else if (typedQuery.upperBound().isPresent()) {
+            rawRangeQuery = RangeQuery.withUpperBound(keyBytes(typedQuery.upperBound().get()));
+        } else {
+            rawRangeQuery = RangeQuery.withNoBounds();
+        }
+        if (!isKeyAscending) {
+            rawRangeQuery = rawRangeQuery.withDescendingKeys();
+        }
+        final QueryResult<KeyValueIterator<Bytes, byte[]>> rawResult =
+                wrapped().query(rawRangeQuery, positionBound, config);
+        if (rawResult.isSuccess()) {
+            final KeyValueIterator<Bytes, byte[]> iterator = rawResult.getResult();
+            final KeyValueIterator<K, V> resultIterator = new MeteredKeyValueTimestampedIterator(
+                    iterator,
+                    getSensor,
+                    getDeserializeValue(serdes, wrapped()),
+                    false
+            );
+            final QueryResult<KeyValueIterator<K, V>> typedQueryResult =
+                    InternalQueryResultUtil.copyAndSubstituteDeserializedResult(
+                            rawResult,
+                            resultIterator
+                    );
+            result = (QueryResult<R>) typedQueryResult;
+        } else {
+            // the generic type doesn't matter, since failed queries have no result set.
+            result = (QueryResult<R>) rawResult;
+        }
+        return result;
+    }
+
+    @SuppressWarnings("unchecked")
+    protected <R> QueryResult<R> runKeyQuery(final Query<R> query,
+                                             final PositionBound positionBound,
+                                             final QueryConfig config) {
+        final QueryResult<R> result;
+        final KeyQuery<K, V> typedKeyQuery = (KeyQuery<K, V>) query;
+        final KeyQuery<Bytes, byte[]> rawKeyQuery =
+                KeyQuery.withKey(keyBytes(typedKeyQuery.getKey()));
+        final QueryResult<byte[]> rawResult =
+                wrapped().query(rawKeyQuery, positionBound, config);
+        if (rawResult.isSuccess()) {
+            final Function<byte[], ValueAndTimestamp<V>> deserializer = getDeserializeValue(serdes, wrapped());
+            final ValueAndTimestamp<V> valueAndTimestamp = deserializer.apply(rawResult.getResult());
+            final V plainValue = valueAndTimestamp == null ? null : valueAndTimestamp.value();
+            final QueryResult<V> typedQueryResult =
+                    InternalQueryResultUtil.copyAndSubstituteDeserializedResult(rawResult, plainValue);
+            result = (QueryResult<R>) typedQueryResult;
+        } else {
+            // the generic type doesn't matter, since failed queries have no result set.
+            result = (QueryResult<R>) rawResult;
+        }
+        return result;
+    }
+
+    @SuppressWarnings("unchecked")
+    protected <R> QueryResult<R> runRangeQuery(final Query<R> query,
+                                               final PositionBound positionBound,
+                                               final QueryConfig config) {
+
+        final QueryResult<R> result;
+        final RangeQuery<K, V> typedQuery = (RangeQuery<K, V>) query;
+        RangeQuery<Bytes, byte[]> rawRangeQuery;
+        final boolean isKeyAscending = typedQuery.isKeyAscending();
+        if (typedQuery.getLowerBound().isPresent() && typedQuery.getUpperBound().isPresent()) {
+            rawRangeQuery = RangeQuery.withRange(
+                    keyBytes(typedQuery.getLowerBound().get()),
+                    keyBytes(typedQuery.getUpperBound().get())
+            );
+        } else if (typedQuery.getLowerBound().isPresent()) {
+            rawRangeQuery = RangeQuery.withLowerBound(keyBytes(typedQuery.getLowerBound().get()));
+        } else if (typedQuery.getUpperBound().isPresent()) {
+            rawRangeQuery = RangeQuery.withUpperBound(keyBytes(typedQuery.getUpperBound().get()));
+        } else {
+            rawRangeQuery = RangeQuery.withNoBounds();
+        }
+        if (!isKeyAscending) {
+            rawRangeQuery = rawRangeQuery.withDescendingKeys();
+        }
+        final QueryResult<KeyValueIterator<Bytes, byte[]>> rawResult =
+                wrapped().query(rawRangeQuery, positionBound, config);
+        if (rawResult.isSuccess()) {
+            final KeyValueIterator<Bytes, byte[]> iterator = rawResult.getResult();
+            final KeyValueIterator<K, V> resultIterator = new MeteredKeyValueTimestampedIterator(

Review Comment:
   For `RangeQuery` we should not return `ValueAndTimestamp`, right? So why are we using ` MeteredKeyValueTimestampedIterator` -- where does the conversion from `ValueAndTimstamp` to "plain value" happen?



##########
streams/src/main/java/org/apache/kafka/streams/state/internals/MeteredTimestampedKeyValueStore.java:
##########
@@ -102,4 +140,230 @@ static class RawAndDeserializedValue<ValueType> {
             this.value = value;
         }
     }
+
+    @SuppressWarnings("unchecked")
+    @Override
+    public <R> QueryResult<R> query(final Query<R> query,
+                                    final PositionBound positionBound,
+                                    final QueryConfig config) {
+
+        final long start = time.nanoseconds();
+        final QueryResult<R> result;
+
+        final StoreQueryUtils.QueryHandler handler = queryHandlers.get(query.getClass());
+        if (handler == null) {
+            result = wrapped().query(query, positionBound, config);
+            if (config.isCollectExecutionInfo()) {
+                result.addExecutionInfo(
+                        "Handled in " + getClass() + " in " + (time.nanoseconds() - start) + "ns");
+            }
+        } else {
+            result = (QueryResult<R>) handler.apply(
+                    query,
+                    positionBound,
+                    config,
+                    this
+            );
+            if (config.isCollectExecutionInfo()) {
+                result.addExecutionInfo(
+                        "Handled in " + getClass() + " with serdes "
+                                + serdes + " in " + (time.nanoseconds() - start) + "ns");
+            }
+        }
+        return result;
+    }
+
+
+
+    @SuppressWarnings("unchecked")
+    protected <R> QueryResult<R> runTimestampKeyQuery(final Query<R> query,
+                                                      final PositionBound positionBound,
+                                                      final QueryConfig config) {
+        final QueryResult<R> result;
+        final TimestampedKeyQuery<K, V> typedKeyQuery = (TimestampedKeyQuery<K, V>) query;
+        final KeyQuery<Bytes, byte[]> rawKeyQuery =
+                KeyQuery.withKey(keyBytes(typedKeyQuery.getKey()));
+        final QueryResult<byte[]> rawResult =
+                wrapped().query(rawKeyQuery, positionBound, config);
+        if (rawResult.isSuccess()) {
+            final Function<byte[], ValueAndTimestamp<V>> deserializer = getDeserializeValue(serdes, wrapped());
+            final ValueAndTimestamp<V> value = deserializer.apply(rawResult.getResult());
+            final QueryResult<ValueAndTimestamp<V>> typedQueryResult =
+                    InternalQueryResultUtil.copyAndSubstituteDeserializedResult(rawResult, value);
+            result = (QueryResult<R>) typedQueryResult;
+        } else {
+            // the generic type doesn't matter, since failed queries have no result set.
+            result = (QueryResult<R>) rawResult;
+        }
+        return result;
+    }
+
+    @SuppressWarnings("unchecked")
+    protected <R> QueryResult<R> runTimestampRangeQuery(final Query<R> query,
+                                                        final PositionBound positionBound,
+                                                        final QueryConfig config) {
+
+        final QueryResult<R> result;
+        final TimestampedRangeQuery<K, V> typedQuery = (TimestampedRangeQuery<K, V>) query;
+
+        final RangeQuery<Bytes, byte[]> rawRangeQuery;
+        if (typedQuery.getLowerBound().isPresent() && typedQuery.getUpperBound().isPresent()) {
+            rawRangeQuery = RangeQuery.withRange(
+                    keyBytes(typedQuery.getLowerBound().get()),
+                    keyBytes(typedQuery.getUpperBound().get())
+            );
+        } else if (typedQuery.getLowerBound().isPresent()) {
+            rawRangeQuery = RangeQuery.withLowerBound(keyBytes(typedQuery.getLowerBound().get()));
+        } else if (typedQuery.getUpperBound().isPresent()) {
+            rawRangeQuery = RangeQuery.withUpperBound(keyBytes(typedQuery.getUpperBound().get()));
+        } else {
+            rawRangeQuery = RangeQuery.withNoBounds();
+        }
+        final QueryResult<KeyValueIterator<Bytes, byte[]>> rawResult =
+                wrapped().query(rawRangeQuery, positionBound, config);
+        if (rawResult.isSuccess()) {
+            final KeyValueIterator<Bytes, byte[]> iterator = rawResult.getResult();
+            final KeyValueIterator<K, V> resultIterator = new MeteredKeyValueTimestampedIterator(
+                    iterator,
+                    getSensor,
+                    getDeserializeValue(serdes, wrapped()),
+                    false
+            );
+            final QueryResult<KeyValueIterator<K, V>> typedQueryResult =
+                    InternalQueryResultUtil.copyAndSubstituteDeserializedResult(
+                            rawResult,
+                            resultIterator
+                    );
+            result = (QueryResult<R>) typedQueryResult;
+        } else {
+            // the generic type doesn't matter, since failed queries have no result set.
+            result = (QueryResult<R>) rawResult;
+        }
+        return result;
+    }
+
+    @SuppressWarnings("unchecked")
+    protected <R> QueryResult<R> runKeyQuery2(final Query<R> query,
+                                             final PositionBound positionBound,
+                                             final QueryConfig config) {
+        final QueryResult<R> result;
+        final KeyQuery<K, V> typedKeyQuery = (KeyQuery<K, V>) query;
+        final KeyQuery<Bytes, byte[]> rawKeyQuery =
+                KeyQuery.withKey(keyBytes(typedKeyQuery.getKey()));
+        final QueryResult<byte[]> rawResult =
+                wrapped().query(rawKeyQuery, positionBound, config);
+        if (rawResult.isSuccess()) {
+            final Function<byte[], ValueAndTimestamp<V>> deserializer = getDeserializeValue2(serdes, wrapped(), true);
+            ValueAndTimestamp<V> value = deserializer.apply(rawResult.getResult());
+            V res = null;
+            if (value != null) {
+                res = value.value();
+            }
+            final QueryResult<V> typedQueryResult =
+                    InternalQueryResultUtil.copyAndSubstituteDeserializedResult(rawResult, res);
+            result = (QueryResult<R>) typedQueryResult;
+        } else {
+            // the generic type doesn't matter, since failed queries have no result set.
+            result = (QueryResult<R>) rawResult;
+        }
+        return result;
+    }
+
+    @SuppressWarnings("unchecked")
+    protected <R> QueryResult<R> runRangeQuery2(final Query<R> query,
+                                               final PositionBound positionBound,
+                                               final QueryConfig config) {
+
+        final QueryResult<R> result;
+        final RangeQuery<K, V> typedQuery = (RangeQuery<K, V>) query;
+        final RangeQuery<Bytes, byte[]> rawRangeQuery;
+        if (typedQuery.getLowerBound().isPresent() && typedQuery.getUpperBound().isPresent()) {
+            rawRangeQuery = RangeQuery.withRange(
+                    keyBytes(typedQuery.getLowerBound().get()),
+                    keyBytes(typedQuery.getUpperBound().get())
+            );
+        } else if (typedQuery.getLowerBound().isPresent()) {
+            rawRangeQuery = RangeQuery.withLowerBound(keyBytes(typedQuery.getLowerBound().get()));
+        } else if (typedQuery.getUpperBound().isPresent()) {
+            rawRangeQuery = RangeQuery.withUpperBound(keyBytes(typedQuery.getUpperBound().get()));
+        } else {
+            rawRangeQuery = RangeQuery.withNoBounds();
+        }
+        final QueryResult<KeyValueIterator<Bytes, byte[]>> rawResult =
+                wrapped().query(rawRangeQuery, positionBound, config);
+        if (rawResult.isSuccess()) {
+            final KeyValueIterator<Bytes, byte[]> iterator = rawResult.getResult();
+            final KeyValueIterator<K,V> resultIterator = new MeteredKeyValueTimestampedIterator(
+                    iterator,
+                    getSensor,
+                    getDeserializeValue(serdes, wrapped()),
+                    true
+            );
+            final QueryResult<KeyValueIterator<K, V>> typedQueryResult =
+                    InternalQueryResultUtil.copyAndSubstituteDeserializedResult(
+                            rawResult,
+                            resultIterator
+                    );
+            result = (QueryResult<R>) typedQueryResult;
+        } else {
+            // the generic type doesn't matter, since failed queries have no result set.
+            result = (QueryResult<R>) rawResult;
+        }
+        return result;
+    }
+
+    @SuppressWarnings("unchecked")
+    private class MeteredKeyValueTimestampedIterator implements KeyValueIterator<K, V> {

Review Comment:
   Seems this comment was addressed yet?



##########
streams/src/main/java/org/apache/kafka/streams/query/TimestampedKeyQuery.java:
##########
@@ -0,0 +1,70 @@
+/*
+ * 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.query;
+
+import org.apache.kafka.common.annotation.InterfaceStability.Evolving;
+import org.apache.kafka.streams.state.ValueAndTimestamp;
+
+import java.util.Objects;
+
+/**
+ * Interactive query for retrieving a single record based on its key.
+ */

Review Comment:
   Seems you did not address this ye.



##########
streams/src/main/java/org/apache/kafka/streams/state/internals/MeteredTimestampedKeyValueStore.java:
##########
@@ -102,4 +139,232 @@ static class RawAndDeserializedValue<ValueType> {
             this.value = value;
         }
     }
+
+    @SuppressWarnings("unchecked")
+    @Override
+    public <R> QueryResult<R> query(final Query<R> query,
+                                    final PositionBound positionBound,
+                                    final QueryConfig config) {
+
+        final long start = time.nanoseconds();
+        final QueryResult<R> result;
+
+        final StoreQueryUtils.QueryHandler handler = queryHandlers.get(query.getClass());
+        if (handler == null) {
+            result = wrapped().query(query, positionBound, config);
+            if (config.isCollectExecutionInfo()) {
+                result.addExecutionInfo(
+                        "Handled in " + getClass() + " in " + (time.nanoseconds() - start) + "ns");
+            }
+        } else {
+            result = (QueryResult<R>) handler.apply(
+                    query,
+                    positionBound,
+                    config,
+                    this
+            );
+            if (config.isCollectExecutionInfo()) {
+                result.addExecutionInfo(
+                        "Handled in " + getClass() + " with serdes "
+                                + serdes + " in " + (time.nanoseconds() - start) + "ns");
+            }
+        }
+        return result;
+    }
+
+
+
+    @SuppressWarnings("unchecked")
+    protected <R> QueryResult<R> runTimestampedKeyQuery(final Query<R> query,
+                                                      final PositionBound positionBound,
+                                                      final QueryConfig config) {
+        final QueryResult<R> result;
+        final TimestampedKeyQuery<K, V> typedKeyQuery = (TimestampedKeyQuery<K, V>) query;
+        final KeyQuery<Bytes, byte[]> rawKeyQuery =
+                KeyQuery.withKey(keyBytes(typedKeyQuery.key()));
+        final QueryResult<byte[]> rawResult =
+                wrapped().query(rawKeyQuery, positionBound, config);
+        if (rawResult.isSuccess()) {
+            final Function<byte[], ValueAndTimestamp<V>> deserializer = getDeserializeValue(serdes, wrapped());
+            final ValueAndTimestamp<V> value = deserializer.apply(rawResult.getResult());
+            final QueryResult<ValueAndTimestamp<V>> typedQueryResult =
+                    InternalQueryResultUtil.copyAndSubstituteDeserializedResult(rawResult, value);
+            result = (QueryResult<R>) typedQueryResult;
+        } else {
+            // the generic type doesn't matter, since failed queries have no result set.
+            result = (QueryResult<R>) rawResult;
+        }
+        return result;
+    }
+
+    @SuppressWarnings("unchecked")
+    protected <R> QueryResult<R> runTimestampedRangeQuery(final Query<R> query,
+                                                        final PositionBound positionBound,
+                                                        final QueryConfig config) {
+
+        final QueryResult<R> result;
+        final TimestampedRangeQuery<K, V> typedQuery = (TimestampedRangeQuery<K, V>) query;
+        RangeQuery<Bytes, byte[]> rawRangeQuery;
+        final boolean isKeyAscending = typedQuery.isKeyAscending();
+        if (typedQuery.lowerBound().isPresent() && typedQuery.upperBound().isPresent()) {
+            rawRangeQuery = RangeQuery.withRange(
+                    keyBytes(typedQuery.lowerBound().get()),
+                    keyBytes(typedQuery.upperBound().get())
+            );
+        } else if (typedQuery.lowerBound().isPresent()) {
+            rawRangeQuery = RangeQuery.withLowerBound(keyBytes(typedQuery.lowerBound().get()));
+        } else if (typedQuery.upperBound().isPresent()) {
+            rawRangeQuery = RangeQuery.withUpperBound(keyBytes(typedQuery.upperBound().get()));
+        } else {
+            rawRangeQuery = RangeQuery.withNoBounds();
+        }
+        if (!isKeyAscending) {
+            rawRangeQuery = rawRangeQuery.withDescendingKeys();
+        }
+        final QueryResult<KeyValueIterator<Bytes, byte[]>> rawResult =
+                wrapped().query(rawRangeQuery, positionBound, config);
+        if (rawResult.isSuccess()) {
+            final KeyValueIterator<Bytes, byte[]> iterator = rawResult.getResult();
+            final KeyValueIterator<K, V> resultIterator = new MeteredKeyValueTimestampedIterator(

Review Comment:
   Return type should be ` KeyValueIterator<K, ValueAndTimestamp<V>>`, right?



##########
streams/src/main/java/org/apache/kafka/streams/state/internals/KeyValueToTimestampedKeyValueByteStoreAdapter.java:
##########
@@ -126,15 +128,22 @@ public <R> QueryResult<R> query(
         final PositionBound positionBound,
         final QueryConfig config) {
 
-
         final long start = config.isCollectExecutionInfo() ? System.nanoTime() : -1L;
-        final QueryResult<R> result = store.query(query, positionBound, config);
+        QueryResult<R> result = store.query(query, positionBound, config);
+        Position position = result.getPosition();
+        if (result.isSuccess()) {
+            byte[] res = (byte[]) result.getResult();
+            byte[] res1 = convertToTimestampedFormat(res);
+            result = (QueryResult<R>) QueryResult.forResult(res1);
+        }
+
         if (config.isCollectExecutionInfo()) {
             final long end = System.nanoTime();
             result.addExecutionInfo(
                 "Handled in " + getClass() + " in " + (end - start) + "ns"
             );
         }
+        result.setPosition(position);

Review Comment:
   Don't see any code change that addresses this comment.



##########
streams/src/main/java/org/apache/kafka/streams/state/internals/MeteredTimestampedKeyValueStore.java:
##########
@@ -102,4 +139,232 @@ static class RawAndDeserializedValue<ValueType> {
             this.value = value;
         }
     }
+
+    @SuppressWarnings("unchecked")
+    @Override
+    public <R> QueryResult<R> query(final Query<R> query,
+                                    final PositionBound positionBound,
+                                    final QueryConfig config) {
+
+        final long start = time.nanoseconds();
+        final QueryResult<R> result;
+
+        final StoreQueryUtils.QueryHandler handler = queryHandlers.get(query.getClass());
+        if (handler == null) {
+            result = wrapped().query(query, positionBound, config);
+            if (config.isCollectExecutionInfo()) {
+                result.addExecutionInfo(
+                        "Handled in " + getClass() + " in " + (time.nanoseconds() - start) + "ns");
+            }
+        } else {
+            result = (QueryResult<R>) handler.apply(
+                    query,
+                    positionBound,
+                    config,
+                    this
+            );
+            if (config.isCollectExecutionInfo()) {
+                result.addExecutionInfo(
+                        "Handled in " + getClass() + " with serdes "
+                                + serdes + " in " + (time.nanoseconds() - start) + "ns");
+            }
+        }
+        return result;
+    }
+
+
+
+    @SuppressWarnings("unchecked")
+    protected <R> QueryResult<R> runTimestampedKeyQuery(final Query<R> query,
+                                                      final PositionBound positionBound,
+                                                      final QueryConfig config) {
+        final QueryResult<R> result;
+        final TimestampedKeyQuery<K, V> typedKeyQuery = (TimestampedKeyQuery<K, V>) query;
+        final KeyQuery<Bytes, byte[]> rawKeyQuery =
+                KeyQuery.withKey(keyBytes(typedKeyQuery.key()));
+        final QueryResult<byte[]> rawResult =
+                wrapped().query(rawKeyQuery, positionBound, config);
+        if (rawResult.isSuccess()) {
+            final Function<byte[], ValueAndTimestamp<V>> deserializer = getDeserializeValue(serdes, wrapped());
+            final ValueAndTimestamp<V> value = deserializer.apply(rawResult.getResult());
+            final QueryResult<ValueAndTimestamp<V>> typedQueryResult =
+                    InternalQueryResultUtil.copyAndSubstituteDeserializedResult(rawResult, value);
+            result = (QueryResult<R>) typedQueryResult;
+        } else {
+            // the generic type doesn't matter, since failed queries have no result set.
+            result = (QueryResult<R>) rawResult;
+        }
+        return result;
+    }
+
+    @SuppressWarnings("unchecked")
+    protected <R> QueryResult<R> runTimestampedRangeQuery(final Query<R> query,
+                                                        final PositionBound positionBound,
+                                                        final QueryConfig config) {
+
+        final QueryResult<R> result;
+        final TimestampedRangeQuery<K, V> typedQuery = (TimestampedRangeQuery<K, V>) query;
+        RangeQuery<Bytes, byte[]> rawRangeQuery;
+        final boolean isKeyAscending = typedQuery.isKeyAscending();
+        if (typedQuery.lowerBound().isPresent() && typedQuery.upperBound().isPresent()) {
+            rawRangeQuery = RangeQuery.withRange(

Review Comment:
   Might be a good cleanup for `runRangeQuery(...)` too (in here, as well as `MeteredKeyValueStore`) -- when `RangeQuery` was added, passing in `null` for upper/lower was not supported to the code needed to be written in this complex way.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: jira-unsubscribe@kafka.apache.org

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


Re: [PR] KAFKA-15629: Proposal to introduce IQv2 Query Types: TimestampedKeyQuery and TimestampedRangeQuery [kafka]

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


##########
streams/src/main/java/org/apache/kafka/streams/state/internals/StoreQueryUtils.java:
##########
@@ -346,6 +346,23 @@ public static <V> Function<byte[], V> getDeserializeValue(final StateSerdes<?, V
         return byteArray -> deserializer.deserialize(serdes.topic(), byteArray);
     }
 
+    @SuppressWarnings({"unchecked", "rawtypes"})
+    public static <V> Function<byte[], V> getDeserializeValue2(final StateSerdes<?, V> serdes,
+                                                               final StateStore wrapped,
+                                                               final boolean isDSLStore ) {
+        final Serde<V> valueSerde = serdes.valueSerde();
+        final boolean timestamped = WrappedStateStore.isTimestamped(wrapped) || isDSLStore;
+        final Deserializer<V> deserializer;
+        if (!timestamped && valueSerde instanceof ValueAndTimestampSerde) {

Review Comment:
   This just solve the KeyQuery temporary, now I am debugging at RangeQuery, we should transfer the `RocksDBRangeIterator `to `KeyValueToTimestampedKeyValueIteratorAdapter` in `KeyValueToTimestampedKeyValueByteStoreAdapter`. Because we want to transfer kv iterator to ts kv iterator.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: jira-unsubscribe@kafka.apache.org

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


Re: [PR] KAFKA-15629: Proposal to introduce IQv2 Query Types: TimestampedKeyQuery and TimestampedRangeQuery [kafka]

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


##########
streams/src/main/java/org/apache/kafka/streams/state/internals/KeyValueToTimestampedKeyValueByteStoreAdapter.java:
##########
@@ -180,5 +201,38 @@ public <PS extends Serializer<P>, P> KeyValueIterator<Bytes, byte[]> prefixScan(
     public long approximateNumEntries() {
         return store.approximateNumEntries();
     }
+}
 
+class WrappedRocksDbIterator extends AbstractIterator implements ManagedKeyValueIterator {
+    final private RocksDbIterator rocksDbIterator;
+    public WrappedRocksDbIterator(final RocksDbIterator rocksDbIterator) {
+        this.rocksDbIterator = rocksDbIterator;
+    }
+    @Override
+    protected Object makeNext() {
+        final KeyValue<Bytes, byte[]> next = rocksDbIterator.makeNext();

Review Comment:
   In the `RockDbIterator`,` makeNext` is public, so I change our method from `protected` to `public`
   you can see `RockDbIterator` actually extend `AbstractIterator` and implement `MangedKeyValueIterator` and it get data from public `makeNext` method, so we actually can do the same thing.
   



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: jira-unsubscribe@kafka.apache.org

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


Re: [PR] KAFKA-15629: Proposal to introduce IQv2 Query Types: TimestampedKeyQuery and TimestampedRangeQuery [kafka]

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


##########
streams/src/main/java/org/apache/kafka/streams/state/internals/MeteredKeyValueStore.java:
##########
@@ -288,6 +298,48 @@ protected <R> QueryResult<R> runRangeQuery(final Query<R> query,
         return result;
     }
 
+    @SuppressWarnings("unchecked")
+    protected <R> QueryResult<R> runTimestampRangeQuery(final Query<R> query,

Review Comment:
   https://github.com/apache/kafka/pull/14570#discussion_r1367663818



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: jira-unsubscribe@kafka.apache.org

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


Re: [PR] KAFKA-15629: Proposal to introduce IQv2 Query Types: TimestampedKeyQuery and TimestampedRangeQuery [kafka]

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


##########
streams/src/main/java/org/apache/kafka/streams/state/internals/MeteredKeyValueStore.java:
##########
@@ -99,9 +101,17 @@ public class MeteredKeyValueStore<K, V>
                 RangeQuery.class,
                 (query, positionBound, config, store) -> runRangeQuery(query, positionBound, config)
             ),
+            mkEntry(
+                TimestampedRangeQuery.class,

Review Comment:
   Not sure what helper function you mean (we call the newly added `runTimestampRangeQuery`)?
   
   But even if there would be a code-reuse problem, it's just the wrong place. `MeteredKeyValueStore` is for plain-kv-store, and should only implement what plain-kv-store supports.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: jira-unsubscribe@kafka.apache.org

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


Re: [PR] KAFKA-15629: Proposal to introduce IQv2 Query Types: TimestampedKeyQuery and TimestampedRangeQuery [kafka]

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


##########
streams/src/main/java/org/apache/kafka/streams/state/internals/MeteredVersionedKeyValueStore.java:
##########
@@ -195,17 +195,15 @@ public <R> QueryResult<R> query(final Query<R> query, final PositionBound positi
             return result;
         }
 
-        @Override
-        protected <R> QueryResult<R> runRangeQuery(final Query<R> query,
-                                                   final PositionBound positionBound,
-                                                   final QueryConfig config) {
+        private <R> QueryResult<R> runRangeQuery(final Query<R> query,
+                                                 final PositionBound positionBound,
+                                                 final QueryConfig config) {
             // throw exception for now to reserve the ability to implement this in the future
             // without clashing with users' custom implementations in the meantime
             throw new UnsupportedOperationException("Versioned stores do not support RangeQuery queries at this time.");
         }
 
-        @Override
-        protected <R> QueryResult<R> runKeyQuery(final Query<R> query,
+        private <R> QueryResult<R> runKeyQuery(final Query<R> query,
                                                  final PositionBound positionBound,

Review Comment:
   fixed it.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: jira-unsubscribe@kafka.apache.org

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


Re: [PR] KAFKA-15629: Proposal to introduce IQv2 Query Types: TimestampedKeyQuery and TimestampedRangeQuery [kafka]

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


##########
streams/src/main/java/org/apache/kafka/streams/query/TimestampedKeyQuery.java:
##########
@@ -0,0 +1,70 @@
+/*
+ * 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.query;
+
+import org.apache.kafka.common.annotation.InterfaceStability.Evolving;
+import org.apache.kafka.streams.state.ValueAndTimestamp;
+
+import java.util.Objects;
+
+/**
+ * Interactive query for retrieving a single record based on its key.
+ */

Review Comment:
   ok



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: jira-unsubscribe@kafka.apache.org

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


Re: [PR] KAFKA-15629: Proposal to introduce IQv2 Query Types: TimestampedKeyQuery and TimestampedRangeQuery [kafka]

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


##########
streams/src/main/java/org/apache/kafka/streams/state/internals/MeteredTimestampedKeyValueStore.java:
##########
@@ -102,4 +140,230 @@ static class RawAndDeserializedValue<ValueType> {
             this.value = value;
         }
     }
+
+    @SuppressWarnings("unchecked")
+    @Override
+    public <R> QueryResult<R> query(final Query<R> query,
+                                    final PositionBound positionBound,
+                                    final QueryConfig config) {
+
+        final long start = time.nanoseconds();
+        final QueryResult<R> result;
+
+        final StoreQueryUtils.QueryHandler handler = queryHandlers.get(query.getClass());
+        if (handler == null) {
+            result = wrapped().query(query, positionBound, config);
+            if (config.isCollectExecutionInfo()) {
+                result.addExecutionInfo(
+                        "Handled in " + getClass() + " in " + (time.nanoseconds() - start) + "ns");
+            }
+        } else {
+            result = (QueryResult<R>) handler.apply(
+                    query,
+                    positionBound,
+                    config,
+                    this
+            );
+            if (config.isCollectExecutionInfo()) {
+                result.addExecutionInfo(
+                        "Handled in " + getClass() + " with serdes "
+                                + serdes + " in " + (time.nanoseconds() - start) + "ns");
+            }
+        }
+        return result;
+    }
+
+
+
+    @SuppressWarnings("unchecked")
+    protected <R> QueryResult<R> runTimestampKeyQuery(final Query<R> query,
+                                                      final PositionBound positionBound,
+                                                      final QueryConfig config) {
+        final QueryResult<R> result;
+        final TimestampedKeyQuery<K, V> typedKeyQuery = (TimestampedKeyQuery<K, V>) query;
+        final KeyQuery<Bytes, byte[]> rawKeyQuery =
+                KeyQuery.withKey(keyBytes(typedKeyQuery.getKey()));
+        final QueryResult<byte[]> rawResult =
+                wrapped().query(rawKeyQuery, positionBound, config);
+        if (rawResult.isSuccess()) {
+            final Function<byte[], ValueAndTimestamp<V>> deserializer = getDeserializeValue(serdes, wrapped());
+            final ValueAndTimestamp<V> value = deserializer.apply(rawResult.getResult());
+            final QueryResult<ValueAndTimestamp<V>> typedQueryResult =
+                    InternalQueryResultUtil.copyAndSubstituteDeserializedResult(rawResult, value);
+            result = (QueryResult<R>) typedQueryResult;
+        } else {
+            // the generic type doesn't matter, since failed queries have no result set.
+            result = (QueryResult<R>) rawResult;
+        }
+        return result;
+    }
+
+    @SuppressWarnings("unchecked")
+    protected <R> QueryResult<R> runTimestampRangeQuery(final Query<R> query,
+                                                        final PositionBound positionBound,
+                                                        final QueryConfig config) {
+
+        final QueryResult<R> result;
+        final TimestampedRangeQuery<K, V> typedQuery = (TimestampedRangeQuery<K, V>) query;
+
+        final RangeQuery<Bytes, byte[]> rawRangeQuery;
+        if (typedQuery.getLowerBound().isPresent() && typedQuery.getUpperBound().isPresent()) {
+            rawRangeQuery = RangeQuery.withRange(
+                    keyBytes(typedQuery.getLowerBound().get()),
+                    keyBytes(typedQuery.getUpperBound().get())
+            );
+        } else if (typedQuery.getLowerBound().isPresent()) {
+            rawRangeQuery = RangeQuery.withLowerBound(keyBytes(typedQuery.getLowerBound().get()));
+        } else if (typedQuery.getUpperBound().isPresent()) {
+            rawRangeQuery = RangeQuery.withUpperBound(keyBytes(typedQuery.getUpperBound().get()));
+        } else {
+            rawRangeQuery = RangeQuery.withNoBounds();
+        }
+        final QueryResult<KeyValueIterator<Bytes, byte[]>> rawResult =
+                wrapped().query(rawRangeQuery, positionBound, config);
+        if (rawResult.isSuccess()) {
+            final KeyValueIterator<Bytes, byte[]> iterator = rawResult.getResult();
+            final KeyValueIterator<K, V> resultIterator = new MeteredKeyValueTimestampedIterator(
+                    iterator,
+                    getSensor,
+                    getDeserializeValue(serdes, wrapped()),
+                    false
+            );
+            final QueryResult<KeyValueIterator<K, V>> typedQueryResult =
+                    InternalQueryResultUtil.copyAndSubstituteDeserializedResult(
+                            rawResult,
+                            resultIterator
+                    );
+            result = (QueryResult<R>) typedQueryResult;
+        } else {
+            // the generic type doesn't matter, since failed queries have no result set.
+            result = (QueryResult<R>) rawResult;
+        }
+        return result;
+    }
+
+    @SuppressWarnings("unchecked")
+    protected <R> QueryResult<R> runKeyQuery2(final Query<R> query,
+                                             final PositionBound positionBound,
+                                             final QueryConfig config) {
+        final QueryResult<R> result;
+        final KeyQuery<K, V> typedKeyQuery = (KeyQuery<K, V>) query;
+        final KeyQuery<Bytes, byte[]> rawKeyQuery =
+                KeyQuery.withKey(keyBytes(typedKeyQuery.getKey()));
+        final QueryResult<byte[]> rawResult =
+                wrapped().query(rawKeyQuery, positionBound, config);
+        if (rawResult.isSuccess()) {
+            final Function<byte[], ValueAndTimestamp<V>> deserializer = getDeserializeValue2(serdes, wrapped(), true);
+            ValueAndTimestamp<V> value = deserializer.apply(rawResult.getResult());
+            V res = null;
+            if (value != null) {
+                res = value.value();
+            }

Review Comment:
   ok



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: jira-unsubscribe@kafka.apache.org

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


Re: [PR] KAFKA-15629: Proposal to introduce IQv2 Query Types: TimestampedKeyQuery and TimestampedRangeQuery [kafka]

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


##########
streams/src/main/java/org/apache/kafka/streams/state/internals/MeteredTimestampedKeyValueStore.java:
##########
@@ -102,4 +140,230 @@ static class RawAndDeserializedValue<ValueType> {
             this.value = value;
         }
     }
+
+    @SuppressWarnings("unchecked")
+    @Override
+    public <R> QueryResult<R> query(final Query<R> query,
+                                    final PositionBound positionBound,
+                                    final QueryConfig config) {
+
+        final long start = time.nanoseconds();
+        final QueryResult<R> result;
+
+        final StoreQueryUtils.QueryHandler handler = queryHandlers.get(query.getClass());
+        if (handler == null) {
+            result = wrapped().query(query, positionBound, config);
+            if (config.isCollectExecutionInfo()) {
+                result.addExecutionInfo(
+                        "Handled in " + getClass() + " in " + (time.nanoseconds() - start) + "ns");
+            }
+        } else {
+            result = (QueryResult<R>) handler.apply(
+                    query,
+                    positionBound,
+                    config,
+                    this
+            );
+            if (config.isCollectExecutionInfo()) {
+                result.addExecutionInfo(
+                        "Handled in " + getClass() + " with serdes "
+                                + serdes + " in " + (time.nanoseconds() - start) + "ns");
+            }
+        }
+        return result;
+    }
+
+
+
+    @SuppressWarnings("unchecked")
+    protected <R> QueryResult<R> runTimestampKeyQuery(final Query<R> query,
+                                                      final PositionBound positionBound,
+                                                      final QueryConfig config) {
+        final QueryResult<R> result;
+        final TimestampedKeyQuery<K, V> typedKeyQuery = (TimestampedKeyQuery<K, V>) query;
+        final KeyQuery<Bytes, byte[]> rawKeyQuery =
+                KeyQuery.withKey(keyBytes(typedKeyQuery.getKey()));
+        final QueryResult<byte[]> rawResult =
+                wrapped().query(rawKeyQuery, positionBound, config);
+        if (rawResult.isSuccess()) {
+            final Function<byte[], ValueAndTimestamp<V>> deserializer = getDeserializeValue(serdes, wrapped());
+            final ValueAndTimestamp<V> value = deserializer.apply(rawResult.getResult());
+            final QueryResult<ValueAndTimestamp<V>> typedQueryResult =
+                    InternalQueryResultUtil.copyAndSubstituteDeserializedResult(rawResult, value);
+            result = (QueryResult<R>) typedQueryResult;
+        } else {
+            // the generic type doesn't matter, since failed queries have no result set.
+            result = (QueryResult<R>) rawResult;
+        }
+        return result;
+    }
+
+    @SuppressWarnings("unchecked")
+    protected <R> QueryResult<R> runTimestampRangeQuery(final Query<R> query,
+                                                        final PositionBound positionBound,
+                                                        final QueryConfig config) {
+
+        final QueryResult<R> result;
+        final TimestampedRangeQuery<K, V> typedQuery = (TimestampedRangeQuery<K, V>) query;
+
+        final RangeQuery<Bytes, byte[]> rawRangeQuery;
+        if (typedQuery.getLowerBound().isPresent() && typedQuery.getUpperBound().isPresent()) {
+            rawRangeQuery = RangeQuery.withRange(
+                    keyBytes(typedQuery.getLowerBound().get()),
+                    keyBytes(typedQuery.getUpperBound().get())
+            );
+        } else if (typedQuery.getLowerBound().isPresent()) {
+            rawRangeQuery = RangeQuery.withLowerBound(keyBytes(typedQuery.getLowerBound().get()));
+        } else if (typedQuery.getUpperBound().isPresent()) {
+            rawRangeQuery = RangeQuery.withUpperBound(keyBytes(typedQuery.getUpperBound().get()));
+        } else {
+            rawRangeQuery = RangeQuery.withNoBounds();
+        }
+        final QueryResult<KeyValueIterator<Bytes, byte[]>> rawResult =
+                wrapped().query(rawRangeQuery, positionBound, config);
+        if (rawResult.isSuccess()) {
+            final KeyValueIterator<Bytes, byte[]> iterator = rawResult.getResult();
+            final KeyValueIterator<K, V> resultIterator = new MeteredKeyValueTimestampedIterator(
+                    iterator,
+                    getSensor,
+                    getDeserializeValue(serdes, wrapped()),
+                    false
+            );
+            final QueryResult<KeyValueIterator<K, V>> typedQueryResult =
+                    InternalQueryResultUtil.copyAndSubstituteDeserializedResult(
+                            rawResult,
+                            resultIterator
+                    );
+            result = (QueryResult<R>) typedQueryResult;
+        } else {
+            // the generic type doesn't matter, since failed queries have no result set.
+            result = (QueryResult<R>) rawResult;
+        }
+        return result;
+    }
+
+    @SuppressWarnings("unchecked")
+    protected <R> QueryResult<R> runKeyQuery2(final Query<R> query,
+                                             final PositionBound positionBound,
+                                             final QueryConfig config) {
+        final QueryResult<R> result;
+        final KeyQuery<K, V> typedKeyQuery = (KeyQuery<K, V>) query;
+        final KeyQuery<Bytes, byte[]> rawKeyQuery =
+                KeyQuery.withKey(keyBytes(typedKeyQuery.getKey()));
+        final QueryResult<byte[]> rawResult =
+                wrapped().query(rawKeyQuery, positionBound, config);
+        if (rawResult.isSuccess()) {
+            final Function<byte[], ValueAndTimestamp<V>> deserializer = getDeserializeValue2(serdes, wrapped(), true);
+            ValueAndTimestamp<V> value = deserializer.apply(rawResult.getResult());

Review Comment:
   ok



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: jira-unsubscribe@kafka.apache.org

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


Re: [PR] KAFKA-15629: Proposal to introduce IQv2 Query Types: TimestampedKeyQuery and TimestampedRangeQuery [kafka]

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


##########
streams/src/main/java/org/apache/kafka/streams/state/internals/StoreQueryUtils.java:
##########
@@ -346,6 +346,23 @@ public static <V> Function<byte[], V> getDeserializeValue(final StateSerdes<?, V
         return byteArray -> deserializer.deserialize(serdes.topic(), byteArray);
     }
 
+    @SuppressWarnings({"unchecked", "rawtypes"})
+    public static <V> Function<byte[], V> getDeserializeValue2(final StateSerdes<?, V> serdes,
+                                                               final StateStore wrapped,
+                                                               final boolean isDSLStore ) {
+        final Serde<V> valueSerde = serdes.valueSerde();
+        final boolean timestamped = WrappedStateStore.isTimestamped(wrapped) || isDSLStore;
+        final Deserializer<V> deserializer;
+        if (!timestamped && valueSerde instanceof ValueAndTimestampSerde) {

Review Comment:
   Yes, I find that bug, that bug in `WrappedStateStore`,  we should add a statement like this
   ```
   public static boolean isTimestamped(final StateStore stateStore) {
           if (stateStore instanceof KeyValueToTimestampedKeyValueByteStoreAdapter) {
               return true;
           }
   
   ```
   
   But this just solve the ROCK_KV DSL store with cache = true.
   Because we the cache = true, we get the data from `CachingKeyValueStore ` but not `KeyValueToTimestampedKeyValueByteStoreAdapter`
   
   
   But we have to force` timestamped` to be true in the `getDeserializeValue`, because like `CachingKeyValueStore `  it's not ts-kv store, but ROCK_KV DSL  get data from this store.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: jira-unsubscribe@kafka.apache.org

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


Re: [PR] KAFKA-15629: Proposal to introduce IQv2 Query Types: TimestampedKeyQuery and TimestampedRangeQuery [kafka]

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


##########
streams/src/main/java/org/apache/kafka/streams/state/internals/MeteredTimestampedKeyValueStore.java:
##########
@@ -102,4 +140,230 @@ static class RawAndDeserializedValue<ValueType> {
             this.value = value;
         }
     }
+
+    @SuppressWarnings("unchecked")
+    @Override
+    public <R> QueryResult<R> query(final Query<R> query,
+                                    final PositionBound positionBound,
+                                    final QueryConfig config) {
+
+        final long start = time.nanoseconds();
+        final QueryResult<R> result;
+
+        final StoreQueryUtils.QueryHandler handler = queryHandlers.get(query.getClass());
+        if (handler == null) {
+            result = wrapped().query(query, positionBound, config);
+            if (config.isCollectExecutionInfo()) {
+                result.addExecutionInfo(
+                        "Handled in " + getClass() + " in " + (time.nanoseconds() - start) + "ns");
+            }
+        } else {
+            result = (QueryResult<R>) handler.apply(
+                    query,
+                    positionBound,
+                    config,
+                    this
+            );
+            if (config.isCollectExecutionInfo()) {
+                result.addExecutionInfo(
+                        "Handled in " + getClass() + " with serdes "
+                                + serdes + " in " + (time.nanoseconds() - start) + "ns");
+            }
+        }
+        return result;
+    }
+
+
+
+    @SuppressWarnings("unchecked")
+    protected <R> QueryResult<R> runTimestampKeyQuery(final Query<R> query,
+                                                      final PositionBound positionBound,
+                                                      final QueryConfig config) {
+        final QueryResult<R> result;
+        final TimestampedKeyQuery<K, V> typedKeyQuery = (TimestampedKeyQuery<K, V>) query;
+        final KeyQuery<Bytes, byte[]> rawKeyQuery =
+                KeyQuery.withKey(keyBytes(typedKeyQuery.getKey()));
+        final QueryResult<byte[]> rawResult =
+                wrapped().query(rawKeyQuery, positionBound, config);
+        if (rawResult.isSuccess()) {
+            final Function<byte[], ValueAndTimestamp<V>> deserializer = getDeserializeValue(serdes, wrapped());
+            final ValueAndTimestamp<V> value = deserializer.apply(rawResult.getResult());
+            final QueryResult<ValueAndTimestamp<V>> typedQueryResult =
+                    InternalQueryResultUtil.copyAndSubstituteDeserializedResult(rawResult, value);
+            result = (QueryResult<R>) typedQueryResult;
+        } else {
+            // the generic type doesn't matter, since failed queries have no result set.
+            result = (QueryResult<R>) rawResult;
+        }
+        return result;
+    }
+
+    @SuppressWarnings("unchecked")
+    protected <R> QueryResult<R> runTimestampRangeQuery(final Query<R> query,
+                                                        final PositionBound positionBound,
+                                                        final QueryConfig config) {
+
+        final QueryResult<R> result;
+        final TimestampedRangeQuery<K, V> typedQuery = (TimestampedRangeQuery<K, V>) query;
+
+        final RangeQuery<Bytes, byte[]> rawRangeQuery;
+        if (typedQuery.getLowerBound().isPresent() && typedQuery.getUpperBound().isPresent()) {
+            rawRangeQuery = RangeQuery.withRange(
+                    keyBytes(typedQuery.getLowerBound().get()),
+                    keyBytes(typedQuery.getUpperBound().get())
+            );
+        } else if (typedQuery.getLowerBound().isPresent()) {
+            rawRangeQuery = RangeQuery.withLowerBound(keyBytes(typedQuery.getLowerBound().get()));
+        } else if (typedQuery.getUpperBound().isPresent()) {
+            rawRangeQuery = RangeQuery.withUpperBound(keyBytes(typedQuery.getUpperBound().get()));
+        } else {
+            rawRangeQuery = RangeQuery.withNoBounds();
+        }
+        final QueryResult<KeyValueIterator<Bytes, byte[]>> rawResult =
+                wrapped().query(rawRangeQuery, positionBound, config);
+        if (rawResult.isSuccess()) {
+            final KeyValueIterator<Bytes, byte[]> iterator = rawResult.getResult();
+            final KeyValueIterator<K, V> resultIterator = new MeteredKeyValueTimestampedIterator(
+                    iterator,
+                    getSensor,
+                    getDeserializeValue(serdes, wrapped()),
+                    false
+            );
+            final QueryResult<KeyValueIterator<K, V>> typedQueryResult =
+                    InternalQueryResultUtil.copyAndSubstituteDeserializedResult(
+                            rawResult,
+                            resultIterator
+                    );
+            result = (QueryResult<R>) typedQueryResult;
+        } else {
+            // the generic type doesn't matter, since failed queries have no result set.
+            result = (QueryResult<R>) rawResult;
+        }
+        return result;
+    }
+
+    @SuppressWarnings("unchecked")
+    protected <R> QueryResult<R> runKeyQuery2(final Query<R> query,
+                                             final PositionBound positionBound,
+                                             final QueryConfig config) {
+        final QueryResult<R> result;
+        final KeyQuery<K, V> typedKeyQuery = (KeyQuery<K, V>) query;
+        final KeyQuery<Bytes, byte[]> rawKeyQuery =
+                KeyQuery.withKey(keyBytes(typedKeyQuery.getKey()));
+        final QueryResult<byte[]> rawResult =
+                wrapped().query(rawKeyQuery, positionBound, config);
+        if (rawResult.isSuccess()) {
+            final Function<byte[], ValueAndTimestamp<V>> deserializer = getDeserializeValue2(serdes, wrapped(), true);

Review Comment:
   ok



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: jira-unsubscribe@kafka.apache.org

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


Re: [PR] KAFKA-15629: Proposal to introduce IQv2 Query Types: TimestampedKeyQuery and TimestampedRangeQuery [kafka]

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


##########
streams/src/main/java/org/apache/kafka/streams/state/internals/KeyValueToTimestampedKeyValueByteStoreAdapter.java:
##########
@@ -127,14 +131,31 @@ public <R> QueryResult<R> query(
         final QueryConfig config) {
 
 
+
         final long start = config.isCollectExecutionInfo() ? System.nanoTime() : -1L;
-        final QueryResult<R> result = store.query(query, positionBound, config);
+        QueryResult<R> result = store.query(query, positionBound, config);
+        final Position position = result.getPosition();
+
+        if (result.isSuccess()) {
+            if (result.getResult() instanceof byte[]) {
+                final byte[] plainValue = (byte[]) result.getResult();
+                final byte[] valueWithTimestamp = convertToTimestampedFormat(plainValue);
+                result = (QueryResult<R>) QueryResult.forResult(valueWithTimestamp);
+            }
+            if (result.getResult() instanceof RocksDbIterator) {
+                final WrappedRocksDbIterator wrappedRocksDBRangeIterator = new WrappedRocksDbIterator((RocksDbIterator) result.getResult());
+                result = (QueryResult<R>) QueryResult.forResult(wrappedRocksDBRangeIterator);
+            }

Review Comment:
   We should chain this with an `else` that would throw an exception (we should never hit the `else` and it would be a bug -- throwing an exception would surface the bug clearly).



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: jira-unsubscribe@kafka.apache.org

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


Re: [PR] KAFKA-15629: Proposal to introduce IQv2 Query Types: TimestampedKeyQuery and TimestampedRangeQuery [kafka]

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


##########
streams/src/main/java/org/apache/kafka/streams/state/internals/MeteredTimestampedKeyValueStore.java:
##########
@@ -102,4 +139,232 @@ static class RawAndDeserializedValue<ValueType> {
             this.value = value;
         }
     }
+
+    @SuppressWarnings("unchecked")
+    @Override
+    public <R> QueryResult<R> query(final Query<R> query,
+                                    final PositionBound positionBound,
+                                    final QueryConfig config) {
+
+        final long start = time.nanoseconds();
+        final QueryResult<R> result;
+
+        final StoreQueryUtils.QueryHandler handler = queryHandlers.get(query.getClass());
+        if (handler == null) {
+            result = wrapped().query(query, positionBound, config);
+            if (config.isCollectExecutionInfo()) {
+                result.addExecutionInfo(
+                        "Handled in " + getClass() + " in " + (time.nanoseconds() - start) + "ns");
+            }
+        } else {
+            result = (QueryResult<R>) handler.apply(
+                    query,
+                    positionBound,
+                    config,
+                    this
+            );
+            if (config.isCollectExecutionInfo()) {
+                result.addExecutionInfo(
+                        "Handled in " + getClass() + " with serdes "
+                                + serdes + " in " + (time.nanoseconds() - start) + "ns");
+            }
+        }
+        return result;
+    }
+
+
+
+    @SuppressWarnings("unchecked")
+    protected <R> QueryResult<R> runTimestampedKeyQuery(final Query<R> query,

Review Comment:
   Because in `MeteredKeyValueStore`, we use protected one. So I follow the `MeteredKeyValueStore`'s one.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: jira-unsubscribe@kafka.apache.org

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


Re: [PR] KAFKA-15629: Proposal to introduce IQv2 Query Types: TimestampedKeyQuery and TimestampedRangeQuery [kafka]

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


##########
streams/src/main/java/org/apache/kafka/streams/query/TimestampedKeyQuery.java:
##########
@@ -0,0 +1,70 @@
+/*
+ * 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.query;
+
+import org.apache.kafka.common.annotation.InterfaceStability.Evolving;
+import org.apache.kafka.streams.state.ValueAndTimestamp;
+
+import java.util.Objects;
+
+/**
+ * Interactive query for retrieving a single record based on its key.
+ */
+@Evolving
+public final class TimestampedKeyQuery<K, V> implements Query<ValueAndTimestamp<V>> {
+
+    private final K key;
+    private final boolean skipCache;
+
+    private TimestampedKeyQuery(final K key, final boolean skipCache) {
+        this.key = Objects.requireNonNull(key);
+        this.skipCache = skipCache;
+    }
+
+    /**
+     * Creates a query that will retrieve the record identified by {@code key} if it exists
+     * (or {@code null} otherwise).
+     * @param key The key to retrieve
+     * @param <K> The type of the key
+     * @param <V> The type of the value that will be retrieved
+     */
+    public static <K, V> TimestampedKeyQuery<K, V> withKey(final K key) {
+        return new TimestampedKeyQuery<>(key, false);
+    }
+
+    /**
+     * Specifies that the cache should be skipped during query evaluation. This means, that the query will always
+     * get forwarded to the underlying store.
+     */
+    public TimestampedKeyQuery<K, V> skipCache() {
+        return new TimestampedKeyQuery<>(key, true);
+    }
+
+    /**
+     * The key that was specified for this query.
+     */

Review Comment:
   If it's missing in `KeyQuery`, too, we should add it. In the end, it should be something like:
   ```
   /**
    * Return the key that was specified for this query.
    *
    * @return The key that was specified for this query.
    */
   ```
   
   While it seems to be somewhat redundant in the code itself, it will result in nicely HTML JavaDocs, so it's preferable this way.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: jira-unsubscribe@kafka.apache.org

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


Re: [PR] KAFKA-15629: Proposal to introduce IQv2 Query Types: TimestampedKeyQuery and TimestampedRangeQuery [kafka]

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

   @mjsax I have already updated the javadoc.


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: jira-unsubscribe@kafka.apache.org

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


Re: [PR] KAFKA-15629: Proposal to introduce IQv2 Query Types: TimestampedKeyQuery and TimestampedRangeQuery [kafka]

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


##########
streams/src/main/java/org/apache/kafka/streams/query/TimestampedRangeQuery.java:
##########
@@ -0,0 +1,130 @@
+/*
+ * 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.query;
+
+
+import org.apache.kafka.common.annotation.InterfaceStability.Evolving;
+import org.apache.kafka.streams.state.KeyValueIterator;
+import org.apache.kafka.streams.state.ValueAndTimestamp;
+
+
+import java.util.Optional;
+
+/**
+ * Interactive query for issuing range queries and scans over Timestamped
+ * KeyValue stores.

Review Comment:
   ok



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: jira-unsubscribe@kafka.apache.org

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


Re: [PR] KAFKA-15629: Proposal to introduce IQv2 Query Types: TimestampedKeyQuery and TimestampedRangeQuery [kafka]

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


##########
streams/src/test/java/org/apache/kafka/streams/integration/IQv2StoreIntegrationTest.java:
##########
@@ -1632,10 +1729,65 @@ public <V> void shouldHandleRangeQuery(
                     IllegalArgumentException.class,
                     queryResult.get(partition)::getFailureMessage
                 );
-
                 try (final KeyValueIterator<Integer, V> iterator = queryResult.get(partition).getResult()) {
                     while (iterator.hasNext()) {
-                        actualValues.add(valueExtactor.apply(iterator.next().value));
+                        actualValues.add((Integer) iterator.next().value);
+                    }
+                }
+                assertThat(queryResult.get(partition).getExecutionInfo(), is(empty()));
+            }
+            assertThat("Result:" + result, actualValues, is(expectedValues));
+            assertThat("Result:" + result, result.getPosition(), is(INPUT_POSITION));
+        }
+    }
+
+    public <V> void shouldHandleTimestampedRangeQuery(
+        final Optional<Integer> lower,
+        final Optional<Integer> upper,
+        final boolean isKeyAscending,
+        final List<Integer> expectedValues) {

Review Comment:
   Cf my comment above -- you need to set the right timestamps for each result. But it should be deterministic because the used ts are set by the test when input data is written.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: jira-unsubscribe@kafka.apache.org

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


Re: [PR] KAFKA-15629: Proposal to introduce IQv2 Query Types: TimestampedKeyQuery and TimestampedRangeQuery [kafka]

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


##########
streams/src/main/java/org/apache/kafka/streams/query/TimestampedRangeQuery.java:
##########
@@ -0,0 +1,130 @@
+/*
+ * 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.query;
+
+
+import org.apache.kafka.common.annotation.InterfaceStability.Evolving;
+import org.apache.kafka.streams.state.KeyValueIterator;
+import org.apache.kafka.streams.state.ValueAndTimestamp;
+
+
+import java.util.Optional;
+
+/**
+ * Interactive query for issuing range queries and scans over Timestamped
+ * KeyValue stores.

Review Comment:
   `Timestamped KeyValue` -> `{@link TimestampedKeyValueStore}`
   
   We should add a similar reference to `TimestampedKeyQuery`.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: jira-unsubscribe@kafka.apache.org

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


Re: [PR] KAFKA-15629: Proposal to introduce IQv2 Query Types: TimestampedKeyQuery and TimestampedRangeQuery [kafka]

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

   Thanks for the KIP and PR. Merged to `trunk`.
   
   One more thing: can you do a follow up PR to update the docs?


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: jira-unsubscribe@kafka.apache.org

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


Re: [PR] KAFKA-15629: Proposal to introduce IQv2 Query Types: TimestampedKeyQuery and TimestampedRangeQuery [kafka]

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


##########
streams/src/main/java/org/apache/kafka/streams/query/TimestampedRangeQuery.java:
##########
@@ -0,0 +1,104 @@
+/*
+ * 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.query;
+
+
+import org.apache.kafka.common.annotation.InterfaceStability.Evolving;
+import org.apache.kafka.streams.state.KeyValueIterator;
+import org.apache.kafka.streams.state.ValueAndTimestamp;
+
+
+import java.util.Optional;
+
+/**
+ * Interactive query for issuing range queries and scans over KeyValue stores.
+ * <p>
+ *  A range query retrieves a set of records, specified using an upper and/or lower bound on the keys.
+ * <p>
+ * A scan query retrieves all records contained in the store.
+ * <p>

Review Comment:
   Unnecessary tag. -- Also generic parameters should be describe -- we should also describe ordering guarantees better (we can wait for your other PR to get finished, and mimic what we did there here.)



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: jira-unsubscribe@kafka.apache.org

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


Re: [PR] KAFKA-15629: Proposal to introduce IQv2 Query Types: TimestampedKeyQuery and TimestampedRangeQuery [kafka]

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


##########
streams/src/main/java/org/apache/kafka/streams/query/TimestampedRangeQuery.java:
##########
@@ -0,0 +1,104 @@
+/*
+ * 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.query;
+
+
+import org.apache.kafka.common.annotation.InterfaceStability.Evolving;
+import org.apache.kafka.streams.state.KeyValueIterator;
+import org.apache.kafka.streams.state.ValueAndTimestamp;
+
+
+import java.util.Optional;
+
+/**
+ * Interactive query for issuing range queries and scans over KeyValue stores.
+ * <p>
+ *  A range query retrieves a set of records, specified using an upper and/or lower bound on the keys.
+ * <p>
+ * A scan query retrieves all records contained in the store.
+ * <p>

Review Comment:
   ok



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: jira-unsubscribe@kafka.apache.org

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


Re: [PR] KAFKA-15629: Proposal to introduce IQv2 Query Types: TimestampedKeyQuery and TimestampedRangeQuery [kafka]

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


##########
streams/src/main/java/org/apache/kafka/streams/state/internals/KeyValueToTimestampedKeyValueByteStoreAdapter.java:
##########
@@ -126,15 +128,22 @@ public <R> QueryResult<R> query(
         final PositionBound positionBound,
         final QueryConfig config) {
 
-
         final long start = config.isCollectExecutionInfo() ? System.nanoTime() : -1L;
-        final QueryResult<R> result = store.query(query, positionBound, config);
+        QueryResult<R> result = store.query(query, positionBound, config);
+        Position position = result.getPosition();
+        if (result.isSuccess()) {
+            byte[] res = (byte[]) result.getResult();
+            byte[] res1 = convertToTimestampedFormat(res);

Review Comment:
   ok



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: jira-unsubscribe@kafka.apache.org

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


Re: [PR] KAFKA-15629: Proposal to introduce IQv2 Query Types: TimestampedKeyQuery and TimestampedRangeQuery [kafka]

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


##########
streams/src/main/java/org/apache/kafka/streams/query/TimestampedRangeQuery.java:
##########
@@ -0,0 +1,131 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+
+package org.apache.kafka.streams.query;
+
+
+import org.apache.kafka.common.annotation.InterfaceStability.Evolving;
+import org.apache.kafka.streams.state.KeyValueIterator;
+import org.apache.kafka.streams.state.ValueAndTimestamp;
+
+
+import java.util.Optional;
+
+/**
+ * Interactive query for issuing range queries and scans over Timestamped
+ * KeyValue stores.
+ * <p>
+ *  A range query retrieves a set of records, specified using an upper and/or lower bound on the keys.
+ * <p>
+ *  A scan query retrieves all records contained in the store.
+ * <p>
+ *  Keys' order is based on the serialized byte[] of the keys, not the 'logical' key order.
+ * <p>

Review Comment:
   ok



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: jira-unsubscribe@kafka.apache.org

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


Re: [PR] KAFKA-15629: Proposal to introduce IQv2 Query Types: TimestampedKeyQuery and TimestampedRangeQuery [kafka]

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


##########
streams/src/main/java/org/apache/kafka/streams/query/TimestampedKeyQuery.java:
##########
@@ -0,0 +1,70 @@
+/*
+ * 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.query;
+
+import org.apache.kafka.common.annotation.InterfaceStability.Evolving;
+import org.apache.kafka.streams.state.ValueAndTimestamp;
+
+import java.util.Objects;
+
+/**
+ * Interactive query for retrieving a single record based on its key.
+ */
+@Evolving
+public final class TimestampedKeyQuery<K, V> implements Query<ValueAndTimestamp<V>> {
+
+    private final K key;
+    private final boolean skipCache;
+
+    private TimestampedKeyQuery(final K key, final boolean skipCache) {
+        this.key = Objects.requireNonNull(key);

Review Comment:
   ok, but it seems that `withkey() `use  `return new KeyQuery<>(key, false);` to do the check now.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: jira-unsubscribe@kafka.apache.org

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


Re: [PR] KAFKA-15629: Proposal to introduce IQv2 Query Types: TimestampedKeyQuery and TimestampedRangeQuery [kafka]

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


##########
streams/src/main/java/org/apache/kafka/streams/query/TimestampedKeyQuery.java:
##########
@@ -0,0 +1,70 @@
+/*
+ * 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.query;
+
+import org.apache.kafka.common.annotation.InterfaceStability.Evolving;
+import org.apache.kafka.streams.state.ValueAndTimestamp;
+
+import java.util.Objects;
+
+/**
+ * Interactive query for retrieving a single record based on its key.
+ */

Review Comment:
   Oh, I add them in RangeQuery, I will add them in KeyQuery too.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: jira-unsubscribe@kafka.apache.org

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


Re: [PR] KAFKA-15629: Proposal to introduce IQv2 Query Types: TimestampedKeyQuery and TimestampedRangeQuery [kafka]

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


##########
streams/src/test/java/org/apache/kafka/streams/integration/IQv2StoreIntegrationTest.java:
##########
@@ -1584,7 +1646,43 @@ public <V> void shouldHandleKeyQuery(
         );
 
         final V result1 = queryResult.getResult();
-        final Integer integer = valueExtactor.apply(result1);
+        final Integer integer = (Integer) result1;
+        assertThat(integer, is(expectedValue));
+        assertThat(queryResult.getExecutionInfo(), is(empty()));
+        assertThat(queryResult.getPosition(), is(POSITION_0));
+    }
+
+    public <V> void shouldHandleTimestampedKeyQuery(
+            final Integer key,
+            final Integer expectedValue) {

Review Comment:
   But in the end we should compare the value in `ValueAndTimestamp`? 
   so we can set the the timestamp of  `ValueAndTimestamp` -1?



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: jira-unsubscribe@kafka.apache.org

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


Re: [PR] KAFKA-15629: Proposal to introduce IQv2 Query Types: TimestampedKeyQuery and TimestampedRangeQuery [kafka]

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


##########
streams/src/test/java/org/apache/kafka/streams/integration/IQv2StoreIntegrationTest.java:
##########
@@ -1584,7 +1646,43 @@ public <V> void shouldHandleKeyQuery(
         );
 
         final V result1 = queryResult.getResult();
-        final Integer integer = valueExtactor.apply(result1);
+        final Integer integer = (Integer) result1;
+        assertThat(integer, is(expectedValue));
+        assertThat(queryResult.getExecutionInfo(), is(empty()));
+        assertThat(queryResult.getPosition(), is(POSITION_0));
+    }
+
+    public <V> void shouldHandleTimestampedKeyQuery(
+            final Integer key,
+            final Integer expectedValue) {

Review Comment:
   I think we should pass in `ValueAndTimestamp` as expected result and also verify that we get the correct timestamp back. (Also rename `expectedValue` to `expectedValueAndTimestamp`.)



##########
streams/src/test/java/org/apache/kafka/streams/integration/IQv2StoreIntegrationTest.java:
##########
@@ -1584,7 +1646,43 @@ public <V> void shouldHandleKeyQuery(
         );
 
         final V result1 = queryResult.getResult();
-        final Integer integer = valueExtactor.apply(result1);
+        final Integer integer = (Integer) result1;
+        assertThat(integer, is(expectedValue));
+        assertThat(queryResult.getExecutionInfo(), is(empty()));
+        assertThat(queryResult.getPosition(), is(POSITION_0));
+    }
+
+    public <V> void shouldHandleTimestampedKeyQuery(
+            final Integer key,
+            final Integer expectedValue) {
+
+        final TimestampedKeyQuery<Integer, V> query = TimestampedKeyQuery.withKey(key);
+        final StateQueryRequest<ValueAndTimestamp<V>> request =
+                inStore(STORE_NAME)
+                        .withQuery(query)
+                        .withPartitions(mkSet(0, 1))
+                        .withPositionBound(PositionBound.at(INPUT_POSITION));
+
+        final StateQueryResult<ValueAndTimestamp<V>> result =
+                IntegrationTestUtils.iqv2WaitForResult(kafkaStreams, request);
+        final QueryResult<ValueAndTimestamp<V>> queryResult = result.getOnlyPartitionResult();
+        if (queryResult == null) {
+            throw new AssertionError("cannot use this query type to query result");
+        }
+        final boolean failure = queryResult.isFailure();
+        if (failure) {
+            throw new AssertionError(queryResult.toString());
+        }
+        assertThat(queryResult.isSuccess(), is(true));
+
+        assertThrows(IllegalArgumentException.class, queryResult::getFailureReason);
+        assertThrows(
+                IllegalArgumentException.class,
+                queryResult::getFailureMessage
+        );
+
+        final ValueAndTimestamp<V> result1 = queryResult.getResult();

Review Comment:
   `result1` is a very bad name. Rename to `valueAndTimestamp`.



##########
streams/src/test/java/org/apache/kafka/streams/integration/IQv2StoreIntegrationTest.java:
##########
@@ -1584,7 +1646,43 @@ public <V> void shouldHandleKeyQuery(
         );
 
         final V result1 = queryResult.getResult();
-        final Integer integer = valueExtactor.apply(result1);
+        final Integer integer = (Integer) result1;
+        assertThat(integer, is(expectedValue));
+        assertThat(queryResult.getExecutionInfo(), is(empty()));
+        assertThat(queryResult.getPosition(), is(POSITION_0));
+    }
+
+    public <V> void shouldHandleTimestampedKeyQuery(
+            final Integer key,
+            final Integer expectedValue) {
+
+        final TimestampedKeyQuery<Integer, V> query = TimestampedKeyQuery.withKey(key);
+        final StateQueryRequest<ValueAndTimestamp<V>> request =
+                inStore(STORE_NAME)
+                        .withQuery(query)
+                        .withPartitions(mkSet(0, 1))
+                        .withPositionBound(PositionBound.at(INPUT_POSITION));
+
+        final StateQueryResult<ValueAndTimestamp<V>> result =
+                IntegrationTestUtils.iqv2WaitForResult(kafkaStreams, request);
+        final QueryResult<ValueAndTimestamp<V>> queryResult = result.getOnlyPartitionResult();
+        if (queryResult == null) {
+            throw new AssertionError("cannot use this query type to query result");
+        }
+        final boolean failure = queryResult.isFailure();
+        if (failure) {
+            throw new AssertionError(queryResult.toString());
+        }
+        assertThat(queryResult.isSuccess(), is(true));
+
+        assertThrows(IllegalArgumentException.class, queryResult::getFailureReason);
+        assertThrows(
+                IllegalArgumentException.class,
+                queryResult::getFailureMessage
+        );
+
+        final ValueAndTimestamp<V> result1 = queryResult.getResult();
+        final Integer integer = (Integer) result1.value();
         assertThat(integer, is(expectedValue));

Review Comment:
   Cf my comments above: I think this can just `  assertThat(valueAndTimestamp, is(expectedValueAndTimestamp));`



##########
streams/src/test/java/org/apache/kafka/streams/integration/IQv2StoreIntegrationTest.java:
##########
@@ -1632,10 +1729,65 @@ public <V> void shouldHandleRangeQuery(
                     IllegalArgumentException.class,
                     queryResult.get(partition)::getFailureMessage
                 );
-
                 try (final KeyValueIterator<Integer, V> iterator = queryResult.get(partition).getResult()) {
                     while (iterator.hasNext()) {
-                        actualValues.add(valueExtactor.apply(iterator.next().value));
+                        actualValues.add((Integer) iterator.next().value);
+                    }
+                }
+                assertThat(queryResult.get(partition).getExecutionInfo(), is(empty()));
+            }
+            assertThat("Result:" + result, actualValues, is(expectedValues));
+            assertThat("Result:" + result, result.getPosition(), is(INPUT_POSITION));
+        }
+    }
+
+    public <V> void shouldHandleTimestampedRangeQuery(
+        final Optional<Integer> lower,
+        final Optional<Integer> upper,
+        final boolean isKeyAscending,
+        final List<Integer> expectedValues) {

Review Comment:
   Similar to above. We should expect a list of `ValueAndTimestamp` to also verify the ts we get back.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: jira-unsubscribe@kafka.apache.org

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


Re: [PR] KAFKA-15629: Proposal to introduce IQv2 Query Types: TimestampedKeyQuery and TimestampedRangeQuery [kafka]

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


##########
streams/src/main/java/org/apache/kafka/streams/state/internals/MeteredTimestampedKeyValueStore.java:
##########
@@ -102,4 +139,216 @@ static class RawAndDeserializedValue<ValueType> {
             this.value = value;
         }
     }
+
+    @SuppressWarnings("unchecked")
+    @Override
+    public <R> QueryResult<R> query(final Query<R> query,
+                                    final PositionBound positionBound,
+                                    final QueryConfig config) {
+
+        final long start = time.nanoseconds();
+        final QueryResult<R> result;
+
+        final StoreQueryUtils.QueryHandler handler = queryHandlers.get(query.getClass());
+        if (handler == null) {
+            result = wrapped().query(query, positionBound, config);
+            if (config.isCollectExecutionInfo()) {
+                result.addExecutionInfo(
+                        "Handled in " + getClass() + " in " + (time.nanoseconds() - start) + "ns");
+            }
+        } else {
+            result = (QueryResult<R>) handler.apply(
+                    query,
+                    positionBound,
+                    config,
+                    this
+            );
+            if (config.isCollectExecutionInfo()) {
+                result.addExecutionInfo(
+                        "Handled in " + getClass() + " with serdes "
+                                + serdes + " in " + (time.nanoseconds() - start) + "ns");
+            }
+        }
+        return result;
+    }
+
+
+
+    @SuppressWarnings("unchecked")
+    private <R> QueryResult<R> runTimestampedKeyQuery(final Query<R> query,
+                                                        final PositionBound positionBound,

Review Comment:
   nit: fix indention



##########
streams/src/main/java/org/apache/kafka/streams/state/internals/KeyValueToTimestampedKeyValueByteStoreAdapter.java:
##########
@@ -127,9 +136,25 @@ public <R> QueryResult<R> query(
         final QueryConfig config) {
 
 
+
         final long start = config.isCollectExecutionInfo() ? System.nanoTime() : -1L;
-        final QueryResult<R> result = store.query(query, positionBound, config);
+        QueryResult<R> result = store.query(query, positionBound, config);
+
+        if (result.isSuccess()) {
+            if (query instanceof KeyQuery || query instanceof TimestampedKeyQuery) {
+                final byte[] plainValue = (byte[]) result.getResult();
+                final byte[] valueWithTimestamp = convertToTimestampedFormat(plainValue);
+                result = (QueryResult<R>) InternalQueryResultUtil.copyAndSubstituteDeserializedResult(result, valueWithTimestamp);
+            } else if (query instanceof RangeQuery || query instanceof TimestampedRangeQuery) {
+                final KeyValueToTimestampedKeyValueAdapterIterator wrappedRocksDBRangeIterator = new KeyValueToTimestampedKeyValueAdapterIterator((RocksDbIterator) result.getResult());
+                result = (QueryResult<R>) InternalQueryResultUtil.copyAndSubstituteDeserializedResult(result, wrappedRocksDBRangeIterator);
+            } else {
+                throw new StreamsException("unsupported query type");

Review Comment:
   Let change this to:
   ```
   throw new IllegalArgumentException("Unsupported query type: " + query.getClass());
   ```



##########
streams/src/main/java/org/apache/kafka/streams/state/internals/MeteredTimestampedKeyValueStore.java:
##########
@@ -102,4 +139,216 @@ static class RawAndDeserializedValue<ValueType> {
             this.value = value;
         }
     }
+
+    @SuppressWarnings("unchecked")
+    @Override
+    public <R> QueryResult<R> query(final Query<R> query,
+                                    final PositionBound positionBound,
+                                    final QueryConfig config) {
+
+        final long start = time.nanoseconds();
+        final QueryResult<R> result;
+
+        final StoreQueryUtils.QueryHandler handler = queryHandlers.get(query.getClass());
+        if (handler == null) {
+            result = wrapped().query(query, positionBound, config);
+            if (config.isCollectExecutionInfo()) {
+                result.addExecutionInfo(
+                        "Handled in " + getClass() + " in " + (time.nanoseconds() - start) + "ns");
+            }
+        } else {
+            result = (QueryResult<R>) handler.apply(
+                    query,
+                    positionBound,
+                    config,
+                    this
+            );
+            if (config.isCollectExecutionInfo()) {
+                result.addExecutionInfo(
+                        "Handled in " + getClass() + " with serdes "
+                                + serdes + " in " + (time.nanoseconds() - start) + "ns");
+            }
+        }
+        return result;
+    }
+
+
+
+    @SuppressWarnings("unchecked")
+    private <R> QueryResult<R> runTimestampedKeyQuery(final Query<R> query,
+                                                        final PositionBound positionBound,
+                                                        final QueryConfig config) {
+        final QueryResult<R> result;
+        final TimestampedKeyQuery<K, V> typedKeyQuery = (TimestampedKeyQuery<K, V>) query;
+        final KeyQuery<Bytes, byte[]> rawKeyQuery =
+                KeyQuery.withKey(keyBytes(typedKeyQuery.key()));
+        final QueryResult<byte[]> rawResult =
+                wrapped().query(rawKeyQuery, positionBound, config);
+        if (rawResult.isSuccess()) {
+            final Function<byte[], ValueAndTimestamp<V>> deserializer = getDeserializeValue(serdes, wrapped());
+            final ValueAndTimestamp<V> valueAndTimestamp = deserializer.apply(rawResult.getResult());
+            final QueryResult<ValueAndTimestamp<V>> typedQueryResult =
+                    InternalQueryResultUtil.copyAndSubstituteDeserializedResult(rawResult, valueAndTimestamp);
+            result = (QueryResult<R>) typedQueryResult;
+        } else {
+            // the generic type doesn't matter, since failed queries have no result set.
+            result = (QueryResult<R>) rawResult;
+        }
+        return result;
+    }
+
+    @SuppressWarnings("unchecked")
+    private <R> QueryResult<R> runTimestampedRangeQuery(final Query<R> query,
+                                                        final PositionBound positionBound,
+                                                        final QueryConfig config) {
+
+        final QueryResult<R> result;
+        final TimestampedRangeQuery<K, V> typedQuery = (TimestampedRangeQuery<K, V>) query;
+        RangeQuery<Bytes, byte[]> rawRangeQuery;
+        final boolean isKeyAscending = typedQuery.isKeyAscending();
+        rawRangeQuery = RangeQuery.withRange(
+                keyBytes(typedQuery.lowerBound().orElse(null)),
+                keyBytes(typedQuery.upperBound().orElse(null))
+        );
+        if (!isKeyAscending) {
+            rawRangeQuery = rawRangeQuery.withDescendingKeys();
+        }
+        final QueryResult<KeyValueIterator<Bytes, byte[]>> rawResult =
+                wrapped().query(rawRangeQuery, positionBound, config);
+        if (rawResult.isSuccess()) {
+            final KeyValueIterator<Bytes, byte[]> iterator = rawResult.getResult();
+            final KeyValueIterator<K, ValueAndTimestamp<V>> resultIterator = (KeyValueIterator<K, ValueAndTimestamp<V>>) new MeteredTimestampedKeyValueStoreIterator(
+                    iterator,
+                    getSensor,
+                    getDeserializeValue(serdes, wrapped()),
+                    false
+            );
+            final QueryResult<KeyValueIterator<K, ValueAndTimestamp<V>>> typedQueryResult =
+                    InternalQueryResultUtil.copyAndSubstituteDeserializedResult(
+                            rawResult,
+                            resultIterator
+                    );
+            result = (QueryResult<R>) typedQueryResult;
+        } else {
+            // the generic type doesn't matter, since failed queries have no result set.
+            result = (QueryResult<R>) rawResult;
+        }
+        return result;
+    }
+
+    @SuppressWarnings("unchecked")
+    private <R> QueryResult<R> runKeyQuery(final Query<R> query,
+                                             final PositionBound positionBound,
+                                             final QueryConfig config) {
+        final QueryResult<R> result;
+        final KeyQuery<K, V> typedKeyQuery = (KeyQuery<K, V>) query;
+        final KeyQuery<Bytes, byte[]> rawKeyQuery =
+                KeyQuery.withKey(keyBytes(typedKeyQuery.getKey()));
+        final QueryResult<byte[]> rawResult =
+                wrapped().query(rawKeyQuery, positionBound, config);
+        if (rawResult.isSuccess()) {
+            final Function<byte[], ValueAndTimestamp<V>> deserializer = getDeserializeValue(serdes, wrapped());
+            final ValueAndTimestamp<V> valueAndTimestamp = deserializer.apply(rawResult.getResult());
+            final V plainValue = valueAndTimestamp == null ? null : valueAndTimestamp.value();
+            final QueryResult<V> typedQueryResult =
+                    InternalQueryResultUtil.copyAndSubstituteDeserializedResult(rawResult, plainValue);
+            result = (QueryResult<R>) typedQueryResult;
+        } else {
+            // the generic type doesn't matter, since failed queries have no result set.
+            result = (QueryResult<R>) rawResult;
+        }
+        return result;
+    }
+
+    @SuppressWarnings("unchecked")
+    private  <R> QueryResult<R> runRangeQuery(final Query<R> query,
+                                               final PositionBound positionBound,
+                                               final QueryConfig config) {
+
+        final QueryResult<R> result;
+        final RangeQuery<K, V> typedQuery = (RangeQuery<K, V>) query;
+        RangeQuery<Bytes, byte[]> rawRangeQuery;
+        final boolean isKeyAscending = typedQuery.isKeyAscending();
+        rawRangeQuery = RangeQuery.withRange(
+                keyBytes(typedQuery.getLowerBound().orElse(null)),
+                keyBytes(typedQuery.getUpperBound().orElse(null))
+        );
+        if (!isKeyAscending) {
+            rawRangeQuery = rawRangeQuery.withDescendingKeys();
+        }
+        final QueryResult<KeyValueIterator<Bytes, byte[]>> rawResult =
+                wrapped().query(rawRangeQuery, positionBound, config);
+        if (rawResult.isSuccess()) {
+            final KeyValueIterator<Bytes, byte[]> iterator = rawResult.getResult();
+            final KeyValueIterator<K, V> resultIterator = new MeteredTimestampedKeyValueStoreIterator(
+                iterator,
+                getSensor,
+                getDeserializeValue(serdes, wrapped()),
+                true
+            );
+            final QueryResult<KeyValueIterator<K, V>> typedQueryResult =
+                    InternalQueryResultUtil.copyAndSubstituteDeserializedResult(
+                            rawResult,
+                            resultIterator
+                    );
+            result = (QueryResult<R>) typedQueryResult;
+        } else {
+            // the generic type doesn't matter, since failed queries have no result set.
+            result = (QueryResult<R>) rawResult;
+        }
+        return result;
+    }
+
+    @SuppressWarnings("unchecked")
+    private class MeteredTimestampedKeyValueStoreIterator implements KeyValueIterator<K, V> {
+
+        private final KeyValueIterator<Bytes, byte[]> iter;
+        private final Sensor sensor;
+        private final long startNs;
+        private final Function<byte[], ValueAndTimestamp<V>> valueDeserializer;
+
+        private final boolean isKeyOrRangeQuery;
+
+        private MeteredTimestampedKeyValueStoreIterator(final KeyValueIterator<Bytes, byte[]> iter,
+                                                   final Sensor sensor,
+                                                   final Function<byte[], ValueAndTimestamp<V>> valueDeserializer,
+                                                   final boolean isKeyOrRangeQuery) {

Review Comment:
   `isKeyOrRangeQuery` -> `returnPlainValue`
   
   For KeyQuery we don't create an iterator at all, and `returnPlainValue` is more descriptive



##########
streams/src/main/java/org/apache/kafka/streams/state/internals/MeteredTimestampedKeyValueStore.java:
##########
@@ -102,4 +139,216 @@ static class RawAndDeserializedValue<ValueType> {
             this.value = value;
         }
     }
+
+    @SuppressWarnings("unchecked")
+    @Override
+    public <R> QueryResult<R> query(final Query<R> query,
+                                    final PositionBound positionBound,
+                                    final QueryConfig config) {
+
+        final long start = time.nanoseconds();
+        final QueryResult<R> result;
+
+        final StoreQueryUtils.QueryHandler handler = queryHandlers.get(query.getClass());
+        if (handler == null) {
+            result = wrapped().query(query, positionBound, config);
+            if (config.isCollectExecutionInfo()) {
+                result.addExecutionInfo(
+                        "Handled in " + getClass() + " in " + (time.nanoseconds() - start) + "ns");
+            }
+        } else {
+            result = (QueryResult<R>) handler.apply(
+                    query,
+                    positionBound,
+                    config,
+                    this
+            );
+            if (config.isCollectExecutionInfo()) {
+                result.addExecutionInfo(
+                        "Handled in " + getClass() + " with serdes "
+                                + serdes + " in " + (time.nanoseconds() - start) + "ns");
+            }
+        }
+        return result;
+    }
+
+
+
+    @SuppressWarnings("unchecked")
+    private <R> QueryResult<R> runTimestampedKeyQuery(final Query<R> query,
+                                                        final PositionBound positionBound,
+                                                        final QueryConfig config) {
+        final QueryResult<R> result;
+        final TimestampedKeyQuery<K, V> typedKeyQuery = (TimestampedKeyQuery<K, V>) query;
+        final KeyQuery<Bytes, byte[]> rawKeyQuery =
+                KeyQuery.withKey(keyBytes(typedKeyQuery.key()));
+        final QueryResult<byte[]> rawResult =
+                wrapped().query(rawKeyQuery, positionBound, config);
+        if (rawResult.isSuccess()) {
+            final Function<byte[], ValueAndTimestamp<V>> deserializer = getDeserializeValue(serdes, wrapped());
+            final ValueAndTimestamp<V> valueAndTimestamp = deserializer.apply(rawResult.getResult());
+            final QueryResult<ValueAndTimestamp<V>> typedQueryResult =
+                    InternalQueryResultUtil.copyAndSubstituteDeserializedResult(rawResult, valueAndTimestamp);
+            result = (QueryResult<R>) typedQueryResult;
+        } else {
+            // the generic type doesn't matter, since failed queries have no result set.
+            result = (QueryResult<R>) rawResult;
+        }
+        return result;
+    }
+
+    @SuppressWarnings("unchecked")
+    private <R> QueryResult<R> runTimestampedRangeQuery(final Query<R> query,
+                                                        final PositionBound positionBound,
+                                                        final QueryConfig config) {
+
+        final QueryResult<R> result;
+        final TimestampedRangeQuery<K, V> typedQuery = (TimestampedRangeQuery<K, V>) query;
+        RangeQuery<Bytes, byte[]> rawRangeQuery;
+        final boolean isKeyAscending = typedQuery.isKeyAscending();
+        rawRangeQuery = RangeQuery.withRange(
+                keyBytes(typedQuery.lowerBound().orElse(null)),
+                keyBytes(typedQuery.upperBound().orElse(null))
+        );
+        if (!isKeyAscending) {
+            rawRangeQuery = rawRangeQuery.withDescendingKeys();
+        }
+        final QueryResult<KeyValueIterator<Bytes, byte[]>> rawResult =
+                wrapped().query(rawRangeQuery, positionBound, config);
+        if (rawResult.isSuccess()) {
+            final KeyValueIterator<Bytes, byte[]> iterator = rawResult.getResult();
+            final KeyValueIterator<K, ValueAndTimestamp<V>> resultIterator = (KeyValueIterator<K, ValueAndTimestamp<V>>) new MeteredTimestampedKeyValueStoreIterator(
+                    iterator,
+                    getSensor,
+                    getDeserializeValue(serdes, wrapped()),
+                    false
+            );
+            final QueryResult<KeyValueIterator<K, ValueAndTimestamp<V>>> typedQueryResult =
+                    InternalQueryResultUtil.copyAndSubstituteDeserializedResult(
+                            rawResult,
+                            resultIterator
+                    );
+            result = (QueryResult<R>) typedQueryResult;
+        } else {
+            // the generic type doesn't matter, since failed queries have no result set.
+            result = (QueryResult<R>) rawResult;
+        }
+        return result;
+    }
+
+    @SuppressWarnings("unchecked")
+    private <R> QueryResult<R> runKeyQuery(final Query<R> query,
+                                             final PositionBound positionBound,
+                                             final QueryConfig config) {
+        final QueryResult<R> result;
+        final KeyQuery<K, V> typedKeyQuery = (KeyQuery<K, V>) query;
+        final KeyQuery<Bytes, byte[]> rawKeyQuery =
+                KeyQuery.withKey(keyBytes(typedKeyQuery.getKey()));
+        final QueryResult<byte[]> rawResult =
+                wrapped().query(rawKeyQuery, positionBound, config);
+        if (rawResult.isSuccess()) {
+            final Function<byte[], ValueAndTimestamp<V>> deserializer = getDeserializeValue(serdes, wrapped());
+            final ValueAndTimestamp<V> valueAndTimestamp = deserializer.apply(rawResult.getResult());
+            final V plainValue = valueAndTimestamp == null ? null : valueAndTimestamp.value();
+            final QueryResult<V> typedQueryResult =
+                    InternalQueryResultUtil.copyAndSubstituteDeserializedResult(rawResult, plainValue);
+            result = (QueryResult<R>) typedQueryResult;
+        } else {
+            // the generic type doesn't matter, since failed queries have no result set.
+            result = (QueryResult<R>) rawResult;
+        }
+        return result;
+    }
+
+    @SuppressWarnings("unchecked")
+    private  <R> QueryResult<R> runRangeQuery(final Query<R> query,
+                                               final PositionBound positionBound,
+                                               final QueryConfig config) {
+
+        final QueryResult<R> result;
+        final RangeQuery<K, V> typedQuery = (RangeQuery<K, V>) query;
+        RangeQuery<Bytes, byte[]> rawRangeQuery;
+        final boolean isKeyAscending = typedQuery.isKeyAscending();
+        rawRangeQuery = RangeQuery.withRange(
+                keyBytes(typedQuery.getLowerBound().orElse(null)),
+                keyBytes(typedQuery.getUpperBound().orElse(null))
+        );
+        if (!isKeyAscending) {
+            rawRangeQuery = rawRangeQuery.withDescendingKeys();
+        }
+        final QueryResult<KeyValueIterator<Bytes, byte[]>> rawResult =
+                wrapped().query(rawRangeQuery, positionBound, config);
+        if (rawResult.isSuccess()) {
+            final KeyValueIterator<Bytes, byte[]> iterator = rawResult.getResult();
+            final KeyValueIterator<K, V> resultIterator = new MeteredTimestampedKeyValueStoreIterator(
+                iterator,
+                getSensor,
+                getDeserializeValue(serdes, wrapped()),
+                true
+            );
+            final QueryResult<KeyValueIterator<K, V>> typedQueryResult =
+                    InternalQueryResultUtil.copyAndSubstituteDeserializedResult(
+                            rawResult,
+                            resultIterator
+                    );
+            result = (QueryResult<R>) typedQueryResult;
+        } else {
+            // the generic type doesn't matter, since failed queries have no result set.
+            result = (QueryResult<R>) rawResult;
+        }
+        return result;
+    }
+
+    @SuppressWarnings("unchecked")
+    private class MeteredTimestampedKeyValueStoreIterator implements KeyValueIterator<K, V> {
+
+        private final KeyValueIterator<Bytes, byte[]> iter;
+        private final Sensor sensor;
+        private final long startNs;
+        private final Function<byte[], ValueAndTimestamp<V>> valueDeserializer;
+
+        private final boolean isKeyOrRangeQuery;
+
+        private MeteredTimestampedKeyValueStoreIterator(final KeyValueIterator<Bytes, byte[]> iter,
+                                                   final Sensor sensor,
+                                                   final Function<byte[], ValueAndTimestamp<V>> valueDeserializer,
+                                                   final boolean isKeyOrRangeQuery) {
+            this.iter = iter;
+            this.sensor = sensor;
+            this.valueDeserializer = valueDeserializer;
+            this.startNs = time.nanoseconds();
+            this.isKeyOrRangeQuery = isKeyOrRangeQuery;
+        }
+
+        @Override
+        public boolean hasNext() {
+            return iter.hasNext();
+        }
+
+        @Override
+        public KeyValue<K, V> next() {
+            final KeyValue<Bytes, byte[]> keyValue = iter.next();
+            if (isKeyOrRangeQuery) {
+                final V value = valueDeserializer.apply(keyValue.value).value();

Review Comment:
   `value` -> `plainValue`



##########
streams/src/main/java/org/apache/kafka/streams/state/internals/MeteredKeyValueStore.java:
##########
@@ -247,26 +247,18 @@ public Position getPosition() {
     }
 
     @SuppressWarnings("unchecked")
-    protected <R> QueryResult<R> runRangeQuery(final Query<R> query,
+    private <R> QueryResult<R> runRangeQuery(final Query<R> query,
                                                final PositionBound positionBound,

Review Comment:
   nit: adjust indention



##########
streams/src/main/java/org/apache/kafka/streams/state/internals/MeteredTimestampedKeyValueStore.java:
##########
@@ -102,4 +139,216 @@ static class RawAndDeserializedValue<ValueType> {
             this.value = value;
         }
     }
+
+    @SuppressWarnings("unchecked")
+    @Override
+    public <R> QueryResult<R> query(final Query<R> query,
+                                    final PositionBound positionBound,
+                                    final QueryConfig config) {
+
+        final long start = time.nanoseconds();
+        final QueryResult<R> result;
+
+        final StoreQueryUtils.QueryHandler handler = queryHandlers.get(query.getClass());
+        if (handler == null) {
+            result = wrapped().query(query, positionBound, config);
+            if (config.isCollectExecutionInfo()) {
+                result.addExecutionInfo(
+                        "Handled in " + getClass() + " in " + (time.nanoseconds() - start) + "ns");
+            }
+        } else {
+            result = (QueryResult<R>) handler.apply(
+                    query,
+                    positionBound,
+                    config,
+                    this
+            );
+            if (config.isCollectExecutionInfo()) {
+                result.addExecutionInfo(
+                        "Handled in " + getClass() + " with serdes "
+                                + serdes + " in " + (time.nanoseconds() - start) + "ns");
+            }
+        }
+        return result;
+    }
+
+
+
+    @SuppressWarnings("unchecked")
+    private <R> QueryResult<R> runTimestampedKeyQuery(final Query<R> query,
+                                                        final PositionBound positionBound,
+                                                        final QueryConfig config) {
+        final QueryResult<R> result;
+        final TimestampedKeyQuery<K, V> typedKeyQuery = (TimestampedKeyQuery<K, V>) query;
+        final KeyQuery<Bytes, byte[]> rawKeyQuery =
+                KeyQuery.withKey(keyBytes(typedKeyQuery.key()));
+        final QueryResult<byte[]> rawResult =
+                wrapped().query(rawKeyQuery, positionBound, config);
+        if (rawResult.isSuccess()) {
+            final Function<byte[], ValueAndTimestamp<V>> deserializer = getDeserializeValue(serdes, wrapped());
+            final ValueAndTimestamp<V> valueAndTimestamp = deserializer.apply(rawResult.getResult());
+            final QueryResult<ValueAndTimestamp<V>> typedQueryResult =
+                    InternalQueryResultUtil.copyAndSubstituteDeserializedResult(rawResult, valueAndTimestamp);
+            result = (QueryResult<R>) typedQueryResult;
+        } else {
+            // the generic type doesn't matter, since failed queries have no result set.
+            result = (QueryResult<R>) rawResult;
+        }
+        return result;
+    }
+
+    @SuppressWarnings("unchecked")
+    private <R> QueryResult<R> runTimestampedRangeQuery(final Query<R> query,
+                                                        final PositionBound positionBound,
+                                                        final QueryConfig config) {
+
+        final QueryResult<R> result;
+        final TimestampedRangeQuery<K, V> typedQuery = (TimestampedRangeQuery<K, V>) query;
+        RangeQuery<Bytes, byte[]> rawRangeQuery;
+        final boolean isKeyAscending = typedQuery.isKeyAscending();
+        rawRangeQuery = RangeQuery.withRange(
+                keyBytes(typedQuery.lowerBound().orElse(null)),
+                keyBytes(typedQuery.upperBound().orElse(null))
+        );
+        if (!isKeyAscending) {
+            rawRangeQuery = rawRangeQuery.withDescendingKeys();
+        }
+        final QueryResult<KeyValueIterator<Bytes, byte[]>> rawResult =
+                wrapped().query(rawRangeQuery, positionBound, config);
+        if (rawResult.isSuccess()) {
+            final KeyValueIterator<Bytes, byte[]> iterator = rawResult.getResult();
+            final KeyValueIterator<K, ValueAndTimestamp<V>> resultIterator = (KeyValueIterator<K, ValueAndTimestamp<V>>) new MeteredTimestampedKeyValueStoreIterator(
+                    iterator,
+                    getSensor,
+                    getDeserializeValue(serdes, wrapped()),
+                    false
+            );
+            final QueryResult<KeyValueIterator<K, ValueAndTimestamp<V>>> typedQueryResult =
+                    InternalQueryResultUtil.copyAndSubstituteDeserializedResult(
+                            rawResult,
+                            resultIterator
+                    );
+            result = (QueryResult<R>) typedQueryResult;
+        } else {
+            // the generic type doesn't matter, since failed queries have no result set.
+            result = (QueryResult<R>) rawResult;
+        }
+        return result;
+    }
+
+    @SuppressWarnings("unchecked")
+    private <R> QueryResult<R> runKeyQuery(final Query<R> query,
+                                             final PositionBound positionBound,
+                                             final QueryConfig config) {
+        final QueryResult<R> result;
+        final KeyQuery<K, V> typedKeyQuery = (KeyQuery<K, V>) query;
+        final KeyQuery<Bytes, byte[]> rawKeyQuery =
+                KeyQuery.withKey(keyBytes(typedKeyQuery.getKey()));
+        final QueryResult<byte[]> rawResult =
+                wrapped().query(rawKeyQuery, positionBound, config);
+        if (rawResult.isSuccess()) {
+            final Function<byte[], ValueAndTimestamp<V>> deserializer = getDeserializeValue(serdes, wrapped());
+            final ValueAndTimestamp<V> valueAndTimestamp = deserializer.apply(rawResult.getResult());
+            final V plainValue = valueAndTimestamp == null ? null : valueAndTimestamp.value();
+            final QueryResult<V> typedQueryResult =
+                    InternalQueryResultUtil.copyAndSubstituteDeserializedResult(rawResult, plainValue);
+            result = (QueryResult<R>) typedQueryResult;
+        } else {
+            // the generic type doesn't matter, since failed queries have no result set.
+            result = (QueryResult<R>) rawResult;
+        }
+        return result;
+    }
+
+    @SuppressWarnings("unchecked")
+    private  <R> QueryResult<R> runRangeQuery(final Query<R> query,
+                                               final PositionBound positionBound,
+                                               final QueryConfig config) {
+
+        final QueryResult<R> result;
+        final RangeQuery<K, V> typedQuery = (RangeQuery<K, V>) query;
+        RangeQuery<Bytes, byte[]> rawRangeQuery;
+        final boolean isKeyAscending = typedQuery.isKeyAscending();
+        rawRangeQuery = RangeQuery.withRange(
+                keyBytes(typedQuery.getLowerBound().orElse(null)),
+                keyBytes(typedQuery.getUpperBound().orElse(null))
+        );
+        if (!isKeyAscending) {
+            rawRangeQuery = rawRangeQuery.withDescendingKeys();
+        }
+        final QueryResult<KeyValueIterator<Bytes, byte[]>> rawResult =
+                wrapped().query(rawRangeQuery, positionBound, config);
+        if (rawResult.isSuccess()) {
+            final KeyValueIterator<Bytes, byte[]> iterator = rawResult.getResult();
+            final KeyValueIterator<K, V> resultIterator = new MeteredTimestampedKeyValueStoreIterator(
+                iterator,
+                getSensor,
+                getDeserializeValue(serdes, wrapped()),
+                true
+            );
+            final QueryResult<KeyValueIterator<K, V>> typedQueryResult =
+                    InternalQueryResultUtil.copyAndSubstituteDeserializedResult(
+                            rawResult,
+                            resultIterator
+                    );
+            result = (QueryResult<R>) typedQueryResult;
+        } else {
+            // the generic type doesn't matter, since failed queries have no result set.
+            result = (QueryResult<R>) rawResult;
+        }
+        return result;
+    }
+
+    @SuppressWarnings("unchecked")
+    private class MeteredTimestampedKeyValueStoreIterator implements KeyValueIterator<K, V> {
+
+        private final KeyValueIterator<Bytes, byte[]> iter;
+        private final Sensor sensor;
+        private final long startNs;
+        private final Function<byte[], ValueAndTimestamp<V>> valueDeserializer;
+
+        private final boolean isKeyOrRangeQuery;
+
+        private MeteredTimestampedKeyValueStoreIterator(final KeyValueIterator<Bytes, byte[]> iter,
+                                                   final Sensor sensor,
+                                                   final Function<byte[], ValueAndTimestamp<V>> valueDeserializer,

Review Comment:
   `valueDeserializer` -> `valueAndTimestampDeserializer`



##########
streams/src/main/java/org/apache/kafka/streams/state/internals/MeteredKeyValueStore.java:
##########
@@ -247,26 +247,18 @@ public Position getPosition() {
     }
 
     @SuppressWarnings("unchecked")
-    protected <R> QueryResult<R> runRangeQuery(final Query<R> query,
+    private <R> QueryResult<R> runRangeQuery(final Query<R> query,
                                                final PositionBound positionBound,
                                                final QueryConfig config) {
 
         final QueryResult<R> result;
         final RangeQuery<K, V> typedQuery = (RangeQuery<K, V>) query;
         RangeQuery<Bytes, byte[]> rawRangeQuery;
         final boolean isKeyAscending = typedQuery.isKeyAscending();
-        if (typedQuery.getLowerBound().isPresent() && typedQuery.getUpperBound().isPresent()) {
-            rawRangeQuery = RangeQuery.withRange(
-                keyBytes(typedQuery.getLowerBound().get()),
-                keyBytes(typedQuery.getUpperBound().get())
-            );
-        } else if (typedQuery.getLowerBound().isPresent()) {
-            rawRangeQuery = RangeQuery.withLowerBound(keyBytes(typedQuery.getLowerBound().get()));
-        } else if (typedQuery.getUpperBound().isPresent()) {
-            rawRangeQuery = RangeQuery.withUpperBound(keyBytes(typedQuery.getUpperBound().get()));
-        } else {
-            rawRangeQuery = RangeQuery.withNoBounds();
-        }
+        rawRangeQuery = RangeQuery.withRange(
+                keyBytes(typedQuery.getLowerBound().orElse(null)),
+                keyBytes(typedQuery.getUpperBound().orElse(null))
+        );

Review Comment:
   Thanks for this cleanup. Very nice!



##########
streams/src/main/java/org/apache/kafka/streams/state/internals/MeteredVersionedKeyValueStore.java:
##########
@@ -195,17 +195,15 @@ public <R> QueryResult<R> query(final Query<R> query, final PositionBound positi
             return result;
         }
 
-        @Override
-        protected <R> QueryResult<R> runRangeQuery(final Query<R> query,
-                                                   final PositionBound positionBound,
-                                                   final QueryConfig config) {
+        private <R> QueryResult<R> runRangeQuery(final Query<R> query,
+                                                 final PositionBound positionBound,
+                                                 final QueryConfig config) {
             // throw exception for now to reserve the ability to implement this in the future
             // without clashing with users' custom implementations in the meantime
             throw new UnsupportedOperationException("Versioned stores do not support RangeQuery queries at this time.");
         }
 
-        @Override
-        protected <R> QueryResult<R> runKeyQuery(final Query<R> query,
+        private <R> QueryResult<R> runKeyQuery(final Query<R> query,
                                                  final PositionBound positionBound,

Review Comment:
   nit: adjust indention



##########
streams/src/main/java/org/apache/kafka/streams/state/internals/MeteredKeyValueStore.java:
##########
@@ -293,7 +285,7 @@ protected <R> QueryResult<R> runRangeQuery(final Query<R> query,
     }
 
     @SuppressWarnings("unchecked")
-    protected <R> QueryResult<R> runKeyQuery(final Query<R> query,
+    private  <R> QueryResult<R> runKeyQuery(final Query<R> query,
                                              final PositionBound positionBound,

Review Comment:
   adjust indention



##########
streams/src/main/java/org/apache/kafka/streams/state/internals/MeteredTimestampedKeyValueStore.java:
##########
@@ -102,4 +139,216 @@ static class RawAndDeserializedValue<ValueType> {
             this.value = value;
         }
     }
+
+    @SuppressWarnings("unchecked")
+    @Override
+    public <R> QueryResult<R> query(final Query<R> query,
+                                    final PositionBound positionBound,
+                                    final QueryConfig config) {
+
+        final long start = time.nanoseconds();
+        final QueryResult<R> result;
+
+        final StoreQueryUtils.QueryHandler handler = queryHandlers.get(query.getClass());
+        if (handler == null) {
+            result = wrapped().query(query, positionBound, config);
+            if (config.isCollectExecutionInfo()) {
+                result.addExecutionInfo(
+                        "Handled in " + getClass() + " in " + (time.nanoseconds() - start) + "ns");
+            }
+        } else {
+            result = (QueryResult<R>) handler.apply(
+                    query,
+                    positionBound,
+                    config,
+                    this
+            );
+            if (config.isCollectExecutionInfo()) {
+                result.addExecutionInfo(
+                        "Handled in " + getClass() + " with serdes "
+                                + serdes + " in " + (time.nanoseconds() - start) + "ns");
+            }
+        }
+        return result;
+    }
+
+
+
+    @SuppressWarnings("unchecked")
+    private <R> QueryResult<R> runTimestampedKeyQuery(final Query<R> query,
+                                                        final PositionBound positionBound,
+                                                        final QueryConfig config) {
+        final QueryResult<R> result;
+        final TimestampedKeyQuery<K, V> typedKeyQuery = (TimestampedKeyQuery<K, V>) query;
+        final KeyQuery<Bytes, byte[]> rawKeyQuery =
+                KeyQuery.withKey(keyBytes(typedKeyQuery.key()));
+        final QueryResult<byte[]> rawResult =
+                wrapped().query(rawKeyQuery, positionBound, config);
+        if (rawResult.isSuccess()) {
+            final Function<byte[], ValueAndTimestamp<V>> deserializer = getDeserializeValue(serdes, wrapped());

Review Comment:
   With the fix to add the `TimestampedByteStore` marker interface to the adaptor class, I think we can simplify `getDeserializeValue(...)` -- as a matter of fact, it should become so simple that we might not need this helper any longer at all, and we can pull in the code into the callers?



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: jira-unsubscribe@kafka.apache.org

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


Re: [PR] KAFKA-15629: Proposal to introduce IQv2 Query Types: TimestampedKeyQuery and TimestampedRangeQuery [kafka]

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

   Hey folks. It seems that this PR has introduced failures in trunk. From the last build:
   
   ```
   Build / JDK 11 and Scala 2.13 / shouldHaveSamePositionBoundActiveAndStandBy – org.apache.kafka.streams.integration.ConsistencyVectorIntegrationTest
   13s
   Build / JDK 11 and Scala 2.13 / shouldHaveSamePositionBoundActiveAndStandBy – org.apache.kafka.streams.integration.ConsistencyVectorIntegrationTest
   5s
   Build / JDK 21 and Scala 2.13 / shouldHaveSamePositionBoundActiveAndStandBy – org.apache.kafka.streams.integration.ConsistencyVectorIntegrationTest
   47s
   Build / JDK 21 and Scala 2.13 / shouldHaveSamePositionBoundActiveAndStandBy – org.apache.kafka.streams.integration.ConsistencyVectorIntegrationTest
   12s
   Build / JDK 17 and Scala 2.13 / shouldHaveSamePositionBoundActiveAndStandBy – org.apache.kafka.streams.integration.ConsistencyVectorIntegrationTest
   17s
   Build / JDK 17 and Scala 2.13 / shouldHaveSamePositionBoundActiveAndStandBy – org.apache.kafka.streams.integration.ConsistencyVectorIntegrationTest
   15s
   Build / JDK 8 and Scala 2.12 / shouldHaveSamePositionBoundActiveAndStandBy – org.apache.kafka.streams.integration.ConsistencyVectorIntegrationTest
   50s
   Build / JDK 8 and Scala 2.12 / shouldHaveSamePositionBoundActiveAndStandBy – org.apache.kafka.streams.integration.ConsistencyVectorIntegrationTest
   ```
   
   Could you please double check?


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: jira-unsubscribe@kafka.apache.org

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


Re: [PR] KAFKA-15629: Proposal to introduce IQv2 Query Types: TimestampedKeyQuery and TimestampedRangeQuery [kafka]

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


##########
streams/src/main/java/org/apache/kafka/streams/state/internals/MeteredTimestampedKeyValueStore.java:
##########
@@ -102,4 +139,232 @@ static class RawAndDeserializedValue<ValueType> {
             this.value = value;
         }
     }
+
+    @SuppressWarnings("unchecked")
+    @Override
+    public <R> QueryResult<R> query(final Query<R> query,
+                                    final PositionBound positionBound,
+                                    final QueryConfig config) {
+
+        final long start = time.nanoseconds();
+        final QueryResult<R> result;
+
+        final StoreQueryUtils.QueryHandler handler = queryHandlers.get(query.getClass());
+        if (handler == null) {
+            result = wrapped().query(query, positionBound, config);
+            if (config.isCollectExecutionInfo()) {
+                result.addExecutionInfo(
+                        "Handled in " + getClass() + " in " + (time.nanoseconds() - start) + "ns");
+            }
+        } else {
+            result = (QueryResult<R>) handler.apply(
+                    query,
+                    positionBound,
+                    config,
+                    this
+            );
+            if (config.isCollectExecutionInfo()) {
+                result.addExecutionInfo(
+                        "Handled in " + getClass() + " with serdes "
+                                + serdes + " in " + (time.nanoseconds() - start) + "ns");
+            }
+        }
+        return result;
+    }
+
+
+
+    @SuppressWarnings("unchecked")
+    protected <R> QueryResult<R> runTimestampedKeyQuery(final Query<R> query,
+                                                      final PositionBound positionBound,
+                                                      final QueryConfig config) {
+        final QueryResult<R> result;
+        final TimestampedKeyQuery<K, V> typedKeyQuery = (TimestampedKeyQuery<K, V>) query;
+        final KeyQuery<Bytes, byte[]> rawKeyQuery =
+                KeyQuery.withKey(keyBytes(typedKeyQuery.key()));
+        final QueryResult<byte[]> rawResult =
+                wrapped().query(rawKeyQuery, positionBound, config);
+        if (rawResult.isSuccess()) {
+            final Function<byte[], ValueAndTimestamp<V>> deserializer = getDeserializeValue(serdes, wrapped());
+            final ValueAndTimestamp<V> value = deserializer.apply(rawResult.getResult());
+            final QueryResult<ValueAndTimestamp<V>> typedQueryResult =
+                    InternalQueryResultUtil.copyAndSubstituteDeserializedResult(rawResult, value);
+            result = (QueryResult<R>) typedQueryResult;
+        } else {
+            // the generic type doesn't matter, since failed queries have no result set.
+            result = (QueryResult<R>) rawResult;
+        }
+        return result;
+    }
+
+    @SuppressWarnings("unchecked")
+    protected <R> QueryResult<R> runTimestampedRangeQuery(final Query<R> query,
+                                                        final PositionBound positionBound,
+                                                        final QueryConfig config) {
+
+        final QueryResult<R> result;
+        final TimestampedRangeQuery<K, V> typedQuery = (TimestampedRangeQuery<K, V>) query;
+        RangeQuery<Bytes, byte[]> rawRangeQuery;
+        final boolean isKeyAscending = typedQuery.isKeyAscending();
+        if (typedQuery.lowerBound().isPresent() && typedQuery.upperBound().isPresent()) {
+            rawRangeQuery = RangeQuery.withRange(

Review Comment:
   Yes, I reuse the code in the` MeteredKeyValueStore`.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: jira-unsubscribe@kafka.apache.org

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


Re: [PR] KAFKA-15629: Proposal to introduce IQv2 Query Types: TimestampedKeyQuery and TimestampedRangeQuery [kafka]

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


##########
streams/src/main/java/org/apache/kafka/streams/state/internals/MeteredTimestampedKeyValueStore.java:
##########
@@ -102,4 +139,232 @@ static class RawAndDeserializedValue<ValueType> {
             this.value = value;
         }
     }
+
+    @SuppressWarnings("unchecked")
+    @Override
+    public <R> QueryResult<R> query(final Query<R> query,
+                                    final PositionBound positionBound,
+                                    final QueryConfig config) {
+
+        final long start = time.nanoseconds();
+        final QueryResult<R> result;
+
+        final StoreQueryUtils.QueryHandler handler = queryHandlers.get(query.getClass());
+        if (handler == null) {
+            result = wrapped().query(query, positionBound, config);
+            if (config.isCollectExecutionInfo()) {
+                result.addExecutionInfo(
+                        "Handled in " + getClass() + " in " + (time.nanoseconds() - start) + "ns");
+            }
+        } else {
+            result = (QueryResult<R>) handler.apply(
+                    query,
+                    positionBound,
+                    config,
+                    this
+            );
+            if (config.isCollectExecutionInfo()) {
+                result.addExecutionInfo(
+                        "Handled in " + getClass() + " with serdes "
+                                + serdes + " in " + (time.nanoseconds() - start) + "ns");
+            }
+        }
+        return result;
+    }
+
+
+
+    @SuppressWarnings("unchecked")
+    protected <R> QueryResult<R> runTimestampedKeyQuery(final Query<R> query,
+                                                      final PositionBound positionBound,
+                                                      final QueryConfig config) {
+        final QueryResult<R> result;
+        final TimestampedKeyQuery<K, V> typedKeyQuery = (TimestampedKeyQuery<K, V>) query;
+        final KeyQuery<Bytes, byte[]> rawKeyQuery =
+                KeyQuery.withKey(keyBytes(typedKeyQuery.key()));
+        final QueryResult<byte[]> rawResult =
+                wrapped().query(rawKeyQuery, positionBound, config);
+        if (rawResult.isSuccess()) {
+            final Function<byte[], ValueAndTimestamp<V>> deserializer = getDeserializeValue(serdes, wrapped());
+            final ValueAndTimestamp<V> value = deserializer.apply(rawResult.getResult());
+            final QueryResult<ValueAndTimestamp<V>> typedQueryResult =
+                    InternalQueryResultUtil.copyAndSubstituteDeserializedResult(rawResult, value);
+            result = (QueryResult<R>) typedQueryResult;
+        } else {
+            // the generic type doesn't matter, since failed queries have no result set.
+            result = (QueryResult<R>) rawResult;
+        }
+        return result;
+    }
+
+    @SuppressWarnings("unchecked")
+    protected <R> QueryResult<R> runTimestampedRangeQuery(final Query<R> query,
+                                                        final PositionBound positionBound,
+                                                        final QueryConfig config) {
+
+        final QueryResult<R> result;
+        final TimestampedRangeQuery<K, V> typedQuery = (TimestampedRangeQuery<K, V>) query;
+        RangeQuery<Bytes, byte[]> rawRangeQuery;
+        final boolean isKeyAscending = typedQuery.isKeyAscending();
+        if (typedQuery.lowerBound().isPresent() && typedQuery.upperBound().isPresent()) {
+            rawRangeQuery = RangeQuery.withRange(

Review Comment:
   Yes, I reuse the code in the` MeteredKeyValueStore`. I will cleanup the code.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: jira-unsubscribe@kafka.apache.org

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


Re: [PR] KAFKA-15629: Proposal to introduce IQv2 Query Types: TimestampedKeyQuery and TimestampedRangeQuery [kafka]

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


##########
streams/src/main/java/org/apache/kafka/streams/state/internals/KeyValueToTimestampedKeyValueByteStoreAdapter.java:
##########
@@ -180,5 +201,38 @@ public <PS extends Serializer<P>, P> KeyValueIterator<Bytes, byte[]> prefixScan(
     public long approximateNumEntries() {
         return store.approximateNumEntries();
     }
+}
 
+class WrappedRocksDbIterator extends AbstractIterator implements ManagedKeyValueIterator {
+    final private RocksDbIterator rocksDbIterator;
+    public WrappedRocksDbIterator(final RocksDbIterator rocksDbIterator) {
+        this.rocksDbIterator = rocksDbIterator;
+    }
+    @Override
+    protected Object makeNext() {
+        final KeyValue<Bytes, byte[]> next = rocksDbIterator.makeNext();

Review Comment:
   In the `RockDbIterator`,` makeNext` is public, so I change our method from `protected` to `public`
   you can see RockDbIterator` actually extend `AbstractIterator` and implement `MangedKeyValueIterator` and it get data from public `makeNext` method, so we actually can do the same thing.
   



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: jira-unsubscribe@kafka.apache.org

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


Re: [PR] KAFKA-15629: Proposal to introduce IQv2 Query Types: TimestampedKeyQuery and TimestampedRangeQuery [kafka]

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


##########
streams/src/main/java/org/apache/kafka/streams/state/internals/KeyValueToTimestampedKeyValueByteStoreAdapter.java:
##########
@@ -180,5 +201,38 @@ public <PS extends Serializer<P>, P> KeyValueIterator<Bytes, byte[]> prefixScan(
     public long approximateNumEntries() {
         return store.approximateNumEntries();
     }
+}
 
+class WrappedRocksDbIterator extends AbstractIterator implements ManagedKeyValueIterator {
+    final private RocksDbIterator rocksDbIterator;
+    public WrappedRocksDbIterator(final RocksDbIterator rocksDbIterator) {

Review Comment:
   ok



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: jira-unsubscribe@kafka.apache.org

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


Re: [PR] KAFKA-15629: Proposal to introduce IQv2 Query Types: TimestampedKeyQuery and TimestampedRangeQuery [kafka]

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


##########
streams/src/main/java/org/apache/kafka/streams/state/internals/MeteredTimestampedKeyValueStore.java:
##########
@@ -102,4 +139,232 @@ static class RawAndDeserializedValue<ValueType> {
             this.value = value;
         }
     }
+
+    @SuppressWarnings("unchecked")
+    @Override
+    public <R> QueryResult<R> query(final Query<R> query,
+                                    final PositionBound positionBound,
+                                    final QueryConfig config) {
+
+        final long start = time.nanoseconds();
+        final QueryResult<R> result;
+
+        final StoreQueryUtils.QueryHandler handler = queryHandlers.get(query.getClass());
+        if (handler == null) {
+            result = wrapped().query(query, positionBound, config);
+            if (config.isCollectExecutionInfo()) {
+                result.addExecutionInfo(
+                        "Handled in " + getClass() + " in " + (time.nanoseconds() - start) + "ns");
+            }
+        } else {
+            result = (QueryResult<R>) handler.apply(
+                    query,
+                    positionBound,
+                    config,
+                    this
+            );
+            if (config.isCollectExecutionInfo()) {
+                result.addExecutionInfo(
+                        "Handled in " + getClass() + " with serdes "
+                                + serdes + " in " + (time.nanoseconds() - start) + "ns");
+            }
+        }
+        return result;
+    }
+
+
+
+    @SuppressWarnings("unchecked")
+    protected <R> QueryResult<R> runTimestampedKeyQuery(final Query<R> query,

Review Comment:
   Hi, @mjsax, if we change `protected` to `private`, it has a related problem, that is we have to change all other class's `runRangeQuery` or `runKeyQuery` methods from `proteced` to `private` and remove `@Override `annotation, such as the `runRangeQuery` method in `MeteredVersionKeyValueStore`.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: jira-unsubscribe@kafka.apache.org

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


Re: [PR] KAFKA-15629: Proposal to introduce IQv2 Query Types: TimestampedKeyQuery and TimestampedRangeQuery [kafka]

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


##########
streams/src/main/java/org/apache/kafka/streams/state/internals/KeyValueToTimestampedKeyValueByteStoreAdapter.java:
##########
@@ -127,9 +136,25 @@ public <R> QueryResult<R> query(
         final QueryConfig config) {
 
 
+
         final long start = config.isCollectExecutionInfo() ? System.nanoTime() : -1L;
-        final QueryResult<R> result = store.query(query, positionBound, config);
+        QueryResult<R> result = store.query(query, positionBound, config);
+
+        if (result.isSuccess()) {
+            if (query instanceof KeyQuery || query instanceof TimestampedKeyQuery) {

Review Comment:
   We should add a comment above this line:
   ```
   // this adapter always needs to return a `value-with-timestamp` result to hold up its contract
   // thus, we need to add the dummy `-1` timestamp even for `KeyQuery` and `RangeQuery`
   ```



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: jira-unsubscribe@kafka.apache.org

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


Re: [PR] KAFKA-15629: Proposal to introduce IQv2 Query Types: TimestampedKeyQuery and TimestampedRangeQuery [kafka]

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


##########
streams/src/main/java/org/apache/kafka/streams/state/internals/MeteredKeyValueStore.java:
##########
@@ -247,26 +247,18 @@ public Position getPosition() {
     }
 
     @SuppressWarnings("unchecked")
-    protected <R> QueryResult<R> runRangeQuery(final Query<R> query,
+    private <R> QueryResult<R> runRangeQuery(final Query<R> query,
                                                final PositionBound positionBound,

Review Comment:
   fixed



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: jira-unsubscribe@kafka.apache.org

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


Re: [PR] KAFKA-15629: Proposal to introduce IQv2 Query Types: TimestampedKeyQuery and TimestampedRangeQuery [kafka]

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


##########
streams/src/main/java/org/apache/kafka/streams/state/internals/StoreQueryUtils.java:
##########
@@ -346,6 +346,23 @@ public static <V> Function<byte[], V> getDeserializeValue(final StateSerdes<?, V
         return byteArray -> deserializer.deserialize(serdes.topic(), byteArray);
     }
 
+    @SuppressWarnings({"unchecked", "rawtypes"})
+    public static <V> Function<byte[], V> getDeserializeValue2(final StateSerdes<?, V> serdes,
+                                                               final StateStore wrapped,
+                                                               final boolean isDSLStore ) {
+        final Serde<V> valueSerde = serdes.valueSerde();
+        final boolean timestamped = WrappedStateStore.isTimestamped(wrapped) || isDSLStore;
+        final Deserializer<V> deserializer;
+        if (!timestamped && valueSerde instanceof ValueAndTimestampSerde) {

Review Comment:
   As discussed in person: for `RangeQuery`, `KeyValueToTimestampedKeyValueIteratorAdapter` need to wrap the provided `RocksDBRangeIterator` to translate between plain-byte[] format what we receive from the inner store, to the required timestamped-byte[] format that the upper layer expect.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: jira-unsubscribe@kafka.apache.org

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


Re: [PR] KAFKA-15629: Proposal to introduce IQv2 Query Types: TimestampedKeyQuery and TimestampedRangeQuery [kafka]

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


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: jira-unsubscribe@kafka.apache.org

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


Re: [PR] KAFKA-15629: Proposal to introduce IQv2 Query Types: TimestampedKeyQuery and TimestampedRangeQuery [kafka]

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


##########
streams/src/test/java/org/apache/kafka/streams/integration/IQv2StoreIntegrationTest.java:
##########
@@ -782,14 +784,15 @@ public void verifyStore() {
                 final String kind = this.kind;
                 if (storeToTest.keyValue()) {
                     if (storeToTest.timestamped()) {
-                        final Function<ValueAndTimestamp<Integer>, Integer> valueExtractor =
-                            ValueAndTimestamp::value;
-                        shouldHandleKeyQuery(2, valueExtractor, 5);
-                        shouldHandleRangeQueries(valueExtractor);
+                        shouldHandleKeyQuery(2,  5);
+                        shouldHandleTimestampedKeyQuery(2, 5);
+                        shouldHandleRangeQueries();
+                        shouldHandleTimestampedRangeQueries();
                     } else {
-                        final Function<Integer, Integer> valueExtractor = Function.identity();
-                        shouldHandleKeyQuery(2, valueExtractor, 5);
-                        shouldHandleRangeQueries(valueExtractor);
+                        shouldHandleKeyQuery(2, 5);
+                        shouldHandleRangeQueries();
+//                        shouldHandleTimestampedKeyQuery(2, 5);
+//                        shouldHandleTimestampedRangeQueries();

Review Comment:
   We've decided not to include tests for `shouldHandleTimestampedRangeQueries()` and `shouldHandleTimestampedKeyQuery(2, 5)` in this PR. 
   
   The rationale for excluding the test for `shouldHandleTimestampedRangeQueries()` is that if a failure occurs, the code throws an` AssertionError`, which inevitably leads to a failed test, regardless of the correctness of the underlying logic.
   
   Similarly,` shouldHandleTimestampedKeyQuery(2, 5)` is theoretically equivalent to `shouldHandleTimestampedRangeQueries()`. However, it exhibits a discrepancy because `queryResult` is null, and as per the existing code, it should ideally provide an error-containing `queryResult` instead of null. 
   
   Consequently, even if the logic is accurate, the thrown exception prevents the test suite from passing completely.
   
   So, we can solve this problem in this ticket https://issues.apache.org/jira/browse/KAFKA-15768
   @mjsax 
                   



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: jira-unsubscribe@kafka.apache.org

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


Re: [PR] KAFKA-15629: Proposal to introduce IQv2 Query Types: TimestampedKeyQuery and TimestampedRangeQuery [kafka]

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


##########
streams/src/main/java/org/apache/kafka/streams/state/internals/KeyValueToTimestampedKeyValueByteStoreAdapter.java:
##########
@@ -127,14 +131,31 @@ public <R> QueryResult<R> query(
         final QueryConfig config) {
 
 
+
         final long start = config.isCollectExecutionInfo() ? System.nanoTime() : -1L;
-        final QueryResult<R> result = store.query(query, positionBound, config);
+        QueryResult<R> result = store.query(query, positionBound, config);
+        final Position position = result.getPosition();
+
+        if (result.isSuccess()) {
+            if (result.getResult() instanceof byte[]) {

Review Comment:
   ok



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: jira-unsubscribe@kafka.apache.org

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


Re: [PR] KAFKA-15629: Proposal to introduce IQv2 Query Types: TimestampedKeyQuery and TimestampedRangeQuery [kafka]

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


##########
streams/src/main/java/org/apache/kafka/streams/state/internals/KeyValueToTimestampedKeyValueByteStoreAdapter.java:
##########
@@ -126,15 +128,22 @@ public <R> QueryResult<R> query(
         final PositionBound positionBound,
         final QueryConfig config) {
 
-
         final long start = config.isCollectExecutionInfo() ? System.nanoTime() : -1L;
-        final QueryResult<R> result = store.query(query, positionBound, config);
+        QueryResult<R> result = store.query(query, positionBound, config);
+        Position position = result.getPosition();
+        if (result.isSuccess()) {
+            byte[] res = (byte[]) result.getResult();
+            byte[] res1 = convertToTimestampedFormat(res);
+            result = (QueryResult<R>) QueryResult.forResult(res1);

Review Comment:
   ok



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: jira-unsubscribe@kafka.apache.org

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


Re: [PR] KAFKA-15629: Proposal to introduce IQv2 Query Types: TimestampedKeyQuery and TimestampedRangeQuery [kafka]

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


##########
streams/src/main/java/org/apache/kafka/streams/state/internals/MeteredKeyValueStore.java:
##########
@@ -312,6 +364,29 @@ protected <R> QueryResult<R> runKeyQuery(final Query<R> query,
         return result;
     }
 
+    @SuppressWarnings("unchecked")
+    protected <R> QueryResult<R> runTimestampKeyQuery(final Query<R> query,

Review Comment:
   ok



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: jira-unsubscribe@kafka.apache.org

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


Re: [PR] KAFKA-15629: Proposal to introduce IQv2 Query Types: TimestampedKeyQuery and TimestampedRangeQuery [kafka]

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


##########
streams/src/main/java/org/apache/kafka/streams/state/internals/MeteredTimestampedKeyValueStore.java:
##########
@@ -102,4 +140,230 @@ static class RawAndDeserializedValue<ValueType> {
             this.value = value;
         }
     }
+
+    @SuppressWarnings("unchecked")
+    @Override
+    public <R> QueryResult<R> query(final Query<R> query,
+                                    final PositionBound positionBound,
+                                    final QueryConfig config) {
+
+        final long start = time.nanoseconds();
+        final QueryResult<R> result;
+
+        final StoreQueryUtils.QueryHandler handler = queryHandlers.get(query.getClass());
+        if (handler == null) {
+            result = wrapped().query(query, positionBound, config);
+            if (config.isCollectExecutionInfo()) {
+                result.addExecutionInfo(
+                        "Handled in " + getClass() + " in " + (time.nanoseconds() - start) + "ns");
+            }
+        } else {
+            result = (QueryResult<R>) handler.apply(
+                    query,
+                    positionBound,
+                    config,
+                    this
+            );
+            if (config.isCollectExecutionInfo()) {
+                result.addExecutionInfo(
+                        "Handled in " + getClass() + " with serdes "
+                                + serdes + " in " + (time.nanoseconds() - start) + "ns");
+            }
+        }
+        return result;
+    }
+
+
+
+    @SuppressWarnings("unchecked")
+    protected <R> QueryResult<R> runTimestampKeyQuery(final Query<R> query,
+                                                      final PositionBound positionBound,
+                                                      final QueryConfig config) {
+        final QueryResult<R> result;
+        final TimestampedKeyQuery<K, V> typedKeyQuery = (TimestampedKeyQuery<K, V>) query;
+        final KeyQuery<Bytes, byte[]> rawKeyQuery =
+                KeyQuery.withKey(keyBytes(typedKeyQuery.getKey()));
+        final QueryResult<byte[]> rawResult =
+                wrapped().query(rawKeyQuery, positionBound, config);
+        if (rawResult.isSuccess()) {
+            final Function<byte[], ValueAndTimestamp<V>> deserializer = getDeserializeValue(serdes, wrapped());
+            final ValueAndTimestamp<V> value = deserializer.apply(rawResult.getResult());
+            final QueryResult<ValueAndTimestamp<V>> typedQueryResult =
+                    InternalQueryResultUtil.copyAndSubstituteDeserializedResult(rawResult, value);
+            result = (QueryResult<R>) typedQueryResult;
+        } else {
+            // the generic type doesn't matter, since failed queries have no result set.
+            result = (QueryResult<R>) rawResult;
+        }
+        return result;
+    }
+
+    @SuppressWarnings("unchecked")
+    protected <R> QueryResult<R> runTimestampRangeQuery(final Query<R> query,
+                                                        final PositionBound positionBound,
+                                                        final QueryConfig config) {
+
+        final QueryResult<R> result;
+        final TimestampedRangeQuery<K, V> typedQuery = (TimestampedRangeQuery<K, V>) query;
+
+        final RangeQuery<Bytes, byte[]> rawRangeQuery;
+        if (typedQuery.getLowerBound().isPresent() && typedQuery.getUpperBound().isPresent()) {
+            rawRangeQuery = RangeQuery.withRange(
+                    keyBytes(typedQuery.getLowerBound().get()),
+                    keyBytes(typedQuery.getUpperBound().get())
+            );
+        } else if (typedQuery.getLowerBound().isPresent()) {
+            rawRangeQuery = RangeQuery.withLowerBound(keyBytes(typedQuery.getLowerBound().get()));
+        } else if (typedQuery.getUpperBound().isPresent()) {
+            rawRangeQuery = RangeQuery.withUpperBound(keyBytes(typedQuery.getUpperBound().get()));
+        } else {
+            rawRangeQuery = RangeQuery.withNoBounds();
+        }
+        final QueryResult<KeyValueIterator<Bytes, byte[]>> rawResult =
+                wrapped().query(rawRangeQuery, positionBound, config);
+        if (rawResult.isSuccess()) {
+            final KeyValueIterator<Bytes, byte[]> iterator = rawResult.getResult();
+            final KeyValueIterator<K, V> resultIterator = new MeteredKeyValueTimestampedIterator(
+                    iterator,
+                    getSensor,
+                    getDeserializeValue(serdes, wrapped()),
+                    false
+            );
+            final QueryResult<KeyValueIterator<K, V>> typedQueryResult =
+                    InternalQueryResultUtil.copyAndSubstituteDeserializedResult(
+                            rawResult,
+                            resultIterator
+                    );
+            result = (QueryResult<R>) typedQueryResult;
+        } else {
+            // the generic type doesn't matter, since failed queries have no result set.
+            result = (QueryResult<R>) rawResult;
+        }
+        return result;
+    }
+
+    @SuppressWarnings("unchecked")
+    protected <R> QueryResult<R> runKeyQuery2(final Query<R> query,
+                                             final PositionBound positionBound,
+                                             final QueryConfig config) {
+        final QueryResult<R> result;
+        final KeyQuery<K, V> typedKeyQuery = (KeyQuery<K, V>) query;
+        final KeyQuery<Bytes, byte[]> rawKeyQuery =
+                KeyQuery.withKey(keyBytes(typedKeyQuery.getKey()));
+        final QueryResult<byte[]> rawResult =
+                wrapped().query(rawKeyQuery, positionBound, config);
+        if (rawResult.isSuccess()) {
+            final Function<byte[], ValueAndTimestamp<V>> deserializer = getDeserializeValue2(serdes, wrapped(), true);
+            ValueAndTimestamp<V> value = deserializer.apply(rawResult.getResult());
+            V res = null;
+            if (value != null) {
+                res = value.value();
+            }
+            final QueryResult<V> typedQueryResult =
+                    InternalQueryResultUtil.copyAndSubstituteDeserializedResult(rawResult, res);
+            result = (QueryResult<R>) typedQueryResult;
+        } else {
+            // the generic type doesn't matter, since failed queries have no result set.
+            result = (QueryResult<R>) rawResult;
+        }
+        return result;
+    }
+
+    @SuppressWarnings("unchecked")
+    protected <R> QueryResult<R> runRangeQuery2(final Query<R> query,

Review Comment:
   fixed



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: jira-unsubscribe@kafka.apache.org

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


Re: [PR] KAFKA-15629: Proposal to introduce IQv2 Query Types: TimestampedKeyQuery and TimestampedRangeQuery [kafka]

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


##########
streams/src/main/java/org/apache/kafka/streams/query/TimestampedRangeQuery.java:
##########
@@ -0,0 +1,104 @@
+/*
+ * 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.query;
+
+
+import org.apache.kafka.common.annotation.InterfaceStability.Evolving;
+import org.apache.kafka.streams.state.KeyValueIterator;
+import org.apache.kafka.streams.state.ValueAndTimestamp;
+
+
+import java.util.Optional;
+
+/**
+ * Interactive query for issuing range queries and scans over KeyValue stores.
+ * <p>
+ *  A range query retrieves a set of records, specified using an upper and/or lower bound on the keys.
+ * <p>
+ * A scan query retrieves all records contained in the store.
+ * <p>

Review Comment:
   ok



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: jira-unsubscribe@kafka.apache.org

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


Re: [PR] KAFKA-15629: Proposal to introduce IQv2 Query Types: TimestampedKeyQuery and TimestampedRangeQuery [kafka]

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


##########
streams/src/main/java/org/apache/kafka/streams/state/internals/MeteredTimestampedKeyValueStore.java:
##########
@@ -102,4 +139,216 @@ static class RawAndDeserializedValue<ValueType> {
             this.value = value;
         }
     }
+
+    @SuppressWarnings("unchecked")
+    @Override
+    public <R> QueryResult<R> query(final Query<R> query,
+                                    final PositionBound positionBound,
+                                    final QueryConfig config) {
+
+        final long start = time.nanoseconds();
+        final QueryResult<R> result;
+
+        final StoreQueryUtils.QueryHandler handler = queryHandlers.get(query.getClass());
+        if (handler == null) {
+            result = wrapped().query(query, positionBound, config);
+            if (config.isCollectExecutionInfo()) {
+                result.addExecutionInfo(
+                        "Handled in " + getClass() + " in " + (time.nanoseconds() - start) + "ns");
+            }
+        } else {
+            result = (QueryResult<R>) handler.apply(
+                    query,
+                    positionBound,
+                    config,
+                    this
+            );
+            if (config.isCollectExecutionInfo()) {
+                result.addExecutionInfo(
+                        "Handled in " + getClass() + " with serdes "
+                                + serdes + " in " + (time.nanoseconds() - start) + "ns");
+            }
+        }
+        return result;
+    }
+
+
+
+    @SuppressWarnings("unchecked")
+    private <R> QueryResult<R> runTimestampedKeyQuery(final Query<R> query,
+                                                        final PositionBound positionBound,
+                                                        final QueryConfig config) {
+        final QueryResult<R> result;
+        final TimestampedKeyQuery<K, V> typedKeyQuery = (TimestampedKeyQuery<K, V>) query;
+        final KeyQuery<Bytes, byte[]> rawKeyQuery =
+                KeyQuery.withKey(keyBytes(typedKeyQuery.key()));
+        final QueryResult<byte[]> rawResult =
+                wrapped().query(rawKeyQuery, positionBound, config);
+        if (rawResult.isSuccess()) {
+            final Function<byte[], ValueAndTimestamp<V>> deserializer = getDeserializeValue(serdes, wrapped());
+            final ValueAndTimestamp<V> valueAndTimestamp = deserializer.apply(rawResult.getResult());
+            final QueryResult<ValueAndTimestamp<V>> typedQueryResult =
+                    InternalQueryResultUtil.copyAndSubstituteDeserializedResult(rawResult, valueAndTimestamp);
+            result = (QueryResult<R>) typedQueryResult;
+        } else {
+            // the generic type doesn't matter, since failed queries have no result set.
+            result = (QueryResult<R>) rawResult;
+        }
+        return result;
+    }
+
+    @SuppressWarnings("unchecked")
+    private <R> QueryResult<R> runTimestampedRangeQuery(final Query<R> query,
+                                                        final PositionBound positionBound,
+                                                        final QueryConfig config) {
+
+        final QueryResult<R> result;
+        final TimestampedRangeQuery<K, V> typedQuery = (TimestampedRangeQuery<K, V>) query;
+        RangeQuery<Bytes, byte[]> rawRangeQuery;
+        final boolean isKeyAscending = typedQuery.isKeyAscending();
+        rawRangeQuery = RangeQuery.withRange(
+                keyBytes(typedQuery.lowerBound().orElse(null)),
+                keyBytes(typedQuery.upperBound().orElse(null))
+        );
+        if (!isKeyAscending) {
+            rawRangeQuery = rawRangeQuery.withDescendingKeys();
+        }
+        final QueryResult<KeyValueIterator<Bytes, byte[]>> rawResult =
+                wrapped().query(rawRangeQuery, positionBound, config);
+        if (rawResult.isSuccess()) {
+            final KeyValueIterator<Bytes, byte[]> iterator = rawResult.getResult();
+            final KeyValueIterator<K, ValueAndTimestamp<V>> resultIterator = (KeyValueIterator<K, ValueAndTimestamp<V>>) new MeteredTimestampedKeyValueStoreIterator(
+                    iterator,
+                    getSensor,
+                    getDeserializeValue(serdes, wrapped()),
+                    false
+            );
+            final QueryResult<KeyValueIterator<K, ValueAndTimestamp<V>>> typedQueryResult =
+                    InternalQueryResultUtil.copyAndSubstituteDeserializedResult(
+                            rawResult,
+                            resultIterator
+                    );
+            result = (QueryResult<R>) typedQueryResult;
+        } else {
+            // the generic type doesn't matter, since failed queries have no result set.
+            result = (QueryResult<R>) rawResult;
+        }
+        return result;
+    }
+
+    @SuppressWarnings("unchecked")
+    private <R> QueryResult<R> runKeyQuery(final Query<R> query,
+                                             final PositionBound positionBound,
+                                             final QueryConfig config) {
+        final QueryResult<R> result;
+        final KeyQuery<K, V> typedKeyQuery = (KeyQuery<K, V>) query;
+        final KeyQuery<Bytes, byte[]> rawKeyQuery =
+                KeyQuery.withKey(keyBytes(typedKeyQuery.getKey()));
+        final QueryResult<byte[]> rawResult =
+                wrapped().query(rawKeyQuery, positionBound, config);
+        if (rawResult.isSuccess()) {
+            final Function<byte[], ValueAndTimestamp<V>> deserializer = getDeserializeValue(serdes, wrapped());
+            final ValueAndTimestamp<V> valueAndTimestamp = deserializer.apply(rawResult.getResult());
+            final V plainValue = valueAndTimestamp == null ? null : valueAndTimestamp.value();
+            final QueryResult<V> typedQueryResult =
+                    InternalQueryResultUtil.copyAndSubstituteDeserializedResult(rawResult, plainValue);
+            result = (QueryResult<R>) typedQueryResult;
+        } else {
+            // the generic type doesn't matter, since failed queries have no result set.
+            result = (QueryResult<R>) rawResult;
+        }
+        return result;
+    }
+
+    @SuppressWarnings("unchecked")
+    private  <R> QueryResult<R> runRangeQuery(final Query<R> query,
+                                               final PositionBound positionBound,
+                                               final QueryConfig config) {
+
+        final QueryResult<R> result;
+        final RangeQuery<K, V> typedQuery = (RangeQuery<K, V>) query;
+        RangeQuery<Bytes, byte[]> rawRangeQuery;
+        final boolean isKeyAscending = typedQuery.isKeyAscending();
+        rawRangeQuery = RangeQuery.withRange(
+                keyBytes(typedQuery.getLowerBound().orElse(null)),
+                keyBytes(typedQuery.getUpperBound().orElse(null))
+        );
+        if (!isKeyAscending) {
+            rawRangeQuery = rawRangeQuery.withDescendingKeys();
+        }
+        final QueryResult<KeyValueIterator<Bytes, byte[]>> rawResult =
+                wrapped().query(rawRangeQuery, positionBound, config);
+        if (rawResult.isSuccess()) {
+            final KeyValueIterator<Bytes, byte[]> iterator = rawResult.getResult();
+            final KeyValueIterator<K, V> resultIterator = new MeteredTimestampedKeyValueStoreIterator(
+                iterator,
+                getSensor,
+                getDeserializeValue(serdes, wrapped()),
+                true
+            );
+            final QueryResult<KeyValueIterator<K, V>> typedQueryResult =
+                    InternalQueryResultUtil.copyAndSubstituteDeserializedResult(
+                            rawResult,
+                            resultIterator
+                    );
+            result = (QueryResult<R>) typedQueryResult;
+        } else {
+            // the generic type doesn't matter, since failed queries have no result set.
+            result = (QueryResult<R>) rawResult;
+        }
+        return result;
+    }
+
+    @SuppressWarnings("unchecked")
+    private class MeteredTimestampedKeyValueStoreIterator implements KeyValueIterator<K, V> {
+
+        private final KeyValueIterator<Bytes, byte[]> iter;
+        private final Sensor sensor;
+        private final long startNs;
+        private final Function<byte[], ValueAndTimestamp<V>> valueDeserializer;
+
+        private final boolean isKeyOrRangeQuery;
+
+        private MeteredTimestampedKeyValueStoreIterator(final KeyValueIterator<Bytes, byte[]> iter,
+                                                   final Sensor sensor,
+                                                   final Function<byte[], ValueAndTimestamp<V>> valueDeserializer,

Review Comment:
   fixed it.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: jira-unsubscribe@kafka.apache.org

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


Re: [PR] KAFKA-15629: Proposal to introduce IQv2 Query Types: TimestampedKeyQuery and TimestampedRangeQuery [kafka]

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


##########
streams/src/main/java/org/apache/kafka/streams/query/TimestampedRangeQuery.java:
##########
@@ -0,0 +1,130 @@
+/*
+ * 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.query;
+
+
+import org.apache.kafka.common.annotation.InterfaceStability.Evolving;
+import org.apache.kafka.streams.state.KeyValueIterator;
+import org.apache.kafka.streams.state.ValueAndTimestamp;
+
+
+import java.util.Optional;
+
+/**
+ * Interactive query for issuing range queries and scans over Timestamped
+ * KeyValue stores.

Review Comment:
   It seems that we do have a TimestampedKeyValueStore.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: jira-unsubscribe@kafka.apache.org

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


Re: [PR] KAFKA-15629: Proposal to introduce IQv2 Query Types: TimestampedKeyQuery and TimestampedRangeQuery [kafka]

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


##########
streams/src/main/java/org/apache/kafka/streams/state/internals/KeyValueToTimestampedKeyValueByteStoreAdapter.java:
##########
@@ -127,14 +131,31 @@ public <R> QueryResult<R> query(
         final QueryConfig config) {
 
 
+
         final long start = config.isCollectExecutionInfo() ? System.nanoTime() : -1L;
-        final QueryResult<R> result = store.query(query, positionBound, config);
+        QueryResult<R> result = store.query(query, positionBound, config);
+        final Position position = result.getPosition();
+
+        if (result.isSuccess()) {
+            if (result.getResult() instanceof byte[]) {
+                final byte[] plainValue = (byte[]) result.getResult();
+                final byte[] valueWithTimestamp = convertToTimestampedFormat(plainValue);
+                result = (QueryResult<R>) QueryResult.forResult(valueWithTimestamp);
+            }
+            if (result.getResult() instanceof RocksDbIterator) {

Review Comment:
   ok



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: jira-unsubscribe@kafka.apache.org

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


Re: [PR] KAFKA-15629: Proposal to introduce IQv2 Query Types: TimestampedKeyQuery and TimestampedRangeQuery [kafka]

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


##########
streams/src/main/java/org/apache/kafka/streams/state/internals/MeteredTimestampedKeyValueStore.java:
##########
@@ -102,4 +140,230 @@ static class RawAndDeserializedValue<ValueType> {
             this.value = value;
         }
     }
+
+    @SuppressWarnings("unchecked")
+    @Override
+    public <R> QueryResult<R> query(final Query<R> query,
+                                    final PositionBound positionBound,
+                                    final QueryConfig config) {
+
+        final long start = time.nanoseconds();
+        final QueryResult<R> result;
+
+        final StoreQueryUtils.QueryHandler handler = queryHandlers.get(query.getClass());
+        if (handler == null) {
+            result = wrapped().query(query, positionBound, config);
+            if (config.isCollectExecutionInfo()) {
+                result.addExecutionInfo(
+                        "Handled in " + getClass() + " in " + (time.nanoseconds() - start) + "ns");
+            }
+        } else {
+            result = (QueryResult<R>) handler.apply(
+                    query,
+                    positionBound,
+                    config,
+                    this
+            );
+            if (config.isCollectExecutionInfo()) {
+                result.addExecutionInfo(
+                        "Handled in " + getClass() + " with serdes "
+                                + serdes + " in " + (time.nanoseconds() - start) + "ns");
+            }
+        }
+        return result;
+    }
+
+
+
+    @SuppressWarnings("unchecked")
+    protected <R> QueryResult<R> runTimestampKeyQuery(final Query<R> query,
+                                                      final PositionBound positionBound,
+                                                      final QueryConfig config) {
+        final QueryResult<R> result;
+        final TimestampedKeyQuery<K, V> typedKeyQuery = (TimestampedKeyQuery<K, V>) query;
+        final KeyQuery<Bytes, byte[]> rawKeyQuery =
+                KeyQuery.withKey(keyBytes(typedKeyQuery.getKey()));
+        final QueryResult<byte[]> rawResult =
+                wrapped().query(rawKeyQuery, positionBound, config);
+        if (rawResult.isSuccess()) {
+            final Function<byte[], ValueAndTimestamp<V>> deserializer = getDeserializeValue(serdes, wrapped());
+            final ValueAndTimestamp<V> value = deserializer.apply(rawResult.getResult());
+            final QueryResult<ValueAndTimestamp<V>> typedQueryResult =
+                    InternalQueryResultUtil.copyAndSubstituteDeserializedResult(rawResult, value);
+            result = (QueryResult<R>) typedQueryResult;
+        } else {
+            // the generic type doesn't matter, since failed queries have no result set.
+            result = (QueryResult<R>) rawResult;
+        }
+        return result;
+    }
+
+    @SuppressWarnings("unchecked")
+    protected <R> QueryResult<R> runTimestampRangeQuery(final Query<R> query,
+                                                        final PositionBound positionBound,
+                                                        final QueryConfig config) {
+
+        final QueryResult<R> result;
+        final TimestampedRangeQuery<K, V> typedQuery = (TimestampedRangeQuery<K, V>) query;
+
+        final RangeQuery<Bytes, byte[]> rawRangeQuery;
+        if (typedQuery.getLowerBound().isPresent() && typedQuery.getUpperBound().isPresent()) {
+            rawRangeQuery = RangeQuery.withRange(
+                    keyBytes(typedQuery.getLowerBound().get()),
+                    keyBytes(typedQuery.getUpperBound().get())
+            );
+        } else if (typedQuery.getLowerBound().isPresent()) {
+            rawRangeQuery = RangeQuery.withLowerBound(keyBytes(typedQuery.getLowerBound().get()));
+        } else if (typedQuery.getUpperBound().isPresent()) {
+            rawRangeQuery = RangeQuery.withUpperBound(keyBytes(typedQuery.getUpperBound().get()));
+        } else {
+            rawRangeQuery = RangeQuery.withNoBounds();
+        }
+        final QueryResult<KeyValueIterator<Bytes, byte[]>> rawResult =
+                wrapped().query(rawRangeQuery, positionBound, config);
+        if (rawResult.isSuccess()) {
+            final KeyValueIterator<Bytes, byte[]> iterator = rawResult.getResult();
+            final KeyValueIterator<K, V> resultIterator = new MeteredKeyValueTimestampedIterator(
+                    iterator,
+                    getSensor,
+                    getDeserializeValue(serdes, wrapped()),
+                    false
+            );
+            final QueryResult<KeyValueIterator<K, V>> typedQueryResult =
+                    InternalQueryResultUtil.copyAndSubstituteDeserializedResult(
+                            rawResult,
+                            resultIterator
+                    );
+            result = (QueryResult<R>) typedQueryResult;
+        } else {
+            // the generic type doesn't matter, since failed queries have no result set.
+            result = (QueryResult<R>) rawResult;
+        }
+        return result;
+    }
+
+    @SuppressWarnings("unchecked")
+    protected <R> QueryResult<R> runKeyQuery2(final Query<R> query,
+                                             final PositionBound positionBound,
+                                             final QueryConfig config) {
+        final QueryResult<R> result;
+        final KeyQuery<K, V> typedKeyQuery = (KeyQuery<K, V>) query;
+        final KeyQuery<Bytes, byte[]> rawKeyQuery =
+                KeyQuery.withKey(keyBytes(typedKeyQuery.getKey()));
+        final QueryResult<byte[]> rawResult =
+                wrapped().query(rawKeyQuery, positionBound, config);
+        if (rawResult.isSuccess()) {
+            final Function<byte[], ValueAndTimestamp<V>> deserializer = getDeserializeValue2(serdes, wrapped(), true);
+            ValueAndTimestamp<V> value = deserializer.apply(rawResult.getResult());
+            V res = null;
+            if (value != null) {
+                res = value.value();
+            }
+            final QueryResult<V> typedQueryResult =
+                    InternalQueryResultUtil.copyAndSubstituteDeserializedResult(rawResult, res);
+            result = (QueryResult<R>) typedQueryResult;
+        } else {
+            // the generic type doesn't matter, since failed queries have no result set.
+            result = (QueryResult<R>) rawResult;
+        }
+        return result;
+    }
+
+    @SuppressWarnings("unchecked")
+    protected <R> QueryResult<R> runRangeQuery2(final Query<R> query,
+                                               final PositionBound positionBound,
+                                               final QueryConfig config) {
+
+        final QueryResult<R> result;
+        final RangeQuery<K, V> typedQuery = (RangeQuery<K, V>) query;
+        final RangeQuery<Bytes, byte[]> rawRangeQuery;
+        if (typedQuery.getLowerBound().isPresent() && typedQuery.getUpperBound().isPresent()) {
+            rawRangeQuery = RangeQuery.withRange(
+                    keyBytes(typedQuery.getLowerBound().get()),
+                    keyBytes(typedQuery.getUpperBound().get())
+            );
+        } else if (typedQuery.getLowerBound().isPresent()) {
+            rawRangeQuery = RangeQuery.withLowerBound(keyBytes(typedQuery.getLowerBound().get()));
+        } else if (typedQuery.getUpperBound().isPresent()) {
+            rawRangeQuery = RangeQuery.withUpperBound(keyBytes(typedQuery.getUpperBound().get()));
+        } else {
+            rawRangeQuery = RangeQuery.withNoBounds();
+        }
+        final QueryResult<KeyValueIterator<Bytes, byte[]>> rawResult =
+                wrapped().query(rawRangeQuery, positionBound, config);
+        if (rawResult.isSuccess()) {
+            final KeyValueIterator<Bytes, byte[]> iterator = rawResult.getResult();
+            final KeyValueIterator<K,V> resultIterator = new MeteredKeyValueTimestampedIterator(
+                    iterator,
+                    getSensor,
+                    getDeserializeValue(serdes, wrapped()),
+                    true
+            );
+            final QueryResult<KeyValueIterator<K, V>> typedQueryResult =
+                    InternalQueryResultUtil.copyAndSubstituteDeserializedResult(
+                            rawResult,
+                            resultIterator
+                    );
+            result = (QueryResult<R>) typedQueryResult;
+        } else {
+            // the generic type doesn't matter, since failed queries have no result set.
+            result = (QueryResult<R>) rawResult;
+        }
+        return result;
+    }
+
+    @SuppressWarnings("unchecked")
+    private class MeteredKeyValueTimestampedIterator implements KeyValueIterator<K, V> {

Review Comment:
   Yes, we reuse the code, but the name not change yet.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: jira-unsubscribe@kafka.apache.org

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


Re: [PR] KAFKA-15629: Proposal to introduce IQv2 Query Types: TimestampedKeyQuery and TimestampedRangeQuery [kafka]

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


##########
streams/src/main/java/org/apache/kafka/streams/query/TimestampedKeyQuery.java:
##########
@@ -0,0 +1,70 @@
+/*
+ * 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.query;
+
+import org.apache.kafka.common.annotation.InterfaceStability.Evolving;
+import org.apache.kafka.streams.state.ValueAndTimestamp;
+
+import java.util.Objects;
+
+/**
+ * Interactive query for retrieving a single record based on its key.
+ */
+@Evolving
+public final class TimestampedKeyQuery<K, V> implements Query<ValueAndTimestamp<V>> {
+
+    private final K key;
+    private final boolean skipCache;
+
+    private TimestampedKeyQuery(final K key, final boolean skipCache) {
+        this.key = Objects.requireNonNull(key);
+        this.skipCache = skipCache;
+    }
+
+    /**
+     * Creates a query that will retrieve the record identified by {@code key} if it exists
+     * (or {@code null} otherwise).
+     * @param key The key to retrieve
+     * @param <K> The type of the key
+     * @param <V> The type of the value that will be retrieved
+     */
+    public static <K, V> TimestampedKeyQuery<K, V> withKey(final K key) {
+        return new TimestampedKeyQuery<>(key, false);
+    }
+
+    /**
+     * Specifies that the cache should be skipped during query evaluation. This means, that the query will always
+     * get forwarded to the underlying store.
+     */
+    public TimestampedKeyQuery<K, V> skipCache() {
+        return new TimestampedKeyQuery<>(key, true);
+    }
+
+    /**
+     * The key that was specified for this query.
+     */
+    public K getKey() {

Review Comment:
   Yes, I have already updated it, do we need change it in KeyQuery too?



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: jira-unsubscribe@kafka.apache.org

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


Re: [PR] KAFKA-15629: Proposal to introduce IQv2 Query Types: TimestampedKeyQuery and TimestampedRangeQuery [kafka]

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


##########
streams/src/main/java/org/apache/kafka/streams/state/internals/MeteredTimestampedKeyValueStore.java:
##########
@@ -102,4 +139,232 @@ static class RawAndDeserializedValue<ValueType> {
             this.value = value;
         }
     }
+
+    @SuppressWarnings("unchecked")
+    @Override
+    public <R> QueryResult<R> query(final Query<R> query,
+                                    final PositionBound positionBound,
+                                    final QueryConfig config) {
+
+        final long start = time.nanoseconds();
+        final QueryResult<R> result;
+
+        final StoreQueryUtils.QueryHandler handler = queryHandlers.get(query.getClass());
+        if (handler == null) {
+            result = wrapped().query(query, positionBound, config);
+            if (config.isCollectExecutionInfo()) {
+                result.addExecutionInfo(
+                        "Handled in " + getClass() + " in " + (time.nanoseconds() - start) + "ns");
+            }
+        } else {
+            result = (QueryResult<R>) handler.apply(
+                    query,
+                    positionBound,
+                    config,
+                    this
+            );
+            if (config.isCollectExecutionInfo()) {
+                result.addExecutionInfo(
+                        "Handled in " + getClass() + " with serdes "
+                                + serdes + " in " + (time.nanoseconds() - start) + "ns");
+            }
+        }
+        return result;
+    }
+
+
+
+    @SuppressWarnings("unchecked")
+    protected <R> QueryResult<R> runTimestampedKeyQuery(final Query<R> query,
+                                                      final PositionBound positionBound,
+                                                      final QueryConfig config) {
+        final QueryResult<R> result;
+        final TimestampedKeyQuery<K, V> typedKeyQuery = (TimestampedKeyQuery<K, V>) query;
+        final KeyQuery<Bytes, byte[]> rawKeyQuery =
+                KeyQuery.withKey(keyBytes(typedKeyQuery.key()));
+        final QueryResult<byte[]> rawResult =
+                wrapped().query(rawKeyQuery, positionBound, config);
+        if (rawResult.isSuccess()) {
+            final Function<byte[], ValueAndTimestamp<V>> deserializer = getDeserializeValue(serdes, wrapped());
+            final ValueAndTimestamp<V> value = deserializer.apply(rawResult.getResult());
+            final QueryResult<ValueAndTimestamp<V>> typedQueryResult =
+                    InternalQueryResultUtil.copyAndSubstituteDeserializedResult(rawResult, value);
+            result = (QueryResult<R>) typedQueryResult;
+        } else {
+            // the generic type doesn't matter, since failed queries have no result set.
+            result = (QueryResult<R>) rawResult;
+        }
+        return result;
+    }
+
+    @SuppressWarnings("unchecked")
+    protected <R> QueryResult<R> runTimestampedRangeQuery(final Query<R> query,
+                                                        final PositionBound positionBound,
+                                                        final QueryConfig config) {
+
+        final QueryResult<R> result;
+        final TimestampedRangeQuery<K, V> typedQuery = (TimestampedRangeQuery<K, V>) query;
+        RangeQuery<Bytes, byte[]> rawRangeQuery;
+        final boolean isKeyAscending = typedQuery.isKeyAscending();
+        if (typedQuery.lowerBound().isPresent() && typedQuery.upperBound().isPresent()) {
+            rawRangeQuery = RangeQuery.withRange(
+                    keyBytes(typedQuery.lowerBound().get()),
+                    keyBytes(typedQuery.upperBound().get())
+            );
+        } else if (typedQuery.lowerBound().isPresent()) {
+            rawRangeQuery = RangeQuery.withLowerBound(keyBytes(typedQuery.lowerBound().get()));
+        } else if (typedQuery.upperBound().isPresent()) {
+            rawRangeQuery = RangeQuery.withUpperBound(keyBytes(typedQuery.upperBound().get()));
+        } else {
+            rawRangeQuery = RangeQuery.withNoBounds();
+        }
+        if (!isKeyAscending) {
+            rawRangeQuery = rawRangeQuery.withDescendingKeys();
+        }
+        final QueryResult<KeyValueIterator<Bytes, byte[]>> rawResult =
+                wrapped().query(rawRangeQuery, positionBound, config);
+        if (rawResult.isSuccess()) {
+            final KeyValueIterator<Bytes, byte[]> iterator = rawResult.getResult();
+            final KeyValueIterator<K, V> resultIterator = new MeteredKeyValueTimestampedIterator(
+                    iterator,
+                    getSensor,
+                    getDeserializeValue(serdes, wrapped()),
+                    false
+            );
+            final QueryResult<KeyValueIterator<K, V>> typedQueryResult =
+                    InternalQueryResultUtil.copyAndSubstituteDeserializedResult(
+                            rawResult,
+                            resultIterator
+                    );
+            result = (QueryResult<R>) typedQueryResult;
+        } else {
+            // the generic type doesn't matter, since failed queries have no result set.
+            result = (QueryResult<R>) rawResult;
+        }
+        return result;
+    }
+
+    @SuppressWarnings("unchecked")
+    protected <R> QueryResult<R> runKeyQuery(final Query<R> query,
+                                             final PositionBound positionBound,
+                                             final QueryConfig config) {
+        final QueryResult<R> result;
+        final KeyQuery<K, V> typedKeyQuery = (KeyQuery<K, V>) query;
+        final KeyQuery<Bytes, byte[]> rawKeyQuery =
+                KeyQuery.withKey(keyBytes(typedKeyQuery.getKey()));
+        final QueryResult<byte[]> rawResult =
+                wrapped().query(rawKeyQuery, positionBound, config);
+        if (rawResult.isSuccess()) {
+            final Function<byte[], ValueAndTimestamp<V>> deserializer = getDeserializeValue(serdes, wrapped());
+            final ValueAndTimestamp<V> valueAndTimestamp = deserializer.apply(rawResult.getResult());
+            final V plainValue = valueAndTimestamp == null ? null : valueAndTimestamp.value();
+            final QueryResult<V> typedQueryResult =
+                    InternalQueryResultUtil.copyAndSubstituteDeserializedResult(rawResult, plainValue);
+            result = (QueryResult<R>) typedQueryResult;
+        } else {
+            // the generic type doesn't matter, since failed queries have no result set.
+            result = (QueryResult<R>) rawResult;
+        }
+        return result;
+    }
+
+    @SuppressWarnings("unchecked")
+    protected <R> QueryResult<R> runRangeQuery(final Query<R> query,
+                                               final PositionBound positionBound,
+                                               final QueryConfig config) {
+
+        final QueryResult<R> result;
+        final RangeQuery<K, V> typedQuery = (RangeQuery<K, V>) query;
+        RangeQuery<Bytes, byte[]> rawRangeQuery;
+        final boolean isKeyAscending = typedQuery.isKeyAscending();
+        if (typedQuery.getLowerBound().isPresent() && typedQuery.getUpperBound().isPresent()) {
+            rawRangeQuery = RangeQuery.withRange(
+                    keyBytes(typedQuery.getLowerBound().get()),
+                    keyBytes(typedQuery.getUpperBound().get())
+            );
+        } else if (typedQuery.getLowerBound().isPresent()) {
+            rawRangeQuery = RangeQuery.withLowerBound(keyBytes(typedQuery.getLowerBound().get()));
+        } else if (typedQuery.getUpperBound().isPresent()) {
+            rawRangeQuery = RangeQuery.withUpperBound(keyBytes(typedQuery.getUpperBound().get()));
+        } else {
+            rawRangeQuery = RangeQuery.withNoBounds();
+        }
+        if (!isKeyAscending) {
+            rawRangeQuery = rawRangeQuery.withDescendingKeys();
+        }
+        final QueryResult<KeyValueIterator<Bytes, byte[]>> rawResult =
+                wrapped().query(rawRangeQuery, positionBound, config);
+        if (rawResult.isSuccess()) {
+            final KeyValueIterator<Bytes, byte[]> iterator = rawResult.getResult();
+            final KeyValueIterator<K, V> resultIterator = new MeteredKeyValueTimestampedIterator(

Review Comment:
   I see -- let me think about this -- not sure if that's the right way to go -- but maybe it's ok...



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: jira-unsubscribe@kafka.apache.org

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


Re: [PR] KAFKA-15629: Proposal to introduce IQv2 Query Types: TimestampedKeyQuery and TimestampedRangeQuery [kafka]

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


##########
streams/src/main/java/org/apache/kafka/streams/state/internals/WrappedStateStore.java:
##########
@@ -34,6 +34,9 @@
 public abstract class WrappedStateStore<S extends StateStore, K, V> implements StateStore, CachedStateStore<K, V> {
 
     public static boolean isTimestamped(final StateStore stateStore) {
+        if (stateStore instanceof KeyValueToTimestampedKeyValueByteStoreAdapter) {

Review Comment:
   but now` TimestampedBytesStore` like this:
   
   ```
   public interface TimestampedBytesStore {
       static byte[] convertToTimestampedFormat(final byte[] plainValue) {
           if (plainValue == null) {
               return null;
           }
           return ByteBuffer
               .allocate(8 + plainValue.length)
               .putLong(NO_TIMESTAMP)
               .put(plainValue)
               .array();
       }
   }
   ```
   
   you mean we implement a method return true in this interface?



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: jira-unsubscribe@kafka.apache.org

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


Re: [PR] KAFKA-15629: Proposal to introduce IQv2 Query Types: TimestampedKeyQuery and TimestampedRangeQuery [kafka]

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


##########
streams/src/main/java/org/apache/kafka/streams/state/internals/WrappedStateStore.java:
##########
@@ -34,6 +34,9 @@
 public abstract class WrappedStateStore<S extends StateStore, K, V> implements StateStore, CachedStateStore<K, V> {
 
     public static boolean isTimestamped(final StateStore stateStore) {
+        if (stateStore instanceof KeyValueToTimestampedKeyValueByteStoreAdapter) {

Review Comment:
   got it.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: jira-unsubscribe@kafka.apache.org

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


Re: [PR] KAFKA-15629: Proposal to introduce IQv2 Query Types: TimestampedKeyQuery and TimestampedRangeQuery [kafka]

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


##########
streams/src/main/java/org/apache/kafka/streams/state/internals/MeteredTimestampedKeyValueStore.java:
##########
@@ -102,4 +139,216 @@ static class RawAndDeserializedValue<ValueType> {
             this.value = value;
         }
     }
+
+    @SuppressWarnings("unchecked")
+    @Override
+    public <R> QueryResult<R> query(final Query<R> query,
+                                    final PositionBound positionBound,
+                                    final QueryConfig config) {
+
+        final long start = time.nanoseconds();
+        final QueryResult<R> result;
+
+        final StoreQueryUtils.QueryHandler handler = queryHandlers.get(query.getClass());
+        if (handler == null) {
+            result = wrapped().query(query, positionBound, config);
+            if (config.isCollectExecutionInfo()) {
+                result.addExecutionInfo(
+                        "Handled in " + getClass() + " in " + (time.nanoseconds() - start) + "ns");
+            }
+        } else {
+            result = (QueryResult<R>) handler.apply(
+                    query,
+                    positionBound,
+                    config,
+                    this
+            );
+            if (config.isCollectExecutionInfo()) {
+                result.addExecutionInfo(
+                        "Handled in " + getClass() + " with serdes "
+                                + serdes + " in " + (time.nanoseconds() - start) + "ns");
+            }
+        }
+        return result;
+    }
+
+
+
+    @SuppressWarnings("unchecked")
+    private <R> QueryResult<R> runTimestampedKeyQuery(final Query<R> query,
+                                                        final PositionBound positionBound,

Review Comment:
   fixed



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: jira-unsubscribe@kafka.apache.org

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


Re: [PR] KAFKA-15629: Proposal to introduce IQv2 Query Types: TimestampedKeyQuery and TimestampedRangeQuery [kafka]

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


##########
streams/src/main/java/org/apache/kafka/streams/state/internals/KeyValueToTimestampedKeyValueByteStoreAdapter.java:
##########
@@ -127,9 +136,25 @@ public <R> QueryResult<R> query(
         final QueryConfig config) {
 
 
+
         final long start = config.isCollectExecutionInfo() ? System.nanoTime() : -1L;
-        final QueryResult<R> result = store.query(query, positionBound, config);
+        QueryResult<R> result = store.query(query, positionBound, config);
+
+        if (result.isSuccess()) {
+            if (query instanceof KeyQuery || query instanceof TimestampedKeyQuery) {
+                final byte[] plainValue = (byte[]) result.getResult();
+                final byte[] valueWithTimestamp = convertToTimestampedFormat(plainValue);
+                result = (QueryResult<R>) InternalQueryResultUtil.copyAndSubstituteDeserializedResult(result, valueWithTimestamp);
+            } else if (query instanceof RangeQuery || query instanceof TimestampedRangeQuery) {
+                final KeyValueToTimestampedKeyValueAdapterIterator wrappedRocksDBRangeIterator = new KeyValueToTimestampedKeyValueAdapterIterator((RocksDbIterator) result.getResult());
+                result = (QueryResult<R>) InternalQueryResultUtil.copyAndSubstituteDeserializedResult(result, wrappedRocksDBRangeIterator);
+            } else {
+                throw new StreamsException("unsupported query type");

Review Comment:
   ok



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: jira-unsubscribe@kafka.apache.org

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


Re: [PR] KAFKA-15629: Proposal to introduce IQv2 Query Types: TimestampedKeyQuery and TimestampedRangeQuery [kafka]

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


##########
streams/src/main/java/org/apache/kafka/streams/state/internals/MeteredTimestampedKeyValueStore.java:
##########
@@ -102,4 +139,216 @@ static class RawAndDeserializedValue<ValueType> {
             this.value = value;
         }
     }
+
+    @SuppressWarnings("unchecked")
+    @Override
+    public <R> QueryResult<R> query(final Query<R> query,
+                                    final PositionBound positionBound,
+                                    final QueryConfig config) {
+
+        final long start = time.nanoseconds();
+        final QueryResult<R> result;
+
+        final StoreQueryUtils.QueryHandler handler = queryHandlers.get(query.getClass());
+        if (handler == null) {
+            result = wrapped().query(query, positionBound, config);
+            if (config.isCollectExecutionInfo()) {
+                result.addExecutionInfo(
+                        "Handled in " + getClass() + " in " + (time.nanoseconds() - start) + "ns");
+            }
+        } else {
+            result = (QueryResult<R>) handler.apply(
+                    query,
+                    positionBound,
+                    config,
+                    this
+            );
+            if (config.isCollectExecutionInfo()) {
+                result.addExecutionInfo(
+                        "Handled in " + getClass() + " with serdes "
+                                + serdes + " in " + (time.nanoseconds() - start) + "ns");
+            }
+        }
+        return result;
+    }
+
+
+
+    @SuppressWarnings("unchecked")
+    private <R> QueryResult<R> runTimestampedKeyQuery(final Query<R> query,
+                                                        final PositionBound positionBound,
+                                                        final QueryConfig config) {
+        final QueryResult<R> result;
+        final TimestampedKeyQuery<K, V> typedKeyQuery = (TimestampedKeyQuery<K, V>) query;
+        final KeyQuery<Bytes, byte[]> rawKeyQuery =
+                KeyQuery.withKey(keyBytes(typedKeyQuery.key()));
+        final QueryResult<byte[]> rawResult =
+                wrapped().query(rawKeyQuery, positionBound, config);
+        if (rawResult.isSuccess()) {
+            final Function<byte[], ValueAndTimestamp<V>> deserializer = getDeserializeValue(serdes, wrapped());
+            final ValueAndTimestamp<V> valueAndTimestamp = deserializer.apply(rawResult.getResult());
+            final QueryResult<ValueAndTimestamp<V>> typedQueryResult =
+                    InternalQueryResultUtil.copyAndSubstituteDeserializedResult(rawResult, valueAndTimestamp);
+            result = (QueryResult<R>) typedQueryResult;
+        } else {
+            // the generic type doesn't matter, since failed queries have no result set.
+            result = (QueryResult<R>) rawResult;
+        }
+        return result;
+    }
+
+    @SuppressWarnings("unchecked")
+    private <R> QueryResult<R> runTimestampedRangeQuery(final Query<R> query,
+                                                        final PositionBound positionBound,
+                                                        final QueryConfig config) {
+
+        final QueryResult<R> result;
+        final TimestampedRangeQuery<K, V> typedQuery = (TimestampedRangeQuery<K, V>) query;
+        RangeQuery<Bytes, byte[]> rawRangeQuery;
+        final boolean isKeyAscending = typedQuery.isKeyAscending();
+        rawRangeQuery = RangeQuery.withRange(
+                keyBytes(typedQuery.lowerBound().orElse(null)),
+                keyBytes(typedQuery.upperBound().orElse(null))
+        );
+        if (!isKeyAscending) {
+            rawRangeQuery = rawRangeQuery.withDescendingKeys();
+        }
+        final QueryResult<KeyValueIterator<Bytes, byte[]>> rawResult =
+                wrapped().query(rawRangeQuery, positionBound, config);
+        if (rawResult.isSuccess()) {
+            final KeyValueIterator<Bytes, byte[]> iterator = rawResult.getResult();
+            final KeyValueIterator<K, ValueAndTimestamp<V>> resultIterator = (KeyValueIterator<K, ValueAndTimestamp<V>>) new MeteredTimestampedKeyValueStoreIterator(
+                    iterator,
+                    getSensor,
+                    getDeserializeValue(serdes, wrapped()),
+                    false
+            );
+            final QueryResult<KeyValueIterator<K, ValueAndTimestamp<V>>> typedQueryResult =
+                    InternalQueryResultUtil.copyAndSubstituteDeserializedResult(
+                            rawResult,
+                            resultIterator
+                    );
+            result = (QueryResult<R>) typedQueryResult;
+        } else {
+            // the generic type doesn't matter, since failed queries have no result set.
+            result = (QueryResult<R>) rawResult;
+        }
+        return result;
+    }
+
+    @SuppressWarnings("unchecked")
+    private <R> QueryResult<R> runKeyQuery(final Query<R> query,
+                                             final PositionBound positionBound,
+                                             final QueryConfig config) {
+        final QueryResult<R> result;
+        final KeyQuery<K, V> typedKeyQuery = (KeyQuery<K, V>) query;
+        final KeyQuery<Bytes, byte[]> rawKeyQuery =
+                KeyQuery.withKey(keyBytes(typedKeyQuery.getKey()));
+        final QueryResult<byte[]> rawResult =
+                wrapped().query(rawKeyQuery, positionBound, config);
+        if (rawResult.isSuccess()) {
+            final Function<byte[], ValueAndTimestamp<V>> deserializer = getDeserializeValue(serdes, wrapped());
+            final ValueAndTimestamp<V> valueAndTimestamp = deserializer.apply(rawResult.getResult());
+            final V plainValue = valueAndTimestamp == null ? null : valueAndTimestamp.value();
+            final QueryResult<V> typedQueryResult =
+                    InternalQueryResultUtil.copyAndSubstituteDeserializedResult(rawResult, plainValue);
+            result = (QueryResult<R>) typedQueryResult;
+        } else {
+            // the generic type doesn't matter, since failed queries have no result set.
+            result = (QueryResult<R>) rawResult;
+        }
+        return result;
+    }
+
+    @SuppressWarnings("unchecked")
+    private  <R> QueryResult<R> runRangeQuery(final Query<R> query,
+                                               final PositionBound positionBound,
+                                               final QueryConfig config) {
+
+        final QueryResult<R> result;
+        final RangeQuery<K, V> typedQuery = (RangeQuery<K, V>) query;
+        RangeQuery<Bytes, byte[]> rawRangeQuery;
+        final boolean isKeyAscending = typedQuery.isKeyAscending();
+        rawRangeQuery = RangeQuery.withRange(
+                keyBytes(typedQuery.getLowerBound().orElse(null)),
+                keyBytes(typedQuery.getUpperBound().orElse(null))
+        );
+        if (!isKeyAscending) {
+            rawRangeQuery = rawRangeQuery.withDescendingKeys();
+        }
+        final QueryResult<KeyValueIterator<Bytes, byte[]>> rawResult =
+                wrapped().query(rawRangeQuery, positionBound, config);
+        if (rawResult.isSuccess()) {
+            final KeyValueIterator<Bytes, byte[]> iterator = rawResult.getResult();
+            final KeyValueIterator<K, V> resultIterator = new MeteredTimestampedKeyValueStoreIterator(
+                iterator,
+                getSensor,
+                getDeserializeValue(serdes, wrapped()),
+                true
+            );
+            final QueryResult<KeyValueIterator<K, V>> typedQueryResult =
+                    InternalQueryResultUtil.copyAndSubstituteDeserializedResult(
+                            rawResult,
+                            resultIterator
+                    );
+            result = (QueryResult<R>) typedQueryResult;
+        } else {
+            // the generic type doesn't matter, since failed queries have no result set.
+            result = (QueryResult<R>) rawResult;
+        }
+        return result;
+    }
+
+    @SuppressWarnings("unchecked")
+    private class MeteredTimestampedKeyValueStoreIterator implements KeyValueIterator<K, V> {
+
+        private final KeyValueIterator<Bytes, byte[]> iter;
+        private final Sensor sensor;
+        private final long startNs;
+        private final Function<byte[], ValueAndTimestamp<V>> valueDeserializer;
+
+        private final boolean isKeyOrRangeQuery;
+
+        private MeteredTimestampedKeyValueStoreIterator(final KeyValueIterator<Bytes, byte[]> iter,
+                                                   final Sensor sensor,
+                                                   final Function<byte[], ValueAndTimestamp<V>> valueDeserializer,
+                                                   final boolean isKeyOrRangeQuery) {
+            this.iter = iter;
+            this.sensor = sensor;
+            this.valueDeserializer = valueDeserializer;
+            this.startNs = time.nanoseconds();
+            this.isKeyOrRangeQuery = isKeyOrRangeQuery;
+        }
+
+        @Override
+        public boolean hasNext() {
+            return iter.hasNext();
+        }
+
+        @Override
+        public KeyValue<K, V> next() {
+            final KeyValue<Bytes, byte[]> keyValue = iter.next();
+            if (isKeyOrRangeQuery) {
+                final V value = valueDeserializer.apply(keyValue.value).value();

Review Comment:
   fixed it.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: jira-unsubscribe@kafka.apache.org

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


Re: [PR] KAFKA-15629: Proposal to introduce IQv2 Query Types: TimestampedKeyQuery and TimestampedRangeQuery [kafka]

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


##########
streams/src/test/java/org/apache/kafka/streams/integration/IQv2StoreIntegrationTest.java:
##########
@@ -1584,7 +1646,43 @@ public <V> void shouldHandleKeyQuery(
         );
 
         final V result1 = queryResult.getResult();
-        final Integer integer = valueExtactor.apply(result1);
+        final Integer integer = (Integer) result1;
+        assertThat(integer, is(expectedValue));
+        assertThat(queryResult.getExecutionInfo(), is(empty()));
+        assertThat(queryResult.getPosition(), is(POSITION_0));
+    }
+
+    public <V> void shouldHandleTimestampedKeyQuery(
+            final Integer key,
+            final Integer expectedValue) {

Review Comment:
   But in the end we should compare the value in `ValueAndTimestamp`? 



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: jira-unsubscribe@kafka.apache.org

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


Re: [PR] KAFKA-15629: Proposal to introduce IQv2 Query Types: TimestampedKeyQuery and TimestampedRangeQuery [kafka]

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


##########
streams/src/test/java/org/apache/kafka/streams/integration/IQv2StoreIntegrationTest.java:
##########
@@ -1632,10 +1729,65 @@ public <V> void shouldHandleRangeQuery(
                     IllegalArgumentException.class,
                     queryResult.get(partition)::getFailureMessage
                 );
-
                 try (final KeyValueIterator<Integer, V> iterator = queryResult.get(partition).getResult()) {
                     while (iterator.hasNext()) {
-                        actualValues.add(valueExtactor.apply(iterator.next().value));
+                        actualValues.add((Integer) iterator.next().value);
+                    }
+                }
+                assertThat(queryResult.get(partition).getExecutionInfo(), is(empty()));
+            }
+            assertThat("Result:" + result, actualValues, is(expectedValues));
+            assertThat("Result:" + result, result.getPosition(), is(INPUT_POSITION));
+        }
+    }
+
+    public <V> void shouldHandleTimestampedRangeQuery(
+        final Optional<Integer> lower,
+        final Optional<Integer> upper,
+        final boolean isKeyAscending,
+        final List<Integer> expectedValues) {

Review Comment:
   It seem every time the timestamp of ` ValueAndTimestamp` is change, so we cannot compare ` ValueAndTimestamp`.



##########
streams/src/test/java/org/apache/kafka/streams/integration/IQv2StoreIntegrationTest.java:
##########
@@ -1632,10 +1729,65 @@ public <V> void shouldHandleRangeQuery(
                     IllegalArgumentException.class,
                     queryResult.get(partition)::getFailureMessage
                 );
-
                 try (final KeyValueIterator<Integer, V> iterator = queryResult.get(partition).getResult()) {
                     while (iterator.hasNext()) {
-                        actualValues.add(valueExtactor.apply(iterator.next().value));
+                        actualValues.add((Integer) iterator.next().value);
+                    }
+                }
+                assertThat(queryResult.get(partition).getExecutionInfo(), is(empty()));
+            }
+            assertThat("Result:" + result, actualValues, is(expectedValues));
+            assertThat("Result:" + result, result.getPosition(), is(INPUT_POSITION));
+        }
+    }
+
+    public <V> void shouldHandleTimestampedRangeQuery(
+        final Optional<Integer> lower,
+        final Optional<Integer> upper,
+        final boolean isKeyAscending,
+        final List<Integer> expectedValues) {

Review Comment:
   It seems every time the timestamp of ` ValueAndTimestamp` is change, so we cannot compare ` ValueAndTimestamp`.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: jira-unsubscribe@kafka.apache.org

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


Re: [PR] KAFKA-15629: Proposal to introduce IQv2 Query Types: TimestampedKeyQuery and TimestampedRangeQuery [kafka]

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


##########
streams/src/main/java/org/apache/kafka/streams/state/internals/MeteredKeyValueStore.java:
##########
@@ -99,9 +101,17 @@ public class MeteredKeyValueStore<K, V>
                 RangeQuery.class,
                 (query, positionBound, config, store) -> runRangeQuery(query, positionBound, config)
             ),
+            mkEntry(
+                TimestampedRangeQuery.class,

Review Comment:
   Currently, implementing this method in `MeteredTimestampKeyValueStore `requires copying helper functions from `MeteredKeyValueStore`. However, by implementing it in `MeteredKeyValueStore`, we can directly utilize these helper functions and achieve code reuse.



##########
streams/src/main/java/org/apache/kafka/streams/state/internals/MeteredKeyValueStore.java:
##########
@@ -99,9 +101,17 @@ public class MeteredKeyValueStore<K, V>
                 RangeQuery.class,
                 (query, positionBound, config, store) -> runRangeQuery(query, positionBound, config)
             ),
+            mkEntry(
+                TimestampedRangeQuery.class,
+                (query, positionBound, config, store) -> runTimestampRangeQuery(query, positionBound, config)
+            ),
             mkEntry(
                 KeyQuery.class,
                 (query, positionBound, config, store) -> runKeyQuery(query, positionBound, config)
+            ),
+            mkEntry(
+                TimestampedKeyQuery.class,

Review Comment:
   https://github.com/apache/kafka/pull/14570#discussion_r1367663818



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: jira-unsubscribe@kafka.apache.org

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


Re: [PR] KAFKA-15629: Proposal to introduce IQv2 Query Types: TimestampedKeyQuery and TimestampedRangeQuery [kafka]

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


##########
streams/src/main/java/org/apache/kafka/streams/state/internals/StoreQueryUtils.java:
##########
@@ -346,6 +346,23 @@ public static <V> Function<byte[], V> getDeserializeValue(final StateSerdes<?, V
         return byteArray -> deserializer.deserialize(serdes.topic(), byteArray);
     }
 
+    @SuppressWarnings({"unchecked", "rawtypes"})
+    public static <V> Function<byte[], V> getDeserializeValue2(final StateSerdes<?, V> serdes,
+                                                               final StateStore wrapped,
+                                                               final boolean isDSLStore ) {
+        final Serde<V> valueSerde = serdes.valueSerde();
+        final boolean timestamped = WrappedStateStore.isTimestamped(wrapped) || isDSLStore;

Review Comment:
   ok



##########
streams/src/main/java/org/apache/kafka/streams/state/internals/StoreQueryUtils.java:
##########
@@ -346,6 +346,23 @@ public static <V> Function<byte[], V> getDeserializeValue(final StateSerdes<?, V
         return byteArray -> deserializer.deserialize(serdes.topic(), byteArray);
     }
 
+    @SuppressWarnings({"unchecked", "rawtypes"})
+    public static <V> Function<byte[], V> getDeserializeValue2(final StateSerdes<?, V> serdes,
+                                                               final StateStore wrapped,
+                                                               final boolean isDSLStore ) {
+        final Serde<V> valueSerde = serdes.valueSerde();
+        final boolean timestamped = WrappedStateStore.isTimestamped(wrapped) || isDSLStore;
+        final Deserializer<V> deserializer;
+        if (!timestamped && valueSerde instanceof ValueAndTimestampSerde) {

Review Comment:
   ok



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: jira-unsubscribe@kafka.apache.org

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


Re: [PR] KAFKA-15629: Proposal to introduce IQv2 Query Types: TimestampedKeyQuery and TimestampedRangeQuery [kafka]

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


##########
streams/src/main/java/org/apache/kafka/streams/state/internals/MeteredTimestampedKeyValueStore.java:
##########
@@ -102,4 +139,232 @@ static class RawAndDeserializedValue<ValueType> {
             this.value = value;
         }
     }
+
+    @SuppressWarnings("unchecked")
+    @Override
+    public <R> QueryResult<R> query(final Query<R> query,
+                                    final PositionBound positionBound,
+                                    final QueryConfig config) {
+
+        final long start = time.nanoseconds();
+        final QueryResult<R> result;
+
+        final StoreQueryUtils.QueryHandler handler = queryHandlers.get(query.getClass());
+        if (handler == null) {
+            result = wrapped().query(query, positionBound, config);
+            if (config.isCollectExecutionInfo()) {
+                result.addExecutionInfo(
+                        "Handled in " + getClass() + " in " + (time.nanoseconds() - start) + "ns");
+            }
+        } else {
+            result = (QueryResult<R>) handler.apply(
+                    query,
+                    positionBound,
+                    config,
+                    this
+            );
+            if (config.isCollectExecutionInfo()) {
+                result.addExecutionInfo(
+                        "Handled in " + getClass() + " with serdes "
+                                + serdes + " in " + (time.nanoseconds() - start) + "ns");
+            }
+        }
+        return result;
+    }
+
+
+
+    @SuppressWarnings("unchecked")
+    protected <R> QueryResult<R> runTimestampedKeyQuery(final Query<R> query,
+                                                      final PositionBound positionBound,
+                                                      final QueryConfig config) {
+        final QueryResult<R> result;
+        final TimestampedKeyQuery<K, V> typedKeyQuery = (TimestampedKeyQuery<K, V>) query;
+        final KeyQuery<Bytes, byte[]> rawKeyQuery =
+                KeyQuery.withKey(keyBytes(typedKeyQuery.key()));
+        final QueryResult<byte[]> rawResult =
+                wrapped().query(rawKeyQuery, positionBound, config);
+        if (rawResult.isSuccess()) {
+            final Function<byte[], ValueAndTimestamp<V>> deserializer = getDeserializeValue(serdes, wrapped());
+            final ValueAndTimestamp<V> value = deserializer.apply(rawResult.getResult());
+            final QueryResult<ValueAndTimestamp<V>> typedQueryResult =
+                    InternalQueryResultUtil.copyAndSubstituteDeserializedResult(rawResult, value);
+            result = (QueryResult<R>) typedQueryResult;
+        } else {
+            // the generic type doesn't matter, since failed queries have no result set.
+            result = (QueryResult<R>) rawResult;
+        }
+        return result;
+    }
+
+    @SuppressWarnings("unchecked")
+    protected <R> QueryResult<R> runTimestampedRangeQuery(final Query<R> query,
+                                                        final PositionBound positionBound,
+                                                        final QueryConfig config) {
+
+        final QueryResult<R> result;
+        final TimestampedRangeQuery<K, V> typedQuery = (TimestampedRangeQuery<K, V>) query;
+        RangeQuery<Bytes, byte[]> rawRangeQuery;
+        final boolean isKeyAscending = typedQuery.isKeyAscending();
+        if (typedQuery.lowerBound().isPresent() && typedQuery.upperBound().isPresent()) {
+            rawRangeQuery = RangeQuery.withRange(
+                    keyBytes(typedQuery.lowerBound().get()),
+                    keyBytes(typedQuery.upperBound().get())
+            );
+        } else if (typedQuery.lowerBound().isPresent()) {
+            rawRangeQuery = RangeQuery.withLowerBound(keyBytes(typedQuery.lowerBound().get()));
+        } else if (typedQuery.upperBound().isPresent()) {
+            rawRangeQuery = RangeQuery.withUpperBound(keyBytes(typedQuery.upperBound().get()));
+        } else {
+            rawRangeQuery = RangeQuery.withNoBounds();
+        }
+        if (!isKeyAscending) {
+            rawRangeQuery = rawRangeQuery.withDescendingKeys();
+        }
+        final QueryResult<KeyValueIterator<Bytes, byte[]>> rawResult =
+                wrapped().query(rawRangeQuery, positionBound, config);
+        if (rawResult.isSuccess()) {
+            final KeyValueIterator<Bytes, byte[]> iterator = rawResult.getResult();
+            final KeyValueIterator<K, V> resultIterator = new MeteredKeyValueTimestampedIterator(
+                    iterator,
+                    getSensor,
+                    getDeserializeValue(serdes, wrapped()),
+                    false
+            );
+            final QueryResult<KeyValueIterator<K, V>> typedQueryResult =
+                    InternalQueryResultUtil.copyAndSubstituteDeserializedResult(
+                            rawResult,
+                            resultIterator
+                    );
+            result = (QueryResult<R>) typedQueryResult;
+        } else {
+            // the generic type doesn't matter, since failed queries have no result set.
+            result = (QueryResult<R>) rawResult;
+        }
+        return result;
+    }
+
+    @SuppressWarnings("unchecked")
+    protected <R> QueryResult<R> runKeyQuery(final Query<R> query,
+                                             final PositionBound positionBound,
+                                             final QueryConfig config) {
+        final QueryResult<R> result;
+        final KeyQuery<K, V> typedKeyQuery = (KeyQuery<K, V>) query;
+        final KeyQuery<Bytes, byte[]> rawKeyQuery =
+                KeyQuery.withKey(keyBytes(typedKeyQuery.getKey()));
+        final QueryResult<byte[]> rawResult =
+                wrapped().query(rawKeyQuery, positionBound, config);
+        if (rawResult.isSuccess()) {
+            final Function<byte[], ValueAndTimestamp<V>> deserializer = getDeserializeValue(serdes, wrapped());
+            final ValueAndTimestamp<V> valueAndTimestamp = deserializer.apply(rawResult.getResult());
+            final V plainValue = valueAndTimestamp == null ? null : valueAndTimestamp.value();
+            final QueryResult<V> typedQueryResult =
+                    InternalQueryResultUtil.copyAndSubstituteDeserializedResult(rawResult, plainValue);
+            result = (QueryResult<R>) typedQueryResult;
+        } else {
+            // the generic type doesn't matter, since failed queries have no result set.
+            result = (QueryResult<R>) rawResult;
+        }
+        return result;
+    }
+
+    @SuppressWarnings("unchecked")
+    protected <R> QueryResult<R> runRangeQuery(final Query<R> query,
+                                               final PositionBound positionBound,
+                                               final QueryConfig config) {
+
+        final QueryResult<R> result;
+        final RangeQuery<K, V> typedQuery = (RangeQuery<K, V>) query;
+        RangeQuery<Bytes, byte[]> rawRangeQuery;
+        final boolean isKeyAscending = typedQuery.isKeyAscending();
+        if (typedQuery.getLowerBound().isPresent() && typedQuery.getUpperBound().isPresent()) {
+            rawRangeQuery = RangeQuery.withRange(
+                    keyBytes(typedQuery.getLowerBound().get()),
+                    keyBytes(typedQuery.getUpperBound().get())
+            );
+        } else if (typedQuery.getLowerBound().isPresent()) {
+            rawRangeQuery = RangeQuery.withLowerBound(keyBytes(typedQuery.getLowerBound().get()));
+        } else if (typedQuery.getUpperBound().isPresent()) {
+            rawRangeQuery = RangeQuery.withUpperBound(keyBytes(typedQuery.getUpperBound().get()));
+        } else {
+            rawRangeQuery = RangeQuery.withNoBounds();
+        }
+        if (!isKeyAscending) {
+            rawRangeQuery = rawRangeQuery.withDescendingKeys();
+        }
+        final QueryResult<KeyValueIterator<Bytes, byte[]>> rawResult =
+                wrapped().query(rawRangeQuery, positionBound, config);
+        if (rawResult.isSuccess()) {
+            final KeyValueIterator<Bytes, byte[]> iterator = rawResult.getResult();
+            final KeyValueIterator<K, V> resultIterator = new MeteredKeyValueTimestampedIterator(

Review Comment:
   In the `MeteredKeyValueTimestampedIterator`
   ```
     @Override
           public KeyValue<K, V> next() {
               final KeyValue<Bytes, byte[]> keyValue = iter.next();
               if (isKeyOrRangeQuery) {
                   final V value = valueDeserializer.apply(keyValue.value).value();
                   return KeyValue.pair(
                           serdes.keyFrom(keyValue.key.get()), value);
               }
               return (KeyValue<K, V>) KeyValue.pair(
                       serdes.keyFrom(keyValue.key.get()),
                       valueDeserializer.apply(keyValue.value));
           }
   ```



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: jira-unsubscribe@kafka.apache.org

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


Re: [PR] KAFKA-15629: Proposal to introduce IQv2 Query Types: TimestampedKeyQuery and TimestampedRangeQuery [kafka]

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


##########
streams/src/main/java/org/apache/kafka/streams/state/internals/KeyValueToTimestampedKeyValueByteStoreAdapter.java:
##########
@@ -180,5 +201,38 @@ public <PS extends Serializer<P>, P> KeyValueIterator<Bytes, byte[]> prefixScan(
     public long approximateNumEntries() {
         return store.approximateNumEntries();
     }
+}
 
+class WrappedRocksDbIterator extends AbstractIterator implements ManagedKeyValueIterator {
+    final private RocksDbIterator rocksDbIterator;
+    public WrappedRocksDbIterator(final RocksDbIterator rocksDbIterator) {
+        this.rocksDbIterator = rocksDbIterator;
+    }
+    @Override
+    protected Object makeNext() {
+        final KeyValue<Bytes, byte[]> next = rocksDbIterator.makeNext();
+        if (next == null) {
+            allDone();
+            return null;
+        }
+        final Bytes key = next.key;
+        final byte[] value = next.value;
+        final byte[] res = convertToTimestampedFormat(value);
+        return KeyValue.pair(key, res);

Review Comment:
   ok



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: jira-unsubscribe@kafka.apache.org

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


Re: [PR] KAFKA-15629: Proposal to introduce IQv2 Query Types: TimestampedKeyQuery and TimestampedRangeQuery [kafka]

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


##########
streams/src/main/java/org/apache/kafka/streams/query/TimestampedKeyQuery.java:
##########
@@ -0,0 +1,70 @@
+/*
+ * 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.query;
+
+import org.apache.kafka.common.annotation.InterfaceStability.Evolving;
+import org.apache.kafka.streams.state.ValueAndTimestamp;
+
+import java.util.Objects;
+
+/**
+ * Interactive query for retrieving a single record based on its key.
+ */
+@Evolving
+public final class TimestampedKeyQuery<K, V> implements Query<ValueAndTimestamp<V>> {
+
+    private final K key;
+    private final boolean skipCache;
+
+    private TimestampedKeyQuery(final K key, final boolean skipCache) {
+        this.key = Objects.requireNonNull(key);
+        this.skipCache = skipCache;
+    }
+
+    /**
+     * Creates a query that will retrieve the record identified by {@code key} if it exists
+     * (or {@code null} otherwise).
+     * @param key The key to retrieve
+     * @param <K> The type of the key
+     * @param <V> The type of the value that will be retrieved
+     */
+    public static <K, V> TimestampedKeyQuery<K, V> withKey(final K key) {
+        return new TimestampedKeyQuery<>(key, false);
+    }
+
+    /**
+     * Specifies that the cache should be skipped during query evaluation. This means, that the query will always
+     * get forwarded to the underlying store.
+     */
+    public TimestampedKeyQuery<K, V> skipCache() {
+        return new TimestampedKeyQuery<>(key, true);
+    }
+
+    /**
+     * The key that was specified for this query.
+     */

Review Comment:
   It seems that KeyQuery doesn't have the `@return` ? 
   
   so it should be
   `@return The key that was specified for this query.`



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: jira-unsubscribe@kafka.apache.org

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


Re: [PR] KAFKA-15629: Proposal to introduce IQv2 Query Types: TimestampedKeyQuery and TimestampedRangeQuery [kafka]

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


##########
streams/src/main/java/org/apache/kafka/streams/state/internals/KeyValueToTimestampedKeyValueByteStoreAdapter.java:
##########
@@ -180,5 +201,38 @@ public <PS extends Serializer<P>, P> KeyValueIterator<Bytes, byte[]> prefixScan(
     public long approximateNumEntries() {
         return store.approximateNumEntries();
     }
+}
 
+class WrappedRocksDbIterator extends AbstractIterator implements ManagedKeyValueIterator {
+    final private RocksDbIterator rocksDbIterator;
+    public WrappedRocksDbIterator(final RocksDbIterator rocksDbIterator) {
+        this.rocksDbIterator = rocksDbIterator;
+    }
+    @Override
+    protected Object makeNext() {
+        final KeyValue<Bytes, byte[]> next = rocksDbIterator.makeNext();

Review Comment:
   Not sure if I understand what you are trying to say? Can you elaborate?
   
   `makeNext` is not public API, but `protected` -- because this code "extends" `AbstractIterator` we are allowed to call `makeNext` but it seem not to be clean... Cf https://github.com/apache/kafka/pull/14570#discussion_r1379541488 -- If we change this class to only `implements MangedKeyValueIterator` I believe we won't be able to call `makeNext` any longer, what indicates that we should not do it.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: jira-unsubscribe@kafka.apache.org

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


Re: [PR] KAFKA-15629: Proposal to introduce IQv2 Query Types: TimestampedKeyQuery and TimestampedRangeQuery [kafka]

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


##########
streams/src/main/java/org/apache/kafka/streams/query/TimestampedKeyQuery.java:
##########
@@ -0,0 +1,70 @@
+/*
+ * 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.query;
+
+import org.apache.kafka.common.annotation.InterfaceStability.Evolving;
+import org.apache.kafka.streams.state.ValueAndTimestamp;
+
+import java.util.Objects;
+
+/**
+ * Interactive query for retrieving a single record based on its key.
+ */
+@Evolving
+public final class TimestampedKeyQuery<K, V> implements Query<ValueAndTimestamp<V>> {
+
+    private final K key;
+    private final boolean skipCache;
+
+    private TimestampedKeyQuery(final K key, final boolean skipCache) {
+        this.key = Objects.requireNonNull(key);
+        this.skipCache = skipCache;
+    }
+
+    /**
+     * Creates a query that will retrieve the record identified by {@code key} if it exists
+     * (or {@code null} otherwise).
+     * @param key The key to retrieve
+     * @param <K> The type of the key
+     * @param <V> The type of the value that will be retrieved
+     */
+    public static <K, V> TimestampedKeyQuery<K, V> withKey(final K key) {
+        return new TimestampedKeyQuery<>(key, false);
+    }
+
+    /**
+     * Specifies that the cache should be skipped during query evaluation. This means, that the query will always
+     * get forwarded to the underlying store.
+     */
+    public TimestampedKeyQuery<K, V> skipCache() {
+        return new TimestampedKeyQuery<>(key, true);
+    }
+
+    /**
+     * The key that was specified for this query.
+     */

Review Comment:
   ok



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: jira-unsubscribe@kafka.apache.org

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


Re: [PR] KAFKA-15629: Proposal to introduce IQv2 Query Types: TimestampedKeyQuery and TimestampedRangeQuery [kafka]

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


##########
streams/src/main/java/org/apache/kafka/streams/state/internals/MeteredTimestampedKeyValueStore.java:
##########
@@ -102,4 +139,232 @@ static class RawAndDeserializedValue<ValueType> {
             this.value = value;
         }
     }
+
+    @SuppressWarnings("unchecked")
+    @Override
+    public <R> QueryResult<R> query(final Query<R> query,
+                                    final PositionBound positionBound,
+                                    final QueryConfig config) {
+
+        final long start = time.nanoseconds();
+        final QueryResult<R> result;
+
+        final StoreQueryUtils.QueryHandler handler = queryHandlers.get(query.getClass());
+        if (handler == null) {
+            result = wrapped().query(query, positionBound, config);
+            if (config.isCollectExecutionInfo()) {
+                result.addExecutionInfo(
+                        "Handled in " + getClass() + " in " + (time.nanoseconds() - start) + "ns");
+            }
+        } else {
+            result = (QueryResult<R>) handler.apply(
+                    query,
+                    positionBound,
+                    config,
+                    this
+            );
+            if (config.isCollectExecutionInfo()) {
+                result.addExecutionInfo(
+                        "Handled in " + getClass() + " with serdes "
+                                + serdes + " in " + (time.nanoseconds() - start) + "ns");
+            }
+        }
+        return result;
+    }
+
+
+
+    @SuppressWarnings("unchecked")
+    protected <R> QueryResult<R> runTimestampedKeyQuery(final Query<R> query,

Review Comment:
   I don't know why the contributor use protected here, but I will try it out.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: jira-unsubscribe@kafka.apache.org

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


Re: [PR] KAFKA-15629: Proposal to introduce IQv2 Query Types: TimestampedKeyQuery and TimestampedRangeQuery [kafka]

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


##########
streams/src/main/java/org/apache/kafka/streams/state/internals/MeteredKeyValueStore.java:
##########
@@ -99,9 +101,17 @@ public class MeteredKeyValueStore<K, V>
                 RangeQuery.class,
                 (query, positionBound, config, store) -> runRangeQuery(query, positionBound, config)
             ),
+            mkEntry(
+                TimestampedRangeQuery.class,

Review Comment:
   ok



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: jira-unsubscribe@kafka.apache.org

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


Re: [PR] KAFKA-15629: Proposal to introduce IQv2 Query Types: TimestampedKeyQuery and TimestampedRangeQuery [kafka]

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


##########
streams/src/test/java/org/apache/kafka/streams/integration/IQv2StoreIntegrationTest.java:
##########
@@ -1632,10 +1729,65 @@ public <V> void shouldHandleRangeQuery(
                     IllegalArgumentException.class,
                     queryResult.get(partition)::getFailureMessage
                 );
-
                 try (final KeyValueIterator<Integer, V> iterator = queryResult.get(partition).getResult()) {
                     while (iterator.hasNext()) {
-                        actualValues.add(valueExtactor.apply(iterator.next().value));
+                        actualValues.add((Integer) iterator.next().value);
+                    }
+                }
+                assertThat(queryResult.get(partition).getExecutionInfo(), is(empty()));
+            }
+            assertThat("Result:" + result, actualValues, is(expectedValues));
+            assertThat("Result:" + result, result.getPosition(), is(INPUT_POSITION));
+        }
+    }
+
+    public <V> void shouldHandleTimestampedRangeQuery(
+        final Optional<Integer> lower,
+        final Optional<Integer> upper,
+        final boolean isKeyAscending,
+        final List<Integer> expectedValues) {

Review Comment:
   ok



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: jira-unsubscribe@kafka.apache.org

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


Re: [PR] KAFKA-15629: Proposal to introduce IQv2 Query Types: TimestampedKeyQuery and TimestampedRangeQuery [kafka]

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


##########
streams/src/test/java/org/apache/kafka/streams/integration/IQv2StoreIntegrationTest.java:
##########
@@ -1584,7 +1646,43 @@ public <V> void shouldHandleKeyQuery(
         );
 
         final V result1 = queryResult.getResult();
-        final Integer integer = valueExtactor.apply(result1);
+        final Integer integer = (Integer) result1;
+        assertThat(integer, is(expectedValue));
+        assertThat(queryResult.getExecutionInfo(), is(empty()));
+        assertThat(queryResult.getPosition(), is(POSITION_0));
+    }
+
+    public <V> void shouldHandleTimestampedKeyQuery(
+            final Integer key,
+            final Integer expectedValue) {

Review Comment:
   We should compare both (what happens automatically if you compare `ValueAndTimestamp` type). Thus, you need to set the right timestamp on expected `ValueAndTimestamp`.
   
   The ts comes from the data, and is set in `before()` to `WINDOW_START + Duration.ofMinutes(2).toMillis() * i` when input data is written.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: jira-unsubscribe@kafka.apache.org

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


Re: [PR] KAFKA-15629: Proposal to introduce IQv2 Query Types: TimestampedKeyQuery and TimestampedRangeQuery [kafka]

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


##########
streams/src/test/java/org/apache/kafka/streams/integration/IQv2StoreIntegrationTest.java:
##########
@@ -1584,7 +1646,43 @@ public <V> void shouldHandleKeyQuery(
         );
 
         final V result1 = queryResult.getResult();
-        final Integer integer = valueExtactor.apply(result1);
+        final Integer integer = (Integer) result1;
+        assertThat(integer, is(expectedValue));
+        assertThat(queryResult.getExecutionInfo(), is(empty()));
+        assertThat(queryResult.getPosition(), is(POSITION_0));
+    }
+
+    public <V> void shouldHandleTimestampedKeyQuery(
+            final Integer key,
+            final Integer expectedValue) {
+
+        final TimestampedKeyQuery<Integer, V> query = TimestampedKeyQuery.withKey(key);
+        final StateQueryRequest<ValueAndTimestamp<V>> request =
+                inStore(STORE_NAME)
+                        .withQuery(query)
+                        .withPartitions(mkSet(0, 1))
+                        .withPositionBound(PositionBound.at(INPUT_POSITION));
+
+        final StateQueryResult<ValueAndTimestamp<V>> result =
+                IntegrationTestUtils.iqv2WaitForResult(kafkaStreams, request);
+        final QueryResult<ValueAndTimestamp<V>> queryResult = result.getOnlyPartitionResult();
+        if (queryResult == null) {
+            throw new AssertionError("cannot use this query type to query result");
+        }
+        final boolean failure = queryResult.isFailure();
+        if (failure) {
+            throw new AssertionError(queryResult.toString());
+        }
+        assertThat(queryResult.isSuccess(), is(true));
+
+        assertThrows(IllegalArgumentException.class, queryResult::getFailureReason);
+        assertThrows(
+                IllegalArgumentException.class,
+                queryResult::getFailureMessage
+        );
+
+        final ValueAndTimestamp<V> result1 = queryResult.getResult();

Review Comment:
   ok



##########
streams/src/test/java/org/apache/kafka/streams/integration/IQv2StoreIntegrationTest.java:
##########
@@ -1584,7 +1646,43 @@ public <V> void shouldHandleKeyQuery(
         );
 
         final V result1 = queryResult.getResult();
-        final Integer integer = valueExtactor.apply(result1);
+        final Integer integer = (Integer) result1;
+        assertThat(integer, is(expectedValue));
+        assertThat(queryResult.getExecutionInfo(), is(empty()));
+        assertThat(queryResult.getPosition(), is(POSITION_0));
+    }
+
+    public <V> void shouldHandleTimestampedKeyQuery(
+            final Integer key,
+            final Integer expectedValue) {
+
+        final TimestampedKeyQuery<Integer, V> query = TimestampedKeyQuery.withKey(key);
+        final StateQueryRequest<ValueAndTimestamp<V>> request =
+                inStore(STORE_NAME)
+                        .withQuery(query)
+                        .withPartitions(mkSet(0, 1))
+                        .withPositionBound(PositionBound.at(INPUT_POSITION));
+
+        final StateQueryResult<ValueAndTimestamp<V>> result =
+                IntegrationTestUtils.iqv2WaitForResult(kafkaStreams, request);
+        final QueryResult<ValueAndTimestamp<V>> queryResult = result.getOnlyPartitionResult();
+        if (queryResult == null) {
+            throw new AssertionError("cannot use this query type to query result");
+        }
+        final boolean failure = queryResult.isFailure();
+        if (failure) {
+            throw new AssertionError(queryResult.toString());
+        }
+        assertThat(queryResult.isSuccess(), is(true));
+
+        assertThrows(IllegalArgumentException.class, queryResult::getFailureReason);
+        assertThrows(
+                IllegalArgumentException.class,
+                queryResult::getFailureMessage
+        );
+
+        final ValueAndTimestamp<V> result1 = queryResult.getResult();
+        final Integer integer = (Integer) result1.value();
         assertThat(integer, is(expectedValue));

Review Comment:
   ok



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: jira-unsubscribe@kafka.apache.org

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


Re: [PR] KAFKA-15629: Proposal to introduce IQv2 Query Types: TimestampedKeyQuery and TimestampedRangeQuery [kafka]

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


##########
streams/src/main/java/org/apache/kafka/streams/state/internals/MeteredTimestampedKeyValueStore.java:
##########
@@ -102,4 +139,232 @@ static class RawAndDeserializedValue<ValueType> {
             this.value = value;
         }
     }
+
+    @SuppressWarnings("unchecked")
+    @Override
+    public <R> QueryResult<R> query(final Query<R> query,
+                                    final PositionBound positionBound,
+                                    final QueryConfig config) {
+
+        final long start = time.nanoseconds();
+        final QueryResult<R> result;
+
+        final StoreQueryUtils.QueryHandler handler = queryHandlers.get(query.getClass());
+        if (handler == null) {
+            result = wrapped().query(query, positionBound, config);
+            if (config.isCollectExecutionInfo()) {
+                result.addExecutionInfo(
+                        "Handled in " + getClass() + " in " + (time.nanoseconds() - start) + "ns");
+            }
+        } else {
+            result = (QueryResult<R>) handler.apply(
+                    query,
+                    positionBound,
+                    config,
+                    this
+            );
+            if (config.isCollectExecutionInfo()) {
+                result.addExecutionInfo(
+                        "Handled in " + getClass() + " with serdes "
+                                + serdes + " in " + (time.nanoseconds() - start) + "ns");
+            }
+        }
+        return result;
+    }
+
+
+
+    @SuppressWarnings("unchecked")
+    protected <R> QueryResult<R> runTimestampedKeyQuery(final Query<R> query,
+                                                      final PositionBound positionBound,
+                                                      final QueryConfig config) {
+        final QueryResult<R> result;
+        final TimestampedKeyQuery<K, V> typedKeyQuery = (TimestampedKeyQuery<K, V>) query;
+        final KeyQuery<Bytes, byte[]> rawKeyQuery =
+                KeyQuery.withKey(keyBytes(typedKeyQuery.key()));
+        final QueryResult<byte[]> rawResult =
+                wrapped().query(rawKeyQuery, positionBound, config);
+        if (rawResult.isSuccess()) {
+            final Function<byte[], ValueAndTimestamp<V>> deserializer = getDeserializeValue(serdes, wrapped());
+            final ValueAndTimestamp<V> value = deserializer.apply(rawResult.getResult());
+            final QueryResult<ValueAndTimestamp<V>> typedQueryResult =
+                    InternalQueryResultUtil.copyAndSubstituteDeserializedResult(rawResult, value);
+            result = (QueryResult<R>) typedQueryResult;
+        } else {
+            // the generic type doesn't matter, since failed queries have no result set.
+            result = (QueryResult<R>) rawResult;
+        }
+        return result;
+    }
+
+    @SuppressWarnings("unchecked")
+    protected <R> QueryResult<R> runTimestampedRangeQuery(final Query<R> query,
+                                                        final PositionBound positionBound,
+                                                        final QueryConfig config) {
+
+        final QueryResult<R> result;
+        final TimestampedRangeQuery<K, V> typedQuery = (TimestampedRangeQuery<K, V>) query;
+        RangeQuery<Bytes, byte[]> rawRangeQuery;
+        final boolean isKeyAscending = typedQuery.isKeyAscending();
+        if (typedQuery.lowerBound().isPresent() && typedQuery.upperBound().isPresent()) {
+            rawRangeQuery = RangeQuery.withRange(
+                    keyBytes(typedQuery.lowerBound().get()),
+                    keyBytes(typedQuery.upperBound().get())
+            );
+        } else if (typedQuery.lowerBound().isPresent()) {
+            rawRangeQuery = RangeQuery.withLowerBound(keyBytes(typedQuery.lowerBound().get()));
+        } else if (typedQuery.upperBound().isPresent()) {
+            rawRangeQuery = RangeQuery.withUpperBound(keyBytes(typedQuery.upperBound().get()));
+        } else {
+            rawRangeQuery = RangeQuery.withNoBounds();
+        }
+        if (!isKeyAscending) {
+            rawRangeQuery = rawRangeQuery.withDescendingKeys();
+        }
+        final QueryResult<KeyValueIterator<Bytes, byte[]>> rawResult =
+                wrapped().query(rawRangeQuery, positionBound, config);
+        if (rawResult.isSuccess()) {
+            final KeyValueIterator<Bytes, byte[]> iterator = rawResult.getResult();
+            final KeyValueIterator<K, V> resultIterator = new MeteredKeyValueTimestampedIterator(

Review Comment:
   Yes, I will cast it to  `KeyValueIterator<K, ValueAndTimestamp<V>>`



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: jira-unsubscribe@kafka.apache.org

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


Re: [PR] KAFKA-15629: Proposal to introduce IQv2 Query Types: TimestampedKeyQuery and TimestampedRangeQuery [kafka]

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


##########
streams/src/main/java/org/apache/kafka/streams/state/internals/KeyValueToTimestampedKeyValueByteStoreAdapter.java:
##########
@@ -180,5 +201,38 @@ public <PS extends Serializer<P>, P> KeyValueIterator<Bytes, byte[]> prefixScan(
     public long approximateNumEntries() {
         return store.approximateNumEntries();
     }
+}
 
+class WrappedRocksDbIterator extends AbstractIterator implements ManagedKeyValueIterator {
+    final private RocksDbIterator rocksDbIterator;
+    public WrappedRocksDbIterator(final RocksDbIterator rocksDbIterator) {
+        this.rocksDbIterator = rocksDbIterator;
+    }
+    @Override
+    protected Object makeNext() {
+        final KeyValue<Bytes, byte[]> next = rocksDbIterator.makeNext();

Review Comment:
   It seems that `RocksDbIterator` use `makeNext `get data.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: jira-unsubscribe@kafka.apache.org

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


Re: [PR] KAFKA-15629: Proposal to introduce IQv2 Query Types: TimestampedKeyQuery and TimestampedRangeQuery [kafka]

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


##########
streams/src/main/java/org/apache/kafka/streams/state/internals/KeyValueToTimestampedKeyValueByteStoreAdapter.java:
##########
@@ -180,5 +201,38 @@ public <PS extends Serializer<P>, P> KeyValueIterator<Bytes, byte[]> prefixScan(
     public long approximateNumEntries() {
         return store.approximateNumEntries();
     }
+}
 
+class WrappedRocksDbIterator extends AbstractIterator implements ManagedKeyValueIterator {
+    final private RocksDbIterator rocksDbIterator;
+    public WrappedRocksDbIterator(final RocksDbIterator rocksDbIterator) {
+        this.rocksDbIterator = rocksDbIterator;
+    }
+    @Override
+    protected Object makeNext() {
+        final KeyValue<Bytes, byte[]> next = rocksDbIterator.makeNext();

Review Comment:
   In the `RockDbIterator`,` makeNext` is public, so I change our method from protected to public



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: jira-unsubscribe@kafka.apache.org

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


Re: [PR] KAFKA-15629: Proposal to introduce IQv2 Query Types: TimestampedKeyQuery and TimestampedRangeQuery [kafka]

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


##########
streams/src/main/java/org/apache/kafka/streams/state/internals/MeteredTimestampedKeyValueStore.java:
##########
@@ -102,4 +139,232 @@ static class RawAndDeserializedValue<ValueType> {
             this.value = value;
         }
     }
+
+    @SuppressWarnings("unchecked")
+    @Override
+    public <R> QueryResult<R> query(final Query<R> query,
+                                    final PositionBound positionBound,
+                                    final QueryConfig config) {
+
+        final long start = time.nanoseconds();
+        final QueryResult<R> result;
+
+        final StoreQueryUtils.QueryHandler handler = queryHandlers.get(query.getClass());
+        if (handler == null) {
+            result = wrapped().query(query, positionBound, config);
+            if (config.isCollectExecutionInfo()) {
+                result.addExecutionInfo(
+                        "Handled in " + getClass() + " in " + (time.nanoseconds() - start) + "ns");
+            }
+        } else {
+            result = (QueryResult<R>) handler.apply(
+                    query,
+                    positionBound,
+                    config,
+                    this
+            );
+            if (config.isCollectExecutionInfo()) {
+                result.addExecutionInfo(
+                        "Handled in " + getClass() + " with serdes "
+                                + serdes + " in " + (time.nanoseconds() - start) + "ns");
+            }
+        }
+        return result;
+    }
+
+
+
+    @SuppressWarnings("unchecked")
+    protected <R> QueryResult<R> runTimestampedKeyQuery(final Query<R> query,
+                                                      final PositionBound positionBound,

Review Comment:
   ok



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: jira-unsubscribe@kafka.apache.org

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


Re: [PR] KAFKA-15629: Proposal to introduce IQv2 Query Types: TimestampedKeyQuery and TimestampedRangeQuery [kafka]

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


##########
streams/src/main/java/org/apache/kafka/streams/query/RangeQuery.java:
##########
@@ -34,6 +34,8 @@
  * <p>
  *  Keys' order is based on the serialized byte[] of the keys, not the 'logical' key order.
  * <p>

Review Comment:
   ok



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: jira-unsubscribe@kafka.apache.org

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


Re: [PR] KAFKA-15629: Proposal to introduce IQv2 Query Types: TimestampedKeyQuery and TimestampedRangeQuery [kafka]

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


##########
streams/src/main/java/org/apache/kafka/streams/state/internals/MeteredTimestampedKeyValueStore.java:
##########
@@ -102,4 +139,216 @@ static class RawAndDeserializedValue<ValueType> {
             this.value = value;
         }
     }
+
+    @SuppressWarnings("unchecked")
+    @Override
+    public <R> QueryResult<R> query(final Query<R> query,
+                                    final PositionBound positionBound,
+                                    final QueryConfig config) {
+
+        final long start = time.nanoseconds();
+        final QueryResult<R> result;
+
+        final StoreQueryUtils.QueryHandler handler = queryHandlers.get(query.getClass());
+        if (handler == null) {
+            result = wrapped().query(query, positionBound, config);
+            if (config.isCollectExecutionInfo()) {
+                result.addExecutionInfo(
+                        "Handled in " + getClass() + " in " + (time.nanoseconds() - start) + "ns");
+            }
+        } else {
+            result = (QueryResult<R>) handler.apply(
+                    query,
+                    positionBound,
+                    config,
+                    this
+            );
+            if (config.isCollectExecutionInfo()) {
+                result.addExecutionInfo(
+                        "Handled in " + getClass() + " with serdes "
+                                + serdes + " in " + (time.nanoseconds() - start) + "ns");
+            }
+        }
+        return result;
+    }
+
+
+
+    @SuppressWarnings("unchecked")
+    private <R> QueryResult<R> runTimestampedKeyQuery(final Query<R> query,
+                                                        final PositionBound positionBound,
+                                                        final QueryConfig config) {
+        final QueryResult<R> result;
+        final TimestampedKeyQuery<K, V> typedKeyQuery = (TimestampedKeyQuery<K, V>) query;
+        final KeyQuery<Bytes, byte[]> rawKeyQuery =
+                KeyQuery.withKey(keyBytes(typedKeyQuery.key()));
+        final QueryResult<byte[]> rawResult =
+                wrapped().query(rawKeyQuery, positionBound, config);
+        if (rawResult.isSuccess()) {
+            final Function<byte[], ValueAndTimestamp<V>> deserializer = getDeserializeValue(serdes, wrapped());
+            final ValueAndTimestamp<V> valueAndTimestamp = deserializer.apply(rawResult.getResult());
+            final QueryResult<ValueAndTimestamp<V>> typedQueryResult =
+                    InternalQueryResultUtil.copyAndSubstituteDeserializedResult(rawResult, valueAndTimestamp);
+            result = (QueryResult<R>) typedQueryResult;
+        } else {
+            // the generic type doesn't matter, since failed queries have no result set.
+            result = (QueryResult<R>) rawResult;
+        }
+        return result;
+    }
+
+    @SuppressWarnings("unchecked")
+    private <R> QueryResult<R> runTimestampedRangeQuery(final Query<R> query,
+                                                        final PositionBound positionBound,
+                                                        final QueryConfig config) {
+
+        final QueryResult<R> result;
+        final TimestampedRangeQuery<K, V> typedQuery = (TimestampedRangeQuery<K, V>) query;
+        RangeQuery<Bytes, byte[]> rawRangeQuery;
+        final boolean isKeyAscending = typedQuery.isKeyAscending();
+        rawRangeQuery = RangeQuery.withRange(
+                keyBytes(typedQuery.lowerBound().orElse(null)),
+                keyBytes(typedQuery.upperBound().orElse(null))
+        );
+        if (!isKeyAscending) {
+            rawRangeQuery = rawRangeQuery.withDescendingKeys();
+        }
+        final QueryResult<KeyValueIterator<Bytes, byte[]>> rawResult =
+                wrapped().query(rawRangeQuery, positionBound, config);
+        if (rawResult.isSuccess()) {
+            final KeyValueIterator<Bytes, byte[]> iterator = rawResult.getResult();
+            final KeyValueIterator<K, ValueAndTimestamp<V>> resultIterator = (KeyValueIterator<K, ValueAndTimestamp<V>>) new MeteredTimestampedKeyValueStoreIterator(
+                    iterator,
+                    getSensor,
+                    getDeserializeValue(serdes, wrapped()),
+                    false
+            );
+            final QueryResult<KeyValueIterator<K, ValueAndTimestamp<V>>> typedQueryResult =
+                    InternalQueryResultUtil.copyAndSubstituteDeserializedResult(
+                            rawResult,
+                            resultIterator
+                    );
+            result = (QueryResult<R>) typedQueryResult;
+        } else {
+            // the generic type doesn't matter, since failed queries have no result set.
+            result = (QueryResult<R>) rawResult;
+        }
+        return result;
+    }
+
+    @SuppressWarnings("unchecked")
+    private <R> QueryResult<R> runKeyQuery(final Query<R> query,
+                                             final PositionBound positionBound,
+                                             final QueryConfig config) {
+        final QueryResult<R> result;
+        final KeyQuery<K, V> typedKeyQuery = (KeyQuery<K, V>) query;
+        final KeyQuery<Bytes, byte[]> rawKeyQuery =
+                KeyQuery.withKey(keyBytes(typedKeyQuery.getKey()));
+        final QueryResult<byte[]> rawResult =
+                wrapped().query(rawKeyQuery, positionBound, config);
+        if (rawResult.isSuccess()) {
+            final Function<byte[], ValueAndTimestamp<V>> deserializer = getDeserializeValue(serdes, wrapped());
+            final ValueAndTimestamp<V> valueAndTimestamp = deserializer.apply(rawResult.getResult());
+            final V plainValue = valueAndTimestamp == null ? null : valueAndTimestamp.value();
+            final QueryResult<V> typedQueryResult =
+                    InternalQueryResultUtil.copyAndSubstituteDeserializedResult(rawResult, plainValue);
+            result = (QueryResult<R>) typedQueryResult;
+        } else {
+            // the generic type doesn't matter, since failed queries have no result set.
+            result = (QueryResult<R>) rawResult;
+        }
+        return result;
+    }
+
+    @SuppressWarnings("unchecked")
+    private  <R> QueryResult<R> runRangeQuery(final Query<R> query,
+                                               final PositionBound positionBound,
+                                               final QueryConfig config) {
+
+        final QueryResult<R> result;
+        final RangeQuery<K, V> typedQuery = (RangeQuery<K, V>) query;
+        RangeQuery<Bytes, byte[]> rawRangeQuery;
+        final boolean isKeyAscending = typedQuery.isKeyAscending();
+        rawRangeQuery = RangeQuery.withRange(
+                keyBytes(typedQuery.getLowerBound().orElse(null)),
+                keyBytes(typedQuery.getUpperBound().orElse(null))
+        );
+        if (!isKeyAscending) {
+            rawRangeQuery = rawRangeQuery.withDescendingKeys();
+        }
+        final QueryResult<KeyValueIterator<Bytes, byte[]>> rawResult =
+                wrapped().query(rawRangeQuery, positionBound, config);
+        if (rawResult.isSuccess()) {
+            final KeyValueIterator<Bytes, byte[]> iterator = rawResult.getResult();
+            final KeyValueIterator<K, V> resultIterator = new MeteredTimestampedKeyValueStoreIterator(
+                iterator,
+                getSensor,
+                getDeserializeValue(serdes, wrapped()),
+                true
+            );
+            final QueryResult<KeyValueIterator<K, V>> typedQueryResult =
+                    InternalQueryResultUtil.copyAndSubstituteDeserializedResult(
+                            rawResult,
+                            resultIterator
+                    );
+            result = (QueryResult<R>) typedQueryResult;
+        } else {
+            // the generic type doesn't matter, since failed queries have no result set.
+            result = (QueryResult<R>) rawResult;
+        }
+        return result;
+    }
+
+    @SuppressWarnings("unchecked")
+    private class MeteredTimestampedKeyValueStoreIterator implements KeyValueIterator<K, V> {
+
+        private final KeyValueIterator<Bytes, byte[]> iter;
+        private final Sensor sensor;
+        private final long startNs;
+        private final Function<byte[], ValueAndTimestamp<V>> valueDeserializer;
+
+        private final boolean isKeyOrRangeQuery;
+
+        private MeteredTimestampedKeyValueStoreIterator(final KeyValueIterator<Bytes, byte[]> iter,
+                                                   final Sensor sensor,
+                                                   final Function<byte[], ValueAndTimestamp<V>> valueDeserializer,
+                                                   final boolean isKeyOrRangeQuery) {

Review Comment:
   fixed it.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: jira-unsubscribe@kafka.apache.org

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


Re: [PR] KAFKA-15629: Proposal to introduce IQv2 Query Types: TimestampedKeyQuery and TimestampedRangeQuery [kafka]

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


##########
streams/src/main/java/org/apache/kafka/streams/state/internals/MeteredTimestampedKeyValueStore.java:
##########
@@ -102,4 +139,216 @@ static class RawAndDeserializedValue<ValueType> {
             this.value = value;
         }
     }
+
+    @SuppressWarnings("unchecked")
+    @Override
+    public <R> QueryResult<R> query(final Query<R> query,
+                                    final PositionBound positionBound,
+                                    final QueryConfig config) {
+
+        final long start = time.nanoseconds();
+        final QueryResult<R> result;
+
+        final StoreQueryUtils.QueryHandler handler = queryHandlers.get(query.getClass());
+        if (handler == null) {
+            result = wrapped().query(query, positionBound, config);
+            if (config.isCollectExecutionInfo()) {
+                result.addExecutionInfo(
+                        "Handled in " + getClass() + " in " + (time.nanoseconds() - start) + "ns");
+            }
+        } else {
+            result = (QueryResult<R>) handler.apply(
+                    query,
+                    positionBound,
+                    config,
+                    this
+            );
+            if (config.isCollectExecutionInfo()) {
+                result.addExecutionInfo(
+                        "Handled in " + getClass() + " with serdes "
+                                + serdes + " in " + (time.nanoseconds() - start) + "ns");
+            }
+        }
+        return result;
+    }
+
+
+
+    @SuppressWarnings("unchecked")
+    private <R> QueryResult<R> runTimestampedKeyQuery(final Query<R> query,
+                                                        final PositionBound positionBound,
+                                                        final QueryConfig config) {
+        final QueryResult<R> result;
+        final TimestampedKeyQuery<K, V> typedKeyQuery = (TimestampedKeyQuery<K, V>) query;
+        final KeyQuery<Bytes, byte[]> rawKeyQuery =
+                KeyQuery.withKey(keyBytes(typedKeyQuery.key()));
+        final QueryResult<byte[]> rawResult =
+                wrapped().query(rawKeyQuery, positionBound, config);
+        if (rawResult.isSuccess()) {
+            final Function<byte[], ValueAndTimestamp<V>> deserializer = getDeserializeValue(serdes, wrapped());

Review Comment:
   I am not very sure, but` MeterKeyValueStore` also use getDeserializeValue(...), we can talk it tomorrow. 
   This helper function actually is in `StoreQueryUtils`



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: jira-unsubscribe@kafka.apache.org

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


Re: [PR] KAFKA-15629: Proposal to introduce IQv2 Query Types: TimestampedKeyQuery and TimestampedRangeQuery [kafka]

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


##########
streams/src/main/java/org/apache/kafka/streams/state/internals/MeteredKeyValueStore.java:
##########
@@ -99,9 +101,17 @@ public class MeteredKeyValueStore<K, V>
                 RangeQuery.class,
                 (query, positionBound, config, store) -> runRangeQuery(query, positionBound, config)
             ),
+            mkEntry(
+                TimestampedRangeQuery.class,

Review Comment:
   Not sure what helper function you mean (we call the newly added `runTimestampRangeQuery` which should be added to `TimestampedMeteredKeyValueStore`)?
   
   But even if there would be a code-reuse problem, it's just the wrong place. `MeteredKeyValueStore` is for plain-kv-store, and should only implement what plain-kv-store supports.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: jira-unsubscribe@kafka.apache.org

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


Re: [PR] KAFKA-15629: Proposal to introduce IQv2 Query Types: TimestampedKeyQuery and TimestampedRangeQuery [kafka]

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


##########
streams/src/test/java/org/apache/kafka/streams/integration/IQv2StoreIntegrationTest.java:
##########
@@ -776,64 +779,55 @@ public void verifyStore() {
                 globalShouldRejectAllQueries();
             } else {
                 shouldRejectUnknownQuery();
-                shouldCollectExecutionInfo();
+//                shouldCollectExecutionInfo();
                 shouldCollectExecutionInfoUnderFailure();
                 final String kind = this.kind;
                 if (storeToTest.keyValue()) {
                     if (storeToTest.timestamped()) {
-                        final Function<ValueAndTimestamp<Integer>, Integer> valueExtractor =
-                            ValueAndTimestamp::value;
-                        if (kind.equals("DSL")) {
-                            shouldHandleKeyQuery(2, valueExtractor, 5);
-                            shouldHandleRangeDSLQueries(valueExtractor);
-                        } else {
-                            shouldHandleKeyQuery(2, valueExtractor, 5);
-                            shouldHandleRangePAPIQueries(valueExtractor);
-                        }
-                    } else {
-                        final Function<Integer, Integer> valueExtractor = Function.identity();
-                        if (kind.equals("DSL")) {
-                            shouldHandleKeyQuery(2, valueExtractor, 5);
-                            shouldHandleRangeDSLQueries(valueExtractor);
-                        } else {
-                            shouldHandleKeyQuery(2, valueExtractor, 5);
-                            shouldHandleRangePAPIQueries(valueExtractor);
-                        }
-                    }
-                }
+                        shouldHandleKeyQuery(2,  5);
+                        shouldHandleTimestampedKeyQuery(2, 5);
+                        shouldHandleRangeQueries();
+                        shouldHandleTimestampRangeQueries();
+                  }
+                    else {
+                        shouldHandleKeyQuery(2, 5);

Review Comment:
   ROCK_KV DSL store were execute the code in this else statement.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: jira-unsubscribe@kafka.apache.org

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


Re: [PR] KAFKA-15629: Proposal to introduce IQv2 Query Types: TimestampedKeyQuery and TimestampedRangeQuery [kafka]

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


##########
streams/src/main/java/org/apache/kafka/streams/state/internals/KeyValueToTimestampedKeyValueByteStoreAdapter.java:
##########
@@ -126,15 +128,22 @@ public <R> QueryResult<R> query(
         final PositionBound positionBound,
         final QueryConfig config) {
 
-
         final long start = config.isCollectExecutionInfo() ? System.nanoTime() : -1L;
-        final QueryResult<R> result = store.query(query, positionBound, config);
+        QueryResult<R> result = store.query(query, positionBound, config);
+        Position position = result.getPosition();
+        if (result.isSuccess()) {
+            byte[] res = (byte[]) result.getResult();
+            byte[] res1 = convertToTimestampedFormat(res);
+            result = (QueryResult<R>) QueryResult.forResult(res1);
+        }
+
         if (config.isCollectExecutionInfo()) {
             final long end = System.nanoTime();
             result.addExecutionInfo(
                 "Handled in " + getClass() + " in " + (end - start) + "ns"
             );
         }
+        result.setPosition(position);

Review Comment:
   solved 



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: jira-unsubscribe@kafka.apache.org

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


Re: [PR] KAFKA-15629: Proposal to introduce IQv2 Query Types: TimestampedKeyQuery and TimestampedRangeQuery [kafka]

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


##########
streams/src/test/java/org/apache/kafka/streams/integration/IQv2StoreIntegrationTest.java:
##########
@@ -782,14 +784,15 @@ public void verifyStore() {
                 final String kind = this.kind;
                 if (storeToTest.keyValue()) {
                     if (storeToTest.timestamped()) {
-                        final Function<ValueAndTimestamp<Integer>, Integer> valueExtractor =
-                            ValueAndTimestamp::value;
-                        shouldHandleKeyQuery(2, valueExtractor, 5);
-                        shouldHandleRangeQueries(valueExtractor);
+                        shouldHandleKeyQuery(2,  5);
+                        shouldHandleTimestampedKeyQuery(2, 5);
+                        shouldHandleRangeQueries();
+                        shouldHandleTimestampedRangeQueries();
                     } else {
-                        final Function<Integer, Integer> valueExtractor = Function.identity();
-                        shouldHandleKeyQuery(2, valueExtractor, 5);
-                        shouldHandleRangeQueries(valueExtractor);
+                        shouldHandleKeyQuery(2, 5);
+                        shouldHandleRangeQueries();
+//                        shouldHandleTimestampedKeyQuery(2, 5);
+//                        shouldHandleTimestampedRangeQueries();

Review Comment:
   We've decided not to include tests for `shouldHandleTimestampedRangeQueries()` and `shouldHandleTimestampedKeyQuery(2, 5)` in this PR. 
   
   The rationale for excluding the test for `shouldHandleTimestampedRangeQueries()` is that if a failure(https://github.com/apache/kafka/pull/14570/files#r1379080018) occurs, the code throws an` AssertionError`, which inevitably leads to a failed test, regardless of the correctness of the underlying logic.
   
   Similarly,` shouldHandleTimestampedKeyQuery(2, 5)` is theoretically equivalent to `shouldHandleTimestampedRangeQueries()`. However, it exhibits a discrepancy because `queryResult` is null, and as per the existing code, it should ideally provide an error-containing `queryResult` instead of null. 
   
   Consequently, even if the logic is accurate, the thrown exception prevents the test suite from passing completely.
   
   So, we can solve this problem in this ticket https://issues.apache.org/jira/browse/KAFKA-15768
   @mjsax 
                   



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: jira-unsubscribe@kafka.apache.org

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


Re: [PR] KAFKA-15629: Proposal to introduce IQv2 Query Types: TimestampedKeyQuery and TimestampedRangeQuery [kafka]

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


##########
streams/src/main/java/org/apache/kafka/streams/state/internals/KeyValueToTimestampedKeyValueByteStoreAdapter.java:
##########
@@ -127,14 +131,31 @@ public <R> QueryResult<R> query(
         final QueryConfig config) {
 
 
+
         final long start = config.isCollectExecutionInfo() ? System.nanoTime() : -1L;
-        final QueryResult<R> result = store.query(query, positionBound, config);
+        QueryResult<R> result = store.query(query, positionBound, config);
+        final Position position = result.getPosition();
+
+        if (result.isSuccess()) {
+            if (result.getResult() instanceof byte[]) {
+                final byte[] plainValue = (byte[]) result.getResult();
+                final byte[] valueWithTimestamp = convertToTimestampedFormat(plainValue);
+                result = (QueryResult<R>) QueryResult.forResult(valueWithTimestamp);
+            }
+            if (result.getResult() instanceof RocksDbIterator) {
+                final WrappedRocksDbIterator wrappedRocksDBRangeIterator = new WrappedRocksDbIterator((RocksDbIterator) result.getResult());
+                result = (QueryResult<R>) QueryResult.forResult(wrappedRocksDBRangeIterator);
+            }

Review Comment:
   ok



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: jira-unsubscribe@kafka.apache.org

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


Re: [PR] KAFKA-15629: Proposal to introduce IQv2 Query Types: TimestampedKeyQuery and TimestampedRangeQuery [kafka]

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


##########
streams/src/test/java/org/apache/kafka/streams/integration/IQv2StoreIntegrationTest.java:
##########
@@ -782,14 +784,15 @@ public void verifyStore() {
                 final String kind = this.kind;
                 if (storeToTest.keyValue()) {
                     if (storeToTest.timestamped()) {
-                        final Function<ValueAndTimestamp<Integer>, Integer> valueExtractor =
-                            ValueAndTimestamp::value;
-                        shouldHandleKeyQuery(2, valueExtractor, 5);
-                        shouldHandleRangeQueries(valueExtractor);
+                        shouldHandleKeyQuery(2,  5);
+                        shouldHandleTimestampedKeyQuery(2, 5);
+                        shouldHandleRangeQueries();
+                        shouldHandleTimestampedRangeQueries();
                     } else {
-                        final Function<Integer, Integer> valueExtractor = Function.identity();
-                        shouldHandleKeyQuery(2, valueExtractor, 5);
-                        shouldHandleRangeQueries(valueExtractor);
+                        shouldHandleKeyQuery(2, 5);
+                        shouldHandleRangeQueries();
+//                        shouldHandleTimestampedKeyQuery(2, 5);
+//                        shouldHandleTimestampedRangeQueries();

Review Comment:
   We've decided not to include tests for `shouldHandleTimestampedRangeQueries()` and `shouldHandleTimestampedKeyQuery(2, 5)` in this PR. 
   
   The rationale for excluding the test for `shouldHandleTimestampedRangeQueries()` is that if a failure occurs, the code throws an` AssertionError`, which inevitably leads to a failed test, regardless of the correctness of the underlying logic.
   
   Similarly,` shouldHandleTimestampedKeyQuery(2, 5)` is theoretically equivalent to `shouldHandleTimestampedRangeQueries()`. However, it exhibits a discrepancy because `queryResult` is null, and as per the existing code, it should ideally provide an error-containing `queryResult` instead of null. 
   
   Consequently, even if the logic is accurate, the thrown exception prevents the test suite from passing completely.
   
   So, we can solve this problem in this ticket https://issues.apache.org/jira/browse/KAFKA-15768
   
                   



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: jira-unsubscribe@kafka.apache.org

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


Re: [PR] KAFKA-15629: Proposal to introduce IQv2 Query Types: TimestampedKeyQuery and TimestampedRangeQuery [kafka]

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


##########
streams/src/main/java/org/apache/kafka/streams/state/internals/KeyValueToTimestampedKeyValueByteStoreAdapter.java:
##########
@@ -127,14 +131,31 @@ public <R> QueryResult<R> query(
         final QueryConfig config) {
 
 
+
         final long start = config.isCollectExecutionInfo() ? System.nanoTime() : -1L;
-        final QueryResult<R> result = store.query(query, positionBound, config);
+        QueryResult<R> result = store.query(query, positionBound, config);
+        final Position position = result.getPosition();
+
+        if (result.isSuccess()) {
+            if (result.getResult() instanceof byte[]) {

Review Comment:
   I think we should actually check the input `query` type instead:
   ```
   if (query instanceof KeyQuery || query instanceof TimestampedKeyQuery)
   ```



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: jira-unsubscribe@kafka.apache.org

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


Re: [PR] KAFKA-15629: Proposal to introduce IQv2 Query Types: TimestampedKeyQuery and TimestampedRangeQuery [kafka]

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


##########
streams/src/main/java/org/apache/kafka/streams/query/TimestampedKeyQuery.java:
##########
@@ -0,0 +1,70 @@
+/*
+ * 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.query;
+
+import org.apache.kafka.common.annotation.InterfaceStability.Evolving;
+import org.apache.kafka.streams.state.ValueAndTimestamp;
+
+import java.util.Objects;
+
+/**
+ * Interactive query for retrieving a single record based on its key.
+ */

Review Comment:
   Seems you did not address this yet.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: jira-unsubscribe@kafka.apache.org

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


Re: [PR] KAFKA-15629: Proposal to introduce IQv2 Query Types: TimestampedKeyQuery and TimestampedRangeQuery [kafka]

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


##########
streams/src/main/java/org/apache/kafka/streams/query/TimestampedKeyQuery.java:
##########
@@ -0,0 +1,70 @@
+/*
+ * 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.query;
+
+import org.apache.kafka.common.annotation.InterfaceStability.Evolving;
+import org.apache.kafka.streams.state.ValueAndTimestamp;
+
+import java.util.Objects;
+
+/**
+ * Interactive query for retrieving a single record based on its key.
+ */
+@Evolving
+public final class TimestampedKeyQuery<K, V> implements Query<ValueAndTimestamp<V>> {
+
+    private final K key;
+    private final boolean skipCache;
+
+    private TimestampedKeyQuery(final K key, final boolean skipCache) {
+        this.key = Objects.requireNonNull(key);
+        this.skipCache = skipCache;
+    }
+
+    /**
+     * Creates a query that will retrieve the record identified by {@code key} if it exists
+     * (or {@code null} otherwise).
+     * @param key The key to retrieve
+     * @param <K> The type of the key
+     * @param <V> The type of the value that will be retrieved
+     */
+    public static <K, V> TimestampedKeyQuery<K, V> withKey(final K key) {
+        return new TimestampedKeyQuery<>(key, false);
+    }
+
+    /**
+     * Specifies that the cache should be skipped during query evaluation. This means, that the query will always
+     * get forwarded to the underlying store.
+     */
+    public TimestampedKeyQuery<K, V> skipCache() {
+        return new TimestampedKeyQuery<>(key, true);
+    }
+
+    /**
+     * The key that was specified for this query.
+     */
+    public K getKey() {

Review Comment:
   As discussed on the KIP, should be changed to `key()` -- similar elsewhere.



##########
streams/src/main/java/org/apache/kafka/streams/query/TimestampedRangeQuery.java:
##########
@@ -0,0 +1,104 @@
+/*
+ * 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.query;
+
+
+import org.apache.kafka.common.annotation.InterfaceStability.Evolving;
+import org.apache.kafka.streams.state.KeyValueIterator;
+import org.apache.kafka.streams.state.ValueAndTimestamp;
+
+
+import java.util.Optional;
+
+/**
+ * Interactive query for issuing range queries and scans over KeyValue stores.
+ * <p>
+ *  A range query retrieves a set of records, specified using an upper and/or lower bound on the keys.
+ * <p>
+ * A scan query retrieves all records contained in the store.
+ * <p>

Review Comment:
   Unnecessary tag. -- Also generic parameters should be describe -- we should also describe ordering guarantees better (we can wait for your other PR to get finished, and mimic what we did there here.)



##########
streams/src/main/java/org/apache/kafka/streams/query/TimestampedKeyQuery.java:
##########
@@ -0,0 +1,70 @@
+/*
+ * 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.query;
+
+import org.apache.kafka.common.annotation.InterfaceStability.Evolving;
+import org.apache.kafka.streams.state.ValueAndTimestamp;
+
+import java.util.Objects;
+
+/**
+ * Interactive query for retrieving a single record based on its key.
+ */

Review Comment:
   We should add `@param <K> ...` (also for `<V>`) to describe the generic parameters



##########
streams/src/main/java/org/apache/kafka/streams/state/internals/MeteredKeyValueStore.java:
##########
@@ -99,9 +101,17 @@ public class MeteredKeyValueStore<K, V>
                 RangeQuery.class,
                 (query, positionBound, config, store) -> runRangeQuery(query, positionBound, config)
             ),
+            mkEntry(
+                TimestampedRangeQuery.class,

Review Comment:
   Why does `MeteredKeyValueStore` implement this? I thought this would only go into `MeteredTimestampKeyValueStore`?



##########
streams/src/main/java/org/apache/kafka/streams/state/internals/MeteredKeyValueStore.java:
##########
@@ -288,6 +298,48 @@ protected <R> QueryResult<R> runRangeQuery(final Query<R> query,
         return result;
     }
 
+    @SuppressWarnings("unchecked")
+    protected <R> QueryResult<R> runTimestampRangeQuery(final Query<R> query,
+                                               final PositionBound positionBound,
+                                               final QueryConfig config) {

Review Comment:
   nit: fix indention



##########
streams/src/main/java/org/apache/kafka/streams/state/internals/MeteredTimestampedKeyValueStore.java:
##########
@@ -47,7 +59,26 @@ public class MeteredTimestampedKeyValueStore<K, V>
         super(inner, metricScope, time, keySerde, valueSerde);
     }
 
-
+    @SuppressWarnings("rawtypes")
+    private final Map<Class, StoreQueryUtils.QueryHandler> queryHandlers =
+            mkMap(
+                    mkEntry(
+                            RangeQuery.class,
+                            (query, positionBound, config, store) -> runRangeQuery(query, positionBound, config)

Review Comment:
   I think we need to overwrite `runRangeQuery` in this class, and change the behavior to unwrap the `ValueAndTimestamp` we get from the inner store, to only return "plain V". (Same for `runKeyQuery`.)



##########
streams/src/main/java/org/apache/kafka/streams/state/internals/MeteredKeyValueStore.java:
##########
@@ -99,9 +101,17 @@ public class MeteredKeyValueStore<K, V>
                 RangeQuery.class,
                 (query, positionBound, config, store) -> runRangeQuery(query, positionBound, config)
             ),
+            mkEntry(
+                TimestampedRangeQuery.class,
+                (query, positionBound, config, store) -> runTimestampRangeQuery(query, positionBound, config)
+            ),
             mkEntry(
                 KeyQuery.class,
                 (query, positionBound, config, store) -> runKeyQuery(query, positionBound, config)
+            ),
+            mkEntry(
+                TimestampedKeyQuery.class,

Review Comment:
   As above.



##########
streams/src/main/java/org/apache/kafka/streams/state/internals/MeteredKeyValueStore.java:
##########
@@ -312,6 +364,29 @@ protected <R> QueryResult<R> runKeyQuery(final Query<R> query,
         return result;
     }
 
+    @SuppressWarnings("unchecked")
+    protected <R> QueryResult<R> runTimestampKeyQuery(final Query<R> query,

Review Comment:
   Same



##########
streams/src/main/java/org/apache/kafka/streams/state/internals/MeteredKeyValueStore.java:
##########
@@ -288,6 +298,48 @@ protected <R> QueryResult<R> runRangeQuery(final Query<R> query,
         return result;
     }
 
+    @SuppressWarnings("unchecked")
+    protected <R> QueryResult<R> runTimestampRangeQuery(final Query<R> query,

Review Comment:
   as above



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: jira-unsubscribe@kafka.apache.org

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


Re: [PR] KAFKA-15629: Proposal to introduce IQv2 Query Types: TimestampedKeyQuery and TimestampedRangeQuery [kafka]

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


##########
streams/src/main/java/org/apache/kafka/streams/state/internals/KeyValueToTimestampedKeyValueByteStoreAdapter.java:
##########
@@ -127,9 +136,25 @@ public <R> QueryResult<R> query(
         final QueryConfig config) {
 
 
+
         final long start = config.isCollectExecutionInfo() ? System.nanoTime() : -1L;
-        final QueryResult<R> result = store.query(query, positionBound, config);
+        QueryResult<R> result = store.query(query, positionBound, config);
+
+        if (result.isSuccess()) {
+            if (query instanceof KeyQuery || query instanceof TimestampedKeyQuery) {

Review Comment:
   ok



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: jira-unsubscribe@kafka.apache.org

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


Re: [PR] KAFKA-15629: Proposal to introduce IQv2 Query Types: TimestampedKeyQuery and TimestampedRangeQuery [kafka]

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


##########
streams/src/main/java/org/apache/kafka/streams/state/internals/MeteredTimestampedKeyValueStore.java:
##########
@@ -102,4 +139,216 @@ static class RawAndDeserializedValue<ValueType> {
             this.value = value;
         }
     }
+
+    @SuppressWarnings("unchecked")
+    @Override
+    public <R> QueryResult<R> query(final Query<R> query,
+                                    final PositionBound positionBound,
+                                    final QueryConfig config) {
+
+        final long start = time.nanoseconds();
+        final QueryResult<R> result;
+
+        final StoreQueryUtils.QueryHandler handler = queryHandlers.get(query.getClass());
+        if (handler == null) {
+            result = wrapped().query(query, positionBound, config);
+            if (config.isCollectExecutionInfo()) {
+                result.addExecutionInfo(
+                        "Handled in " + getClass() + " in " + (time.nanoseconds() - start) + "ns");
+            }
+        } else {
+            result = (QueryResult<R>) handler.apply(
+                    query,
+                    positionBound,
+                    config,
+                    this
+            );
+            if (config.isCollectExecutionInfo()) {
+                result.addExecutionInfo(
+                        "Handled in " + getClass() + " with serdes "
+                                + serdes + " in " + (time.nanoseconds() - start) + "ns");
+            }
+        }
+        return result;
+    }
+
+
+
+    @SuppressWarnings("unchecked")
+    private <R> QueryResult<R> runTimestampedKeyQuery(final Query<R> query,
+                                                        final PositionBound positionBound,
+                                                        final QueryConfig config) {
+        final QueryResult<R> result;
+        final TimestampedKeyQuery<K, V> typedKeyQuery = (TimestampedKeyQuery<K, V>) query;
+        final KeyQuery<Bytes, byte[]> rawKeyQuery =
+                KeyQuery.withKey(keyBytes(typedKeyQuery.key()));
+        final QueryResult<byte[]> rawResult =
+                wrapped().query(rawKeyQuery, positionBound, config);
+        if (rawResult.isSuccess()) {
+            final Function<byte[], ValueAndTimestamp<V>> deserializer = getDeserializeValue(serdes, wrapped());

Review Comment:
   I am not very sure, but MeterKeyValueStore also use getDeserializeValue(...), we can talk it tomorrow. 
   This helper function actually is in `StoreQueryUtils`



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: jira-unsubscribe@kafka.apache.org

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


Re: [PR] KAFKA-15629: Proposal to introduce IQv2 Query Types: TimestampedKeyQuery and TimestampedRangeQuery [kafka]

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

   > `Build / JDK 17 and Scala 2.13 / verifyStore[cache=true, log=true, supplier=ROCKS_KV, kind=DSL] – org.apache.kafka.streams.integration.IQv2StoreIntegrationTest` failed.
   > 
   > ```
   > org.apache.kafka.streams.errors.InvalidStateStoreException: Store kv-store is currently closed.
   > 	at app//org.apache.kafka.streams.state.internals.WrappedStateStore.validateStoreOpen(WrappedStateStore.java:116)
   > 	at app//org.apache.kafka.streams.state.internals.CachingKeyValueStore.query(CachingKeyValueStore.java:146)
   > 	at app//org.apache.kafka.streams.state.internals.MeteredTimestampedKeyValueStore.runKeyQuery(MeteredTimestampedKeyValueStore.java:248)
   > 	at app//org.apache.kafka.streams.state.internals.MeteredTimestampedKeyValueStore.lambda$new$2(MeteredTimestampedKeyValueStore.java:81)
   > 	at app//org.apache.kafka.streams.state.internals.MeteredTimestampedKeyValueStore.query(MeteredTimestampedKeyValueStore.java:160)
   > 	at app//org.apache.kafka.streams.KafkaStreams.query(KafkaStreams.java:1971)
   > 	at app//org.apache.kafka.streams.integration.utils.IntegrationTestUtils.iqv2WaitForResult(IntegrationTestUtils.java:168)
   > 	at app//org.apache.kafka.streams.integration.IQv2StoreIntegrationTest.shouldCollectExecutionInfo(IQv2StoreIntegrationTest.java:1964)
   > 	at app//org.apache.kafka.streams.integration.IQv2StoreIntegrationTest.verifyStore(IQv2StoreIntegrationTest.java:782)
   > ```
   > 
   > I don't think it's related to this PR, but I'll trigger a re-run to make sure.
   
   ok


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: jira-unsubscribe@kafka.apache.org

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


Re: [PR] KAFKA-15629: Proposal to introduce IQv2 Query Types: TimestampedKeyQuery and TimestampedRangeQuery [kafka]

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


##########
streams/src/main/java/org/apache/kafka/streams/state/internals/KeyValueToTimestampedKeyValueByteStoreAdapter.java:
##########
@@ -126,15 +128,22 @@ public <R> QueryResult<R> query(
         final PositionBound positionBound,
         final QueryConfig config) {
 
-
         final long start = config.isCollectExecutionInfo() ? System.nanoTime() : -1L;
-        final QueryResult<R> result = store.query(query, positionBound, config);
+        QueryResult<R> result = store.query(query, positionBound, config);
+        Position position = result.getPosition();
+        if (result.isSuccess()) {
+            byte[] res = (byte[]) result.getResult();
+            byte[] res1 = convertToTimestampedFormat(res);
+            result = (QueryResult<R>) QueryResult.forResult(res1);
+        }
+
         if (config.isCollectExecutionInfo()) {
             final long end = System.nanoTime();
             result.addExecutionInfo(
                 "Handled in " + getClass() + " in " + (end - start) + "ns"
             );
         }
+        result.setPosition(position);

Review Comment:
   Why this change?



##########
streams/src/main/java/org/apache/kafka/streams/state/internals/KeyValueToTimestampedKeyValueByteStoreAdapter.java:
##########
@@ -126,15 +128,22 @@ public <R> QueryResult<R> query(
         final PositionBound positionBound,
         final QueryConfig config) {
 
-
         final long start = config.isCollectExecutionInfo() ? System.nanoTime() : -1L;
-        final QueryResult<R> result = store.query(query, positionBound, config);
+        QueryResult<R> result = store.query(query, positionBound, config);
+        Position position = result.getPosition();
+        if (result.isSuccess()) {
+            byte[] res = (byte[]) result.getResult();
+            byte[] res1 = convertToTimestampedFormat(res);
+            result = (QueryResult<R>) QueryResult.forResult(res1);

Review Comment:
   We need to set the position on the newly created result. We should also copy the "execution information" (also wondering if we should add a new entry to it?) \cc @aliehsaeedii WDYT?
   
   Maybe we can actually re-use `InternalQueryResultUtil.copyAndSubstituteDeserializedResult` ?



##########
streams/src/main/java/org/apache/kafka/streams/state/internals/KeyValueToTimestampedKeyValueByteStoreAdapter.java:
##########
@@ -126,15 +128,22 @@ public <R> QueryResult<R> query(
         final PositionBound positionBound,
         final QueryConfig config) {
 
-
         final long start = config.isCollectExecutionInfo() ? System.nanoTime() : -1L;
-        final QueryResult<R> result = store.query(query, positionBound, config);
+        QueryResult<R> result = store.query(query, positionBound, config);
+        Position position = result.getPosition();
+        if (result.isSuccess()) {
+            byte[] res = (byte[]) result.getResult();
+            byte[] res1 = convertToTimestampedFormat(res);

Review Comment:
   Use better variable names. Eg `res` -> `plainValue` and `res2` -> `valueWithTimestamp`



##########
streams/src/main/java/org/apache/kafka/streams/state/internals/MeteredTimestampedKeyValueStore.java:
##########
@@ -102,4 +140,230 @@ static class RawAndDeserializedValue<ValueType> {
             this.value = value;
         }
     }
+
+    @SuppressWarnings("unchecked")
+    @Override
+    public <R> QueryResult<R> query(final Query<R> query,
+                                    final PositionBound positionBound,
+                                    final QueryConfig config) {
+
+        final long start = time.nanoseconds();
+        final QueryResult<R> result;
+
+        final StoreQueryUtils.QueryHandler handler = queryHandlers.get(query.getClass());
+        if (handler == null) {
+            result = wrapped().query(query, positionBound, config);
+            if (config.isCollectExecutionInfo()) {
+                result.addExecutionInfo(
+                        "Handled in " + getClass() + " in " + (time.nanoseconds() - start) + "ns");
+            }
+        } else {
+            result = (QueryResult<R>) handler.apply(
+                    query,
+                    positionBound,
+                    config,
+                    this
+            );
+            if (config.isCollectExecutionInfo()) {
+                result.addExecutionInfo(
+                        "Handled in " + getClass() + " with serdes "
+                                + serdes + " in " + (time.nanoseconds() - start) + "ns");
+            }
+        }
+        return result;
+    }
+
+
+
+    @SuppressWarnings("unchecked")
+    protected <R> QueryResult<R> runTimestampKeyQuery(final Query<R> query,
+                                                      final PositionBound positionBound,
+                                                      final QueryConfig config) {
+        final QueryResult<R> result;
+        final TimestampedKeyQuery<K, V> typedKeyQuery = (TimestampedKeyQuery<K, V>) query;
+        final KeyQuery<Bytes, byte[]> rawKeyQuery =
+                KeyQuery.withKey(keyBytes(typedKeyQuery.getKey()));
+        final QueryResult<byte[]> rawResult =
+                wrapped().query(rawKeyQuery, positionBound, config);
+        if (rawResult.isSuccess()) {
+            final Function<byte[], ValueAndTimestamp<V>> deserializer = getDeserializeValue(serdes, wrapped());
+            final ValueAndTimestamp<V> value = deserializer.apply(rawResult.getResult());
+            final QueryResult<ValueAndTimestamp<V>> typedQueryResult =
+                    InternalQueryResultUtil.copyAndSubstituteDeserializedResult(rawResult, value);
+            result = (QueryResult<R>) typedQueryResult;
+        } else {
+            // the generic type doesn't matter, since failed queries have no result set.
+            result = (QueryResult<R>) rawResult;
+        }
+        return result;
+    }
+
+    @SuppressWarnings("unchecked")
+    protected <R> QueryResult<R> runTimestampRangeQuery(final Query<R> query,
+                                                        final PositionBound positionBound,
+                                                        final QueryConfig config) {
+
+        final QueryResult<R> result;
+        final TimestampedRangeQuery<K, V> typedQuery = (TimestampedRangeQuery<K, V>) query;
+
+        final RangeQuery<Bytes, byte[]> rawRangeQuery;
+        if (typedQuery.getLowerBound().isPresent() && typedQuery.getUpperBound().isPresent()) {
+            rawRangeQuery = RangeQuery.withRange(
+                    keyBytes(typedQuery.getLowerBound().get()),
+                    keyBytes(typedQuery.getUpperBound().get())
+            );
+        } else if (typedQuery.getLowerBound().isPresent()) {
+            rawRangeQuery = RangeQuery.withLowerBound(keyBytes(typedQuery.getLowerBound().get()));
+        } else if (typedQuery.getUpperBound().isPresent()) {
+            rawRangeQuery = RangeQuery.withUpperBound(keyBytes(typedQuery.getUpperBound().get()));
+        } else {
+            rawRangeQuery = RangeQuery.withNoBounds();
+        }
+        final QueryResult<KeyValueIterator<Bytes, byte[]>> rawResult =
+                wrapped().query(rawRangeQuery, positionBound, config);
+        if (rawResult.isSuccess()) {
+            final KeyValueIterator<Bytes, byte[]> iterator = rawResult.getResult();
+            final KeyValueIterator<K, V> resultIterator = new MeteredKeyValueTimestampedIterator(
+                    iterator,
+                    getSensor,
+                    getDeserializeValue(serdes, wrapped()),
+                    false
+            );
+            final QueryResult<KeyValueIterator<K, V>> typedQueryResult =
+                    InternalQueryResultUtil.copyAndSubstituteDeserializedResult(
+                            rawResult,
+                            resultIterator
+                    );
+            result = (QueryResult<R>) typedQueryResult;
+        } else {
+            // the generic type doesn't matter, since failed queries have no result set.
+            result = (QueryResult<R>) rawResult;
+        }
+        return result;
+    }
+
+    @SuppressWarnings("unchecked")
+    protected <R> QueryResult<R> runKeyQuery2(final Query<R> query,

Review Comment:
   Why `2` in the end of the name?



##########
streams/src/main/java/org/apache/kafka/streams/state/internals/MeteredTimestampedKeyValueStore.java:
##########
@@ -102,4 +140,230 @@ static class RawAndDeserializedValue<ValueType> {
             this.value = value;
         }
     }
+
+    @SuppressWarnings("unchecked")
+    @Override
+    public <R> QueryResult<R> query(final Query<R> query,
+                                    final PositionBound positionBound,
+                                    final QueryConfig config) {
+
+        final long start = time.nanoseconds();
+        final QueryResult<R> result;
+
+        final StoreQueryUtils.QueryHandler handler = queryHandlers.get(query.getClass());
+        if (handler == null) {
+            result = wrapped().query(query, positionBound, config);
+            if (config.isCollectExecutionInfo()) {
+                result.addExecutionInfo(
+                        "Handled in " + getClass() + " in " + (time.nanoseconds() - start) + "ns");
+            }
+        } else {
+            result = (QueryResult<R>) handler.apply(
+                    query,
+                    positionBound,
+                    config,
+                    this
+            );
+            if (config.isCollectExecutionInfo()) {
+                result.addExecutionInfo(
+                        "Handled in " + getClass() + " with serdes "
+                                + serdes + " in " + (time.nanoseconds() - start) + "ns");
+            }
+        }
+        return result;
+    }
+
+
+
+    @SuppressWarnings("unchecked")
+    protected <R> QueryResult<R> runTimestampKeyQuery(final Query<R> query,
+                                                      final PositionBound positionBound,
+                                                      final QueryConfig config) {
+        final QueryResult<R> result;
+        final TimestampedKeyQuery<K, V> typedKeyQuery = (TimestampedKeyQuery<K, V>) query;
+        final KeyQuery<Bytes, byte[]> rawKeyQuery =
+                KeyQuery.withKey(keyBytes(typedKeyQuery.getKey()));
+        final QueryResult<byte[]> rawResult =
+                wrapped().query(rawKeyQuery, positionBound, config);
+        if (rawResult.isSuccess()) {
+            final Function<byte[], ValueAndTimestamp<V>> deserializer = getDeserializeValue(serdes, wrapped());
+            final ValueAndTimestamp<V> value = deserializer.apply(rawResult.getResult());
+            final QueryResult<ValueAndTimestamp<V>> typedQueryResult =
+                    InternalQueryResultUtil.copyAndSubstituteDeserializedResult(rawResult, value);
+            result = (QueryResult<R>) typedQueryResult;
+        } else {
+            // the generic type doesn't matter, since failed queries have no result set.
+            result = (QueryResult<R>) rawResult;
+        }
+        return result;
+    }
+
+    @SuppressWarnings("unchecked")
+    protected <R> QueryResult<R> runTimestampRangeQuery(final Query<R> query,
+                                                        final PositionBound positionBound,
+                                                        final QueryConfig config) {
+
+        final QueryResult<R> result;
+        final TimestampedRangeQuery<K, V> typedQuery = (TimestampedRangeQuery<K, V>) query;
+
+        final RangeQuery<Bytes, byte[]> rawRangeQuery;
+        if (typedQuery.getLowerBound().isPresent() && typedQuery.getUpperBound().isPresent()) {
+            rawRangeQuery = RangeQuery.withRange(
+                    keyBytes(typedQuery.getLowerBound().get()),
+                    keyBytes(typedQuery.getUpperBound().get())
+            );
+        } else if (typedQuery.getLowerBound().isPresent()) {
+            rawRangeQuery = RangeQuery.withLowerBound(keyBytes(typedQuery.getLowerBound().get()));
+        } else if (typedQuery.getUpperBound().isPresent()) {
+            rawRangeQuery = RangeQuery.withUpperBound(keyBytes(typedQuery.getUpperBound().get()));
+        } else {
+            rawRangeQuery = RangeQuery.withNoBounds();
+        }
+        final QueryResult<KeyValueIterator<Bytes, byte[]>> rawResult =
+                wrapped().query(rawRangeQuery, positionBound, config);
+        if (rawResult.isSuccess()) {
+            final KeyValueIterator<Bytes, byte[]> iterator = rawResult.getResult();
+            final KeyValueIterator<K, V> resultIterator = new MeteredKeyValueTimestampedIterator(
+                    iterator,
+                    getSensor,
+                    getDeserializeValue(serdes, wrapped()),
+                    false
+            );
+            final QueryResult<KeyValueIterator<K, V>> typedQueryResult =
+                    InternalQueryResultUtil.copyAndSubstituteDeserializedResult(
+                            rawResult,
+                            resultIterator
+                    );
+            result = (QueryResult<R>) typedQueryResult;
+        } else {
+            // the generic type doesn't matter, since failed queries have no result set.
+            result = (QueryResult<R>) rawResult;
+        }
+        return result;
+    }
+
+    @SuppressWarnings("unchecked")
+    protected <R> QueryResult<R> runKeyQuery2(final Query<R> query,
+                                             final PositionBound positionBound,
+                                             final QueryConfig config) {
+        final QueryResult<R> result;
+        final KeyQuery<K, V> typedKeyQuery = (KeyQuery<K, V>) query;
+        final KeyQuery<Bytes, byte[]> rawKeyQuery =
+                KeyQuery.withKey(keyBytes(typedKeyQuery.getKey()));
+        final QueryResult<byte[]> rawResult =
+                wrapped().query(rawKeyQuery, positionBound, config);
+        if (rawResult.isSuccess()) {
+            final Function<byte[], ValueAndTimestamp<V>> deserializer = getDeserializeValue2(serdes, wrapped(), true);
+            ValueAndTimestamp<V> value = deserializer.apply(rawResult.getResult());
+            V res = null;
+            if (value != null) {
+                res = value.value();
+            }

Review Comment:
   Maybe make this a one-linger, allowing you to use `final` (also, use better variable names `res` is not very descriptive):
   ```
   final V plainValue = value == null ? null : value.value();
   ```



##########
streams/src/main/java/org/apache/kafka/streams/state/internals/MeteredTimestampedKeyValueStore.java:
##########
@@ -102,4 +140,230 @@ static class RawAndDeserializedValue<ValueType> {
             this.value = value;
         }
     }
+
+    @SuppressWarnings("unchecked")
+    @Override
+    public <R> QueryResult<R> query(final Query<R> query,
+                                    final PositionBound positionBound,
+                                    final QueryConfig config) {
+
+        final long start = time.nanoseconds();
+        final QueryResult<R> result;
+
+        final StoreQueryUtils.QueryHandler handler = queryHandlers.get(query.getClass());
+        if (handler == null) {
+            result = wrapped().query(query, positionBound, config);
+            if (config.isCollectExecutionInfo()) {
+                result.addExecutionInfo(
+                        "Handled in " + getClass() + " in " + (time.nanoseconds() - start) + "ns");
+            }
+        } else {
+            result = (QueryResult<R>) handler.apply(
+                    query,
+                    positionBound,
+                    config,
+                    this
+            );
+            if (config.isCollectExecutionInfo()) {
+                result.addExecutionInfo(
+                        "Handled in " + getClass() + " with serdes "
+                                + serdes + " in " + (time.nanoseconds() - start) + "ns");
+            }
+        }
+        return result;
+    }
+
+
+
+    @SuppressWarnings("unchecked")
+    protected <R> QueryResult<R> runTimestampKeyQuery(final Query<R> query,
+                                                      final PositionBound positionBound,
+                                                      final QueryConfig config) {
+        final QueryResult<R> result;
+        final TimestampedKeyQuery<K, V> typedKeyQuery = (TimestampedKeyQuery<K, V>) query;
+        final KeyQuery<Bytes, byte[]> rawKeyQuery =
+                KeyQuery.withKey(keyBytes(typedKeyQuery.getKey()));
+        final QueryResult<byte[]> rawResult =
+                wrapped().query(rawKeyQuery, positionBound, config);
+        if (rawResult.isSuccess()) {
+            final Function<byte[], ValueAndTimestamp<V>> deserializer = getDeserializeValue(serdes, wrapped());
+            final ValueAndTimestamp<V> value = deserializer.apply(rawResult.getResult());
+            final QueryResult<ValueAndTimestamp<V>> typedQueryResult =
+                    InternalQueryResultUtil.copyAndSubstituteDeserializedResult(rawResult, value);
+            result = (QueryResult<R>) typedQueryResult;
+        } else {
+            // the generic type doesn't matter, since failed queries have no result set.
+            result = (QueryResult<R>) rawResult;
+        }
+        return result;
+    }
+
+    @SuppressWarnings("unchecked")
+    protected <R> QueryResult<R> runTimestampRangeQuery(final Query<R> query,
+                                                        final PositionBound positionBound,
+                                                        final QueryConfig config) {
+
+        final QueryResult<R> result;
+        final TimestampedRangeQuery<K, V> typedQuery = (TimestampedRangeQuery<K, V>) query;
+
+        final RangeQuery<Bytes, byte[]> rawRangeQuery;
+        if (typedQuery.getLowerBound().isPresent() && typedQuery.getUpperBound().isPresent()) {
+            rawRangeQuery = RangeQuery.withRange(
+                    keyBytes(typedQuery.getLowerBound().get()),
+                    keyBytes(typedQuery.getUpperBound().get())
+            );
+        } else if (typedQuery.getLowerBound().isPresent()) {
+            rawRangeQuery = RangeQuery.withLowerBound(keyBytes(typedQuery.getLowerBound().get()));
+        } else if (typedQuery.getUpperBound().isPresent()) {
+            rawRangeQuery = RangeQuery.withUpperBound(keyBytes(typedQuery.getUpperBound().get()));
+        } else {
+            rawRangeQuery = RangeQuery.withNoBounds();
+        }
+        final QueryResult<KeyValueIterator<Bytes, byte[]>> rawResult =
+                wrapped().query(rawRangeQuery, positionBound, config);
+        if (rawResult.isSuccess()) {
+            final KeyValueIterator<Bytes, byte[]> iterator = rawResult.getResult();
+            final KeyValueIterator<K, V> resultIterator = new MeteredKeyValueTimestampedIterator(
+                    iterator,
+                    getSensor,
+                    getDeserializeValue(serdes, wrapped()),
+                    false
+            );
+            final QueryResult<KeyValueIterator<K, V>> typedQueryResult =
+                    InternalQueryResultUtil.copyAndSubstituteDeserializedResult(
+                            rawResult,
+                            resultIterator
+                    );
+            result = (QueryResult<R>) typedQueryResult;
+        } else {
+            // the generic type doesn't matter, since failed queries have no result set.
+            result = (QueryResult<R>) rawResult;
+        }
+        return result;
+    }
+
+    @SuppressWarnings("unchecked")
+    protected <R> QueryResult<R> runKeyQuery2(final Query<R> query,
+                                             final PositionBound positionBound,
+                                             final QueryConfig config) {
+        final QueryResult<R> result;
+        final KeyQuery<K, V> typedKeyQuery = (KeyQuery<K, V>) query;
+        final KeyQuery<Bytes, byte[]> rawKeyQuery =
+                KeyQuery.withKey(keyBytes(typedKeyQuery.getKey()));
+        final QueryResult<byte[]> rawResult =
+                wrapped().query(rawKeyQuery, positionBound, config);
+        if (rawResult.isSuccess()) {
+            final Function<byte[], ValueAndTimestamp<V>> deserializer = getDeserializeValue2(serdes, wrapped(), true);
+            ValueAndTimestamp<V> value = deserializer.apply(rawResult.getResult());
+            V res = null;
+            if (value != null) {
+                res = value.value();
+            }
+            final QueryResult<V> typedQueryResult =
+                    InternalQueryResultUtil.copyAndSubstituteDeserializedResult(rawResult, res);
+            result = (QueryResult<R>) typedQueryResult;
+        } else {
+            // the generic type doesn't matter, since failed queries have no result set.
+            result = (QueryResult<R>) rawResult;
+        }
+        return result;
+    }
+
+    @SuppressWarnings("unchecked")
+    protected <R> QueryResult<R> runRangeQuery2(final Query<R> query,
+                                               final PositionBound positionBound,
+                                               final QueryConfig config) {
+
+        final QueryResult<R> result;
+        final RangeQuery<K, V> typedQuery = (RangeQuery<K, V>) query;
+        final RangeQuery<Bytes, byte[]> rawRangeQuery;
+        if (typedQuery.getLowerBound().isPresent() && typedQuery.getUpperBound().isPresent()) {
+            rawRangeQuery = RangeQuery.withRange(
+                    keyBytes(typedQuery.getLowerBound().get()),
+                    keyBytes(typedQuery.getUpperBound().get())
+            );
+        } else if (typedQuery.getLowerBound().isPresent()) {
+            rawRangeQuery = RangeQuery.withLowerBound(keyBytes(typedQuery.getLowerBound().get()));
+        } else if (typedQuery.getUpperBound().isPresent()) {
+            rawRangeQuery = RangeQuery.withUpperBound(keyBytes(typedQuery.getUpperBound().get()));
+        } else {
+            rawRangeQuery = RangeQuery.withNoBounds();
+        }
+        final QueryResult<KeyValueIterator<Bytes, byte[]>> rawResult =
+                wrapped().query(rawRangeQuery, positionBound, config);
+        if (rawResult.isSuccess()) {
+            final KeyValueIterator<Bytes, byte[]> iterator = rawResult.getResult();
+            final KeyValueIterator<K,V> resultIterator = new MeteredKeyValueTimestampedIterator(
+                    iterator,
+                    getSensor,
+                    getDeserializeValue(serdes, wrapped()),
+                    true
+            );
+            final QueryResult<KeyValueIterator<K, V>> typedQueryResult =
+                    InternalQueryResultUtil.copyAndSubstituteDeserializedResult(
+                            rawResult,
+                            resultIterator
+                    );
+            result = (QueryResult<R>) typedQueryResult;
+        } else {
+            // the generic type doesn't matter, since failed queries have no result set.
+            result = (QueryResult<R>) rawResult;
+        }
+        return result;
+    }
+
+    @SuppressWarnings("unchecked")
+    private class MeteredKeyValueTimestampedIterator implements KeyValueIterator<K, V> {

Review Comment:
   Seems this is copy of existing `MeteredKeyValueTimestampedIterator` from `MeteredKeyValueStore`.
   
   I think we should not just make a duplication of the code, but implement is in a way to re-use code (in the end, the difference is only that we need an additional "unwrapping", that I think we can get done eg by making it part of the `Function` that we pass in.
   
   Side note: as discussed in person, the original class should be renamed -- not sure why it has `Timestamped` in it's name -- does not make any sense.



##########
streams/src/main/java/org/apache/kafka/streams/state/internals/MeteredTimestampedKeyValueStore.java:
##########
@@ -102,4 +140,230 @@ static class RawAndDeserializedValue<ValueType> {
             this.value = value;
         }
     }
+
+    @SuppressWarnings("unchecked")
+    @Override
+    public <R> QueryResult<R> query(final Query<R> query,
+                                    final PositionBound positionBound,
+                                    final QueryConfig config) {
+
+        final long start = time.nanoseconds();
+        final QueryResult<R> result;
+
+        final StoreQueryUtils.QueryHandler handler = queryHandlers.get(query.getClass());
+        if (handler == null) {
+            result = wrapped().query(query, positionBound, config);
+            if (config.isCollectExecutionInfo()) {
+                result.addExecutionInfo(
+                        "Handled in " + getClass() + " in " + (time.nanoseconds() - start) + "ns");
+            }
+        } else {
+            result = (QueryResult<R>) handler.apply(
+                    query,
+                    positionBound,
+                    config,
+                    this
+            );
+            if (config.isCollectExecutionInfo()) {
+                result.addExecutionInfo(
+                        "Handled in " + getClass() + " with serdes "
+                                + serdes + " in " + (time.nanoseconds() - start) + "ns");
+            }
+        }
+        return result;
+    }
+
+
+
+    @SuppressWarnings("unchecked")
+    protected <R> QueryResult<R> runTimestampKeyQuery(final Query<R> query,
+                                                      final PositionBound positionBound,
+                                                      final QueryConfig config) {
+        final QueryResult<R> result;
+        final TimestampedKeyQuery<K, V> typedKeyQuery = (TimestampedKeyQuery<K, V>) query;
+        final KeyQuery<Bytes, byte[]> rawKeyQuery =
+                KeyQuery.withKey(keyBytes(typedKeyQuery.getKey()));
+        final QueryResult<byte[]> rawResult =
+                wrapped().query(rawKeyQuery, positionBound, config);
+        if (rawResult.isSuccess()) {
+            final Function<byte[], ValueAndTimestamp<V>> deserializer = getDeserializeValue(serdes, wrapped());
+            final ValueAndTimestamp<V> value = deserializer.apply(rawResult.getResult());
+            final QueryResult<ValueAndTimestamp<V>> typedQueryResult =
+                    InternalQueryResultUtil.copyAndSubstituteDeserializedResult(rawResult, value);
+            result = (QueryResult<R>) typedQueryResult;
+        } else {
+            // the generic type doesn't matter, since failed queries have no result set.
+            result = (QueryResult<R>) rawResult;
+        }
+        return result;
+    }
+
+    @SuppressWarnings("unchecked")
+    protected <R> QueryResult<R> runTimestampRangeQuery(final Query<R> query,
+                                                        final PositionBound positionBound,
+                                                        final QueryConfig config) {
+
+        final QueryResult<R> result;
+        final TimestampedRangeQuery<K, V> typedQuery = (TimestampedRangeQuery<K, V>) query;
+
+        final RangeQuery<Bytes, byte[]> rawRangeQuery;
+        if (typedQuery.getLowerBound().isPresent() && typedQuery.getUpperBound().isPresent()) {
+            rawRangeQuery = RangeQuery.withRange(
+                    keyBytes(typedQuery.getLowerBound().get()),
+                    keyBytes(typedQuery.getUpperBound().get())
+            );
+        } else if (typedQuery.getLowerBound().isPresent()) {
+            rawRangeQuery = RangeQuery.withLowerBound(keyBytes(typedQuery.getLowerBound().get()));
+        } else if (typedQuery.getUpperBound().isPresent()) {
+            rawRangeQuery = RangeQuery.withUpperBound(keyBytes(typedQuery.getUpperBound().get()));
+        } else {
+            rawRangeQuery = RangeQuery.withNoBounds();
+        }
+        final QueryResult<KeyValueIterator<Bytes, byte[]>> rawResult =
+                wrapped().query(rawRangeQuery, positionBound, config);
+        if (rawResult.isSuccess()) {
+            final KeyValueIterator<Bytes, byte[]> iterator = rawResult.getResult();
+            final KeyValueIterator<K, V> resultIterator = new MeteredKeyValueTimestampedIterator(
+                    iterator,
+                    getSensor,
+                    getDeserializeValue(serdes, wrapped()),
+                    false
+            );
+            final QueryResult<KeyValueIterator<K, V>> typedQueryResult =
+                    InternalQueryResultUtil.copyAndSubstituteDeserializedResult(
+                            rawResult,
+                            resultIterator
+                    );
+            result = (QueryResult<R>) typedQueryResult;
+        } else {
+            // the generic type doesn't matter, since failed queries have no result set.
+            result = (QueryResult<R>) rawResult;
+        }
+        return result;
+    }
+
+    @SuppressWarnings("unchecked")
+    protected <R> QueryResult<R> runKeyQuery2(final Query<R> query,
+                                             final PositionBound positionBound,
+                                             final QueryConfig config) {
+        final QueryResult<R> result;
+        final KeyQuery<K, V> typedKeyQuery = (KeyQuery<K, V>) query;
+        final KeyQuery<Bytes, byte[]> rawKeyQuery =
+                KeyQuery.withKey(keyBytes(typedKeyQuery.getKey()));
+        final QueryResult<byte[]> rawResult =
+                wrapped().query(rawKeyQuery, positionBound, config);
+        if (rawResult.isSuccess()) {
+            final Function<byte[], ValueAndTimestamp<V>> deserializer = getDeserializeValue2(serdes, wrapped(), true);
+            ValueAndTimestamp<V> value = deserializer.apply(rawResult.getResult());

Review Comment:
   nit: `value` -> `valueAndTimestamp`.



##########
streams/src/main/java/org/apache/kafka/streams/state/internals/StoreQueryUtils.java:
##########
@@ -346,6 +346,23 @@ public static <V> Function<byte[], V> getDeserializeValue(final StateSerdes<?, V
         return byteArray -> deserializer.deserialize(serdes.topic(), byteArray);
     }
 
+    @SuppressWarnings({"unchecked", "rawtypes"})
+    public static <V> Function<byte[], V> getDeserializeValue2(final StateSerdes<?, V> serdes,
+                                                               final StateStore wrapped,
+                                                               final boolean isDSLStore ) {
+        final Serde<V> valueSerde = serdes.valueSerde();
+        final boolean timestamped = WrappedStateStore.isTimestamped(wrapped) || isDSLStore;
+        final Deserializer<V> deserializer;
+        if (!timestamped && valueSerde instanceof ValueAndTimestampSerde) {

Review Comment:
   We did discuss this part of the code in person, and we where both confused why it's needed -- I think it's needed because of the underlying "bug" that the `KeyValueToTimestampedKeyValueByteStoreAdapter` did not add the missing timestamp on the query result and is not recognized as a `TimestampedBytestStore` -- after this is fixed, I believe we might not need this code any longer (did not try it out, but we should explore it as side cleanup).



##########
streams/src/main/java/org/apache/kafka/streams/state/internals/MeteredTimestampedKeyValueStore.java:
##########
@@ -102,4 +140,230 @@ static class RawAndDeserializedValue<ValueType> {
             this.value = value;
         }
     }
+
+    @SuppressWarnings("unchecked")
+    @Override
+    public <R> QueryResult<R> query(final Query<R> query,
+                                    final PositionBound positionBound,
+                                    final QueryConfig config) {
+
+        final long start = time.nanoseconds();
+        final QueryResult<R> result;
+
+        final StoreQueryUtils.QueryHandler handler = queryHandlers.get(query.getClass());
+        if (handler == null) {
+            result = wrapped().query(query, positionBound, config);
+            if (config.isCollectExecutionInfo()) {
+                result.addExecutionInfo(
+                        "Handled in " + getClass() + " in " + (time.nanoseconds() - start) + "ns");
+            }
+        } else {
+            result = (QueryResult<R>) handler.apply(
+                    query,
+                    positionBound,
+                    config,
+                    this
+            );
+            if (config.isCollectExecutionInfo()) {
+                result.addExecutionInfo(
+                        "Handled in " + getClass() + " with serdes "
+                                + serdes + " in " + (time.nanoseconds() - start) + "ns");
+            }
+        }
+        return result;
+    }
+
+
+
+    @SuppressWarnings("unchecked")
+    protected <R> QueryResult<R> runTimestampKeyQuery(final Query<R> query,
+                                                      final PositionBound positionBound,
+                                                      final QueryConfig config) {
+        final QueryResult<R> result;
+        final TimestampedKeyQuery<K, V> typedKeyQuery = (TimestampedKeyQuery<K, V>) query;
+        final KeyQuery<Bytes, byte[]> rawKeyQuery =
+                KeyQuery.withKey(keyBytes(typedKeyQuery.getKey()));
+        final QueryResult<byte[]> rawResult =
+                wrapped().query(rawKeyQuery, positionBound, config);
+        if (rawResult.isSuccess()) {
+            final Function<byte[], ValueAndTimestamp<V>> deserializer = getDeserializeValue(serdes, wrapped());
+            final ValueAndTimestamp<V> value = deserializer.apply(rawResult.getResult());
+            final QueryResult<ValueAndTimestamp<V>> typedQueryResult =
+                    InternalQueryResultUtil.copyAndSubstituteDeserializedResult(rawResult, value);
+            result = (QueryResult<R>) typedQueryResult;
+        } else {
+            // the generic type doesn't matter, since failed queries have no result set.
+            result = (QueryResult<R>) rawResult;
+        }
+        return result;
+    }
+
+    @SuppressWarnings("unchecked")
+    protected <R> QueryResult<R> runTimestampRangeQuery(final Query<R> query,
+                                                        final PositionBound positionBound,
+                                                        final QueryConfig config) {
+
+        final QueryResult<R> result;
+        final TimestampedRangeQuery<K, V> typedQuery = (TimestampedRangeQuery<K, V>) query;
+
+        final RangeQuery<Bytes, byte[]> rawRangeQuery;
+        if (typedQuery.getLowerBound().isPresent() && typedQuery.getUpperBound().isPresent()) {
+            rawRangeQuery = RangeQuery.withRange(
+                    keyBytes(typedQuery.getLowerBound().get()),
+                    keyBytes(typedQuery.getUpperBound().get())
+            );
+        } else if (typedQuery.getLowerBound().isPresent()) {
+            rawRangeQuery = RangeQuery.withLowerBound(keyBytes(typedQuery.getLowerBound().get()));
+        } else if (typedQuery.getUpperBound().isPresent()) {
+            rawRangeQuery = RangeQuery.withUpperBound(keyBytes(typedQuery.getUpperBound().get()));
+        } else {
+            rawRangeQuery = RangeQuery.withNoBounds();
+        }
+        final QueryResult<KeyValueIterator<Bytes, byte[]>> rawResult =
+                wrapped().query(rawRangeQuery, positionBound, config);
+        if (rawResult.isSuccess()) {
+            final KeyValueIterator<Bytes, byte[]> iterator = rawResult.getResult();
+            final KeyValueIterator<K, V> resultIterator = new MeteredKeyValueTimestampedIterator(
+                    iterator,
+                    getSensor,
+                    getDeserializeValue(serdes, wrapped()),
+                    false
+            );
+            final QueryResult<KeyValueIterator<K, V>> typedQueryResult =
+                    InternalQueryResultUtil.copyAndSubstituteDeserializedResult(
+                            rawResult,
+                            resultIterator
+                    );
+            result = (QueryResult<R>) typedQueryResult;
+        } else {
+            // the generic type doesn't matter, since failed queries have no result set.
+            result = (QueryResult<R>) rawResult;
+        }
+        return result;
+    }
+
+    @SuppressWarnings("unchecked")
+    protected <R> QueryResult<R> runKeyQuery2(final Query<R> query,
+                                             final PositionBound positionBound,
+                                             final QueryConfig config) {
+        final QueryResult<R> result;
+        final KeyQuery<K, V> typedKeyQuery = (KeyQuery<K, V>) query;
+        final KeyQuery<Bytes, byte[]> rawKeyQuery =
+                KeyQuery.withKey(keyBytes(typedKeyQuery.getKey()));
+        final QueryResult<byte[]> rawResult =
+                wrapped().query(rawKeyQuery, positionBound, config);
+        if (rawResult.isSuccess()) {
+            final Function<byte[], ValueAndTimestamp<V>> deserializer = getDeserializeValue2(serdes, wrapped(), true);
+            ValueAndTimestamp<V> value = deserializer.apply(rawResult.getResult());
+            V res = null;
+            if (value != null) {
+                res = value.value();
+            }
+            final QueryResult<V> typedQueryResult =
+                    InternalQueryResultUtil.copyAndSubstituteDeserializedResult(rawResult, res);
+            result = (QueryResult<R>) typedQueryResult;
+        } else {
+            // the generic type doesn't matter, since failed queries have no result set.
+            result = (QueryResult<R>) rawResult;
+        }
+        return result;
+    }
+
+    @SuppressWarnings("unchecked")
+    protected <R> QueryResult<R> runRangeQuery2(final Query<R> query,

Review Comment:
   Why `2` at the end?



##########
streams/src/main/java/org/apache/kafka/streams/state/internals/StoreQueryUtils.java:
##########
@@ -346,6 +346,23 @@ public static <V> Function<byte[], V> getDeserializeValue(final StateSerdes<?, V
         return byteArray -> deserializer.deserialize(serdes.topic(), byteArray);
     }
 
+    @SuppressWarnings({"unchecked", "rawtypes"})
+    public static <V> Function<byte[], V> getDeserializeValue2(final StateSerdes<?, V> serdes,
+                                                               final StateStore wrapped,
+                                                               final boolean isDSLStore ) {
+        final Serde<V> valueSerde = serdes.valueSerde();
+        final boolean timestamped = WrappedStateStore.isTimestamped(wrapped) || isDSLStore;

Review Comment:
   The issue is actually inside `isTimestamped` -- for the `KeyValueToTimestampedKeyValueByteStoreAdapter` it incorrectly returns `false` while it should return `true`. The root cause is a bug in `KeyValueToTimestampedKeyValueByteStoreAdapter` itself: it does not implement the marker interface `TimestampedBytesStore` but it should.



##########
streams/src/main/java/org/apache/kafka/streams/state/internals/StoreQueryUtils.java:
##########
@@ -346,6 +346,23 @@ public static <V> Function<byte[], V> getDeserializeValue(final StateSerdes<?, V
         return byteArray -> deserializer.deserialize(serdes.topic(), byteArray);
     }
 
+    @SuppressWarnings({"unchecked", "rawtypes"})
+    public static <V> Function<byte[], V> getDeserializeValue2(final StateSerdes<?, V> serdes,

Review Comment:
   Adding this function is not the right fix IMHO.



##########
streams/src/main/java/org/apache/kafka/streams/state/internals/MeteredTimestampedKeyValueStore.java:
##########
@@ -102,4 +140,230 @@ static class RawAndDeserializedValue<ValueType> {
             this.value = value;
         }
     }
+
+    @SuppressWarnings("unchecked")
+    @Override
+    public <R> QueryResult<R> query(final Query<R> query,
+                                    final PositionBound positionBound,
+                                    final QueryConfig config) {
+
+        final long start = time.nanoseconds();
+        final QueryResult<R> result;
+
+        final StoreQueryUtils.QueryHandler handler = queryHandlers.get(query.getClass());
+        if (handler == null) {
+            result = wrapped().query(query, positionBound, config);
+            if (config.isCollectExecutionInfo()) {
+                result.addExecutionInfo(
+                        "Handled in " + getClass() + " in " + (time.nanoseconds() - start) + "ns");
+            }
+        } else {
+            result = (QueryResult<R>) handler.apply(
+                    query,
+                    positionBound,
+                    config,
+                    this
+            );
+            if (config.isCollectExecutionInfo()) {
+                result.addExecutionInfo(
+                        "Handled in " + getClass() + " with serdes "
+                                + serdes + " in " + (time.nanoseconds() - start) + "ns");
+            }
+        }
+        return result;
+    }
+
+
+
+    @SuppressWarnings("unchecked")
+    protected <R> QueryResult<R> runTimestampKeyQuery(final Query<R> query,
+                                                      final PositionBound positionBound,
+                                                      final QueryConfig config) {
+        final QueryResult<R> result;
+        final TimestampedKeyQuery<K, V> typedKeyQuery = (TimestampedKeyQuery<K, V>) query;
+        final KeyQuery<Bytes, byte[]> rawKeyQuery =
+                KeyQuery.withKey(keyBytes(typedKeyQuery.getKey()));
+        final QueryResult<byte[]> rawResult =
+                wrapped().query(rawKeyQuery, positionBound, config);
+        if (rawResult.isSuccess()) {
+            final Function<byte[], ValueAndTimestamp<V>> deserializer = getDeserializeValue(serdes, wrapped());
+            final ValueAndTimestamp<V> value = deserializer.apply(rawResult.getResult());
+            final QueryResult<ValueAndTimestamp<V>> typedQueryResult =
+                    InternalQueryResultUtil.copyAndSubstituteDeserializedResult(rawResult, value);
+            result = (QueryResult<R>) typedQueryResult;
+        } else {
+            // the generic type doesn't matter, since failed queries have no result set.
+            result = (QueryResult<R>) rawResult;
+        }
+        return result;
+    }
+
+    @SuppressWarnings("unchecked")
+    protected <R> QueryResult<R> runTimestampRangeQuery(final Query<R> query,
+                                                        final PositionBound positionBound,
+                                                        final QueryConfig config) {
+
+        final QueryResult<R> result;
+        final TimestampedRangeQuery<K, V> typedQuery = (TimestampedRangeQuery<K, V>) query;
+
+        final RangeQuery<Bytes, byte[]> rawRangeQuery;
+        if (typedQuery.getLowerBound().isPresent() && typedQuery.getUpperBound().isPresent()) {
+            rawRangeQuery = RangeQuery.withRange(
+                    keyBytes(typedQuery.getLowerBound().get()),
+                    keyBytes(typedQuery.getUpperBound().get())
+            );
+        } else if (typedQuery.getLowerBound().isPresent()) {
+            rawRangeQuery = RangeQuery.withLowerBound(keyBytes(typedQuery.getLowerBound().get()));
+        } else if (typedQuery.getUpperBound().isPresent()) {
+            rawRangeQuery = RangeQuery.withUpperBound(keyBytes(typedQuery.getUpperBound().get()));
+        } else {
+            rawRangeQuery = RangeQuery.withNoBounds();
+        }
+        final QueryResult<KeyValueIterator<Bytes, byte[]>> rawResult =
+                wrapped().query(rawRangeQuery, positionBound, config);
+        if (rawResult.isSuccess()) {
+            final KeyValueIterator<Bytes, byte[]> iterator = rawResult.getResult();
+            final KeyValueIterator<K, V> resultIterator = new MeteredKeyValueTimestampedIterator(
+                    iterator,
+                    getSensor,
+                    getDeserializeValue(serdes, wrapped()),
+                    false
+            );
+            final QueryResult<KeyValueIterator<K, V>> typedQueryResult =
+                    InternalQueryResultUtil.copyAndSubstituteDeserializedResult(
+                            rawResult,
+                            resultIterator
+                    );
+            result = (QueryResult<R>) typedQueryResult;
+        } else {
+            // the generic type doesn't matter, since failed queries have no result set.
+            result = (QueryResult<R>) rawResult;
+        }
+        return result;
+    }
+
+    @SuppressWarnings("unchecked")
+    protected <R> QueryResult<R> runKeyQuery2(final Query<R> query,
+                                             final PositionBound positionBound,
+                                             final QueryConfig config) {
+        final QueryResult<R> result;
+        final KeyQuery<K, V> typedKeyQuery = (KeyQuery<K, V>) query;
+        final KeyQuery<Bytes, byte[]> rawKeyQuery =
+                KeyQuery.withKey(keyBytes(typedKeyQuery.getKey()));
+        final QueryResult<byte[]> rawResult =
+                wrapped().query(rawKeyQuery, positionBound, config);
+        if (rawResult.isSuccess()) {
+            final Function<byte[], ValueAndTimestamp<V>> deserializer = getDeserializeValue2(serdes, wrapped(), true);

Review Comment:
   It's not save to pass in `true` as third parameter -- this code is also use for PAPI stores...



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: jira-unsubscribe@kafka.apache.org

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


Re: [PR] KAFKA-15629: Proposal to introduce IQv2 Query Types: TimestampedKeyQuery and TimestampedRangeQuery [kafka]

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


##########
streams/src/main/java/org/apache/kafka/streams/state/internals/WrappedStateStore.java:
##########
@@ -34,6 +34,9 @@
 public abstract class WrappedStateStore<S extends StateStore, K, V> implements StateStore, CachedStateStore<K, V> {
 
     public static boolean isTimestamped(final StateStore stateStore) {
+        if (stateStore instanceof KeyValueToTimestampedKeyValueByteStoreAdapter) {

Review Comment:
   We should not add this case, but rather let `KeyValueToTimestampedKeyValueByteStoreAdapter` implement the marker interface `TimestampedBytesStore` such that the existing condition returns `true` for this store.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: jira-unsubscribe@kafka.apache.org

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


Re: [PR] KAFKA-15629: Proposal to introduce IQv2 Query Types: TimestampedKeyQuery and TimestampedRangeQuery [kafka]

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


##########
streams/src/test/java/org/apache/kafka/streams/integration/IQv2StoreIntegrationTest.java:
##########
@@ -776,64 +779,55 @@ public void verifyStore() {
                 globalShouldRejectAllQueries();
             } else {
                 shouldRejectUnknownQuery();
-                shouldCollectExecutionInfo();
+//                shouldCollectExecutionInfo();
                 shouldCollectExecutionInfoUnderFailure();
                 final String kind = this.kind;
                 if (storeToTest.keyValue()) {
                     if (storeToTest.timestamped()) {
-                        final Function<ValueAndTimestamp<Integer>, Integer> valueExtractor =
-                            ValueAndTimestamp::value;
-                        if (kind.equals("DSL")) {
-                            shouldHandleKeyQuery(2, valueExtractor, 5);
-                            shouldHandleRangeDSLQueries(valueExtractor);
-                        } else {
-                            shouldHandleKeyQuery(2, valueExtractor, 5);
-                            shouldHandleRangePAPIQueries(valueExtractor);
-                        }
-                    } else {
-                        final Function<Integer, Integer> valueExtractor = Function.identity();
-                        if (kind.equals("DSL")) {
-                            shouldHandleKeyQuery(2, valueExtractor, 5);
-                            shouldHandleRangeDSLQueries(valueExtractor);
-                        } else {
-                            shouldHandleKeyQuery(2, valueExtractor, 5);
-                            shouldHandleRangePAPIQueries(valueExtractor);
-                        }
-                    }
-                }
+                        shouldHandleKeyQuery(2,  5);
+                        shouldHandleTimestampedKeyQuery(2, 5);
+                        shouldHandleRangeQueries();
+                        shouldHandleTimestampRangeQueries();
+                  }
+                    else {
+                        shouldHandleKeyQuery(2, 5);

Review Comment:
   For ROCK_KV DSL store, and this time Cache is true, the data we get is not through the `KeyValueToTimestampedKeyValueByteStoreAdapter `'s query



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: jira-unsubscribe@kafka.apache.org

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


Re: [PR] KAFKA-15629: Proposal to introduce IQv2 Query Types: TimestampedKeyQuery and TimestampedRangeQuery [kafka]

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


##########
streams/src/main/java/org/apache/kafka/streams/state/internals/MeteredTimestampedKeyValueStore.java:
##########
@@ -102,4 +139,232 @@ static class RawAndDeserializedValue<ValueType> {
             this.value = value;
         }
     }
+
+    @SuppressWarnings("unchecked")
+    @Override
+    public <R> QueryResult<R> query(final Query<R> query,
+                                    final PositionBound positionBound,
+                                    final QueryConfig config) {
+
+        final long start = time.nanoseconds();
+        final QueryResult<R> result;
+
+        final StoreQueryUtils.QueryHandler handler = queryHandlers.get(query.getClass());
+        if (handler == null) {
+            result = wrapped().query(query, positionBound, config);
+            if (config.isCollectExecutionInfo()) {
+                result.addExecutionInfo(
+                        "Handled in " + getClass() + " in " + (time.nanoseconds() - start) + "ns");
+            }
+        } else {
+            result = (QueryResult<R>) handler.apply(
+                    query,
+                    positionBound,
+                    config,
+                    this
+            );
+            if (config.isCollectExecutionInfo()) {
+                result.addExecutionInfo(
+                        "Handled in " + getClass() + " with serdes "
+                                + serdes + " in " + (time.nanoseconds() - start) + "ns");
+            }
+        }
+        return result;
+    }
+
+
+
+    @SuppressWarnings("unchecked")
+    protected <R> QueryResult<R> runTimestampedKeyQuery(final Query<R> query,
+                                                      final PositionBound positionBound,
+                                                      final QueryConfig config) {
+        final QueryResult<R> result;
+        final TimestampedKeyQuery<K, V> typedKeyQuery = (TimestampedKeyQuery<K, V>) query;
+        final KeyQuery<Bytes, byte[]> rawKeyQuery =
+                KeyQuery.withKey(keyBytes(typedKeyQuery.key()));
+        final QueryResult<byte[]> rawResult =
+                wrapped().query(rawKeyQuery, positionBound, config);
+        if (rawResult.isSuccess()) {
+            final Function<byte[], ValueAndTimestamp<V>> deserializer = getDeserializeValue(serdes, wrapped());
+            final ValueAndTimestamp<V> value = deserializer.apply(rawResult.getResult());

Review Comment:
   ok



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: jira-unsubscribe@kafka.apache.org

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


Re: [PR] KAFKA-15629: Proposal to introduce IQv2 Query Types: TimestampedKeyQuery and TimestampedRangeQuery [kafka]

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


##########
streams/src/main/java/org/apache/kafka/streams/state/internals/KeyValueToTimestampedKeyValueByteStoreAdapter.java:
##########
@@ -180,5 +201,38 @@ public <PS extends Serializer<P>, P> KeyValueIterator<Bytes, byte[]> prefixScan(
     public long approximateNumEntries() {
         return store.approximateNumEntries();
     }
+}
 
+class WrappedRocksDbIterator extends AbstractIterator implements ManagedKeyValueIterator {
+    final private RocksDbIterator rocksDbIterator;
+    public WrappedRocksDbIterator(final RocksDbIterator rocksDbIterator) {
+        this.rocksDbIterator = rocksDbIterator;
+    }
+    @Override
+    protected Object makeNext() {
+        final KeyValue<Bytes, byte[]> next = rocksDbIterator.makeNext();

Review Comment:
   Not sure if I understand what you are trying to say? Can you elaborate?
   
   `makeNext` is not public API, but `protected` -- because this code "extends" `AbstractIterator` we are allowed to call `makeNext` but it seem not to be clean... Cf https://github.com/apache/kafka/pull/14570#discussion_r1379541488 -- If we change this class to only `implements MangedKeyValueIterator` I believe we won't be able to call `makeNext` any longer, what indicates that we should not call it (even if we keep `extends AbstractIteror`, what I still feel might no be the right way to go).



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: jira-unsubscribe@kafka.apache.org

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


Re: [PR] KAFKA-15629: Proposal to introduce IQv2 Query Types: TimestampedKeyQuery and TimestampedRangeQuery [kafka]

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


##########
streams/src/main/java/org/apache/kafka/streams/state/internals/KeyValueToTimestampedKeyValueByteStoreAdapter.java:
##########
@@ -180,5 +201,38 @@ public <PS extends Serializer<P>, P> KeyValueIterator<Bytes, byte[]> prefixScan(
     public long approximateNumEntries() {
         return store.approximateNumEntries();
     }
+}
 
+class WrappedRocksDbIterator extends AbstractIterator implements ManagedKeyValueIterator {

Review Comment:
   ok



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: jira-unsubscribe@kafka.apache.org

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


Re: [PR] KAFKA-15629: Proposal to introduce IQv2 Query Types: TimestampedKeyQuery and TimestampedRangeQuery [kafka]

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


##########
streams/src/main/java/org/apache/kafka/streams/state/internals/KeyValueToTimestampedKeyValueByteStoreAdapter.java:
##########
@@ -127,14 +131,31 @@ public <R> QueryResult<R> query(
         final QueryConfig config) {
 
 
+
         final long start = config.isCollectExecutionInfo() ? System.nanoTime() : -1L;
-        final QueryResult<R> result = store.query(query, positionBound, config);
+        QueryResult<R> result = store.query(query, positionBound, config);
+        final Position position = result.getPosition();
+
+        if (result.isSuccess()) {
+            if (result.getResult() instanceof byte[]) {
+                final byte[] plainValue = (byte[]) result.getResult();
+                final byte[] valueWithTimestamp = convertToTimestampedFormat(plainValue);
+                result = (QueryResult<R>) QueryResult.forResult(valueWithTimestamp);
+            }
+            if (result.getResult() instanceof RocksDbIterator) {

Review Comment:
   we should chain with with an `else` to the previous `if`



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: jira-unsubscribe@kafka.apache.org

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


Re: [PR] KAFKA-15629: Proposal to introduce IQv2 Query Types: TimestampedKeyQuery and TimestampedRangeQuery [kafka]

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


##########
streams/src/main/java/org/apache/kafka/streams/state/internals/KeyValueToTimestampedKeyValueByteStoreAdapter.java:
##########
@@ -126,15 +128,22 @@ public <R> QueryResult<R> query(
         final PositionBound positionBound,
         final QueryConfig config) {
 
-
         final long start = config.isCollectExecutionInfo() ? System.nanoTime() : -1L;
-        final QueryResult<R> result = store.query(query, positionBound, config);
+        QueryResult<R> result = store.query(query, positionBound, config);
+        Position position = result.getPosition();
+        if (result.isSuccess()) {
+            byte[] res = (byte[]) result.getResult();
+            byte[] res1 = convertToTimestampedFormat(res);
+            result = (QueryResult<R>) QueryResult.forResult(res1);
+        }
+
         if (config.isCollectExecutionInfo()) {
             final long end = System.nanoTime();
             result.addExecutionInfo(
                 "Handled in " + getClass() + " in " + (end - start) + "ns"
             );
         }
+        result.setPosition(position);

Review Comment:
   fixed



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: jira-unsubscribe@kafka.apache.org

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


Re: [PR] KAFKA-15629: Proposal to introduce IQv2 Query Types: TimestampedKeyQuery and TimestampedRangeQuery [kafka]

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


##########
streams/src/main/java/org/apache/kafka/streams/state/internals/MeteredTimestampedKeyValueStore.java:
##########
@@ -47,7 +59,26 @@ public class MeteredTimestampedKeyValueStore<K, V>
         super(inner, metricScope, time, keySerde, valueSerde);
     }
 
-
+    @SuppressWarnings("rawtypes")
+    private final Map<Class, StoreQueryUtils.QueryHandler> queryHandlers =
+            mkMap(
+                    mkEntry(
+                            RangeQuery.class,
+                            (query, positionBound, config, store) -> runRangeQuery(query, positionBound, config)

Review Comment:
   ok



##########
streams/src/main/java/org/apache/kafka/streams/state/internals/MeteredTimestampedKeyValueStore.java:
##########
@@ -102,4 +140,230 @@ static class RawAndDeserializedValue<ValueType> {
             this.value = value;
         }
     }
+
+    @SuppressWarnings("unchecked")
+    @Override
+    public <R> QueryResult<R> query(final Query<R> query,
+                                    final PositionBound positionBound,
+                                    final QueryConfig config) {
+
+        final long start = time.nanoseconds();
+        final QueryResult<R> result;
+
+        final StoreQueryUtils.QueryHandler handler = queryHandlers.get(query.getClass());
+        if (handler == null) {
+            result = wrapped().query(query, positionBound, config);
+            if (config.isCollectExecutionInfo()) {
+                result.addExecutionInfo(
+                        "Handled in " + getClass() + " in " + (time.nanoseconds() - start) + "ns");
+            }
+        } else {
+            result = (QueryResult<R>) handler.apply(
+                    query,
+                    positionBound,
+                    config,
+                    this
+            );
+            if (config.isCollectExecutionInfo()) {
+                result.addExecutionInfo(
+                        "Handled in " + getClass() + " with serdes "
+                                + serdes + " in " + (time.nanoseconds() - start) + "ns");
+            }
+        }
+        return result;
+    }
+
+
+
+    @SuppressWarnings("unchecked")
+    protected <R> QueryResult<R> runTimestampKeyQuery(final Query<R> query,
+                                                      final PositionBound positionBound,
+                                                      final QueryConfig config) {
+        final QueryResult<R> result;
+        final TimestampedKeyQuery<K, V> typedKeyQuery = (TimestampedKeyQuery<K, V>) query;
+        final KeyQuery<Bytes, byte[]> rawKeyQuery =
+                KeyQuery.withKey(keyBytes(typedKeyQuery.getKey()));
+        final QueryResult<byte[]> rawResult =
+                wrapped().query(rawKeyQuery, positionBound, config);
+        if (rawResult.isSuccess()) {
+            final Function<byte[], ValueAndTimestamp<V>> deserializer = getDeserializeValue(serdes, wrapped());
+            final ValueAndTimestamp<V> value = deserializer.apply(rawResult.getResult());
+            final QueryResult<ValueAndTimestamp<V>> typedQueryResult =
+                    InternalQueryResultUtil.copyAndSubstituteDeserializedResult(rawResult, value);
+            result = (QueryResult<R>) typedQueryResult;
+        } else {
+            // the generic type doesn't matter, since failed queries have no result set.
+            result = (QueryResult<R>) rawResult;
+        }
+        return result;
+    }
+
+    @SuppressWarnings("unchecked")
+    protected <R> QueryResult<R> runTimestampRangeQuery(final Query<R> query,
+                                                        final PositionBound positionBound,
+                                                        final QueryConfig config) {
+
+        final QueryResult<R> result;
+        final TimestampedRangeQuery<K, V> typedQuery = (TimestampedRangeQuery<K, V>) query;
+
+        final RangeQuery<Bytes, byte[]> rawRangeQuery;
+        if (typedQuery.getLowerBound().isPresent() && typedQuery.getUpperBound().isPresent()) {
+            rawRangeQuery = RangeQuery.withRange(
+                    keyBytes(typedQuery.getLowerBound().get()),
+                    keyBytes(typedQuery.getUpperBound().get())
+            );
+        } else if (typedQuery.getLowerBound().isPresent()) {
+            rawRangeQuery = RangeQuery.withLowerBound(keyBytes(typedQuery.getLowerBound().get()));
+        } else if (typedQuery.getUpperBound().isPresent()) {
+            rawRangeQuery = RangeQuery.withUpperBound(keyBytes(typedQuery.getUpperBound().get()));
+        } else {
+            rawRangeQuery = RangeQuery.withNoBounds();
+        }
+        final QueryResult<KeyValueIterator<Bytes, byte[]>> rawResult =
+                wrapped().query(rawRangeQuery, positionBound, config);
+        if (rawResult.isSuccess()) {
+            final KeyValueIterator<Bytes, byte[]> iterator = rawResult.getResult();
+            final KeyValueIterator<K, V> resultIterator = new MeteredKeyValueTimestampedIterator(
+                    iterator,
+                    getSensor,
+                    getDeserializeValue(serdes, wrapped()),
+                    false
+            );
+            final QueryResult<KeyValueIterator<K, V>> typedQueryResult =
+                    InternalQueryResultUtil.copyAndSubstituteDeserializedResult(
+                            rawResult,
+                            resultIterator
+                    );
+            result = (QueryResult<R>) typedQueryResult;
+        } else {
+            // the generic type doesn't matter, since failed queries have no result set.
+            result = (QueryResult<R>) rawResult;
+        }
+        return result;
+    }
+
+    @SuppressWarnings("unchecked")
+    protected <R> QueryResult<R> runKeyQuery2(final Query<R> query,
+                                             final PositionBound positionBound,
+                                             final QueryConfig config) {
+        final QueryResult<R> result;
+        final KeyQuery<K, V> typedKeyQuery = (KeyQuery<K, V>) query;
+        final KeyQuery<Bytes, byte[]> rawKeyQuery =
+                KeyQuery.withKey(keyBytes(typedKeyQuery.getKey()));
+        final QueryResult<byte[]> rawResult =
+                wrapped().query(rawKeyQuery, positionBound, config);
+        if (rawResult.isSuccess()) {
+            final Function<byte[], ValueAndTimestamp<V>> deserializer = getDeserializeValue2(serdes, wrapped(), true);
+            ValueAndTimestamp<V> value = deserializer.apply(rawResult.getResult());
+            V res = null;
+            if (value != null) {
+                res = value.value();
+            }
+            final QueryResult<V> typedQueryResult =
+                    InternalQueryResultUtil.copyAndSubstituteDeserializedResult(rawResult, res);
+            result = (QueryResult<R>) typedQueryResult;
+        } else {
+            // the generic type doesn't matter, since failed queries have no result set.
+            result = (QueryResult<R>) rawResult;
+        }
+        return result;
+    }
+
+    @SuppressWarnings("unchecked")
+    protected <R> QueryResult<R> runRangeQuery2(final Query<R> query,
+                                               final PositionBound positionBound,
+                                               final QueryConfig config) {
+
+        final QueryResult<R> result;
+        final RangeQuery<K, V> typedQuery = (RangeQuery<K, V>) query;
+        final RangeQuery<Bytes, byte[]> rawRangeQuery;
+        if (typedQuery.getLowerBound().isPresent() && typedQuery.getUpperBound().isPresent()) {
+            rawRangeQuery = RangeQuery.withRange(
+                    keyBytes(typedQuery.getLowerBound().get()),
+                    keyBytes(typedQuery.getUpperBound().get())
+            );
+        } else if (typedQuery.getLowerBound().isPresent()) {
+            rawRangeQuery = RangeQuery.withLowerBound(keyBytes(typedQuery.getLowerBound().get()));
+        } else if (typedQuery.getUpperBound().isPresent()) {
+            rawRangeQuery = RangeQuery.withUpperBound(keyBytes(typedQuery.getUpperBound().get()));
+        } else {
+            rawRangeQuery = RangeQuery.withNoBounds();
+        }
+        final QueryResult<KeyValueIterator<Bytes, byte[]>> rawResult =
+                wrapped().query(rawRangeQuery, positionBound, config);
+        if (rawResult.isSuccess()) {
+            final KeyValueIterator<Bytes, byte[]> iterator = rawResult.getResult();
+            final KeyValueIterator<K,V> resultIterator = new MeteredKeyValueTimestampedIterator(
+                    iterator,
+                    getSensor,
+                    getDeserializeValue(serdes, wrapped()),
+                    true
+            );
+            final QueryResult<KeyValueIterator<K, V>> typedQueryResult =
+                    InternalQueryResultUtil.copyAndSubstituteDeserializedResult(
+                            rawResult,
+                            resultIterator
+                    );
+            result = (QueryResult<R>) typedQueryResult;
+        } else {
+            // the generic type doesn't matter, since failed queries have no result set.
+            result = (QueryResult<R>) rawResult;
+        }
+        return result;
+    }
+
+    @SuppressWarnings("unchecked")
+    private class MeteredKeyValueTimestampedIterator implements KeyValueIterator<K, V> {

Review Comment:
   ok



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: jira-unsubscribe@kafka.apache.org

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


Re: [PR] KAFKA-15629: Proposal to introduce IQv2 Query Types: TimestampedKeyQuery and TimestampedRangeQuery [kafka]

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


##########
streams/src/main/java/org/apache/kafka/streams/state/internals/StoreQueryUtils.java:
##########
@@ -346,6 +346,23 @@ public static <V> Function<byte[], V> getDeserializeValue(final StateSerdes<?, V
         return byteArray -> deserializer.deserialize(serdes.topic(), byteArray);
     }
 
+    @SuppressWarnings({"unchecked", "rawtypes"})
+    public static <V> Function<byte[], V> getDeserializeValue2(final StateSerdes<?, V> serdes,

Review Comment:
   solved



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: jira-unsubscribe@kafka.apache.org

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


Re: [PR] KAFKA-15629: Proposal to introduce IQv2 Query Types: TimestampedKeyQuery and TimestampedRangeQuery [kafka]

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


##########
streams/src/main/java/org/apache/kafka/streams/state/internals/MeteredTimestampedKeyValueStore.java:
##########
@@ -102,4 +139,232 @@ static class RawAndDeserializedValue<ValueType> {
             this.value = value;
         }
     }
+
+    @SuppressWarnings("unchecked")
+    @Override
+    public <R> QueryResult<R> query(final Query<R> query,
+                                    final PositionBound positionBound,
+                                    final QueryConfig config) {
+
+        final long start = time.nanoseconds();
+        final QueryResult<R> result;
+
+        final StoreQueryUtils.QueryHandler handler = queryHandlers.get(query.getClass());
+        if (handler == null) {
+            result = wrapped().query(query, positionBound, config);
+            if (config.isCollectExecutionInfo()) {
+                result.addExecutionInfo(
+                        "Handled in " + getClass() + " in " + (time.nanoseconds() - start) + "ns");
+            }
+        } else {
+            result = (QueryResult<R>) handler.apply(
+                    query,
+                    positionBound,
+                    config,
+                    this
+            );
+            if (config.isCollectExecutionInfo()) {
+                result.addExecutionInfo(
+                        "Handled in " + getClass() + " with serdes "
+                                + serdes + " in " + (time.nanoseconds() - start) + "ns");
+            }
+        }
+        return result;
+    }
+
+
+
+    @SuppressWarnings("unchecked")
+    protected <R> QueryResult<R> runTimestampedKeyQuery(final Query<R> query,

Review Comment:
   Because in `MeteredKeyValueStore`, we use `protected` one. So I follow the `MeteredKeyValueStore`'s one.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: jira-unsubscribe@kafka.apache.org

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


Re: [PR] KAFKA-15629: Proposal to introduce IQv2 Query Types: TimestampedKeyQuery and TimestampedRangeQuery [kafka]

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


##########
streams/src/main/java/org/apache/kafka/streams/state/internals/KeyValueToTimestampedKeyValueByteStoreAdapter.java:
##########
@@ -127,14 +131,31 @@ public <R> QueryResult<R> query(
         final QueryConfig config) {
 
 
+
         final long start = config.isCollectExecutionInfo() ? System.nanoTime() : -1L;
-        final QueryResult<R> result = store.query(query, positionBound, config);
+        QueryResult<R> result = store.query(query, positionBound, config);
+        final Position position = result.getPosition();
+
+        if (result.isSuccess()) {
+            if (result.getResult() instanceof byte[]) {
+                final byte[] plainValue = (byte[]) result.getResult();
+                final byte[] valueWithTimestamp = convertToTimestampedFormat(plainValue);
+                result = (QueryResult<R>) QueryResult.forResult(valueWithTimestamp);

Review Comment:
   Yes, it was solved now.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: jira-unsubscribe@kafka.apache.org

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


Re: [PR] KAFKA-15629: Proposal to introduce IQv2 Query Types: TimestampedKeyQuery and TimestampedRangeQuery [kafka]

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


##########
streams/src/main/java/org/apache/kafka/streams/state/internals/KeyValueToTimestampedKeyValueByteStoreAdapter.java:
##########
@@ -180,5 +201,38 @@ public <PS extends Serializer<P>, P> KeyValueIterator<Bytes, byte[]> prefixScan(
     public long approximateNumEntries() {
         return store.approximateNumEntries();
     }
+}
 
+class WrappedRocksDbIterator extends AbstractIterator implements ManagedKeyValueIterator {
+    final private RocksDbIterator rocksDbIterator;
+    public WrappedRocksDbIterator(final RocksDbIterator rocksDbIterator) {
+        this.rocksDbIterator = rocksDbIterator;
+    }
+    @Override
+    protected Object makeNext() {
+        final KeyValue<Bytes, byte[]> next = rocksDbIterator.makeNext();
+        if (next == null) {
+            allDone();
+            return null;
+        }
+        final Bytes key = next.key;
+        final byte[] value = next.value;
+        final byte[] res = convertToTimestampedFormat(value);
+        return KeyValue.pair(key, res);
+    }
+
+    @Override
+    public void close() {

Review Comment:
   ok



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: jira-unsubscribe@kafka.apache.org

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


Re: [PR] KAFKA-15629: Proposal to introduce IQv2 Query Types: TimestampedKeyQuery and TimestampedRangeQuery [kafka]

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


##########
streams/src/test/java/org/apache/kafka/streams/integration/IQv2StoreIntegrationTest.java:
##########
@@ -1584,7 +1646,43 @@ public <V> void shouldHandleKeyQuery(
         );
 
         final V result1 = queryResult.getResult();
-        final Integer integer = valueExtactor.apply(result1);
+        final Integer integer = (Integer) result1;
+        assertThat(integer, is(expectedValue));
+        assertThat(queryResult.getExecutionInfo(), is(empty()));
+        assertThat(queryResult.getPosition(), is(POSITION_0));
+    }
+
+    public <V> void shouldHandleTimestampedKeyQuery(
+            final Integer key,
+            final Integer expectedValue) {

Review Comment:
   ok



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: jira-unsubscribe@kafka.apache.org

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


Re: [PR] KAFKA-15629: Proposal to introduce IQv2 Query Types: TimestampedKeyQuery and TimestampedRangeQuery [kafka]

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

   @mjsax ready for final code review.


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: jira-unsubscribe@kafka.apache.org

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


Re: [PR] KAFKA-15629: Proposal to introduce IQv2 Query Types: TimestampedKeyQuery and TimestampedRangeQuery [kafka]

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


##########
streams/src/main/java/org/apache/kafka/streams/state/internals/MeteredTimestampedKeyValueStore.java:
##########
@@ -102,4 +139,216 @@ static class RawAndDeserializedValue<ValueType> {
             this.value = value;
         }
     }
+
+    @SuppressWarnings("unchecked")
+    @Override
+    public <R> QueryResult<R> query(final Query<R> query,
+                                    final PositionBound positionBound,
+                                    final QueryConfig config) {
+
+        final long start = time.nanoseconds();
+        final QueryResult<R> result;
+
+        final StoreQueryUtils.QueryHandler handler = queryHandlers.get(query.getClass());
+        if (handler == null) {
+            result = wrapped().query(query, positionBound, config);
+            if (config.isCollectExecutionInfo()) {
+                result.addExecutionInfo(
+                        "Handled in " + getClass() + " in " + (time.nanoseconds() - start) + "ns");
+            }
+        } else {
+            result = (QueryResult<R>) handler.apply(
+                    query,
+                    positionBound,
+                    config,
+                    this
+            );
+            if (config.isCollectExecutionInfo()) {
+                result.addExecutionInfo(
+                        "Handled in " + getClass() + " with serdes "
+                                + serdes + " in " + (time.nanoseconds() - start) + "ns");
+            }
+        }
+        return result;
+    }
+
+
+
+    @SuppressWarnings("unchecked")
+    private <R> QueryResult<R> runTimestampedKeyQuery(final Query<R> query,
+                                                        final PositionBound positionBound,
+                                                        final QueryConfig config) {
+        final QueryResult<R> result;
+        final TimestampedKeyQuery<K, V> typedKeyQuery = (TimestampedKeyQuery<K, V>) query;
+        final KeyQuery<Bytes, byte[]> rawKeyQuery =
+                KeyQuery.withKey(keyBytes(typedKeyQuery.key()));
+        final QueryResult<byte[]> rawResult =
+                wrapped().query(rawKeyQuery, positionBound, config);
+        if (rawResult.isSuccess()) {
+            final Function<byte[], ValueAndTimestamp<V>> deserializer = getDeserializeValue(serdes, wrapped());

Review Comment:
   I am very sure, but MeterKeyValueStore also use getDeserializeValue(...), we can talk it tomorrow.



##########
streams/src/main/java/org/apache/kafka/streams/state/internals/MeteredTimestampedKeyValueStore.java:
##########
@@ -102,4 +139,216 @@ static class RawAndDeserializedValue<ValueType> {
             this.value = value;
         }
     }
+
+    @SuppressWarnings("unchecked")
+    @Override
+    public <R> QueryResult<R> query(final Query<R> query,
+                                    final PositionBound positionBound,
+                                    final QueryConfig config) {
+
+        final long start = time.nanoseconds();
+        final QueryResult<R> result;
+
+        final StoreQueryUtils.QueryHandler handler = queryHandlers.get(query.getClass());
+        if (handler == null) {
+            result = wrapped().query(query, positionBound, config);
+            if (config.isCollectExecutionInfo()) {
+                result.addExecutionInfo(
+                        "Handled in " + getClass() + " in " + (time.nanoseconds() - start) + "ns");
+            }
+        } else {
+            result = (QueryResult<R>) handler.apply(
+                    query,
+                    positionBound,
+                    config,
+                    this
+            );
+            if (config.isCollectExecutionInfo()) {
+                result.addExecutionInfo(
+                        "Handled in " + getClass() + " with serdes "
+                                + serdes + " in " + (time.nanoseconds() - start) + "ns");
+            }
+        }
+        return result;
+    }
+
+
+
+    @SuppressWarnings("unchecked")
+    private <R> QueryResult<R> runTimestampedKeyQuery(final Query<R> query,
+                                                        final PositionBound positionBound,
+                                                        final QueryConfig config) {
+        final QueryResult<R> result;
+        final TimestampedKeyQuery<K, V> typedKeyQuery = (TimestampedKeyQuery<K, V>) query;
+        final KeyQuery<Bytes, byte[]> rawKeyQuery =
+                KeyQuery.withKey(keyBytes(typedKeyQuery.key()));
+        final QueryResult<byte[]> rawResult =
+                wrapped().query(rawKeyQuery, positionBound, config);
+        if (rawResult.isSuccess()) {
+            final Function<byte[], ValueAndTimestamp<V>> deserializer = getDeserializeValue(serdes, wrapped());

Review Comment:
   I am not very sure, but MeterKeyValueStore also use getDeserializeValue(...), we can talk it tomorrow.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: jira-unsubscribe@kafka.apache.org

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


Re: [PR] KAFKA-15629: Proposal to introduce IQv2 Query Types: TimestampedKeyQuery and TimestampedRangeQuery [kafka]

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


##########
streams/src/main/java/org/apache/kafka/streams/state/internals/MeteredKeyValueStore.java:
##########
@@ -293,7 +285,7 @@ protected <R> QueryResult<R> runRangeQuery(final Query<R> query,
     }
 
     @SuppressWarnings("unchecked")
-    protected <R> QueryResult<R> runKeyQuery(final Query<R> query,
+    private  <R> QueryResult<R> runKeyQuery(final Query<R> query,
                                              final PositionBound positionBound,

Review Comment:
   fixed



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: jira-unsubscribe@kafka.apache.org

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


Re: [PR] KAFKA-15629: Proposal to introduce IQv2 Query Types: TimestampedKeyQuery and TimestampedRangeQuery [kafka]

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


##########
streams/src/test/java/org/apache/kafka/streams/integration/IQv2StoreIntegrationTest.java:
##########
@@ -1632,10 +1721,65 @@ public <V> void shouldHandleRangeQuery(
                     IllegalArgumentException.class,
                     queryResult.get(partition)::getFailureMessage
                 );
-
                 try (final KeyValueIterator<Integer, V> iterator = queryResult.get(partition).getResult()) {
                     while (iterator.hasNext()) {
-                        actualValues.add(valueExtactor.apply(iterator.next().value));
+                        actualValues.add((Integer) iterator.next().value);
+                    }
+                }
+                assertThat(queryResult.get(partition).getExecutionInfo(), is(empty()));
+            }
+            assertThat("Result:" + result, actualValues, is(expectedValues));
+            assertThat("Result:" + result, result.getPosition(), is(INPUT_POSITION));
+        }
+    }
+
+    public <V> void shouldHandleTimestampedRangeQuery(
+        final Optional<Integer> lower,
+        final Optional<Integer> upper,
+        final boolean isKeyAscending,
+        final List<Integer> expectedValues) {
+
+        TimestampedRangeQuery<Integer, V> query;
+
+        query = TimestampedRangeQuery.withRange(lower.orElse(null), upper.orElse(null));
+
+        if (!isKeyAscending) {
+            query = query.withDescendingKeys();
+        }
+
+        final StateQueryRequest<KeyValueIterator<Integer, ValueAndTimestamp<V>>> request =
+            inStore(STORE_NAME)
+                .withQuery(query)
+                .withPartitions(mkSet(0, 1))
+                .withPositionBound(PositionBound.at(INPUT_POSITION));
+        final StateQueryResult<KeyValueIterator<Integer, ValueAndTimestamp<V>>> result =
+            IntegrationTestUtils.iqv2WaitForResult(kafkaStreams, request);
+
+        if (result.getGlobalResult() != null) {
+            fail("global tables aren't implemented");
+        } else {
+            final List<Integer> actualValues = new ArrayList<>();
+            final Map<Integer, QueryResult<KeyValueIterator<Integer, ValueAndTimestamp<V>>>> queryResult = result.getPartitionResults();
+            final TreeSet<Integer> partitions = new TreeSet<>(queryResult.keySet());
+            for (final int partition : partitions) {
+                final boolean failure = queryResult.get(partition).isFailure();
+                if (failure) {
+                    throw new AssertionError(queryResult.toString());
+                }

Review Comment:
   If we use `TimestampedRangeQuery `query KV-store, here will throw an exception.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: jira-unsubscribe@kafka.apache.org

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


Re: [PR] KAFKA-15629: Proposal to introduce IQv2 Query Types: TimestampedKeyQuery and TimestampedRangeQuery [kafka]

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

   `Build / JDK 17 and Scala 2.13 / verifyStore[cache=true, log=true, supplier=ROCKS_KV, kind=DSL] – org.apache.kafka.streams.integration.IQv2StoreIntegrationTest` failed.
   
   ```
   org.apache.kafka.streams.errors.InvalidStateStoreException: Store kv-store is currently closed.
   	at app//org.apache.kafka.streams.state.internals.WrappedStateStore.validateStoreOpen(WrappedStateStore.java:116)
   	at app//org.apache.kafka.streams.state.internals.CachingKeyValueStore.query(CachingKeyValueStore.java:146)
   	at app//org.apache.kafka.streams.state.internals.MeteredTimestampedKeyValueStore.runKeyQuery(MeteredTimestampedKeyValueStore.java:248)
   	at app//org.apache.kafka.streams.state.internals.MeteredTimestampedKeyValueStore.lambda$new$2(MeteredTimestampedKeyValueStore.java:81)
   	at app//org.apache.kafka.streams.state.internals.MeteredTimestampedKeyValueStore.query(MeteredTimestampedKeyValueStore.java:160)
   	at app//org.apache.kafka.streams.KafkaStreams.query(KafkaStreams.java:1971)
   	at app//org.apache.kafka.streams.integration.utils.IntegrationTestUtils.iqv2WaitForResult(IntegrationTestUtils.java:168)
   	at app//org.apache.kafka.streams.integration.IQv2StoreIntegrationTest.shouldCollectExecutionInfo(IQv2StoreIntegrationTest.java:1964)
   	at app//org.apache.kafka.streams.integration.IQv2StoreIntegrationTest.verifyStore(IQv2StoreIntegrationTest.java:782)
   ```
   
   I don't think it's related to this PR, but I'll trigger a re-run to make sure.


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: jira-unsubscribe@kafka.apache.org

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


Re: [PR] KAFKA-15629: Proposal to introduce IQv2 Query Types: TimestampedKeyQuery and TimestampedRangeQuery [kafka]

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


##########
streams/src/main/java/org/apache/kafka/streams/state/internals/StoreQueryUtils.java:
##########
@@ -346,6 +346,23 @@ public static <V> Function<byte[], V> getDeserializeValue(final StateSerdes<?, V
         return byteArray -> deserializer.deserialize(serdes.topic(), byteArray);
     }
 
+    @SuppressWarnings({"unchecked", "rawtypes"})
+    public static <V> Function<byte[], V> getDeserializeValue2(final StateSerdes<?, V> serdes,
+                                                               final StateStore wrapped,
+                                                               final boolean isDSLStore ) {
+        final Serde<V> valueSerde = serdes.valueSerde();
+        final boolean timestamped = WrappedStateStore.isTimestamped(wrapped) || isDSLStore;
+        final Deserializer<V> deserializer;
+        if (!timestamped && valueSerde instanceof ValueAndTimestampSerde) {

Review Comment:
   Yes, I find that bug, that bug in `WrappedStateStore`,  we should add a statement like this
   ```
   public static boolean isTimestamped(final StateStore stateStore) {
           if (stateStore instanceof KeyValueToTimestampedKeyValueByteStoreAdapter) {
               return true;
           }
           if (stateStore instanceof TimestampedBytesStore) {
               return true;
           } else if (stateStore instanceof WrappedStateStore) {
   
   ```
   
   But this just solve the ROCK_KV DSL store with cache = true.
   
   We have to force` timestamped` to be true.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: jira-unsubscribe@kafka.apache.org

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