sahnib commented on code in PR #45674:
URL: https://github.com/apache/spark/pull/45674#discussion_r1548800286


##########
sql/core/src/test/scala/org/apache/spark/sql/streaming/TransformWithStateTTLSuite.scala:
##########
@@ -0,0 +1,579 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.spark.sql.streaming
+
+import java.sql.Timestamp
+import java.time.Duration
+
+import org.apache.spark.internal.Logging
+import org.apache.spark.sql.Encoders
+import org.apache.spark.sql.execution.streaming.{MemoryStream, 
ValueStateImplWithTTL}
+import org.apache.spark.sql.execution.streaming.state.RocksDBStateStoreProvider
+import org.apache.spark.sql.internal.SQLConf
+import org.apache.spark.sql.streaming.util.StreamManualClock
+
+case class InputEvent(
+    key: String,
+    action: String,
+    value: Int,
+    ttl: Duration,
+    eventTime: Timestamp = null,
+    eventTimeTtl: Timestamp = null)
+
+case class OutputEvent(
+    key: String,
+    value: Int,
+    isTTLValue: Boolean,
+    ttlValue: Long)
+
+object TTLInputProcessFunction {
+  def processRow(
+      ttlMode: TTLMode,
+      row: InputEvent,
+      valueState: ValueStateImplWithTTL[Int]): Iterator[OutputEvent] = {
+    var results = List[OutputEvent]()
+    val key = row.key
+    if (row.action == "get") {
+      val currState = valueState.getOption()
+      if (currState.isDefined) {
+        results = OutputEvent(key, currState.get, isTTLValue = false, -1) :: 
results
+      }
+    } else if (row.action == "get_without_enforcing_ttl") {
+      val currState = valueState.getWithoutEnforcingTTL()
+      if (currState.isDefined) {
+        results = OutputEvent(key, currState.get, isTTLValue = false, -1) :: 
results
+      }
+    } else if (row.action == "get_ttl_value_from_state") {
+      val ttlExpiration = valueState.getTTLValue()
+      if (ttlExpiration.isDefined) {
+        results = OutputEvent(key, -1, isTTLValue = true, ttlExpiration.get) 
:: results
+      }
+    } else if (row.action == "put") {
+      if (ttlMode == TTLMode.EventTimeTTL() && row.eventTimeTtl != null) {
+        valueState.update(row.value, row.eventTimeTtl.getTime)
+      } else if (ttlMode == TTLMode.EventTimeTTL()) {
+        valueState.update(row.value)
+      } else {
+        valueState.update(row.value, row.ttl)
+      }
+    } else if (row.action == "get_values_in_ttl_state") {
+      val ttlValues = valueState.getValuesInTTLState()
+      ttlValues.foreach { v =>
+        results = OutputEvent(key, -1, isTTLValue = true, ttlValue = v) :: 
results
+      }
+    }
+
+    results.iterator
+  }
+}
+
+class ValueStateTTLProcessor
+  extends StatefulProcessor[String, InputEvent, OutputEvent]
+  with Logging {
+
+  @transient private var _valueState: ValueStateImplWithTTL[Int] = _
+  @transient private var _ttlMode: TTLMode = _
+
+  override def init(
+      outputMode: OutputMode,
+      timeoutMode: TimeoutMode,
+      ttlMode: TTLMode): Unit = {
+    _valueState = getHandle
+      .getValueState("valueState", Encoders.scalaInt)
+      .asInstanceOf[ValueStateImplWithTTL[Int]]
+    _ttlMode = ttlMode
+  }
+
+  override def handleInputRows(
+      key: String,
+      inputRows: Iterator[InputEvent],
+      timerValues: TimerValues,
+      expiredTimerInfo: ExpiredTimerInfo): Iterator[OutputEvent] = {
+    var results = List[OutputEvent]()
+
+    for (row <- inputRows) {
+      val resultIter = TTLInputProcessFunction.processRow(_ttlMode, row, 
_valueState)
+      resultIter.foreach { r =>
+        results = r :: results
+      }
+    }
+
+    results.iterator
+  }
+}
+
+case class MultipleValueStatesTTLProcessor(
+    ttlKey: String,
+    noTtlKey: String)
+  extends StatefulProcessor[String, InputEvent, OutputEvent]
+    with Logging {
+
+  @transient private var _valueStateWithTTL: ValueStateImplWithTTL[Int] = _
+  @transient private var _valueStateWithoutTTL: ValueStateImplWithTTL[Int] = _
+  @transient private var _ttlMode: TTLMode = _
+
+  override def init(
+      outputMode: OutputMode,
+      timeoutMode: TimeoutMode,
+      ttlMode: TTLMode): Unit = {
+    _valueStateWithTTL = getHandle
+      .getValueState("valueState", Encoders.scalaInt)
+      .asInstanceOf[ValueStateImplWithTTL[Int]]
+    _valueStateWithoutTTL = getHandle
+      .getValueState("valueState", Encoders.scalaInt)
+      .asInstanceOf[ValueStateImplWithTTL[Int]]
+    _ttlMode = ttlMode
+  }
+
+  override def handleInputRows(
+      key: String,
+      inputRows: Iterator[InputEvent],
+      timerValues: TimerValues,
+      expiredTimerInfo: ExpiredTimerInfo): Iterator[OutputEvent] = {
+    var results = List[OutputEvent]()
+    val state = if (key == ttlKey) {
+      _valueStateWithTTL
+    } else {
+      _valueStateWithoutTTL
+    }
+
+    for (row <- inputRows) {
+      val resultIterator = TTLInputProcessFunction.processRow(_ttlMode, row, 
state)
+      resultIterator.foreach { r =>
+        results = r :: results
+      }
+    }
+    results.iterator
+  }
+}
+
+class TransformWithStateTTLSuite
+  extends StreamTest {
+  import testImplicits._
+
+  test("validate state is evicted at ttl expiry - processing time ttl") {
+    withSQLConf(SQLConf.STATE_STORE_PROVIDER_CLASS.key ->
+      classOf[RocksDBStateStoreProvider].getName) {
+      val inputStream = MemoryStream[InputEvent]
+      val result = inputStream.toDS()
+        .groupByKey(x => x.key)
+        .transformWithState(
+          new ValueStateTTLProcessor(),
+          TimeoutMode.NoTimeouts(),
+          TTLMode.ProcessingTimeTTL())
+
+      val clock = new StreamManualClock
+      testStream(result)(
+        StartStream(Trigger.ProcessingTime("1 second"), triggerClock = clock),
+        AddData(inputStream, InputEvent("k1", "put", 1, 
Duration.ofMinutes(1))),
+        // advance clock to trigger processing
+        AdvanceManualClock(1 * 1000),
+        CheckNewAnswer(),
+        // get this state, and make sure we get unexpired value
+        AddData(inputStream, InputEvent("k1", "get", -1, null)),
+        AdvanceManualClock(1 * 1000),
+        CheckNewAnswer(OutputEvent("k1", 1, isTTLValue = false, -1)),
+        // ensure ttl values were added correctly
+        AddData(inputStream, InputEvent("k1", "get_ttl_value_from_state", -1, 
null)),
+        AdvanceManualClock(1 * 1000),
+        CheckNewAnswer(OutputEvent("k1", -1, isTTLValue = true, 61000)),
+        AddData(inputStream, InputEvent("k1", "get_values_in_ttl_state", -1, 
null)),
+        AdvanceManualClock(1 * 1000),
+        CheckNewAnswer(OutputEvent("k1", -1, isTTLValue = true, 61000)),
+        // advance clock so that state expires
+        AdvanceManualClock(60 * 1000),
+        AddData(inputStream, InputEvent("k1", "get", -1, null)),
+        AdvanceManualClock(1 * 1000),
+        // validate expired value is not returned
+        CheckNewAnswer(),
+        // ensure this state does not exist any longer in State
+        AddData(inputStream, InputEvent("k1", "get_without_enforcing_ttl", -1, 
null)),
+        AdvanceManualClock(1 * 1000),
+        CheckNewAnswer(),
+        AddData(inputStream, InputEvent("k1", "get_values_in_ttl_state", -1, 
null)),
+        AdvanceManualClock(1 * 1000),
+        CheckNewAnswer()
+      )
+    }
+  }
+
+  test("validate ttl update updates the expiration timestamp - processing time 
ttl") {
+    withSQLConf(SQLConf.STATE_STORE_PROVIDER_CLASS.key ->
+      classOf[RocksDBStateStoreProvider].getName) {
+      val inputStream = MemoryStream[InputEvent]
+      val result = inputStream.toDS()
+        .groupByKey(x => x.key)
+        .transformWithState(
+          new ValueStateTTLProcessor(),
+          TimeoutMode.NoTimeouts(),
+          TTLMode.ProcessingTimeTTL())
+
+      val clock = new StreamManualClock
+      testStream(result)(
+        StartStream(Trigger.ProcessingTime("1 second"), triggerClock = clock),
+        AddData(inputStream, InputEvent("k1", "put", 1, 
Duration.ofMinutes(1))),
+        // advance clock to trigger processing
+        AdvanceManualClock(1 * 1000),
+        CheckNewAnswer(),
+        // get this state, and make sure we get unexpired value
+        AddData(inputStream, InputEvent("k1", "get", -1, null)),
+        AdvanceManualClock(1 * 1000),
+        CheckNewAnswer(OutputEvent("k1", 1, isTTLValue = false, -1)),
+        // ensure ttl values were added correctly
+        AddData(inputStream, InputEvent("k1", "get_ttl_value_from_state", -1, 
null)),
+        AdvanceManualClock(1 * 1000),
+        CheckNewAnswer(OutputEvent("k1", -1, isTTLValue = true, 61000)),
+        AddData(inputStream, InputEvent("k1", "get_values_in_ttl_state", -1, 
null)),
+        AdvanceManualClock(1 * 1000),

Review Comment:
   Added. 



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

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]


---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]

Reply via email to