You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@spark.apache.org by ka...@apache.org on 2024/07/19 22:03:21 UTC
(spark) branch master updated: [SPARK-48836] Integrate SQL schema with state schema/metadata
This is an automated email from the ASF dual-hosted git repository.
kabhwan pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/spark.git
The following commit(s) were added to refs/heads/master by this push:
new c629dc0017df [SPARK-48836] Integrate SQL schema with state schema/metadata
c629dc0017df is described below
commit c629dc0017df6500fa7df8d27087cc310f1a6d06
Author: jingz-db <ji...@databricks.com>
AuthorDate: Sat Jul 20 07:03:01 2024 +0900
[SPARK-48836] Integrate SQL schema with state schema/metadata
### What changes were proposed in this pull request?
This PR enables TWS operator writes the "real" schema of the state variables that is initialized on the executors to be written to the `StateSchemaV3` that is being written by drivers. We'll integrate the SQL schema of the state variables with this [StateSchemaV3 implementation PR](https://github.com/apache/spark/pull/47104).
### Why are the changes needed?
When reloading the state after query restart, we'll need the schema/encoder of the state variables before restart.
### Does this PR introduce _any_ user-facing change?
No.
### How was this patch tested?
Integration tests in `TransformWithStateSuite` and `TransformWithStateTTLSuite` that tests with all state variable types to have correct schema. Existing integration tests in `TransformWith*State(TTL)Suite` for verifying SQL serialization is correct.
Existing unit test suites & newly added unit suites in `ValueStateSuite`, `ListStateSuite`, `MapStateSuite`, `TimerSuite` for non-primitive types.
### Was this patch authored or co-authored using generative AI tooling?
No.
Closes #47257 from jingz-db/metadata-schema-compatible.
Authored-by: jingz-db <ji...@databricks.com>
Signed-off-by: Jungtaek Lim <ka...@gmail.com>
---
.../streaming/ColumnFamilySchemaUtils.scala | 69 +++---
.../sql/execution/streaming/ListStateImpl.scala | 11 +-
.../execution/streaming/ListStateImplWithTTL.scala | 50 ++--
.../sql/execution/streaming/MapStateImpl.scala | 15 +-
.../execution/streaming/MapStateImplWithTTL.scala | 45 ++--
.../streaming/StateTypesEncoderUtils.scala | 275 ++++++++++++++-------
.../streaming/StatefulProcessorHandleImpl.scala | 18 +-
.../StatefulProcessorHandleImplBase.scala | 5 +-
.../spark/sql/execution/streaming/TTLState.scala | 78 +++---
.../sql/execution/streaming/TimerStateImpl.scala | 65 ++---
.../streaming/TransformWithStateExec.scala | 25 +-
.../sql/execution/streaming/ValueStateImpl.scala | 11 +-
.../streaming/ValueStateImplWithTTL.scala | 27 +-
.../streaming/state/StateSchemaV3File.scala | 4 +-
.../execution/streaming/state/ListStateSuite.scala | 28 +++
.../execution/streaming/state/MapStateSuite.scala | 32 ++-
.../streaming/state/StateStoreSuite.scala | 1 -
.../sql/execution/streaming/state/TimerSuite.scala | 19 ++
.../streaming/state/ValueStateSuite.scala | 28 +++
.../sql/streaming/TransformWithStateSuite.scala | 129 ++++++++--
.../TransformWithValueStateTTLSuite.scala | 147 ++++++++++-
21 files changed, 748 insertions(+), 334 deletions(-)
diff --git a/sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/ColumnFamilySchemaUtils.scala b/sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/ColumnFamilySchemaUtils.scala
index 68f3fa434389..513f941bdfbd 100644
--- a/sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/ColumnFamilySchemaUtils.scala
+++ b/sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/ColumnFamilySchemaUtils.scala
@@ -17,59 +17,68 @@
package org.apache.spark.sql.execution.streaming
import org.apache.spark.sql.Encoder
-import org.apache.spark.sql.execution.streaming.TransformWithStateKeyValueRowSchema.{COMPOSITE_KEY_ROW_SCHEMA, KEY_ROW_SCHEMA, VALUE_ROW_SCHEMA, VALUE_ROW_SCHEMA_WITH_TTL}
+import org.apache.spark.sql.catalyst.encoders.ExpressionEncoder
+import org.apache.spark.sql.execution.streaming.TransformWithStateKeyValueRowSchemaUtils._
import org.apache.spark.sql.execution.streaming.state.{ColumnFamilySchema, ColumnFamilySchemaV1, NoPrefixKeyStateEncoderSpec, PrefixKeyScanStateEncoderSpec}
trait ColumnFamilySchemaUtils {
- def getValueStateSchema[T](stateName: String, hasTtl: Boolean): ColumnFamilySchema
+ def getValueStateSchema[T](
+ stateName: String,
+ keyEncoder: ExpressionEncoder[Any],
+ valEncoder: Encoder[T],
+ hasTtl: Boolean): ColumnFamilySchema
- def getListStateSchema[T](stateName: String, hasTtl: Boolean): ColumnFamilySchema
+ def getListStateSchema[T](
+ stateName: String,
+ keyEncoder: ExpressionEncoder[Any],
+ valEncoder: Encoder[T],
+ hasTtl: Boolean): ColumnFamilySchema
def getMapStateSchema[K, V](
stateName: String,
+ keyEncoder: ExpressionEncoder[Any],
userKeyEnc: Encoder[K],
+ valEncoder: Encoder[V],
hasTtl: Boolean): ColumnFamilySchema
}
-
object ColumnFamilySchemaUtilsV1 extends ColumnFamilySchemaUtils {
- def getValueStateSchema[T](stateName: String, hasTtl: Boolean): ColumnFamilySchemaV1 = {
- ColumnFamilySchemaV1(
+ def getValueStateSchema[T](
+ stateName: String,
+ keyEncoder: ExpressionEncoder[Any],
+ valEncoder: Encoder[T],
+ hasTtl: Boolean): ColumnFamilySchemaV1 = {
+ new ColumnFamilySchemaV1(
stateName,
- KEY_ROW_SCHEMA,
- if (hasTtl) {
- VALUE_ROW_SCHEMA_WITH_TTL
- } else {
- VALUE_ROW_SCHEMA
- },
- NoPrefixKeyStateEncoderSpec(KEY_ROW_SCHEMA))
+ keyEncoder.schema,
+ getValueSchemaWithTTL(valEncoder.schema, hasTtl),
+ NoPrefixKeyStateEncoderSpec(keyEncoder.schema))
}
- def getListStateSchema[T](stateName: String, hasTtl: Boolean): ColumnFamilySchemaV1 = {
- ColumnFamilySchemaV1(
+ def getListStateSchema[T](
+ stateName: String,
+ keyEncoder: ExpressionEncoder[Any],
+ valEncoder: Encoder[T],
+ hasTtl: Boolean): ColumnFamilySchemaV1 = {
+ new ColumnFamilySchemaV1(
stateName,
- KEY_ROW_SCHEMA,
- if (hasTtl) {
- VALUE_ROW_SCHEMA_WITH_TTL
- } else {
- VALUE_ROW_SCHEMA
- },
- NoPrefixKeyStateEncoderSpec(KEY_ROW_SCHEMA))
+ keyEncoder.schema,
+ getValueSchemaWithTTL(valEncoder.schema, hasTtl),
+ NoPrefixKeyStateEncoderSpec(keyEncoder.schema))
}
def getMapStateSchema[K, V](
stateName: String,
+ keyEncoder: ExpressionEncoder[Any],
userKeyEnc: Encoder[K],
+ valEncoder: Encoder[V],
hasTtl: Boolean): ColumnFamilySchemaV1 = {
- ColumnFamilySchemaV1(
+ val compositeKeySchema = getCompositeKeySchema(keyEncoder.schema, userKeyEnc.schema)
+ new ColumnFamilySchemaV1(
stateName,
- COMPOSITE_KEY_ROW_SCHEMA,
- if (hasTtl) {
- VALUE_ROW_SCHEMA_WITH_TTL
- } else {
- VALUE_ROW_SCHEMA
- },
- PrefixKeyScanStateEncoderSpec(COMPOSITE_KEY_ROW_SCHEMA, 1),
+ compositeKeySchema,
+ getValueSchemaWithTTL(valEncoder.schema, hasTtl),
+ PrefixKeyScanStateEncoderSpec(compositeKeySchema, 1),
Some(userKeyEnc.schema))
}
}
diff --git a/sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/ListStateImpl.scala b/sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/ListStateImpl.scala
index 56c9d2664d9e..497472ce6367 100644
--- a/sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/ListStateImpl.scala
+++ b/sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/ListStateImpl.scala
@@ -19,7 +19,6 @@ package org.apache.spark.sql.execution.streaming
import org.apache.spark.internal.Logging
import org.apache.spark.sql.Encoder
import org.apache.spark.sql.catalyst.encoders.ExpressionEncoder
-import org.apache.spark.sql.execution.streaming.TransformWithStateKeyValueRowSchema.{KEY_ROW_SCHEMA, VALUE_ROW_SCHEMA}
import org.apache.spark.sql.execution.streaming.state.{NoPrefixKeyStateEncoderSpec, StateStore, StateStoreErrors}
import org.apache.spark.sql.streaming.ListState
@@ -29,7 +28,7 @@ import org.apache.spark.sql.streaming.ListState
*
* @param store - reference to the StateStore instance to be used for storing state
* @param stateName - name of logical state partition
- * @param keyEnc - Spark SQL encoder for key
+ * @param keyExprEnc - Spark SQL encoder for key
* @param valEncoder - Spark SQL encoder for value
* @tparam S - data type of object that will be stored in the list
*/
@@ -40,12 +39,10 @@ class ListStateImpl[S](
valEncoder: Encoder[S])
extends ListState[S] with Logging {
- private val keySerializer = keyExprEnc.createSerializer()
+ private val stateTypesEncoder = StateTypesEncoder(keyExprEnc, valEncoder, stateName)
- private val stateTypesEncoder = StateTypesEncoder(keySerializer, valEncoder, stateName)
-
- store.createColFamilyIfAbsent(stateName, KEY_ROW_SCHEMA, VALUE_ROW_SCHEMA,
- NoPrefixKeyStateEncoderSpec(KEY_ROW_SCHEMA), useMultipleValuesPerKey = true)
+ store.createColFamilyIfAbsent(stateName, keyExprEnc.schema, valEncoder.schema,
+ NoPrefixKeyStateEncoderSpec(keyExprEnc.schema), useMultipleValuesPerKey = true)
/** Whether state exists or not. */
override def exists(): Boolean = {
diff --git a/sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/ListStateImplWithTTL.scala b/sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/ListStateImplWithTTL.scala
index dc72f8bcd560..faeec7cb9386 100644
--- a/sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/ListStateImplWithTTL.scala
+++ b/sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/ListStateImplWithTTL.scala
@@ -18,7 +18,8 @@ package org.apache.spark.sql.execution.streaming
import org.apache.spark.sql.Encoder
import org.apache.spark.sql.catalyst.encoders.ExpressionEncoder
-import org.apache.spark.sql.execution.streaming.TransformWithStateKeyValueRowSchema.{KEY_ROW_SCHEMA, VALUE_ROW_SCHEMA_WITH_TTL}
+import org.apache.spark.sql.catalyst.expressions.UnsafeRow
+import org.apache.spark.sql.execution.streaming.TransformWithStateKeyValueRowSchemaUtils._
import org.apache.spark.sql.execution.streaming.state.{NoPrefixKeyStateEncoderSpec, StateStore, StateStoreErrors}
import org.apache.spark.sql.streaming.{ListState, TTLConfig}
import org.apache.spark.util.NextIterator
@@ -42,12 +43,11 @@ class ListStateImplWithTTL[S](
valEncoder: Encoder[S],
ttlConfig: TTLConfig,
batchTimestampMs: Long)
- extends SingleKeyTTLStateImpl(stateName, store, batchTimestampMs) with ListState[S] {
+ extends SingleKeyTTLStateImpl(
+ stateName, store, keyExprEnc, batchTimestampMs) with ListState[S] {
- private lazy val keySerializer = keyExprEnc.createSerializer()
-
- private lazy val stateTypesEncoder = StateTypesEncoder(
- keySerializer, valEncoder, stateName, hasTtl = true)
+ private lazy val stateTypesEncoder = StateTypesEncoder(keyExprEnc, valEncoder,
+ stateName, hasTtl = true)
private lazy val ttlExpirationMs =
StateTTL.calculateExpirationTimeForDuration(ttlConfig.ttlDuration, batchTimestampMs)
@@ -55,8 +55,9 @@ class ListStateImplWithTTL[S](
initialize()
private def initialize(): Unit = {
- store.createColFamilyIfAbsent(stateName, KEY_ROW_SCHEMA, VALUE_ROW_SCHEMA_WITH_TTL,
- NoPrefixKeyStateEncoderSpec(KEY_ROW_SCHEMA), useMultipleValuesPerKey = true)
+ store.createColFamilyIfAbsent(stateName, keyExprEnc.schema,
+ getValueSchemaWithTTL(valEncoder.schema, true),
+ NoPrefixKeyStateEncoderSpec(keyExprEnc.schema), useMultipleValuesPerKey = true)
}
/** Whether state exists or not. */
@@ -96,8 +97,7 @@ class ListStateImplWithTTL[S](
override def put(newState: Array[S]): Unit = {
validateNewState(newState)
- val serializedGroupingKey = stateTypesEncoder.serializeGroupingKey()
- val encodedKey = stateTypesEncoder.encodeSerializedGroupingKey(serializedGroupingKey)
+ val encodedKey = stateTypesEncoder.encodeGroupingKey()
var isFirst = true
newState.foreach { v =>
@@ -109,29 +109,28 @@ class ListStateImplWithTTL[S](
store.merge(encodedKey, encodedValue, stateName)
}
}
- upsertTTLForStateKey(serializedGroupingKey)
+ upsertTTLForStateKey(encodedKey)
}
/** Append an entry to the list. */
override def appendValue(newState: S): Unit = {
StateStoreErrors.requireNonNullStateValue(newState, stateName)
- val serializedGroupingKey = stateTypesEncoder.serializeGroupingKey()
- store.merge(stateTypesEncoder.encodeSerializedGroupingKey(serializedGroupingKey),
+ val encodedKey = stateTypesEncoder.encodeGroupingKey()
+ store.merge(encodedKey,
stateTypesEncoder.encodeValue(newState, ttlExpirationMs), stateName)
- upsertTTLForStateKey(serializedGroupingKey)
+ upsertTTLForStateKey(encodedKey)
}
/** Append an entire list to the existing value. */
override def appendList(newState: Array[S]): Unit = {
validateNewState(newState)
- val serializedGroupingKey = stateTypesEncoder.serializeGroupingKey()
- val encodedKey = stateTypesEncoder.encodeSerializedGroupingKey(serializedGroupingKey)
+ val encodedKey = stateTypesEncoder.encodeGroupingKey()
newState.foreach { v =>
val encodedValue = stateTypesEncoder.encodeValue(v, ttlExpirationMs)
store.merge(encodedKey, encodedValue, stateName)
}
- upsertTTLForStateKey(serializedGroupingKey)
+ upsertTTLForStateKey(encodedKey)
}
/** Remove this state. */
@@ -154,20 +153,19 @@ class ListStateImplWithTTL[S](
* the expired elements from the list.
* @param groupingKey grouping key for which cleanup should be performed.
*/
- override def clearIfExpired(groupingKey: Array[Byte]): Long = {
+ override def clearIfExpired(groupingKey: UnsafeRow): Long = {
var numValuesExpired = 0L
- val encodedGroupingKey = stateTypesEncoder.encodeSerializedGroupingKey(groupingKey)
- val unsafeRowValuesIterator = store.valuesIterator(encodedGroupingKey, stateName)
+ val unsafeRowValuesIterator = store.valuesIterator(groupingKey, stateName)
// We clear the list, and use the iterator to put back all of the non-expired values
- store.remove(encodedGroupingKey, stateName)
+ store.remove(groupingKey, stateName)
var isFirst = true
unsafeRowValuesIterator.foreach { encodedValue =>
if (!stateTypesEncoder.isExpired(encodedValue, batchTimestampMs)) {
if (isFirst) {
- store.put(encodedGroupingKey, encodedValue, stateName)
+ store.put(groupingKey, encodedValue, stateName)
isFirst = false
} else {
- store.merge(encodedGroupingKey, encodedValue, stateName)
+ store.merge(groupingKey, encodedValue, stateName)
}
} else {
numValuesExpired += 1
@@ -176,8 +174,8 @@ class ListStateImplWithTTL[S](
numValuesExpired
}
- private def upsertTTLForStateKey(serializedGroupingKey: Array[Byte]): Unit = {
- upsertTTLForStateKey(ttlExpirationMs, serializedGroupingKey)
+ private def upsertTTLForStateKey(encodedGroupingKey: UnsafeRow): Unit = {
+ upsertTTLForStateKey(ttlExpirationMs, encodedGroupingKey)
}
/*
@@ -216,6 +214,6 @@ class ListStateImplWithTTL[S](
* grouping key.
*/
private[sql] def getValuesInTTLState(): Iterator[Long] = {
- getValuesInTTLState(stateTypesEncoder.serializeGroupingKey())
+ getValuesInTTLState(stateTypesEncoder.encodeGroupingKey())
}
}
diff --git a/sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/MapStateImpl.scala b/sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/MapStateImpl.scala
index c58f32ed756d..2fa6fa415a77 100644
--- a/sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/MapStateImpl.scala
+++ b/sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/MapStateImpl.scala
@@ -19,9 +19,10 @@ package org.apache.spark.sql.execution.streaming
import org.apache.spark.internal.Logging
import org.apache.spark.sql.Encoder
import org.apache.spark.sql.catalyst.encoders.ExpressionEncoder
+import org.apache.spark.sql.execution.streaming.TransformWithStateKeyValueRowSchemaUtils._
import org.apache.spark.sql.execution.streaming.state.{PrefixKeyScanStateEncoderSpec, StateStore, StateStoreErrors, UnsafeRowPair}
import org.apache.spark.sql.streaming.MapState
-import org.apache.spark.sql.types.{BinaryType, StructType}
+import org.apache.spark.sql.types.StructType
class MapStateImpl[K, V](
store: StateStore,
@@ -31,14 +32,12 @@ class MapStateImpl[K, V](
valEncoder: Encoder[V]) extends MapState[K, V] with Logging {
// Pack grouping key and user key together as a prefixed composite key
- private val schemaForCompositeKeyRow: StructType =
- new StructType()
- .add("key", BinaryType)
- .add("userKey", BinaryType)
- private val schemaForValueRow: StructType = new StructType().add("value", BinaryType)
- private val keySerializer = keyExprEnc.createSerializer()
+ private val schemaForCompositeKeyRow: StructType = {
+ getCompositeKeySchema(keyExprEnc.schema, userKeyEnc.schema)
+ }
+ private val schemaForValueRow: StructType = valEncoder.schema
private val stateTypesEncoder = new CompositeKeyStateEncoder(
- keySerializer, userKeyEnc, valEncoder, schemaForCompositeKeyRow, stateName)
+ keyExprEnc, userKeyEnc, valEncoder, stateName)
store.createColFamilyIfAbsent(stateName, schemaForCompositeKeyRow, schemaForValueRow,
PrefixKeyScanStateEncoderSpec(schemaForCompositeKeyRow, 1))
diff --git a/sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/MapStateImplWithTTL.scala b/sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/MapStateImplWithTTL.scala
index 2ab06f36dd5f..a6234636a94f 100644
--- a/sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/MapStateImplWithTTL.scala
+++ b/sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/MapStateImplWithTTL.scala
@@ -19,7 +19,8 @@ package org.apache.spark.sql.execution.streaming
import org.apache.spark.internal.Logging
import org.apache.spark.sql.Encoder
import org.apache.spark.sql.catalyst.encoders.ExpressionEncoder
-import org.apache.spark.sql.execution.streaming.TransformWithStateKeyValueRowSchema.{COMPOSITE_KEY_ROW_SCHEMA, VALUE_ROW_SCHEMA_WITH_TTL}
+import org.apache.spark.sql.catalyst.expressions.UnsafeRow
+import org.apache.spark.sql.execution.streaming.TransformWithStateKeyValueRowSchemaUtils._
import org.apache.spark.sql.execution.streaming.state.{PrefixKeyScanStateEncoderSpec, StateStore, StateStoreErrors}
import org.apache.spark.sql.streaming.{MapState, TTLConfig}
import org.apache.spark.util.NextIterator
@@ -45,12 +46,13 @@ class MapStateImplWithTTL[K, V](
userKeyEnc: Encoder[K],
valEncoder: Encoder[V],
ttlConfig: TTLConfig,
- batchTimestampMs: Long) extends CompositeKeyTTLStateImpl(stateName, store, batchTimestampMs)
+ batchTimestampMs: Long)
+ extends CompositeKeyTTLStateImpl[K](stateName, store,
+ keyExprEnc, userKeyEnc, batchTimestampMs)
with MapState[K, V] with Logging {
- private val keySerializer = keyExprEnc.createSerializer()
private val stateTypesEncoder = new CompositeKeyStateEncoder(
- keySerializer, userKeyEnc, valEncoder, COMPOSITE_KEY_ROW_SCHEMA, stateName, hasTtl = true)
+ keyExprEnc, userKeyEnc, valEncoder, stateName, hasTtl = true)
private val ttlExpirationMs =
StateTTL.calculateExpirationTimeForDuration(ttlConfig.ttlDuration, batchTimestampMs)
@@ -58,8 +60,11 @@ class MapStateImplWithTTL[K, V](
initialize()
private def initialize(): Unit = {
- store.createColFamilyIfAbsent(stateName, COMPOSITE_KEY_ROW_SCHEMA, VALUE_ROW_SCHEMA_WITH_TTL,
- PrefixKeyScanStateEncoderSpec(COMPOSITE_KEY_ROW_SCHEMA, 1))
+ val schemaForCompositeKeyRow =
+ getCompositeKeySchema(keyExprEnc.schema, userKeyEnc.schema)
+ store.createColFamilyIfAbsent(stateName, schemaForCompositeKeyRow,
+ getValueSchemaWithTTL(valEncoder.schema, true),
+ PrefixKeyScanStateEncoderSpec(schemaForCompositeKeyRow, 1))
}
/** Whether state exists or not. */
@@ -95,15 +100,14 @@ class MapStateImplWithTTL[K, V](
StateStoreErrors.requireNonNullStateValue(key, stateName)
StateStoreErrors.requireNonNullStateValue(value, stateName)
- val serializedGroupingKey = stateTypesEncoder.serializeGroupingKey()
- val serializedUserKey = stateTypesEncoder.serializeUserKey(key)
+ val encodedGroupingKey = stateTypesEncoder.encodeGroupingKey()
+ val encodedUserKey = stateTypesEncoder.encodeUserKey(key)
val encodedValue = stateTypesEncoder.encodeValue(value, ttlExpirationMs)
- val encodedCompositeKey = stateTypesEncoder.encodeCompositeKey(
- serializedGroupingKey, serializedUserKey)
+ val encodedCompositeKey = stateTypesEncoder.encodeCompositeKey(key)
store.put(encodedCompositeKey, encodedValue, stateName)
- upsertTTLForStateKey(ttlExpirationMs, serializedGroupingKey, serializedUserKey)
+ upsertTTLForStateKey(ttlExpirationMs, encodedGroupingKey, encodedUserKey)
}
/** Get the map associated with grouping key */
@@ -169,13 +173,16 @@ class MapStateImplWithTTL[K, V](
* @param groupingKey grouping key for which cleanup should be performed.
* @param userKey user key for which cleanup should be performed.
*/
- override def clearIfExpired(groupingKey: Array[Byte], userKey: Array[Byte]): Long = {
- val encodedCompositeKey = stateTypesEncoder.encodeCompositeKey(groupingKey, userKey)
- val retRow = store.get(encodedCompositeKey, stateName)
+ override def clearIfExpired(
+ groupingKeyRow: UnsafeRow,
+ userKeyRow: UnsafeRow): Long = {
+ val compositeKeyRow = stateTypesEncoder.encodeCompositeKey(groupingKeyRow, userKeyRow)
+
+ val retRow = store.get(compositeKeyRow, stateName)
var numRemovedElements = 0L
if (retRow != null) {
if (stateTypesEncoder.isExpired(retRow, batchTimestampMs)) {
- store.remove(encodedCompositeKey, stateName)
+ store.remove(compositeKeyRow, stateName)
numRemovedElements += 1
}
}
@@ -226,7 +233,7 @@ class MapStateImplWithTTL[K, V](
*/
private[sql] def getKeyValuesInTTLState(): Iterator[(K, Long)] = {
val ttlIterator = ttlIndexIterator()
- val implicitGroupingKey = stateTypesEncoder.serializeGroupingKey()
+ val implicitGroupingKey = stateTypesEncoder.encodeGroupingKey()
var nextValue: Option[(K, Long)] = None
new Iterator[(K, Long)] {
@@ -234,8 +241,10 @@ class MapStateImplWithTTL[K, V](
while (nextValue.isEmpty && ttlIterator.hasNext) {
val nextTtlValue = ttlIterator.next()
val groupingKey = nextTtlValue.groupingKey
- if (groupingKey sameElements implicitGroupingKey) {
- val userKey = stateTypesEncoder.decodeUserKeyFromTTLRow(nextTtlValue)
+ if (groupingKey equals implicitGroupingKey.getStruct(
+ 0, keyExprEnc.schema.length)) {
+ val userKey = stateTypesEncoder.decodeUserKey(
+ nextTtlValue.userKey)
nextValue = Some(userKey, nextTtlValue.expirationMs)
}
}
diff --git a/sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/StateTypesEncoderUtils.scala b/sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/StateTypesEncoderUtils.scala
index ed881b49ec1e..1f5ad2fc8547 100644
--- a/sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/StateTypesEncoderUtils.scala
+++ b/sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/StateTypesEncoderUtils.scala
@@ -19,22 +19,44 @@ package org.apache.spark.sql.execution.streaming
import org.apache.spark.sql.Encoder
import org.apache.spark.sql.catalyst.InternalRow
-import org.apache.spark.sql.catalyst.encoders.ExpressionEncoder.Serializer
-import org.apache.spark.sql.catalyst.encoders.encoderFor
+import org.apache.spark.sql.catalyst.encoders.{encoderFor, ExpressionEncoder}
import org.apache.spark.sql.catalyst.expressions.{UnsafeProjection, UnsafeRow}
+import org.apache.spark.sql.execution.streaming.TransformWithStateKeyValueRowSchemaUtils._
import org.apache.spark.sql.execution.streaming.state.StateStoreErrors
-import org.apache.spark.sql.types.{BinaryType, LongType, StructType}
-
-object TransformWithStateKeyValueRowSchema {
- val KEY_ROW_SCHEMA: StructType = new StructType().add("key", BinaryType)
- val COMPOSITE_KEY_ROW_SCHEMA: StructType = new StructType()
- .add("key", BinaryType)
- .add("userKey", BinaryType)
- val VALUE_ROW_SCHEMA: StructType = new StructType()
- .add("value", BinaryType)
- val VALUE_ROW_SCHEMA_WITH_TTL: StructType = new StructType()
- .add("value", BinaryType)
- .add("ttlExpirationMs", LongType)
+import org.apache.spark.sql.types._
+
+/**
+ * Helper object for getting schema of key/value row that are used in state schema
+ * files and to be passed into `RocksDBStateKey(/Value)Encoder`.
+ */
+object TransformWithStateKeyValueRowSchemaUtils {
+ def getCompositeKeySchema(
+ groupingKeySchema: StructType,
+ userKeySchema: StructType): StructType = {
+ new StructType()
+ .add("key", new StructType(groupingKeySchema.fields))
+ .add("userKey", new StructType(userKeySchema.fields))
+ }
+
+ def getSingleKeyTTLRowSchema(keySchema: StructType): StructType =
+ new StructType()
+ .add("expirationMs", LongType)
+ .add("groupingKey", keySchema)
+
+ def getCompositeKeyTTLRowSchema(
+ groupingKeySchema: StructType,
+ userKeySchema: StructType): StructType =
+ new StructType()
+ .add("expirationMs", LongType)
+ .add("groupingKey", new StructType(groupingKeySchema.fields))
+ .add("userKey", new StructType(userKeySchema.fields))
+
+ def getValueSchemaWithTTL(schema: StructType, hasTTL: Boolean): StructType = {
+ if (hasTTL) {
+ new StructType().add("value", schema)
+ .add("ttlExpirationMs", LongType)
+ } else schema
+ }
}
/**
@@ -46,68 +68,42 @@ object TransformWithStateKeyValueRowSchema {
* key and state value respectively. As UnsafeProjection is not thread safe, this
* class is also not thread safe.
*
- * @param keySerializer - serializer to serialize the grouping key of type `GK`
- * to an [[InternalRow]]
+ * @param keyEncoder - SQL encoder for the grouping key, key type is implicit
* @param valEncoder - SQL encoder for value of type `S`
* @param stateName - name of logical state partition
- * @tparam GK - grouping key type
* @tparam V - value type
*/
-class StateTypesEncoder[GK, V](
- keySerializer: Serializer[GK],
+class StateTypesEncoder[V](
+ keyEncoder: ExpressionEncoder[Any],
valEncoder: Encoder[V],
stateName: String,
hasTtl: Boolean) {
- import org.apache.spark.sql.execution.streaming.TransformWithStateKeyValueRowSchema._
-
- /** Variables reused for conversions between byte array and UnsafeRow */
- private val keyProjection = UnsafeProjection.create(KEY_ROW_SCHEMA)
- private val valueProjection = if (hasTtl) {
- UnsafeProjection.create(VALUE_ROW_SCHEMA_WITH_TTL)
- } else {
- UnsafeProjection.create(VALUE_ROW_SCHEMA)
- }
/** Variables reused for value conversions between spark sql and object */
+ private val keySerializer = keyEncoder.createSerializer()
private val valExpressionEnc = encoderFor(valEncoder)
private val objToRowSerializer = valExpressionEnc.createSerializer()
private val rowToObjDeserializer = valExpressionEnc.resolveAndBind().createDeserializer()
- private val reusedValRow = new UnsafeRow(valEncoder.schema.fields.length)
+ // This variable is only used when has Ttl is true
+ private val valueTTLProjection =
+ UnsafeProjection.create(getValueSchemaWithTTL(valEncoder.schema, true))
// TODO: validate places that are trying to encode the key and check if we can eliminate/
// add caching for some of these calls.
def encodeGroupingKey(): UnsafeRow = {
- val keyRow = keyProjection(InternalRow(serializeGroupingKey()))
- keyRow
- }
-
- /**
- * Encodes the provided grouping key into Spark UnsafeRow.
- *
- * @param groupingKeyBytes serialized grouping key byte array
- * @return encoded UnsafeRow
- */
- def encodeSerializedGroupingKey(groupingKeyBytes: Array[Byte]): UnsafeRow = {
- val keyRow = keyProjection(InternalRow(groupingKeyBytes))
- keyRow
- }
-
- def serializeGroupingKey(): Array[Byte] = {
val keyOption = ImplicitGroupingKeyTracker.getImplicitKeyOption
if (keyOption.isEmpty) {
throw StateStoreErrors.implicitKeyNotFound(stateName)
}
- val groupingKey = keyOption.get.asInstanceOf[GK]
- keySerializer.apply(groupingKey).asInstanceOf[UnsafeRow].getBytes()
+
+ keySerializer.apply(keyOption.get).asInstanceOf[UnsafeRow]
}
/**
* Encode the specified value in Spark UnsafeRow with no ttl.
*/
def encodeValue(value: V): UnsafeRow = {
- val objRow: InternalRow = objToRowSerializer.apply(value)
- val bytes = objRow.asInstanceOf[UnsafeRow].getBytes()
- valueProjection(InternalRow(bytes))
+ objToRowSerializer.apply(value).asInstanceOf[UnsafeRow]
}
/**
@@ -116,15 +112,13 @@ class StateTypesEncoder[GK, V](
*/
def encodeValue(value: V, expirationMs: Long): UnsafeRow = {
val objRow: InternalRow = objToRowSerializer.apply(value)
- val bytes = objRow.asInstanceOf[UnsafeRow].getBytes()
- valueProjection(InternalRow(bytes, expirationMs))
+ valueTTLProjection.apply(InternalRow(objRow, expirationMs))
}
def decodeValue(row: UnsafeRow): V = {
- val bytes = row.getBinary(0)
- reusedValRow.pointTo(bytes, bytes.length)
- val value = rowToObjDeserializer.apply(reusedValRow)
- value
+ if (hasTtl) {
+ rowToObjDeserializer.apply(row.getStruct(0, valEncoder.schema.length))
+ } else rowToObjDeserializer.apply(row)
}
/**
@@ -150,71 +144,89 @@ class StateTypesEncoder[GK, V](
}
object StateTypesEncoder {
- def apply[GK, V](
- keySerializer: Serializer[GK],
+ def apply[V](
+ keyEncoder: ExpressionEncoder[Any],
valEncoder: Encoder[V],
stateName: String,
- hasTtl: Boolean = false): StateTypesEncoder[GK, V] = {
- new StateTypesEncoder[GK, V](keySerializer, valEncoder, stateName, hasTtl)
+ hasTtl: Boolean = false): StateTypesEncoder[V] = {
+ new StateTypesEncoder[V](keyEncoder, valEncoder, stateName, hasTtl)
}
}
-class CompositeKeyStateEncoder[GK, K, V](
- keySerializer: Serializer[GK],
+class CompositeKeyStateEncoder[K, V](
+ keyEncoder: ExpressionEncoder[Any],
userKeyEnc: Encoder[K],
valEncoder: Encoder[V],
- schemaForCompositeKeyRow: StructType,
stateName: String,
hasTtl: Boolean = false)
- extends StateTypesEncoder[GK, V](keySerializer, valEncoder, stateName, hasTtl) {
+ extends StateTypesEncoder[V](keyEncoder, valEncoder, stateName, hasTtl) {
+ import org.apache.spark.sql.execution.streaming.TransformWithStateKeyValueRowSchemaUtils._
- private val compositeKeyProjection = UnsafeProjection.create(schemaForCompositeKeyRow)
- private val reusedKeyRow = new UnsafeRow(userKeyEnc.schema.fields.length)
+ /** Encoders */
private val userKeyExpressionEnc = encoderFor(userKeyEnc)
+ /** Schema */
+ private val schemaForGroupingKeyRow = new StructType().add("key", keyEncoder.schema)
+ private val schemaForUserKeyRow = new StructType().add("userKey", userKeyEnc.schema)
+ private val schemaForCompositeKeyRow =
+ getCompositeKeySchema(keyEncoder.schema, userKeyEnc.schema)
+
+ /** Projection */
+ private val userKeyProjection = UnsafeProjection.create(schemaForUserKeyRow)
+ private val groupingKeyProjection = UnsafeProjection.create(schemaForGroupingKeyRow)
+ private val compositeKeyProjection = UnsafeProjection.create(schemaForCompositeKeyRow)
+
+ /** Serializer */
+ private val groupingKeySerializer = keyEncoder.createSerializer()
+ private val userKeySerializer = userKeyExpressionEnc.createSerializer()
+
+ /** Deserializer */
private val userKeyRowToObjDeserializer =
userKeyExpressionEnc.resolveAndBind().createDeserializer()
- private val userKeySerializer = encoderFor(userKeyEnc).createSerializer()
- /**
- * Grouping key and user key are encoded as a row of `schemaForCompositeKeyRow` schema.
- * Grouping key will be encoded in `RocksDBStateEncoder` as the prefix column.
- */
- def encodeCompositeKey(userKey: K): UnsafeRow = {
+ override def encodeGroupingKey(): UnsafeRow = {
val keyOption = ImplicitGroupingKeyTracker.getImplicitKeyOption
if (keyOption.isEmpty) {
throw StateStoreErrors.implicitKeyNotFound(stateName)
}
- val groupingKey = keyOption.get.asInstanceOf[GK]
- // generate grouping key byte array
- val groupingKeyByteArr = keySerializer.apply(groupingKey).asInstanceOf[UnsafeRow].getBytes()
- // generate user key byte array
- val userKeyBytesArr = userKeySerializer.apply(userKey).asInstanceOf[UnsafeRow].getBytes()
+ val groupingKey = keyOption.get
+ val groupingKeyRow = groupingKeySerializer.apply(groupingKey)
- val compositeKeyRow = compositeKeyProjection(InternalRow(groupingKeyByteArr, userKeyBytesArr))
- compositeKeyRow
+ // Create the final unsafeRow mapping column name "key" to the keyRow
+ groupingKeyProjection(InternalRow(groupingKeyRow))
}
- def decodeUserKeyFromTTLRow(row: CompositeKeyTTLRow): K = {
- val bytes = row.userKey
- reusedKeyRow.pointTo(bytes, bytes.length)
- val userKey = userKeyRowToObjDeserializer.apply(reusedKeyRow)
- userKey
+ def encodeUserKey(userKey: K): UnsafeRow = {
+ val userKeyRow = userKeySerializer.apply(userKey)
+
+ // Create the final unsafeRow mapping column name "userKey" to the userKeyRow
+ userKeyProjection(InternalRow(userKeyRow))
}
/**
* Grouping key and user key are encoded as a row of `schemaForCompositeKeyRow` schema.
* Grouping key will be encoded in `RocksDBStateEncoder` as the prefix column.
*/
- def encodeCompositeKey(
- groupingKeyByteArr: Array[Byte],
- userKeyByteArr: Array[Byte]): UnsafeRow = {
- val compositeKeyRow = compositeKeyProjection(InternalRow(groupingKeyByteArr, userKeyByteArr))
- compositeKeyRow
+ def encodeCompositeKey(userKey: K): UnsafeRow = {
+ val keyOption = ImplicitGroupingKeyTracker.getImplicitKeyOption
+ if (keyOption.isEmpty) {
+ throw StateStoreErrors.implicitKeyNotFound(stateName)
+ }
+ val groupingKey = keyOption.get
+
+ val keyRow = groupingKeySerializer.apply(groupingKey)
+ val userKeyRow = userKeySerializer.apply(userKey)
+
+ // Create the final unsafeRow combining the keyRow and userKeyRow
+ compositeKeyProjection(InternalRow(keyRow, userKeyRow))
+ }
+
+ def encodeCompositeKey(groupingKey: UnsafeRow, userKey: UnsafeRow): UnsafeRow = {
+ compositeKeyProjection(InternalRow(groupingKey, userKey))
}
- def serializeUserKey(userKey: K): Array[Byte] = {
- userKeySerializer.apply(userKey).asInstanceOf[UnsafeRow].getBytes
+ def decodeUserKey(row: UnsafeRow): K = {
+ userKeyRowToObjDeserializer.apply(row)
}
/**
@@ -222,9 +234,82 @@ class CompositeKeyStateEncoder[GK, K, V](
* Only user key is returned though grouping key also exist in the row.
*/
def decodeCompositeKey(row: UnsafeRow): K = {
- val bytes = row.getBinary(1)
- reusedKeyRow.pointTo(bytes, bytes.length)
- val userKey = userKeyRowToObjDeserializer.apply(reusedKeyRow)
- userKey
+ userKeyRowToObjDeserializer.apply(row.getStruct(1, userKeyEnc.schema.length))
+ }
+}
+
+/** Class for TTL with single key serialization */
+class SingleKeyTTLEncoder(
+ keyExprEnc: ExpressionEncoder[Any]) {
+
+ private val ttlKeyProjection = UnsafeProjection.create(
+ getSingleKeyTTLRowSchema(keyExprEnc.schema))
+
+ def encodeTTLRow(expirationMs: Long, groupingKey: UnsafeRow): UnsafeRow = {
+ ttlKeyProjection.apply(
+ InternalRow(expirationMs, groupingKey.asInstanceOf[InternalRow]))
+ }
+}
+
+/** Class for TTL with composite key serialization */
+class CompositeKeyTTLEncoder[K](
+ keyExprEnc: ExpressionEncoder[Any],
+ userKeyEnc: Encoder[K]) {
+
+ private val ttlKeyProjection = UnsafeProjection.create(
+ getCompositeKeyTTLRowSchema(keyExprEnc.schema, userKeyEnc.schema))
+
+ def encodeTTLRow(
+ expirationMs: Long,
+ groupingKey: UnsafeRow,
+ userKey: UnsafeRow): UnsafeRow = {
+ ttlKeyProjection.apply(
+ InternalRow(
+ expirationMs,
+ groupingKey.getStruct(0, keyExprEnc.schema.length)
+ .asInstanceOf[InternalRow],
+ userKey.getStruct(0, userKeyEnc.schema.length)
+ .asInstanceOf[InternalRow]))
+ }
+}
+
+/** Class for timer state serialization */
+class TimerKeyEncoder(keyExprEnc: ExpressionEncoder[Any]) {
+ private val schemaForPrefixKey: StructType =
+ new StructType()
+ .add("key", new StructType(keyExprEnc.schema.fields))
+
+ val keySchemaForSecIndex: StructType =
+ new StructType()
+ .add("expiryTimestampMs", LongType, nullable = false)
+ .add("key", new StructType(keyExprEnc.schema.fields))
+
+ val schemaForKeyRow: StructType = new StructType()
+ .add("key", new StructType(keyExprEnc.schema.fields))
+ .add("expiryTimestampMs", LongType, nullable = false)
+
+ private val keySerializer = keyExprEnc.createSerializer()
+ private val keyDeserializer = keyExprEnc.resolveAndBind().createDeserializer()
+ private val prefixKeyProjection = UnsafeProjection.create(schemaForPrefixKey)
+ private val keyRowProjection = UnsafeProjection.create(schemaForKeyRow)
+ private val secIndexKeyProjection = UnsafeProjection.create(keySchemaForSecIndex)
+
+ def encodedKey(groupingKey: Any, expiryTimestampMs: Long): UnsafeRow = {
+ val keyRow = keySerializer.apply(groupingKey)
+ keyRowProjection.apply(InternalRow(keyRow, expiryTimestampMs))
+ }
+
+ def encodeSecIndexKey(groupingKey: Any, expiryTimestampMs: Long): UnsafeRow = {
+ val keyRow = keySerializer.apply(groupingKey)
+ secIndexKeyProjection.apply(InternalRow(expiryTimestampMs, keyRow))
+ }
+
+ def encodePrefixKey(groupingKey: Any): UnsafeRow = {
+ val keyRow = keySerializer.apply(groupingKey)
+ prefixKeyProjection.apply(InternalRow(keyRow))
+ }
+
+ def decodePrefixKey(retUnsafeRow: UnsafeRow): Any = {
+ keyDeserializer.apply(retUnsafeRow)
}
}
diff --git a/sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/StatefulProcessorHandleImpl.scala b/sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/StatefulProcessorHandleImpl.scala
index 277e1516425d..3031faa35b2d 100644
--- a/sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/StatefulProcessorHandleImpl.scala
+++ b/sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/StatefulProcessorHandleImpl.scala
@@ -87,7 +87,7 @@ class StatefulProcessorHandleImpl(
isStreaming: Boolean = true,
batchTimestampMs: Option[Long] = None,
metrics: Map[String, SQLMetric] = Map.empty)
- extends StatefulProcessorHandleImplBase(timeMode) with Logging {
+ extends StatefulProcessorHandleImplBase(timeMode, keyEncoder) with Logging {
import StatefulProcessorHandleState._
/**
@@ -297,8 +297,8 @@ class StatefulProcessorHandleImpl(
* actually done. We need this class because we can only collect the schemas after
* the StatefulProcessor is initialized.
*/
-class DriverStatefulProcessorHandleImpl(timeMode: TimeMode)
- extends StatefulProcessorHandleImplBase(timeMode) {
+class DriverStatefulProcessorHandleImpl(timeMode: TimeMode, keyExprEnc: ExpressionEncoder[Any])
+ extends StatefulProcessorHandleImplBase(timeMode, keyExprEnc) {
private[sql] val columnFamilySchemaUtils = ColumnFamilySchemaUtilsV1
@@ -312,7 +312,7 @@ class DriverStatefulProcessorHandleImpl(timeMode: TimeMode)
override def getValueState[T](stateName: String, valEncoder: Encoder[T]): ValueState[T] = {
verifyStateVarOperations("get_value_state", PRE_INIT)
val colFamilySchema = columnFamilySchemaUtils.
- getValueStateSchema(stateName, false)
+ getValueStateSchema(stateName, keyExprEnc, valEncoder, false)
columnFamilySchemas.put(stateName, colFamilySchema)
null.asInstanceOf[ValueState[T]]
}
@@ -323,7 +323,7 @@ class DriverStatefulProcessorHandleImpl(timeMode: TimeMode)
ttlConfig: TTLConfig): ValueState[T] = {
verifyStateVarOperations("get_value_state", PRE_INIT)
val colFamilySchema = columnFamilySchemaUtils.
- getValueStateSchema(stateName, true)
+ getValueStateSchema(stateName, keyExprEnc, valEncoder, true)
columnFamilySchemas.put(stateName, colFamilySchema)
null.asInstanceOf[ValueState[T]]
}
@@ -331,7 +331,7 @@ class DriverStatefulProcessorHandleImpl(timeMode: TimeMode)
override def getListState[T](stateName: String, valEncoder: Encoder[T]): ListState[T] = {
verifyStateVarOperations("get_list_state", PRE_INIT)
val colFamilySchema = columnFamilySchemaUtils.
- getListStateSchema(stateName, false)
+ getListStateSchema(stateName, keyExprEnc, valEncoder, false)
columnFamilySchemas.put(stateName, colFamilySchema)
null.asInstanceOf[ListState[T]]
}
@@ -342,7 +342,7 @@ class DriverStatefulProcessorHandleImpl(timeMode: TimeMode)
ttlConfig: TTLConfig): ListState[T] = {
verifyStateVarOperations("get_list_state", PRE_INIT)
val colFamilySchema = columnFamilySchemaUtils.
- getListStateSchema(stateName, true)
+ getListStateSchema(stateName, keyExprEnc, valEncoder, true)
columnFamilySchemas.put(stateName, colFamilySchema)
null.asInstanceOf[ListState[T]]
}
@@ -353,7 +353,7 @@ class DriverStatefulProcessorHandleImpl(timeMode: TimeMode)
valEncoder: Encoder[V]): MapState[K, V] = {
verifyStateVarOperations("get_map_state", PRE_INIT)
val colFamilySchema = columnFamilySchemaUtils.
- getMapStateSchema(stateName, userKeyEnc, false)
+ getMapStateSchema(stateName, keyExprEnc, userKeyEnc, valEncoder, false)
columnFamilySchemas.put(stateName, colFamilySchema)
null.asInstanceOf[MapState[K, V]]
}
@@ -365,7 +365,7 @@ class DriverStatefulProcessorHandleImpl(timeMode: TimeMode)
ttlConfig: TTLConfig): MapState[K, V] = {
verifyStateVarOperations("get_map_state", PRE_INIT)
val colFamilySchema = columnFamilySchemaUtils.
- getMapStateSchema(stateName, userKeyEnc, true)
+ getMapStateSchema(stateName, keyExprEnc, userKeyEnc, valEncoder, true)
columnFamilySchemas.put(stateName, colFamilySchema)
null.asInstanceOf[MapState[K, V]]
}
diff --git a/sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/StatefulProcessorHandleImplBase.scala b/sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/StatefulProcessorHandleImplBase.scala
index 3b952967e35d..64d87073ccf9 100644
--- a/sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/StatefulProcessorHandleImplBase.scala
+++ b/sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/StatefulProcessorHandleImplBase.scala
@@ -16,13 +16,14 @@
*/
package org.apache.spark.sql.execution.streaming
+import org.apache.spark.sql.catalyst.encoders.ExpressionEncoder
import org.apache.spark.sql.catalyst.plans.logical.NoTime
import org.apache.spark.sql.execution.streaming.StatefulProcessorHandleState.{INITIALIZED, PRE_INIT, StatefulProcessorHandleState, TIMER_PROCESSED}
import org.apache.spark.sql.execution.streaming.state.StateStoreErrors
import org.apache.spark.sql.streaming.{StatefulProcessorHandle, TimeMode}
-abstract class StatefulProcessorHandleImplBase(timeMode: TimeMode)
- extends StatefulProcessorHandle {
+abstract class StatefulProcessorHandleImplBase(
+ timeMode: TimeMode, keyExprEnc: ExpressionEncoder[Any]) extends StatefulProcessorHandle {
protected var currState: StatefulProcessorHandleState = PRE_INIT
diff --git a/sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/TTLState.scala b/sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/TTLState.scala
index 02efcefe19ca..6065af10ffe8 100644
--- a/sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/TTLState.scala
+++ b/sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/TTLState.scala
@@ -18,19 +18,15 @@ package org.apache.spark.sql.execution.streaming
import java.time.Duration
+import org.apache.spark.sql.Encoder
import org.apache.spark.sql.catalyst.InternalRow
-import org.apache.spark.sql.catalyst.expressions.UnsafeProjection
+import org.apache.spark.sql.catalyst.encoders.ExpressionEncoder
+import org.apache.spark.sql.catalyst.expressions.{UnsafeProjection, UnsafeRow}
+import org.apache.spark.sql.execution.streaming.TransformWithStateKeyValueRowSchemaUtils._
import org.apache.spark.sql.execution.streaming.state.{RangeKeyScanStateEncoderSpec, StateStore}
-import org.apache.spark.sql.types.{BinaryType, DataType, LongType, NullType, StructField, StructType}
+import org.apache.spark.sql.types._
object StateTTLSchema {
- val TTL_KEY_ROW_SCHEMA: StructType = new StructType()
- .add("expirationMs", LongType)
- .add("groupingKey", BinaryType)
- val TTL_COMPOSITE_KEY_ROW_SCHEMA: StructType = new StructType()
- .add("expirationMs", LongType)
- .add("groupingKey", BinaryType)
- .add("userKey", BinaryType)
val TTL_VALUE_ROW_SCHEMA: StructType =
StructType(Array(StructField("__dummy__", NullType)))
}
@@ -42,7 +38,7 @@ object StateTTLSchema {
* @param expirationMs expiration time for the grouping key
*/
case class SingleKeyTTLRow(
- groupingKey: Array[Byte],
+ groupingKey: UnsafeRow,
expirationMs: Long)
/**
@@ -53,8 +49,8 @@ case class SingleKeyTTLRow(
* @param expirationMs expiration time for the grouping key
*/
case class CompositeKeyTTLRow(
- groupingKey: Array[Byte],
- userKey: Array[Byte],
+ groupingKey: UnsafeRow,
+ userKey: UnsafeRow,
expirationMs: Long)
/**
@@ -83,20 +79,22 @@ trait TTLState {
abstract class SingleKeyTTLStateImpl(
stateName: String,
store: StateStore,
+ keyExprEnc: ExpressionEncoder[Any],
ttlExpirationMs: Long)
extends TTLState {
import org.apache.spark.sql.execution.streaming.StateTTLSchema._
private val ttlColumnFamilyName = s"_ttl_$stateName"
- private val ttlKeyEncoder = UnsafeProjection.create(TTL_KEY_ROW_SCHEMA)
+ private val keySchema = getSingleKeyTTLRowSchema(keyExprEnc.schema)
+ private val keyTTLRowEncoder = new SingleKeyTTLEncoder(keyExprEnc)
// empty row used for values
private val EMPTY_ROW =
UnsafeProjection.create(Array[DataType](NullType)).apply(InternalRow.apply(null))
- store.createColFamilyIfAbsent(ttlColumnFamilyName, TTL_KEY_ROW_SCHEMA, TTL_VALUE_ROW_SCHEMA,
- RangeKeyScanStateEncoderSpec(TTL_KEY_ROW_SCHEMA, Seq(0)), isInternal = true)
+ store.createColFamilyIfAbsent(ttlColumnFamilyName, keySchema, TTL_VALUE_ROW_SCHEMA,
+ RangeKeyScanStateEncoderSpec(keySchema, Seq(0)), isInternal = true)
/**
* This function will be called when clear() on State Variables
@@ -112,8 +110,9 @@ abstract class SingleKeyTTLStateImpl(
def upsertTTLForStateKey(
expirationMs: Long,
- groupingKey: Array[Byte]): Unit = {
- val encodedTtlKey = ttlKeyEncoder(InternalRow(expirationMs, groupingKey))
+ groupingKey: UnsafeRow): Unit = {
+ val encodedTtlKey = keyTTLRowEncoder.encodeTTLRow(
+ expirationMs, groupingKey)
store.put(encodedTtlKey, EMPTY_ROW, ttlColumnFamilyName)
}
@@ -128,7 +127,7 @@ abstract class SingleKeyTTLStateImpl(
val expirationMs = kv.key.getLong(0)
StateTTL.isExpired(expirationMs, ttlExpirationMs)
}.foreach { kv =>
- val groupingKey = kv.key.getBinary(1)
+ val groupingKey = kv.key.getStruct(1, keyExprEnc.schema.length)
numValuesExpired += clearIfExpired(groupingKey)
store.remove(kv.key, ttlColumnFamilyName)
}
@@ -145,13 +144,13 @@ abstract class SingleKeyTTLStateImpl(
val kv = ttlIterator.next()
SingleKeyTTLRow(
expirationMs = kv.key.getLong(0),
- groupingKey = kv.key.getBinary(1)
+ groupingKey = kv.key.getStruct(1, keyExprEnc.schema.length)
)
}
}
}
- private[sql] def getValuesInTTLState(groupingKey: Array[Byte]): Iterator[Long] = {
+ private[sql] def getValuesInTTLState(groupingKey: UnsafeRow): Iterator[Long] = {
val ttlIterator = ttlIndexIterator()
var nextValue: Option[Long] = None
@@ -160,7 +159,7 @@ abstract class SingleKeyTTLStateImpl(
while (nextValue.isEmpty && ttlIterator.hasNext) {
val nextTtlValue = ttlIterator.next()
val valueGroupingKey = nextTtlValue.groupingKey
- if (valueGroupingKey sameElements groupingKey) {
+ if (valueGroupingKey equals groupingKey) {
nextValue = Some(nextTtlValue.expirationMs)
}
}
@@ -190,29 +189,36 @@ abstract class SingleKeyTTLStateImpl(
*
* @return true if the state was cleared, false otherwise.
*/
- def clearIfExpired(groupingKey: Array[Byte]): Long
+ def clearIfExpired(groupingKey: UnsafeRow): Long
}
/**
* Manages the ttl information for user state keyed with a single key (grouping key).
*/
-abstract class CompositeKeyTTLStateImpl(
+abstract class CompositeKeyTTLStateImpl[K](
stateName: String,
store: StateStore,
+ keyExprEnc: ExpressionEncoder[Any],
+ userKeyEncoder: Encoder[K],
ttlExpirationMs: Long)
extends TTLState {
import org.apache.spark.sql.execution.streaming.StateTTLSchema._
private val ttlColumnFamilyName = s"_ttl_$stateName"
- private val ttlKeyEncoder = UnsafeProjection.create(TTL_COMPOSITE_KEY_ROW_SCHEMA)
+ private val keySchema = getCompositeKeyTTLRowSchema(
+ keyExprEnc.schema, userKeyEncoder.schema
+ )
+
+ private val keyRowEncoder = new CompositeKeyTTLEncoder[K](
+ keyExprEnc, userKeyEncoder)
// empty row used for values
private val EMPTY_ROW =
UnsafeProjection.create(Array[DataType](NullType)).apply(InternalRow.apply(null))
- store.createColFamilyIfAbsent(ttlColumnFamilyName, TTL_COMPOSITE_KEY_ROW_SCHEMA,
- TTL_VALUE_ROW_SCHEMA, RangeKeyScanStateEncoderSpec(TTL_COMPOSITE_KEY_ROW_SCHEMA,
+ store.createColFamilyIfAbsent(ttlColumnFamilyName, keySchema,
+ TTL_VALUE_ROW_SCHEMA, RangeKeyScanStateEncoderSpec(keySchema,
Seq(0)), isInternal = true)
def clearTTLState(): Unit = {
@@ -224,9 +230,10 @@ abstract class CompositeKeyTTLStateImpl(
def upsertTTLForStateKey(
expirationMs: Long,
- groupingKey: Array[Byte],
- userKey: Array[Byte]): Unit = {
- val encodedTtlKey = ttlKeyEncoder(InternalRow(expirationMs, groupingKey, userKey))
+ groupingKey: UnsafeRow,
+ userKey: UnsafeRow): Unit = {
+ val encodedTtlKey = keyRowEncoder.encodeTTLRow(
+ expirationMs, groupingKey, userKey)
store.put(encodedTtlKey, EMPTY_ROW, ttlColumnFamilyName)
}
@@ -240,9 +247,9 @@ abstract class CompositeKeyTTLStateImpl(
val expirationMs = kv.key.getLong(0)
StateTTL.isExpired(expirationMs, ttlExpirationMs)
}.foreach { kv =>
- val groupingKey = kv.key.getBinary(1)
- val userKey = kv.key.getBinary(2)
- numRemovedElements += clearIfExpired(groupingKey, userKey)
+ numRemovedElements += clearIfExpired(
+ kv.key.getStruct(1, keyExprEnc.schema.length),
+ kv.key.getStruct(2, userKeyEncoder.schema.length))
store.remove(kv.key, ttlColumnFamilyName)
}
numRemovedElements
@@ -258,8 +265,8 @@ abstract class CompositeKeyTTLStateImpl(
val kv = ttlIterator.next()
CompositeKeyTTLRow(
expirationMs = kv.key.getLong(0),
- groupingKey = kv.key.getBinary(1),
- userKey = kv.key.getBinary(2)
+ groupingKey = kv.key.getStruct(1, keyExprEnc.schema.length),
+ userKey = kv.key.getStruct(2, userKeyEncoder.schema.length)
)
}
}
@@ -279,7 +286,8 @@ abstract class CompositeKeyTTLStateImpl(
* @param groupingKey grouping key for which cleanup should be performed.
* @param userKey user key for which cleanup should be performed.
*/
- def clearIfExpired(groupingKey: Array[Byte], userKey: Array[Byte]): Long
+ def clearIfExpired(groupingKeyRow: UnsafeRow,
+ userKeyRow: UnsafeRow): Long
}
/**
diff --git a/sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/TimerStateImpl.scala b/sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/TimerStateImpl.scala
index a9c5a70e995d..650f57039a03 100644
--- a/sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/TimerStateImpl.scala
+++ b/sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/TimerStateImpl.scala
@@ -51,39 +51,26 @@ class TimerStateImpl(
private val EMPTY_ROW =
UnsafeProjection.create(Array[DataType](NullType)).apply(InternalRow.apply(null))
- private val schemaForPrefixKey: StructType = new StructType()
- .add("key", BinaryType)
-
- private val schemaForKeyRow: StructType = new StructType()
- .add("key", BinaryType)
- .add("expiryTimestampMs", LongType, nullable = false)
-
- private val keySchemaForSecIndex: StructType = new StructType()
- .add("expiryTimestampMs", LongType, nullable = false)
- .add("key", BinaryType)
-
private val schemaForValueRow: StructType =
StructType(Array(StructField("__dummy__", NullType)))
- private val keySerializer = keyExprEnc.createSerializer()
-
- private val prefixKeyEncoder = UnsafeProjection.create(schemaForPrefixKey)
-
- private val keyEncoder = UnsafeProjection.create(schemaForKeyRow)
-
- private val secIndexKeyEncoder = UnsafeProjection.create(keySchemaForSecIndex)
-
private val timerCFName = if (timeMode == TimeMode.ProcessingTime) {
TimerStateUtils.PROC_TIMERS_STATE_NAME
} else {
TimerStateUtils.EVENT_TIMERS_STATE_NAME
}
+ private val rowEncoder = new TimerKeyEncoder(keyExprEnc)
+
+ private val schemaForKeyRow = rowEncoder.schemaForKeyRow
private val keyToTsCFName = timerCFName + TimerStateUtils.KEY_TO_TIMESTAMP_CF
store.createColFamilyIfAbsent(keyToTsCFName, schemaForKeyRow,
schemaForValueRow, PrefixKeyScanStateEncoderSpec(schemaForKeyRow, 1),
useMultipleValuesPerKey = false, isInternal = true)
+ // We maintain a secondary index that inverts the ordering of the timestamp
+ // and grouping key
+ private val keySchemaForSecIndex = rowEncoder.keySchemaForSecIndex
private val tsToKeyCFName = timerCFName + TimerStateUtils.TIMESTAMP_TO_KEY_CF
store.createColFamilyIfAbsent(tsToKeyCFName, keySchemaForSecIndex,
schemaForValueRow, RangeKeyScanStateEncoderSpec(keySchemaForSecIndex, Seq(0)),
@@ -97,20 +84,6 @@ class TimerStateImpl(
keyOption.get
}
- private def encodeKey(groupingKey: Any, expiryTimestampMs: Long): UnsafeRow = {
- val keyByteArr = keySerializer.apply(groupingKey).asInstanceOf[UnsafeRow].getBytes()
- val keyRow = keyEncoder(InternalRow(keyByteArr, expiryTimestampMs))
- keyRow
- }
-
- // We maintain a secondary index that inverts the ordering of the timestamp
- // and grouping key
- private def encodeSecIndexKey(groupingKey: Any, expiryTimestampMs: Long): UnsafeRow = {
- val keyByteArr = keySerializer.apply(groupingKey).asInstanceOf[UnsafeRow].getBytes()
- val keyRow = secIndexKeyEncoder(InternalRow(expiryTimestampMs, keyByteArr))
- keyRow
- }
-
/**
* Function to check if the timer for the given key and timestamp is already registered
* @param expiryTimestampMs - expiry timestamp of the timer
@@ -121,7 +94,7 @@ class TimerStateImpl(
}
private def getImpl(groupingKey: Any, expiryTimestampMs: Long): UnsafeRow = {
- store.get(encodeKey(groupingKey, expiryTimestampMs), keyToTsCFName)
+ store.get(rowEncoder.encodedKey(groupingKey, expiryTimestampMs), keyToTsCFName)
}
/**
@@ -134,8 +107,9 @@ class TimerStateImpl(
logWarning(log"Failed to register timer for key=${MDC(KEY, groupingKey)} and " +
log"timestamp=${MDC(EXPIRY_TIMESTAMP, expiryTimestampMs)} ms since it already exists")
} else {
- store.put(encodeKey(groupingKey, expiryTimestampMs), EMPTY_ROW, keyToTsCFName)
- store.put(encodeSecIndexKey(groupingKey, expiryTimestampMs), EMPTY_ROW, tsToKeyCFName)
+ store.put(rowEncoder.encodedKey(groupingKey, expiryTimestampMs), EMPTY_ROW, keyToTsCFName)
+ store.put(rowEncoder.encodeSecIndexKey(groupingKey, expiryTimestampMs),
+ EMPTY_ROW, tsToKeyCFName)
logDebug(s"Registered timer for key=$groupingKey and timestamp=$expiryTimestampMs")
}
}
@@ -151,17 +125,17 @@ class TimerStateImpl(
logWarning(log"Failed to delete timer for key=${MDC(KEY, groupingKey)} and " +
log"timestamp=${MDC(EXPIRY_TIMESTAMP, expiryTimestampMs)} ms since it does not exist")
} else {
- store.remove(encodeKey(groupingKey, expiryTimestampMs), keyToTsCFName)
- store.remove(encodeSecIndexKey(groupingKey, expiryTimestampMs), tsToKeyCFName)
+ store.remove(rowEncoder.encodedKey(groupingKey, expiryTimestampMs), keyToTsCFName)
+ store.remove(rowEncoder.encodeSecIndexKey(groupingKey, expiryTimestampMs), tsToKeyCFName)
logDebug(s"Deleted timer for key=$groupingKey and timestamp=$expiryTimestampMs")
}
}
def listTimers(): Iterator[Long] = {
- val keyByteArr = keySerializer.apply(getGroupingKey(keyToTsCFName))
- .asInstanceOf[UnsafeRow].getBytes()
- val keyRow = prefixKeyEncoder(InternalRow(keyByteArr))
- val iter = store.prefixScan(keyRow, keyToTsCFName)
+ val groupingKey = getGroupingKey(keyToTsCFName)
+ val encodedGroupingKey: UnsafeRow = rowEncoder.encodePrefixKey(groupingKey)
+
+ val iter = store.prefixScan(encodedGroupingKey, keyToTsCFName)
iter.map { kv =>
val keyRow = kv.key
keyRow.getLong(1)
@@ -170,11 +144,8 @@ class TimerStateImpl(
private def getTimerRowFromSecIndex(keyRow: UnsafeRow): (Any, Long) = {
// Decode the key object from the UnsafeRow
- val keyBytes = keyRow.getBinary(1)
- val retUnsafeRow = new UnsafeRow(1)
- retUnsafeRow.pointTo(keyBytes, keyBytes.length)
- val keyObj = keyExprEnc.resolveAndBind()
- .createDeserializer().apply(retUnsafeRow).asInstanceOf[Any]
+ val retUnsafeRow = keyRow.getStruct(1, keyExprEnc.schema.length)
+ val keyObj = rowEncoder.decodePrefixKey(retUnsafeRow)
val expiryTimestampMs = keyRow.getLong(0)
(keyObj, expiryTimestampMs)
diff --git a/sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/TransformWithStateExec.scala b/sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/TransformWithStateExec.scala
index 6af0126efdf8..9014878178a1 100644
--- a/sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/TransformWithStateExec.scala
+++ b/sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/TransformWithStateExec.scala
@@ -31,10 +31,10 @@ import org.apache.spark.sql.catalyst.plans.logical._
import org.apache.spark.sql.catalyst.plans.physical.Distribution
import org.apache.spark.sql.execution._
import org.apache.spark.sql.execution.streaming.StreamingSymmetricHashJoinHelper.StateStoreAwareZipPartitionsHelper
-import org.apache.spark.sql.execution.streaming.TransformWithStateKeyValueRowSchema.{KEY_ROW_SCHEMA, VALUE_ROW_SCHEMA}
import org.apache.spark.sql.execution.streaming.state._
import org.apache.spark.sql.internal.SQLConf
import org.apache.spark.sql.streaming._
+import org.apache.spark.sql.types.{BinaryType, StructType}
import org.apache.spark.util.{CompletionIterator, SerializableConfiguration, Utils}
/**
@@ -80,6 +80,9 @@ case class TransformWithStateExec(
override def shortName: String = "transformWithStateExec"
+ // dummy value schema, the real schema will get during state variable init time
+ private val DUMMY_VALUE_ROW_SCHEMA = new StructType().add("value", BinaryType)
+
override def shouldRunAnotherBatch(newInputWatermark: Long): Boolean = {
if (timeMode == ProcessingTime) {
// TODO: check if we can return true only if actual timers are registered, or there is
@@ -99,7 +102,7 @@ case class TransformWithStateExec(
* @return a new instance of the driver processor handle
*/
private def getDriverProcessorHandle(): DriverStatefulProcessorHandleImpl = {
- val driverProcessorHandle = new DriverStatefulProcessorHandleImpl(timeMode)
+ val driverProcessorHandle = new DriverStatefulProcessorHandleImpl(timeMode, keyEncoder)
driverProcessorHandle.setHandleState(StatefulProcessorHandleState.PRE_INIT)
statefulProcessor.setHandle(driverProcessorHandle)
statefulProcessor.init(outputMode, timeMode)
@@ -439,9 +442,9 @@ case class TransformWithStateExec(
val storeProviderId = StateStoreProviderId(stateStoreId, stateInfo.get.queryRunId)
val store = StateStore.get(
storeProviderId = storeProviderId,
- KEY_ROW_SCHEMA,
- VALUE_ROW_SCHEMA,
- NoPrefixKeyStateEncoderSpec(KEY_ROW_SCHEMA),
+ keyEncoder.schema,
+ DUMMY_VALUE_ROW_SCHEMA,
+ NoPrefixKeyStateEncoderSpec(keyEncoder.schema),
version = stateInfo.get.storeVersion,
useColumnFamilies = true,
storeConf = storeConf,
@@ -459,9 +462,9 @@ case class TransformWithStateExec(
if (isStreaming) {
child.execute().mapPartitionsWithStateStore[InternalRow](
getStateInfo,
- KEY_ROW_SCHEMA,
- VALUE_ROW_SCHEMA,
- NoPrefixKeyStateEncoderSpec(KEY_ROW_SCHEMA),
+ keyEncoder.schema,
+ DUMMY_VALUE_ROW_SCHEMA,
+ NoPrefixKeyStateEncoderSpec(keyEncoder.schema),
session.sessionState,
Some(session.streams.stateStoreCoordinator),
useColumnFamilies = true
@@ -509,9 +512,9 @@ case class TransformWithStateExec(
// Create StateStoreProvider for this partition
val stateStoreProvider = StateStoreProvider.createAndInit(
providerId,
- KEY_ROW_SCHEMA,
- VALUE_ROW_SCHEMA,
- NoPrefixKeyStateEncoderSpec(KEY_ROW_SCHEMA),
+ keyEncoder.schema,
+ DUMMY_VALUE_ROW_SCHEMA,
+ NoPrefixKeyStateEncoderSpec(keyEncoder.schema),
useColumnFamilies = true,
storeConf = storeConf,
hadoopConf = hadoopConfBroadcast.value.value,
diff --git a/sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/ValueStateImpl.scala b/sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/ValueStateImpl.scala
index d916011245c0..63cac4a3b68c 100644
--- a/sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/ValueStateImpl.scala
+++ b/sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/ValueStateImpl.scala
@@ -19,7 +19,6 @@ package org.apache.spark.sql.execution.streaming
import org.apache.spark.internal.Logging
import org.apache.spark.sql.Encoder
import org.apache.spark.sql.catalyst.encoders.ExpressionEncoder
-import org.apache.spark.sql.execution.streaming.TransformWithStateKeyValueRowSchema.{KEY_ROW_SCHEMA, VALUE_ROW_SCHEMA}
import org.apache.spark.sql.execution.streaming.state.{NoPrefixKeyStateEncoderSpec, StateStore}
import org.apache.spark.sql.streaming.ValueState
@@ -39,14 +38,13 @@ class ValueStateImpl[S](
valEncoder: Encoder[S])
extends ValueState[S] with Logging {
- private val keySerializer = keyExprEnc.createSerializer()
- private val stateTypesEncoder = StateTypesEncoder(keySerializer, valEncoder, stateName)
+ private val stateTypesEncoder = StateTypesEncoder(keyExprEnc, valEncoder, stateName)
initialize()
private def initialize(): Unit = {
- store.createColFamilyIfAbsent(stateName, KEY_ROW_SCHEMA, VALUE_ROW_SCHEMA,
- NoPrefixKeyStateEncoderSpec(KEY_ROW_SCHEMA))
+ store.createColFamilyIfAbsent(stateName, keyExprEnc.schema, valEncoder.schema,
+ NoPrefixKeyStateEncoderSpec(keyExprEnc.schema))
}
/** Function to check if state exists. Returns true if present and false otherwise */
@@ -74,8 +72,7 @@ class ValueStateImpl[S](
/** Function to update and overwrite state associated with given key */
override def update(newState: S): Unit = {
val encodedValue = stateTypesEncoder.encodeValue(newState)
- val serializedGroupingKey = stateTypesEncoder.serializeGroupingKey()
- store.put(stateTypesEncoder.encodeSerializedGroupingKey(serializedGroupingKey),
+ store.put(stateTypesEncoder.encodeGroupingKey(),
encodedValue, stateName)
}
diff --git a/sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/ValueStateImplWithTTL.scala b/sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/ValueStateImplWithTTL.scala
index 0ed5a6f29a98..c6d11b155866 100644
--- a/sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/ValueStateImplWithTTL.scala
+++ b/sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/ValueStateImplWithTTL.scala
@@ -18,7 +18,8 @@ package org.apache.spark.sql.execution.streaming
import org.apache.spark.sql.Encoder
import org.apache.spark.sql.catalyst.encoders.ExpressionEncoder
-import org.apache.spark.sql.execution.streaming.TransformWithStateKeyValueRowSchema.{KEY_ROW_SCHEMA, VALUE_ROW_SCHEMA_WITH_TTL}
+import org.apache.spark.sql.catalyst.expressions.UnsafeRow
+import org.apache.spark.sql.execution.streaming.TransformWithStateKeyValueRowSchemaUtils._
import org.apache.spark.sql.execution.streaming.state.{NoPrefixKeyStateEncoderSpec, StateStore}
import org.apache.spark.sql.streaming.{TTLConfig, ValueState}
@@ -41,10 +42,10 @@ class ValueStateImplWithTTL[S](
valEncoder: Encoder[S],
ttlConfig: TTLConfig,
batchTimestampMs: Long)
- extends SingleKeyTTLStateImpl(stateName, store, batchTimestampMs) with ValueState[S] {
+ extends SingleKeyTTLStateImpl(
+ stateName, store, keyExprEnc, batchTimestampMs) with ValueState[S] {
- private val keySerializer = keyExprEnc.createSerializer()
- private val stateTypesEncoder = StateTypesEncoder(keySerializer, valEncoder,
+ private val stateTypesEncoder = StateTypesEncoder(keyExprEnc, valEncoder,
stateName, hasTtl = true)
private val ttlExpirationMs =
StateTTL.calculateExpirationTimeForDuration(ttlConfig.ttlDuration, batchTimestampMs)
@@ -52,8 +53,9 @@ class ValueStateImplWithTTL[S](
initialize()
private def initialize(): Unit = {
- store.createColFamilyIfAbsent(stateName, KEY_ROW_SCHEMA, VALUE_ROW_SCHEMA_WITH_TTL,
- NoPrefixKeyStateEncoderSpec(KEY_ROW_SCHEMA))
+ store.createColFamilyIfAbsent(stateName,
+ keyExprEnc.schema, getValueSchemaWithTTL(valEncoder.schema, true),
+ NoPrefixKeyStateEncoderSpec(keyExprEnc.schema))
}
/** Function to check if state exists. Returns true if present and false otherwise */
@@ -87,8 +89,8 @@ class ValueStateImplWithTTL[S](
/** Function to update and overwrite state associated with given key */
override def update(newState: S): Unit = {
val encodedValue = stateTypesEncoder.encodeValue(newState, ttlExpirationMs)
- val serializedGroupingKey = stateTypesEncoder.serializeGroupingKey()
- store.put(stateTypesEncoder.encodeSerializedGroupingKey(serializedGroupingKey),
+ val serializedGroupingKey = stateTypesEncoder.encodeGroupingKey()
+ store.put(serializedGroupingKey,
encodedValue, stateName)
upsertTTLForStateKey(ttlExpirationMs, serializedGroupingKey)
}
@@ -99,14 +101,13 @@ class ValueStateImplWithTTL[S](
clearTTLState()
}
- def clearIfExpired(groupingKey: Array[Byte]): Long = {
- val encodedGroupingKey = stateTypesEncoder.encodeSerializedGroupingKey(groupingKey)
- val retRow = store.get(encodedGroupingKey, stateName)
+ def clearIfExpired(groupingKey: UnsafeRow): Long = {
+ val retRow = store.get(groupingKey, stateName)
var result = 0L
if (retRow != null) {
if (stateTypesEncoder.isExpired(retRow, batchTimestampMs)) {
- store.remove(encodedGroupingKey, stateName)
+ store.remove(groupingKey, stateName)
result = 1L
}
}
@@ -158,7 +159,7 @@ class ValueStateImplWithTTL[S](
* grouping key.
*/
private[sql] def getValuesInTTLState(): Iterator[Long] = {
- getValuesInTTLState(stateTypesEncoder.serializeGroupingKey())
+ getValuesInTTLState(stateTypesEncoder.encodeGroupingKey())
}
}
diff --git a/sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/state/StateSchemaV3File.scala b/sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/state/StateSchemaV3File.scala
index 38e648472812..482e802b7d87 100644
--- a/sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/state/StateSchemaV3File.scala
+++ b/sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/state/StateSchemaV3File.scala
@@ -50,7 +50,7 @@ class StateSchemaV3File(
fileManager.mkdirs(metadataPath)
}
- private def deserialize(in: InputStream): List[ColumnFamilySchema] = {
+ private[sql] def deserialize(in: InputStream): List[ColumnFamilySchema] = {
val lines = IOSource.fromInputStream(in, UTF_8.name()).getLines()
if (!lines.hasNext) {
@@ -63,7 +63,7 @@ class StateSchemaV3File(
lines.map(ColumnFamilySchemaV1.fromJson).toList
}
- private def serialize(schemas: List[ColumnFamilySchema], out: OutputStream): Unit = {
+ private[sql] def serialize(schemas: List[ColumnFamilySchema], out: OutputStream): Unit = {
out.write(s"v${StateSchemaV3File.VERSION}".getBytes(UTF_8))
out.write('\n')
out.write(schemas.map(_.json).mkString("\n").getBytes(UTF_8))
diff --git a/sql/core/src/test/scala/org/apache/spark/sql/execution/streaming/state/ListStateSuite.scala b/sql/core/src/test/scala/org/apache/spark/sql/execution/streaming/state/ListStateSuite.scala
index 1e6136fd38a3..48816486cbd0 100644
--- a/sql/core/src/test/scala/org/apache/spark/sql/execution/streaming/state/ListStateSuite.scala
+++ b/sql/core/src/test/scala/org/apache/spark/sql/execution/streaming/state/ListStateSuite.scala
@@ -244,4 +244,32 @@ class ListStateSuite extends StateVariableSuiteBase {
}
}
}
+
+ test("ListState TTL with non-primitive types") {
+ tryWithProviderResource(newStoreProviderWithStateVariable(true)) { provider =>
+ val store = provider.getStore(0)
+ val timestampMs = 10
+ val handle = new StatefulProcessorHandleImpl(store, UUID.randomUUID(),
+ Encoders.bean(classOf[POJOTestClass]).asInstanceOf[ExpressionEncoder[Any]],
+ TimeMode.ProcessingTime(), batchTimestampMs = Some(timestampMs))
+
+ val ttlConfig = TTLConfig(ttlDuration = Duration.ofMinutes(1))
+ val testState: ListStateImplWithTTL[TestClass] =
+ handle.getListState[TestClass]("testState",
+ Encoders.product[TestClass], ttlConfig).asInstanceOf[ListStateImplWithTTL[TestClass]]
+ ImplicitGroupingKeyTracker.setImplicitKey(new POJOTestClass("gk1", 1))
+ testState.put(Array(TestClass(1L, "v1"), TestClass(2L, "v2"), TestClass(3L, "v3")))
+ assert(testState.get().toSeq ===
+ Seq(TestClass(1L, "v1"), TestClass(2L, "v2"), TestClass(3L, "v3")))
+ assert(testState.getWithoutEnforcingTTL().toSeq ===
+ Seq(TestClass(1L, "v1"), TestClass(2L, "v2"), TestClass(3L, "v3")))
+
+ val ttlExpirationMs = timestampMs + 60000
+ val ttlValues = testState.getTTLValues()
+ assert(ttlValues.nonEmpty)
+ assert(ttlValues.forall(_._2 === ttlExpirationMs))
+ val ttlStateValueIterator = testState.getValuesInTTLState()
+ assert(ttlStateValueIterator.hasNext)
+ }
+ }
}
diff --git a/sql/core/src/test/scala/org/apache/spark/sql/execution/streaming/state/MapStateSuite.scala b/sql/core/src/test/scala/org/apache/spark/sql/execution/streaming/state/MapStateSuite.scala
index 5b304c55dd5a..b5ba25518a5e 100644
--- a/sql/core/src/test/scala/org/apache/spark/sql/execution/streaming/state/MapStateSuite.scala
+++ b/sql/core/src/test/scala/org/apache/spark/sql/execution/streaming/state/MapStateSuite.scala
@@ -32,7 +32,7 @@ import org.apache.spark.sql.types.{BinaryType, StructType}
* operators such as transformWithState
*/
class MapStateSuite extends StateVariableSuiteBase {
- // Overwrite Key schema as MapState use composite key
+ // dummy schema for initializing rocksdb provider
override def schemaForKeyRow: StructType = new StructType()
.add("key", BinaryType)
.add("userKey", BinaryType)
@@ -255,4 +255,34 @@ class MapStateSuite extends StateVariableSuiteBase {
}
}
}
+
+ test("Map state with TTL with non-primitive types") {
+ tryWithProviderResource(newStoreProviderWithStateVariable(true)) { provider =>
+ val store = provider.getStore(0)
+ val timestampMs = 10
+ val handle = new StatefulProcessorHandleImpl(store, UUID.randomUUID(),
+ Encoders.STRING.asInstanceOf[ExpressionEncoder[Any]], TimeMode.ProcessingTime(),
+ batchTimestampMs = Some(timestampMs))
+
+ val ttlConfig = TTLConfig(ttlDuration = Duration.ofMinutes(1))
+ val testState: MapStateImplWithTTL[POJOTestClass, TestClass] =
+ handle.getMapState[POJOTestClass, TestClass]("testState",
+ Encoders.bean(classOf[POJOTestClass]),
+ Encoders.product[TestClass], ttlConfig)
+ .asInstanceOf[MapStateImplWithTTL[POJOTestClass, TestClass]]
+
+ ImplicitGroupingKeyTracker.setImplicitKey("testKey")
+ testState.updateValue(new POJOTestClass("k1", 1), TestClass(1L, "v1"))
+ assert(testState.getValue(new POJOTestClass("k1", 1)) === TestClass(1L, "v1"))
+ assert(testState.getWithoutEnforcingTTL(
+ new POJOTestClass("k1", 1)).get === TestClass(1L, "v1"))
+
+ val ttlExpirationMs = timestampMs + 60000
+ val ttlValue = testState.getTTLValue(new POJOTestClass("k1", 1))
+ assert(ttlValue.isDefined)
+ assert(ttlValue.get._2 === ttlExpirationMs)
+ val ttlStateValueIterator = testState.getKeyValuesInTTLState().map(_._2)
+ assert(ttlStateValueIterator.hasNext)
+ }
+ }
}
diff --git a/sql/core/src/test/scala/org/apache/spark/sql/execution/streaming/state/StateStoreSuite.scala b/sql/core/src/test/scala/org/apache/spark/sql/execution/streaming/state/StateStoreSuite.scala
index 2c4111ec026a..1e7bffe7ca4d 100644
--- a/sql/core/src/test/scala/org/apache/spark/sql/execution/streaming/state/StateStoreSuite.scala
+++ b/sql/core/src/test/scala/org/apache/spark/sql/execution/streaming/state/StateStoreSuite.scala
@@ -43,7 +43,6 @@ import org.apache.spark.sql.catalyst.expressions.{GenericInternalRow, UnsafeProj
import org.apache.spark.sql.catalyst.util.quietly
import org.apache.spark.sql.execution.streaming._
import org.apache.spark.sql.execution.streaming.state.StateStoreCoordinatorSuite.withCoordinatorRef
-import org.apache.spark.sql.execution.streaming.state.StateStoreValueRowFormatValidationFailure
import org.apache.spark.sql.functions.count
import org.apache.spark.sql.internal.SQLConf
import org.apache.spark.sql.types._
diff --git a/sql/core/src/test/scala/org/apache/spark/sql/execution/streaming/state/TimerSuite.scala b/sql/core/src/test/scala/org/apache/spark/sql/execution/streaming/state/TimerSuite.scala
index 0bf160d8b321..df6a3fd7b23e 100644
--- a/sql/core/src/test/scala/org/apache/spark/sql/execution/streaming/state/TimerSuite.scala
+++ b/sql/core/src/test/scala/org/apache/spark/sql/execution/streaming/state/TimerSuite.scala
@@ -165,4 +165,23 @@ class TimerSuite extends StateVariableSuiteBase {
(timerTimestamps1 ++ timerTimestamps2 ++ timerTimerStamps3).sorted.takeWhile(_ < 8000L))
}
}
+
+ testWithTimeMode("Timer state operations with non-primitive type") { timeMode =>
+ tryWithProviderResource(newStoreProviderWithStateVariable(true)) { provider =>
+ val store = provider.getStore(0)
+ ImplicitGroupingKeyTracker.setImplicitKey(TestClass(1L, "k1"))
+ val timerState = new TimerStateImpl(store, timeMode,
+ Encoders.product[TestClass].asInstanceOf[ExpressionEncoder[Any]])
+
+ timerState.registerTimer(1L * 1000)
+ assert(timerState.listTimers().toSet === Set(1000L))
+ assert(timerState.getExpiredTimers(Long.MaxValue).toSeq === Seq((TestClass(1L, "k1"), 1000L)))
+ assert(timerState.getExpiredTimers(Long.MinValue).toSeq === Seq.empty[Long])
+
+ timerState.registerTimer(20L * 1000)
+ assert(timerState.listTimers().toSet === Set(20000L, 1000L))
+ timerState.deleteTimer(20000L)
+ assert(timerState.listTimers().toSet === Set(1000L))
+ }
+ }
}
diff --git a/sql/core/src/test/scala/org/apache/spark/sql/execution/streaming/state/ValueStateSuite.scala b/sql/core/src/test/scala/org/apache/spark/sql/execution/streaming/state/ValueStateSuite.scala
index e5875da947a3..7d5b3e4a6bdc 100644
--- a/sql/core/src/test/scala/org/apache/spark/sql/execution/streaming/state/ValueStateSuite.scala
+++ b/sql/core/src/test/scala/org/apache/spark/sql/execution/streaming/state/ValueStateSuite.scala
@@ -387,6 +387,33 @@ class ValueStateSuite extends StateVariableSuiteBase {
}
}
}
+
+ test("Value state TTL with non-primitive type") {
+ tryWithProviderResource(newStoreProviderWithStateVariable(true)) { provider =>
+ val store = provider.getStore(0)
+ val timestampMs = 10
+ val handle = new StatefulProcessorHandleImpl(store, UUID.randomUUID(),
+ Encoders.product[TestClass].asInstanceOf[ExpressionEncoder[Any]], TimeMode.ProcessingTime(),
+ batchTimestampMs = Some(timestampMs))
+
+ val ttlConfig = TTLConfig(ttlDuration = Duration.ofMinutes(1))
+ val testState: ValueStateImplWithTTL[POJOTestClass] =
+ handle.getValueState[POJOTestClass]("testState",
+ Encoders.bean(classOf[POJOTestClass]), ttlConfig)
+ .asInstanceOf[ValueStateImplWithTTL[POJOTestClass]]
+ ImplicitGroupingKeyTracker.setImplicitKey(TestClass(1L, "k1"))
+ testState.update(new POJOTestClass("n1", 1))
+ assert(testState.get() === new POJOTestClass("n1", 1))
+ assert(testState.getWithoutEnforcingTTL().get === new POJOTestClass("n1", 1))
+
+ val ttlExpirationMs = timestampMs + 60000
+ val ttlValue = testState.getTTLValue()
+ assert(ttlValue.isDefined)
+ assert(ttlValue.get._2 === ttlExpirationMs)
+ val ttlStateValueIterator = testState.getValuesInTTLState()
+ assert(ttlStateValueIterator.hasNext)
+ }
+ }
}
/**
@@ -410,6 +437,7 @@ abstract class StateVariableSuiteBase extends SharedSparkSession
import StateStoreTestsHelper._
+ // dummy schema for initializing rocksdb provider
protected def schemaForKeyRow: StructType = new StructType().add("key", BinaryType)
protected def schemaForValueRow: StructType = new StructType().add("value", BinaryType)
diff --git a/sql/core/src/test/scala/org/apache/spark/sql/streaming/TransformWithStateSuite.scala b/sql/core/src/test/scala/org/apache/spark/sql/streaming/TransformWithStateSuite.scala
index f71967d25993..c649dad76092 100644
--- a/sql/core/src/test/scala/org/apache/spark/sql/streaming/TransformWithStateSuite.scala
+++ b/sql/core/src/test/scala/org/apache/spark/sql/streaming/TransformWithStateSuite.scala
@@ -20,16 +20,18 @@ package org.apache.spark.sql.streaming
import java.io.File
import java.util.UUID
+import org.apache.hadoop.fs.Path
+
import org.apache.spark.SparkRuntimeException
import org.apache.spark.internal.Logging
import org.apache.spark.sql.{Dataset, Encoders}
import org.apache.spark.sql.catalyst.util.stringToFile
import org.apache.spark.sql.execution.streaming._
-import org.apache.spark.sql.execution.streaming.TransformWithStateKeyValueRowSchema.{KEY_ROW_SCHEMA, VALUE_ROW_SCHEMA}
-import org.apache.spark.sql.execution.streaming.state.{AlsoTestWithChangelogCheckpointingEnabled, ColumnFamilySchemaV1, NoPrefixKeyStateEncoderSpec, RocksDBStateStoreProvider, StatefulProcessorCannotPerformOperationWithInvalidHandleState, StateSchemaV3File, StateStoreMultipleColumnFamiliesNotSupportedException}
+import org.apache.spark.sql.execution.streaming.state.{AlsoTestWithChangelogCheckpointingEnabled, ColumnFamilySchemaV1, NoPrefixKeyStateEncoderSpec, POJOTestClass, PrefixKeyScanStateEncoderSpec, RocksDBStateStoreProvider, StatefulProcessorCannotPerformOperationWithInvalidHandleState, StateSchemaV3File, StateStoreMultipleColumnFamiliesNotSupportedException, TestClass}
import org.apache.spark.sql.functions.timestamp_seconds
import org.apache.spark.sql.internal.SQLConf
import org.apache.spark.sql.streaming.util.StreamManualClock
+import org.apache.spark.sql.types.{IntegerType, LongType, StringType, StructType}
object TransformWithStateSuiteUtils {
val NUM_SHUFFLE_PARTITIONS = 5
@@ -306,6 +308,22 @@ class RunningCountStatefulProcessorWithError extends RunningCountStatefulProcess
}
}
+// class for verify state schema is correctly written for all state var types
+class StatefulProcessorWithCompositeTypes extends RunningCountStatefulProcessor {
+ @transient private var _listState: ListState[TestClass] = _
+ @transient private var _mapState: MapState[POJOTestClass, String] = _
+
+ override def init(
+ outputMode: OutputMode,
+ timeMode: TimeMode): Unit = {
+ _countState = getHandle.getValueState[Long]("countState", Encoders.scalaLong)
+ _listState = getHandle.getListState[TestClass](
+ "listState", Encoders.product[TestClass])
+ _mapState = getHandle.getMapState[POJOTestClass, String](
+ "mapState", Encoders.bean(classOf[POJOTestClass]), Encoders.STRING)
+ }
+}
+
/**
* Class that adds tests for transformWithState stateful streaming operator
*/
@@ -794,11 +812,13 @@ class TransformWithStateSuite extends StateStoreMetricsTest
SQLConf.SHUFFLE_PARTITIONS.key ->
TransformWithStateSuiteUtils.NUM_SHUFFLE_PARTITIONS.toString) {
withTempDir { checkpointDir =>
+ val testKeyEncoder = Encoders.STRING
+ val testValueEncoder = Encoders.scalaInt
val schema = List(ColumnFamilySchemaV1(
"countState",
- KEY_ROW_SCHEMA,
- VALUE_ROW_SCHEMA,
- NoPrefixKeyStateEncoderSpec(KEY_ROW_SCHEMA),
+ testKeyEncoder.schema,
+ testValueEncoder.schema,
+ NoPrefixKeyStateEncoderSpec(testKeyEncoder.schema),
None
))
@@ -818,28 +838,29 @@ class TransformWithStateSuite extends StateStoreMetricsTest
SQLConf.SHUFFLE_PARTITIONS.key ->
TransformWithStateSuiteUtils.NUM_SHUFFLE_PARTITIONS.toString) {
withTempDir { checkpointDir =>
-
+ val testKeyEncoder = Encoders.STRING
+ val testValueEncoder = Encoders.scalaInt
val schema0 = List(ColumnFamilySchemaV1(
"countState",
- KEY_ROW_SCHEMA,
- VALUE_ROW_SCHEMA,
- NoPrefixKeyStateEncoderSpec(KEY_ROW_SCHEMA),
+ testKeyEncoder.schema,
+ testValueEncoder.schema,
+ NoPrefixKeyStateEncoderSpec(testKeyEncoder.schema),
None
))
val schema1 = List(
ColumnFamilySchemaV1(
"countState",
- KEY_ROW_SCHEMA,
- VALUE_ROW_SCHEMA,
- NoPrefixKeyStateEncoderSpec(KEY_ROW_SCHEMA),
+ testKeyEncoder.schema,
+ testValueEncoder.schema,
+ NoPrefixKeyStateEncoderSpec(testKeyEncoder.schema),
None
),
ColumnFamilySchemaV1(
"mostRecent",
- KEY_ROW_SCHEMA,
- VALUE_ROW_SCHEMA,
- NoPrefixKeyStateEncoderSpec(KEY_ROW_SCHEMA),
+ testKeyEncoder.schema,
+ testValueEncoder.schema,
+ NoPrefixKeyStateEncoderSpec(testKeyEncoder.schema),
None
)
)
@@ -859,6 +880,84 @@ class TransformWithStateSuite extends StateStoreMetricsTest
}
}
}
+
+ test("transformWithState - verify StateSchemaV3 writes correct SQL schema of key/value") {
+ withSQLConf(SQLConf.STATE_STORE_PROVIDER_CLASS.key ->
+ classOf[RocksDBStateStoreProvider].getName,
+ SQLConf.SHUFFLE_PARTITIONS.key ->
+ TransformWithStateSuiteUtils.NUM_SHUFFLE_PARTITIONS.toString) {
+ withTempDir { checkpointDir =>
+ val metadataPathPostfix = "state/0/default/_metadata"
+ val stateSchemaPath = new Path(checkpointDir.toString,
+ s"$metadataPathPostfix/schema")
+ val hadoopConf = spark.sessionState.newHadoopConf()
+ val fm = CheckpointFileManager.create(stateSchemaPath, hadoopConf)
+
+ val keySchema = new StructType().add("value", StringType)
+ val schema0 = ColumnFamilySchemaV1(
+ "countState",
+ keySchema,
+ new StructType().add("value", LongType, false),
+ NoPrefixKeyStateEncoderSpec(keySchema),
+ None
+ )
+ val schema1 = ColumnFamilySchemaV1(
+ "listState",
+ keySchema,
+ new StructType()
+ .add("id", LongType, false)
+ .add("name", StringType),
+ NoPrefixKeyStateEncoderSpec(keySchema),
+ None
+ )
+
+ val userKeySchema = new StructType()
+ .add("id", IntegerType, false)
+ .add("name", StringType)
+ val compositeKeySchema = new StructType()
+ .add("key", new StructType().add("value", StringType))
+ .add("userKey", userKeySchema)
+ val schema2 = ColumnFamilySchemaV1(
+ "mapState",
+ compositeKeySchema,
+ new StructType().add("value", StringType),
+ PrefixKeyScanStateEncoderSpec(compositeKeySchema, 1),
+ Option(userKeySchema)
+ )
+
+ val inputData = MemoryStream[String]
+ val result = inputData.toDS()
+ .groupByKey(x => x)
+ .transformWithState(new StatefulProcessorWithCompositeTypes(),
+ TimeMode.None(),
+ OutputMode.Update())
+
+ testStream(result, OutputMode.Update())(
+ StartStream(checkpointLocation = checkpointDir.getCanonicalPath),
+ AddData(inputData, "a", "b"),
+ CheckNewAnswer(("a", "1"), ("b", "1")),
+ Execute { q =>
+ val schemaFilePath = fm.list(stateSchemaPath).toSeq.head.getPath
+ val schemaFile = new StateSchemaV3File(hadoopConf, stateSchemaPath.getName)
+ val colFamilySeq = schemaFile.deserialize(fm.open(schemaFilePath))
+
+ assert(TransformWithStateSuiteUtils.NUM_SHUFFLE_PARTITIONS ==
+ q.lastProgress.stateOperators.head.customMetrics.get("numValueStateVars").toInt)
+ assert(TransformWithStateSuiteUtils.NUM_SHUFFLE_PARTITIONS ==
+ q.lastProgress.stateOperators.head.customMetrics.get("numListStateVars").toInt)
+ assert(TransformWithStateSuiteUtils.NUM_SHUFFLE_PARTITIONS ==
+ q.lastProgress.stateOperators.head.customMetrics.get("numMapStateVars").toInt)
+
+ assert(colFamilySeq.length == 3)
+ assert(colFamilySeq.map(_.toString).toSet == Set(
+ schema0, schema1, schema2
+ ).map(_.toString))
+ },
+ StopStream
+ )
+ }
+ }
+ }
}
class TransformWithStateValidationSuite extends StateStoreMetricsTest {
diff --git a/sql/core/src/test/scala/org/apache/spark/sql/streaming/TransformWithValueStateTTLSuite.scala b/sql/core/src/test/scala/org/apache/spark/sql/streaming/TransformWithValueStateTTLSuite.scala
index 54004b419f75..6e6d4de94701 100644
--- a/sql/core/src/test/scala/org/apache/spark/sql/streaming/TransformWithValueStateTTLSuite.scala
+++ b/sql/core/src/test/scala/org/apache/spark/sql/streaming/TransformWithValueStateTTLSuite.scala
@@ -19,12 +19,15 @@ package org.apache.spark.sql.streaming
import java.time.Duration
+import org.apache.hadoop.fs.Path
+
import org.apache.spark.internal.Logging
import org.apache.spark.sql.Encoders
-import org.apache.spark.sql.execution.streaming.{MemoryStream, ValueStateImpl, ValueStateImplWithTTL}
-import org.apache.spark.sql.execution.streaming.state.RocksDBStateStoreProvider
+import org.apache.spark.sql.execution.streaming.{CheckpointFileManager, ListStateImplWithTTL, MapStateImplWithTTL, MemoryStream, ValueStateImpl, ValueStateImplWithTTL}
+import org.apache.spark.sql.execution.streaming.state.{ColumnFamilySchemaV1, NoPrefixKeyStateEncoderSpec, POJOTestClass, PrefixKeyScanStateEncoderSpec, RocksDBStateStoreProvider, StateSchemaV3File, TestClass}
import org.apache.spark.sql.internal.SQLConf
import org.apache.spark.sql.streaming.util.StreamManualClock
+import org.apache.spark.sql.types._
object TTLInputProcessFunction {
def processRow(
@@ -111,21 +114,21 @@ class ValueStateTTLProcessor(ttlConfig: TTLConfig)
}
}
-case class MultipleValueStatesTTLProcessor(
+class MultipleValueStatesTTLProcessor(
ttlKey: String,
noTtlKey: String,
ttlConfig: TTLConfig)
extends StatefulProcessor[String, InputEvent, OutputEvent]
with Logging {
- @transient private var _valueStateWithTTL: ValueStateImplWithTTL[Int] = _
- @transient private var _valueStateWithoutTTL: ValueStateImpl[Int] = _
+ @transient var _valueStateWithTTL: ValueStateImplWithTTL[Int] = _
+ @transient var _valueStateWithoutTTL: ValueStateImpl[Int] = _
override def init(
outputMode: OutputMode,
timeMode: TimeMode): Unit = {
_valueStateWithTTL = getHandle
- .getValueState("valueState", Encoders.scalaInt, ttlConfig)
+ .getValueState("valueStateTTL", Encoders.scalaInt, ttlConfig)
.asInstanceOf[ValueStateImplWithTTL[Int]]
_valueStateWithoutTTL = getHandle
.getValueState("valueState", Encoders.scalaInt)
@@ -160,6 +163,29 @@ case class MultipleValueStatesTTLProcessor(
}
}
+// Class to verify state schema is correctly written for state vars.
+class TTLProcessorWithCompositeTypes(
+ ttlKey: String,
+ noTtlKey: String,
+ ttlConfig: TTLConfig)
+ extends MultipleValueStatesTTLProcessor(ttlKey, noTtlKey, ttlConfig) {
+ @transient private var _listStateWithTTL: ListStateImplWithTTL[TestClass] = _
+ @transient private var _mapStateWithTTL: MapStateImplWithTTL[POJOTestClass, String] = _
+
+ override def init(
+ outputMode: OutputMode,
+ timeMode: TimeMode): Unit = {
+ super.init(outputMode, timeMode)
+ _listStateWithTTL = getHandle
+ .getListState("listState", Encoders.product[TestClass], ttlConfig)
+ .asInstanceOf[ListStateImplWithTTL[TestClass]]
+ _mapStateWithTTL = getHandle
+ .getMapState("mapState", Encoders.bean(classOf[POJOTestClass]),
+ Encoders.STRING, ttlConfig)
+ .asInstanceOf[MapStateImplWithTTL[POJOTestClass, String]]
+ }
+}
+
class TransformWithValueStateTTLSuite extends TransformWithStateTTLTest {
import testImplicits._
@@ -181,7 +207,7 @@ class TransformWithValueStateTTLSuite extends TransformWithStateTTLTest {
val result = inputStream.toDS()
.groupByKey(x => x.key)
.transformWithState(
- MultipleValueStatesTTLProcessor(ttlKey, noTtlKey, ttlConfig),
+ new MultipleValueStatesTTLProcessor(ttlKey, noTtlKey, ttlConfig),
TimeMode.ProcessingTime(),
OutputMode.Append())
@@ -225,4 +251,111 @@ class TransformWithValueStateTTLSuite extends TransformWithStateTTLTest {
)
}
}
+
+ test("verify StateSchemaV3 writes correct SQL schema of key/value and with TTL") {
+ withSQLConf(SQLConf.STATE_STORE_PROVIDER_CLASS.key ->
+ classOf[RocksDBStateStoreProvider].getName,
+ SQLConf.SHUFFLE_PARTITIONS.key ->
+ TransformWithStateSuiteUtils.NUM_SHUFFLE_PARTITIONS.toString) {
+ withTempDir { checkpointDir =>
+ val metadataPathPostfix = "state/0/default/_metadata"
+ val stateSchemaPath = new Path(checkpointDir.toString,
+ s"$metadataPathPostfix/schema")
+ val hadoopConf = spark.sessionState.newHadoopConf()
+ val fm = CheckpointFileManager.create(stateSchemaPath, hadoopConf)
+
+ val keySchema = new StructType().add("value", StringType)
+ val schema0 = ColumnFamilySchemaV1(
+ "valueStateTTL",
+ keySchema,
+ new StructType().add("value",
+ new StructType()
+ .add("value", IntegerType, false))
+ .add("ttlExpirationMs", LongType),
+ NoPrefixKeyStateEncoderSpec(keySchema),
+ None
+ )
+ val schema1 = ColumnFamilySchemaV1(
+ "valueState",
+ keySchema,
+ new StructType().add("value", IntegerType, false),
+ NoPrefixKeyStateEncoderSpec(keySchema),
+ None
+ )
+ val schema2 = ColumnFamilySchemaV1(
+ "listState",
+ keySchema,
+ new StructType().add("value",
+ new StructType()
+ .add("id", LongType, false)
+ .add("name", StringType))
+ .add("ttlExpirationMs", LongType),
+ NoPrefixKeyStateEncoderSpec(keySchema),
+ None
+ )
+
+ val userKeySchema = new StructType()
+ .add("id", IntegerType, false)
+ .add("name", StringType)
+ val compositeKeySchema = new StructType()
+ .add("key", new StructType().add("value", StringType))
+ .add("userKey", userKeySchema)
+ val schema3 = ColumnFamilySchemaV1(
+ "mapState",
+ compositeKeySchema,
+ new StructType().add("value",
+ new StructType()
+ .add("value", StringType))
+ .add("ttlExpirationMs", LongType),
+ PrefixKeyScanStateEncoderSpec(compositeKeySchema, 1),
+ Option(userKeySchema)
+ )
+
+ val ttlKey = "k1"
+ val noTtlKey = "k2"
+ val ttlConfig = TTLConfig(ttlDuration = Duration.ofMinutes(1))
+ val inputStream = MemoryStream[InputEvent]
+ val result = inputStream.toDS()
+ .groupByKey(x => x.key)
+ .transformWithState(
+ new TTLProcessorWithCompositeTypes(ttlKey, noTtlKey, ttlConfig),
+ TimeMode.ProcessingTime(),
+ OutputMode.Append())
+
+ val clock = new StreamManualClock
+ testStream(result)(
+ StartStream(Trigger.ProcessingTime("1 second"), triggerClock = clock,
+ checkpointLocation = checkpointDir.getCanonicalPath),
+ AddData(inputStream, InputEvent(ttlKey, "put", 1)),
+ AddData(inputStream, InputEvent(noTtlKey, "put", 2)),
+ // advance clock to trigger processing
+ AdvanceManualClock(1 * 1000),
+ CheckNewAnswer(),
+ Execute { q =>
+ val schemaFilePath = fm.list(stateSchemaPath).toSeq.head.getPath
+ val schemaFile = new StateSchemaV3File(hadoopConf, stateSchemaPath.getName)
+ val colFamilySeq = schemaFile.deserialize(fm.open(schemaFilePath))
+
+ assert(TransformWithStateSuiteUtils.NUM_SHUFFLE_PARTITIONS ==
+ q.lastProgress.stateOperators.head.customMetrics.get("numValueStateVars").toInt)
+ assert(TransformWithStateSuiteUtils.NUM_SHUFFLE_PARTITIONS ==
+ q.lastProgress.stateOperators.head.customMetrics
+ .get("numValueStateWithTTLVars").toInt)
+ assert(TransformWithStateSuiteUtils.NUM_SHUFFLE_PARTITIONS ==
+ q.lastProgress.stateOperators.head.customMetrics
+ .get("numListStateWithTTLVars").toInt)
+ assert(TransformWithStateSuiteUtils.NUM_SHUFFLE_PARTITIONS ==
+ q.lastProgress.stateOperators.head.customMetrics
+ .get("numMapStateWithTTLVars").toInt)
+
+ assert(colFamilySeq.length == 4)
+ assert(colFamilySeq.map(_.toString).toSet == Set(
+ schema0, schema1, schema2, schema3
+ ).map(_.toString))
+ },
+ StopStream
+ )
+ }
+ }
+ }
}
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@spark.apache.org
For additional commands, e-mail: commits-help@spark.apache.org