Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

This page is meant as a template for writing a KIP. To create a KIP choose Tools->Copy on this page and modify with your content and replace the heading with the next KIP number and a description of your issue. Replace anything in italics with your own description.

Status

Current state: Under Discussion Accpted

Discussion thread: here 
JIRA: here :https://lists.apache.org/thread/ogo7ntmj8srdcko2h86vvd9djjsjfvcj 

Vote thread: https://lists.apache.org/thread/q4kn2g6tmc837ph2zvff40pgpmgzok3d

JIRA:

Jira
serverASF JIRA
serverId5aa69414-a9e9-3523-82ec-879b028fb15b
keyKAFKA-15629

Please keep the discussion on the mailing list rather than commenting on the wiki (wiki discussions get unwieldy fast).

Motivation


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

Code Block
languagejava
titleshouldHandleKeyQuery
public <V> void shouldHandleKeyQuery(
            final Integer key,
            final Function<V, Integer> valueExtactor,
            final Integer expectedValue) {
        ...
	  	final KeyQuery<Integer, V> query = KeyQuery.withKey(key);
	    ...
	  	final StateQueryRequest<V> request =
                inStore(STORE_NAME)
                        .withQuery(query)
                        .withPartitions(mkSet(0, 1))
                        .withPositionBound(PositionBound.at(INPUT_POSITION));
		...
        final StateQueryResult<V> result =
                IntegrationTestUtils.iqv2WaitForResult(kafkaStreams, request);
        ...
        final QueryResult<V> queryResult = result.getOnlyPartitionResult();
        ...
        final V result1 = queryResult.getResult();
        final Integer integer = valueExtactor.apply(result1);
        assertThat(integer, is(expectedValue));
       ...
    } 

Before the introduction of TimestampedKeyQuery , when using KeyQuery , we obtained the result using the following code:

Code Block
final V result1 = queryResult.getResult();

This meant that the returned result could be of two potential data types: plain V  or ValueAndTimestamp<V> . This was a source of inconsistency. For instance, querying a kv-store  with KeyQuery  would return a V  type, but querying a ts-kv-store  would yield a ValueAndTimestamp<V> . This behavior is unintuitive and potentially confusing for developers.

To ensure consistency, we suggest that KeyQuery always return the plain V type, enhancing the predictability of the mentioned code. Likewise, RangeQuery should uniformly return the plain V KeyValueIterator.

For those requiring timestamped values from a ts-kv-store , we recommend introducing a new query type: TimestampedKeyQuery . This new query will specifically target ts-kv-stores  and will return ValueAndTimestamp<V> . Furthermore, to complement this, TimestampedRangeQuery  should be introduced to query ranges in ts-kv-stores , ensuring that the returned value always includes timestamps.To address these concerns, we propose:

Code Block
languagejava
titleTimestampKeyQuery
public final class TimestampKeyQuery<KTimestampedKeyQuery<K, V> implements Query<ValueAndTimestamp<V>>

...

Code Block
languagejava
titleTimestampRangeQuery
public final class TimestampRangeQuery<KTimestampedRangeQuery<K, V> implements Query<KeyValueIterator<K, ValueAndTimestamp<V>>>

Why introduce TimestampKeyQuery TimestampedKeyQuery  and TimestampRangeQuery TimestampedRangeQuery ? The primary motivation behind this is to ensure type safety and foster a clear distinction in our API. They bridge the difference between simple key-value stores and those integrated with timestamps, offering a more robust and intuitive querying mechanism.

Proposed Changes

Within the current IQv2 codebase, there have been distinct interactions between plain-kv-store and ts-kv-store. These differences, especially in return types, have raised concerns over type safety within the API.

To address these challenges and streamline the querying experience, we have decided to refine our approach and introduce two specialized query types: TimestampKeyQuery TimestampedKeyQuery  and TimestampRangeQuery TimestampedRangeQuery .


TimestampKeyQueryTimestampedKeyQuery : This query type will consistently return ValueAndTimestamp<V> , ensuring that there's a clear and predictable return type associated with timestamped key-value stores.

...

Code Block
languagejava
titleTimestampKeyQuery
@Evolving
public final class TimestampKeyQuery<KTimestampedKeyQuery<K, V> implements Query<ValueAndTimestamp<V>> {}

TimestampRangeQuery: Tailored for ranges with timestamps, this query will return a KeyValueIterator<K, ValueAndTimestamp<V>>

Code Block
languagejava
titleTimestampRangeQuery
@Evolving
public final class TimestampRangeQuery<K, V> implements Query<KeyValueIterator<K, ValueAndTimestamp<V>>> {}

Previously, MeteredKeyValueStore was equipped to handle both plain V queries and ValueAndTimestamp<V> queries. With this update, all KeyQuery instances will only return the plain V, eliminating the previously supported ValueAndTimestamp<V>. On the other hand, all TimestampKeyQuery instances are now designed to strictly return ValueAndTimestamp<V>.

This restructuring ensures a more intuitive, type-safe, and consistent querying mechanism for users across different types of key-value stores in the IQv2.

Compatibility, Deprecation, and Migration Plan

  • Utilizing the existing RangeQuery and KeyQuery class, we can make some modifications to realize the concepts of TimestampKeyQuery  and TimestampRangeQuery. 
  • Since nothing is deprecated in this KIP, users have no need to migrate unless they want to.

Test Plan

To ensure the robustness and accuracy of our new query types, TimestampKeyQuery and TimestampRangeQuery, it's essential to have thorough test coverage. With that in mind, we propose the creation of two specific test methods:

shouldHandleTimestampKeyQuery: This test method will validate the functionality of TimestampKeyQuery, ensuring it consistently returns ValueAndTimestamp<V> as expected.

Code Block
languagejava
titleshouldHandleTimestampKeyQuery
public <V> void shouldHandleTimestampKeyQuery(

...

    /**
     * Creates a finalquery Integerthat key,
will retrieve the record identified by {@code key} if    final Function<ValueAndTimestamp<V>, Integer> valueExtactor,it exists
     * (or {@code     final Integer expectedValue) {

null} otherwise).
     * @param key finalThe TimestampKeyQuery<Integer,key V>to queryretrieve
 = TimestampKeyQuery.withKey(key);
   * @param <K> The type finalof StateQueryRequest<ValueAndTimestamp<V>>the request =key
     * @param <V> The type of the value that will  inStore(STORE_NAME)be retrieved
     */
    public static <K, V> TimestampedKeyQuery<K, V> withKey(final K key) 

      .withQuery(query)/**
     * Specifies that the cache should be skipped during query evaluation. This means, that the query    .withPartitions(mkSet(0, 1))will always
     * get forwarded to the underlying store.
     */
    public TimestampedKeyQuery<K, V>  .withPositionBound(PositionBound.at(INPUT_POSITION));skipCache() 

    /**
     final* StateQueryResult<ValueAndTimestamp<V>>The resultkey =
that was specified for this query.
     */
    public K IntegrationTestUtils.iqv2WaitForResult(kafkaStreams, request);key() 

        final QueryResult<ValueAndTimestamp<V>> queryResult = result.getOnlyPartitionResult();/**
     ...

* The flag whether to skip the cache finalor ValueAndTimestamp<V>not result1during =query queryResultevaluation.getResult();
     */
   final Integerpublic integer = valueExtactor.apply(result1);
     ...
    }

boolean isSkipCache() 


TimestampedRangeQuery : Tailored for ranges with timestamps, this query will return a KeyValueIterator<K, ValueAndTimestamp<V>>

According to KIP-968, this KIP introduces the public enum ResultOrder to determine whether keys are sorted in ascending or descending  or unordered order. Order is based on the serialized byte[] of the keys, not the 'logical' key order. employs the withDescendingKeys() and withAscendingKeys() methods to specify that the keys should be ordered in descending or ascending or unordered sequence, and the resultOrder() method to retrieve the value of enum value in  ResultOrder. I've incorporated these variables and methods into the TimestampedRangeQuery  class and modified some method inputs. As a result, we can now use withDescendingKeys() to obtain results in reverse order and use withAscendingKeys to obtain the result in ascending order. shouldHandleTimestampRangeQuery: This method is tailored to verify the TimestampRangeQuery, ensuring that it correctly returns a KeyValueIterator<K, ValueAndTimestamp<V>>.

Code Block
languagejava
titleshouldHandleTimestampRangeQueriesTimestampedRangeQuery
@Evolving
public final class TimestampedRangeQuery<K, V> implements Query<KeyValueIterator<K, ValueAndTimestamp<V>>> {
private <T> void shouldHandleTimestampRangeQueries(final Function<ValueAndTimestamp<T>, Integer> extractor) {
    ...

    shouldHandleTimestampRangeQuery(/**
     * Interactive range query using a  Optional.of(0),
       lower and upper bound to filter the keys returned.
     Optional.of(4),
            extractor,* @param lower The key that specifies the lower bound of the range
     * @param upper The key that specifies the mkSet(1, 3, 5, 7, 9)upper bound of the range
     * @param <K> );

The key type
     * ...
@param <V> The value }

We will focus on conducting a detailed test for shouldHandleTimestampRangeQuery.

Code Block
languagejava
titleshouldHandleTimestampRangeQuery
public <V> void shouldHandleTimestampRangeQuery(
  type
     */
    public static <K, V> TimestampedRangeQuery<K, V> withRange(final Optional<Integer>K lower,
 final K upper) 
 

	/**
     * Determines if finalthe Optional<Integer> upper,
            final Function<ValueAndTimestamp<V>, Integer> valueExtactor,
            final Set<Integer> expectedValue) {

serialized byte[] of the keys in ascending or descending or unordered order.
     * Order is based on the serialized byte[] of the keys, not the 'logical' key order.
     * @return return finalthe TimestampRangeQuery<Integer,order V> query;

        query = TimestampRangeQuery.withRange(lower.orElse(null), upper.orElse(null));

        final StateQueryRequest<KeyValueIterator<Integer, ValueAndTimestamp<V>>> request =of return records base on the serialized byte[] of the keys (can be unordered, or in ascending, or in descending order).
     */
    public ResultOrder resultOrder() {
         inStore(STORE_NAME)return order;
    }

    /**
     * Set the query to return the serialized byte[] of  .withQuery(query)
   the keys in descending order.
     * Order is based on the serialized byte[] of the keys, not the 'logical' key  .withPartitions(mkSet(0, 1))order.
     * @return a new RangeQuery instance with descending flag set.
          .withPositionBound(PositionBound.at(INPUT_POSITION));*/
        final StateQueryResult<KeyValueIterator<Integerpublic TimestampedRangeQuery<K, ValueAndTimestamp<V>>>V> resultwithDescendingKeys() ={
        return new       IntegrationTestUtils.iqv2WaitForResult(kafkaStreams, requestTimestampedRangeQuery<>(this.lower, this.upper, ResultOrder.DESCENDING);
    }

    /**
    ...
 * Set the query to return the serialized byte[] of the finalkeys Map<Integer,in QueryResult<KeyValueIterator<Integer, ValueAndTimestamp<V>>>> queryResult = result.getPartitionResults();Ascending order.
     * Order 
is based on the serialized byte[] of the keys, not the 'logical' key order...

     * @return a new RangeQuery instance with ascending    try (final KeyValueIterator<Integer, ValueAndTimestamp<V>> iterator = queryResult.get(partition).getResult()) {flag set.
     */
    public TimestampedRangeQuery<K,          while (iterator.hasNext())V> withAscendingKeys() {
        return new TimestampedRangeQuery<>(this.lower, this.upper, ResultOrder.ASCENDING);
    }
         actualValue.add(valueExtactor.apply(iterator.next().value))
}

According to KIP-968, we introduce a public enum ResultOrder.

ResultOrder enum
It helps with specifying the order of the returned results by the query.

Code Block
languagejava
titleResultOrder
package org.apache.kafka.streams.query;
  
public enum                 }ResultOrder {
                }ANY,
               ...ASCENDING,
        }
    }

Rejected Alternatives

Initially, our approach was to directly use TimestampKeyQuery and TimestampRangeQuery within each store. This implied that every store would return a ValueAndTimestamp<byte[]>. However, this method introduced complexities due to type transformations.

Given that data within stores under the metered store is typically formatted as <Byte, byte[]>, we would need to wrap the byte[] into ValueAndTimestamp<byte[]> to produce the desired output.

DESCENDING
}


Compatibility, Deprecation, and Migration Plan

  • Changing the semantics of existing KeyQuery and RangeQuery  is a breaking change. However, both classes are marked as @Evolving` and thus a breaking change in a minor release is allowed without a deprecation period. Given that IQv2 is not yet widely adopted, we believe it’s cleaner to make this breaking change right away.
  • Adding new query types does not imply any compatibility concerns.

Test Plan

To ensure the robustness and accuracy of our new query types, TimestampedKeyQuery  and TimestampedRangeQuery , it's essential to have thorough test coverage. With that in mind, we propose the creation of two specific test methods:

shouldHandleTimestampedKeyQuery : This test method will validate the functionality of TimestampedKeyQuery , ensuring it consistently returns ValueAndTimestamp<V>  as expected.

shouldHandleTimestampedRangeQuery : This method is tailored to verify the TimestampedRangeQuery , ensuring that it correctly returns a KeyValueIterator<K, ValueAndTimestamp<V>> .

We will focus on conducting a detailed test for shouldHandleTimestampedRangeQuery .


Rejected Alternatives

The alternative would be to deprecate the existing KeyQuery  and RangeQuery  and add new query types that always return plain value. However, it seems to introduce unnecessary “deprecation noise”, and it would be hard to find good names for these newly added query types. Making a semantics change on the existing queries allows us to keep the existing namesTo streamline this, we opted to leverage existing methods to fetch the byte[] directly, which already encapsulates both value and timestamp. We then perform the deserialization at the meteredTimestampKeyValueStore level, the outermost layer, ensuring that the final output is ValueAndTimestamp<V>.