danny0405 commented on code in PR #20516:
URL: https://github.com/apache/hudi/pull/20516#discussion_r4624998236


##########
hudi-spark-datasource/hudi-spark-common/src/main/scala/org/apache/spark/sql/hudi/streaming/HoodieStreamingSourceSafety.scala:
##########
@@ -0,0 +1,190 @@
+/*
+ * 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.hudi.streaming
+
+import org.apache.hudi.{DataSourceReadOptions, DefaultSource, 
SparkAdapterSupport}
+import org.apache.hudi.common.model.WriteOperationType
+import org.apache.hudi.common.table.HoodieTableMetaClient
+import org.apache.hudi.common.table.timeline.{HoodieInstant, HoodieTimeline}
+import org.apache.hudi.common.util.CleanerUtils
+import org.apache.hudi.exception.HoodieException
+
+import org.apache.spark.{Partition, TaskContext}
+import org.apache.spark.rdd.RDD
+import org.apache.spark.sql.{DataFrame, SQLContext}
+import org.apache.spark.sql.catalyst.InternalRow
+import org.apache.spark.sql.execution.datasources.HadoopFsRelation
+import org.apache.spark.sql.types.StructType
+
+import scala.collection.JavaConverters._
+
+/** Conservative reset and history validation for checkpointed latest-state 
streaming consumers. */
+private[streaming] object HoodieStreamingSourceSafety extends 
SparkAdapterSupport {
+  private class RebuildRequired(message: String, cause: Throwable = null) 
extends HoodieException(message, cause)
+
+  // Spark re-plans the last committed batch on restart and discards it. Delay 
only safety
+  // rejections; healthy scans must remain visible to column pruning and 
predicate pushdown.
+  def deferRejection(sqlContext: SQLContext, schema: => StructType)(batch: => 
DataFrame): DataFrame = {
+    try {
+      batch
+    } catch {
+      case error: RebuildRequired =>
+        val rows = new RDD[InternalRow](sqlContext.sparkContext, Nil) {
+          override protected def getPartitions: Array[Partition] = throw error
+
+          override def compute(split: Partition, context: TaskContext): 
Iterator[InternalRow] = throw error
+        }
+        sparkAdapter.internalCreateDataFrame(sqlContext.sparkSession, rows, 
schema, isStreaming = true)
+    }
+  }
+
+  def strategy(parameters: Map[String, String]): String = {
+    val config = DataSourceReadOptions.STREAMING_READ_RECOVERY_STRATEGY
+    val value = parameters.getOrElse(config.key(), config.defaultValue())
+    require(Set("FAIL", "READ_UPTO_LATEST_COMMIT", 
"READ_LATEST").contains(value),
+      s"Invalid ${config.key()}=$value; expected FAIL, READ_UPTO_LATEST_COMMIT 
or READ_LATEST")
+    value
+  }
+
+  def recover(sqlContext: SQLContext,
+              metaClient: HoodieTableMetaClient,
+              schema: => StructType,
+              parameters: Map[String, String],
+              strategy: String,
+              start: String,
+              end: String,
+              completionTime: Boolean,
+              resumed: Boolean): Option[DataFrame] = {
+    lazy val recoverySchema = schema
+    try {
+      validate(metaClient, start, end, completionTime, resumed)
+      None
+    } catch {
+      case error: RebuildRequired => strategy match {
+        case "FAIL" => throw error
+        case "READ_LATEST" =>
+          Some(sparkAdapter.internalCreateDataFrame(sqlContext.sparkSession,
+            sqlContext.sparkContext.emptyRDD[InternalRow], recoverySchema, 
isStreaming = true))
+        case "READ_UPTO_LATEST_COMMIT" =>
+          // Spark owns the batch end/checkpoint. Never read a newer snapshot 
and checkpoint an older end.
+          val timeline = metaClient.reloadActiveTimeline()
+          val writes = timeline.getCommitsTimeline.filterCompletedInstants()
+            .getInstants.asScala.toSeq
+          def offset(i: HoodieInstant): String = if (completionTime) 
i.getCompletionTime else i.requestedTime()
+          val included = writes.filter(i => offset(i) <= end)
+          val bound = included.map(_.requestedTime()).reduceOption((a, b) => 
if (a > b) a else b)
+          def isTableService(instant: HoodieInstant): Boolean = {
+            val operation = if (instant.getAction == 
HoodieTimeline.REPLACE_COMMIT_ACTION) {
+              timeline.readReplaceCommitMetadata(instant).getOperationType
+            } else {
+              timeline.readCommitMetadata(instant).getOperationType
+            }
+            Set(WriteOperationType.COMPACT, WriteOperationType.LOG_COMPACT, 
WriteOperationType.CLUSTER).contains(operation)
+          }
+          if (bound.isEmpty || writes.exists(i => offset(i) > end && 
i.requestedTime() <= bound.get && !isTableService(i))) {

Review Comment:
   Addressed in 08fe7a2b03a (current head a96f54ace43). Snapshot recovery now 
calls validateTimestampAsOf before constructing the relation and converts its 
cleaner-retention and pending-write failures into RebuildRequired. The cleaner 
error explicitly says the recorded batch end is outside retention and 
recommends READ_LATEST or a coordinated rebuild; the pending-write error also 
explains waiting for pending writes. These remain deferred so Spark can discard 
a committed batch's restart plan.
   
   Added COW/MOR regressions for both offset versions that construct the plan 
successfully and assert the actionable failure on execution. SOURCE_SAFETY.md 
now explains consumer lag versus cleaner/archival retention, why snapshot 
recovery cannot move beyond Spark's recorded end, and returning to FAIL after 
recovery. Final Spark 3.5 / Scala 2.12 / JDK 17 build and both streaming suites 
passed: 34 tests, 0 failures, 2 expected version skips.



##########
hudi-spark-datasource/hudi-spark-common/src/main/scala/org/apache/spark/sql/hudi/streaming/HoodieStreamingSourceSafety.scala:
##########
@@ -0,0 +1,190 @@
+/*
+ * 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.hudi.streaming
+
+import org.apache.hudi.{DataSourceReadOptions, DefaultSource, 
SparkAdapterSupport}
+import org.apache.hudi.common.model.WriteOperationType
+import org.apache.hudi.common.table.HoodieTableMetaClient
+import org.apache.hudi.common.table.timeline.{HoodieInstant, HoodieTimeline}
+import org.apache.hudi.common.util.CleanerUtils
+import org.apache.hudi.exception.HoodieException
+
+import org.apache.spark.{Partition, TaskContext}
+import org.apache.spark.rdd.RDD
+import org.apache.spark.sql.{DataFrame, SQLContext}
+import org.apache.spark.sql.catalyst.InternalRow
+import org.apache.spark.sql.execution.datasources.HadoopFsRelation
+import org.apache.spark.sql.types.StructType
+
+import scala.collection.JavaConverters._
+
+/** Conservative reset and history validation for checkpointed latest-state 
streaming consumers. */
+private[streaming] object HoodieStreamingSourceSafety extends 
SparkAdapterSupport {
+  private class RebuildRequired(message: String, cause: Throwable = null) 
extends HoodieException(message, cause)
+
+  // Spark re-plans the last committed batch on restart and discards it. Delay 
only safety
+  // rejections; healthy scans must remain visible to column pruning and 
predicate pushdown.
+  def deferRejection(sqlContext: SQLContext, schema: => StructType)(batch: => 
DataFrame): DataFrame = {
+    try {
+      batch
+    } catch {
+      case error: RebuildRequired =>
+        val rows = new RDD[InternalRow](sqlContext.sparkContext, Nil) {
+          override protected def getPartitions: Array[Partition] = throw error
+
+          override def compute(split: Partition, context: TaskContext): 
Iterator[InternalRow] = throw error
+        }
+        sparkAdapter.internalCreateDataFrame(sqlContext.sparkSession, rows, 
schema, isStreaming = true)
+    }
+  }
+
+  def strategy(parameters: Map[String, String]): String = {
+    val config = DataSourceReadOptions.STREAMING_READ_RECOVERY_STRATEGY
+    val value = parameters.getOrElse(config.key(), config.defaultValue())
+    require(Set("FAIL", "READ_UPTO_LATEST_COMMIT", 
"READ_LATEST").contains(value),
+      s"Invalid ${config.key()}=$value; expected FAIL, READ_UPTO_LATEST_COMMIT 
or READ_LATEST")
+    value
+  }
+
+  def recover(sqlContext: SQLContext,
+              metaClient: HoodieTableMetaClient,
+              schema: => StructType,
+              parameters: Map[String, String],
+              strategy: String,
+              start: String,
+              end: String,
+              completionTime: Boolean,
+              resumed: Boolean): Option[DataFrame] = {
+    lazy val recoverySchema = schema
+    try {
+      validate(metaClient, start, end, completionTime, resumed)
+      None
+    } catch {
+      case error: RebuildRequired => strategy match {
+        case "FAIL" => throw error
+        case "READ_LATEST" =>
+          Some(sparkAdapter.internalCreateDataFrame(sqlContext.sparkSession,
+            sqlContext.sparkContext.emptyRDD[InternalRow], recoverySchema, 
isStreaming = true))
+        case "READ_UPTO_LATEST_COMMIT" =>
+          // Spark owns the batch end/checkpoint. Never read a newer snapshot 
and checkpoint an older end.
+          val timeline = metaClient.reloadActiveTimeline()
+          val writes = timeline.getCommitsTimeline.filterCompletedInstants()
+            .getInstants.asScala.toSeq
+          def offset(i: HoodieInstant): String = if (completionTime) 
i.getCompletionTime else i.requestedTime()
+          val included = writes.filter(i => offset(i) <= end)
+          val bound = included.map(_.requestedTime()).reduceOption((a, b) => 
if (a > b) a else b)
+          def isTableService(instant: HoodieInstant): Boolean = {
+            val operation = if (instant.getAction == 
HoodieTimeline.REPLACE_COMMIT_ACTION) {
+              timeline.readReplaceCommitMetadata(instant).getOperationType
+            } else {
+              timeline.readCommitMetadata(instant).getOperationType
+            }
+            Set(WriteOperationType.COMPACT, WriteOperationType.LOG_COMPACT, 
WriteOperationType.CLUSTER).contains(operation)
+          }
+          if (bound.isEmpty || writes.exists(i => offset(i) > end && 
i.requestedTime() <= bound.get && !isTableService(i))) {
+            throw new RebuildRequired("Cannot reconstruct the recovery 
snapshot at the checkpointed batch end. "
+              + "Rebuild downstream tables and checkpoints together.", error)
+          }
+          val options = parameters ++ Map(
+            DataSourceReadOptions.QUERY_TYPE.key() -> 
DataSourceReadOptions.QUERY_TYPE_SNAPSHOT_OPT_VAL,
+            DataSourceReadOptions.TIME_TRAVEL_AS_OF_INSTANT.key() -> bound.get)
+          val relation = DefaultSource.createRelation(sqlContext, metaClient, 
recoverySchema, options)
+          Some(relation match {
+            case fsRelation: HadoopFsRelation => 
sparkAdapter.createStreamingDataFrame(sqlContext, fsRelation, recoverySchema)
+            case _ => 
sparkAdapter.internalCreateDataFrame(sqlContext.sparkSession,
+              
sqlContext.baseRelationToDataFrame(relation).queryExecution.toRdd, 
recoverySchema, isStreaming = true)
+          })
+      }
+    }
+  }
+
+  def validate(metaClient: HoodieTableMetaClient,
+               start: String,
+               end: String,
+               completionTime: Boolean,
+               resumed: Boolean): Unit = {
+    if (start != HoodieTimeline.INIT_INSTANT_TS) {
+      validateRetainedRange(metaClient, start, end, completionTime, resumed)
+    }
+  }
+
+  private def validateRetainedRange(metaClient: HoodieTableMetaClient,
+                                    start: String,
+                                    end: String,
+                                    completionTime: Boolean,
+                                    resumed: Boolean): Unit = {
+    val timeline = metaClient.reloadActiveTimeline()
+    val completed = 
timeline.filterCompletedInstants().getInstants.asScala.toSeq
+    def offset(instant: HoodieInstant): String = {
+      if (completionTime) instant.getCompletionTime else 
instant.requestedTime()
+    }
+    def fail(reason: String): Nothing = {
+      throw new RebuildRequired(s"Streaming source rebuild required for 
${metaClient.getBasePath}: $reason. "
+        + "Stop downstream consumers and rebuild affected downstream tables 
and checkpoints in dependency order. "
+        + s"To explicitly accept recovery risks, set 
${DataSourceReadOptions.STREAMING_READ_RECOVERY_STRATEGY.key()} "
+        + "to READ_UPTO_LATEST_COMMIT (snapshot replay) or READ_LATEST (skip 
the gap).")
+    }
+

Review Comment:
   Addressed in 08fe7a2b03a and a96f54ace43.
   
   - Both sources now produce offsets from completed writes only. On restart, 
an active legacy service-time end is retained until writes catch up, rather 
than returning a smaller write offset. Tests cover clean completions not 
advancing offsets, real restore removing the checkpointed write, and resuming 
from a legacy clean-time checkpoint through the next write. The guide 
explicitly notes that legacy service positions cannot prove earlier writes 
survived restore.
   - For v6-to-v8+ upgrades, I took the documented-pinning option: keep 
hoodie.datasource.read.streaming.table.version=6 on every restart of an 
existing requested-time checkpoint. The upgrade regression uses an actual 
v6-to-v8 write upgrade, demonstrates rejection with automatic V2 selection, and 
verifies exact next rows with the pinned V1 reader. Both the release note and 
operational guide explain the migration.
   - Added actual testStream StopStream/StartStream scenarios for each recovery 
strategy: fail under FAIL, replay the failed batch with snapshot or skip, then 
return to FAIL and verify exact downstream rows after another write. Final 
Spark 3.5 / Scala 2.12 / JDK 17 results: 34 passed, 0 failed, 2 expected 
version skips; reactor/style/license checks passed. Spark 4.x and CLI 
acceptance were not rerun locally.
   
   Synced upstream master to include the fork CI workflows; the prior CI (fork) 
check reported that no fork run existed. The new head has been pushed, and 
remote CI is not yet claimed green. The enum refactor and release-note 
consolidation remain follow-ups; the guidance to revert to FAIL is included 
here.



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

To unsubscribe, e-mail: [email protected]

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

Reply via email to