This is an automated email from the ASF dual-hosted git repository. github-merge-queue[bot] pushed a commit to branch gh-readonly-queue/master/pr-20755-0ed986b8ad1c06da88f5465fc5e9d79de379fff6 in repository https://gitbox.apache.org/repos/asf/hudi.git
commit e874d7644dc7308e85a63d53467e52e2cbf20ebd Author: Danny Chan <[email protected]> AuthorDate: Fri Nov 20 06:17:02 2026 +0000 test(spark): complete single-writer SDP streaming acceptance (#20755) --- hudi-integ-test/spark-pipelines/ACCEPTANCE.md | 105 +++++++++++++++++++++ hudi-integ-test/spark-pipelines/README.md | 2 +- .../hudi/TestHoodieSparkConnectPipelines.scala | 98 ++++++++++++++++++- 3 files changed, 201 insertions(+), 4 deletions(-) diff --git a/hudi-integ-test/spark-pipelines/ACCEPTANCE.md b/hudi-integ-test/spark-pipelines/ACCEPTANCE.md index cfcb14196414..02df1cc4551b 100644 --- a/hudi-integ-test/spark-pipelines/ACCEPTANCE.md +++ b/hudi-integ-test/spark-pipelines/ACCEPTANCE.md @@ -67,6 +67,111 @@ fan-in, chaining, or commit/checkpoint failure injection. The generated source, SQL and pipeline specification are retained in the logs as runnable examples within the harness's isolated filesystem layout. +## Single-writer streaming-table acceptance + +The release scope of [#20406](https://github.com/apache/hudi/issues/20406) is +**one writer per Hudi target**. Multiple flows targeting the same Hudi table are +unsupported. Automatic rejection before any target writes is deferred: stock +Spark 4.1.1 does not expose a graph-validation extension for Hudi to enforce it. +Validate this constraint when defining the pipeline; do not assume Spark rejects +fan-in. Future fan-in support is tracked by +[#20530](https://github.com/apache/hudi/issues/20530). + +The automated checks are split across existing suites: + +| Contract | Coverage | +| --- | --- | +| Explicit insert, two input batches, ordinary restart | `phase1_acceptance.py` checks exact rows and unchanged completed Hudi commits. | +| Purge-style full refresh and restart | `TestHoodieSparkConnectPipelines` runs real CLI/Connect flows for COW and MOR with metadata enabled. It checks two initial batches, a quiescent restart, `--full-refresh-all`, replayed rows, removal of old commits, a fresh streaming query identity with committed batch 0, another quiescent restart, and ingestion of new data. | +| Invalid table configuration | The same CLI suite rejects a nonexistent primary-key column and checks that no Hudi data commit was published. | +| Commit/checkpoint interruption and resource cleanup | `TestStreamingSinkRecovery` exercises AvailableNow, explicit stop, and failure for COW/MOR. It checks checkpoint replay, socket/client cleanup, and an unrelated query. Its post-commit metadata-sync failures must not retry the data write. | +| Connect failure isolation | `TestHoodieSparkConnectPipelines` checks a null-key failure followed by a fresh remote query. | + +Run the CLI suite with the layer-2 command in [README.md](README.md). Its +full-refresh checks retain the pipeline storage root: SDP selects the fresh +checkpoint, and Hudi purges the old target timeline and sink batch IDs. This +does not implement timeline-preserving generation isolation from #20404. + +### Manual external connector example: Kafka + +The automated tests use deterministic JSON files and require no broker. The +following is a manual connector recipe, not a claimed Kafka test result. Use a +reachable Kafka broker, an empty single-partition topic `hudi_sdp_events`, JDK 17, +the pinned PySpark dependencies, and the candidate Hudi Spark 4.1 bundle. Keep +all sample records available for replay. See Spark's +[Kafka connector guide](https://spark.apache.org/docs/4.1.1/structured-streaming-kafka-integration.html) +for authentication and deployment details. + +Start a dedicated Connect server in a separate terminal, setting `HUDI_BUNDLE` +to the absolute bundle path. The connector must be installed on the server: + +```sh +spark-submit --master 'local[2]' --driver-memory 2g \ + --jars "$HUDI_BUNDLE" \ + --packages org.apache.spark:spark-sql-kafka-0-10_2.13:4.1.1 \ + --conf spark.sql.extensions=org.apache.spark.sql.hudi.HoodieSparkSessionExtension \ + --conf spark.sql.catalog.spark_catalog=org.apache.spark.sql.hudi.catalog.HoodieCatalog \ + --conf spark.serializer=org.apache.spark.serializer.KryoSerializer \ + --conf spark.kryo.registrator=org.apache.spark.HoodieSparkKryoRegistrar \ + --conf spark.sql.catalogImplementation=in-memory \ + --conf spark.sql.warehouse.dir=file:///tmp/hudi-sdp-kafka-warehouse \ + --conf spark.connect.grpc.binding.address=127.0.0.1 \ + --conf spark.connect.grpc.binding.port=15002 \ + --class org.apache.spark.sql.connect.service.SparkConnectServer +``` + +Place these three files in an empty working directory. Use fresh warehouse and +checkpoint locations if repeating the recipe from scratch. In `source.py`: + +```python +from pyspark import pipelines as dp +from pyspark.sql import SparkSession, functions as F + +spark = SparkSession.active() + [email protected]_view(name="kafka_events") +def kafka_events(): + raw = (spark.readStream.format("kafka") + .option("kafka.bootstrap.servers", spark.conf.get("example.kafka.brokers")) + .option("subscribe", "hudi_sdp_events") + .option("startingOffsets", "earliest").load()) + return raw.select(F.from_json(F.col("value").cast("string"), + "id INT, ts LONG, value STRING").alias("event")).select("event.*") +``` + +In `flows.sql`: + +```sql +SET spark.hoodie.datasource.write.operation=insert; +CREATE STREAMING TABLE kafka_target USING hudi +TBLPROPERTIES ('type'='cow', 'primaryKey'='id', 'preCombineField'='ts') +AS SELECT id, ts, value FROM STREAM kafka_events; +``` + +In `spark-pipeline.yml`, replace the broker address with one reachable from the server: + +```yaml +name: hudi_kafka_append +catalog: spark_catalog +database: kafka_demo +storage: file:///tmp/hudi-sdp-kafka-checkpoints +libraries: + - glob: {include: source.py} + - glob: {include: flows.sql} +configuration: + example.kafka.brokers: localhost:9092 + spark.sql.shuffle.partitions: '2' +``` + +Using Kafka's console producer, publish `{"id":1,"ts":1,"value":"first"}`, +then run `spark-pipelines run --remote sc://127.0.0.1:15002 --spec spark-pipeline.yml`. +Publish `{"id":2,"ts":2,"value":"second"}` and rerun the command. Through a +Connect client, query `spark_catalog.kafka_demo.kafka_target` and verify exactly +those two business rows. Rerun with no new input, then add `--full-refresh-all` +and rerun again: both must retain exactly those two rows. Full refresh starts +from the earliest retained Kafka offsets; it cannot recover expired source data. +Stop this dedicated server with Ctrl-C after the manual check. + ## Truncate and full-refresh limitations The release scope agreed in [#20404](https://github.com/apache/hudi/issues/20404) diff --git a/hudi-integ-test/spark-pipelines/README.md b/hudi-integ-test/spark-pipelines/README.md index 00c65567cba1..33ed67f7f0f4 100644 --- a/hudi-integ-test/spark-pipelines/README.md +++ b/hudi-integ-test/spark-pipelines/README.md @@ -31,7 +31,7 @@ in-JVM `DataflowGraph` calls for the client/server protocol. | Layer | Server | Coverage | Execution | | --- | --- | --- | --- | -| 2: `TestHoodieSparkConnectPipelines` | Connect service in the ScalaTest JVM, Hudi on the Maven test classpath | MV/ST exact rows, independent SQL flow insert/upsert settings, null-key failure and a fresh remote query afterward | Existing Scala-other job on PRs, pushes and merge groups | +| 2: `TestHoodieSparkConnectPipelines` | Connect service in the ScalaTest JVM, Hudi on the Maven test classpath | MV/ST exact rows, independent SQL flow insert/upsert settings, COW/MOR full refresh and restart, invalid table configuration, null-key failure and a fresh remote query afterward | Existing Scala-other job on PRs, pushes and merge groups | | 3: `harness.py` | Separate `spark-submit` JVM with the candidate bundle | Bundle packaging, static server configuration, remote writes/reads, process ownership and cleanup | Existing Scala-DML job on PRs, pushes and merge groups | Both layers run as additional steps in existing `bot.yml` jobs; no new workflow, diff --git a/hudi-spark-datasource/hudi-spark/src/test/scala-spark4.1/org/apache/spark/sql/connect/hudi/TestHoodieSparkConnectPipelines.scala b/hudi-spark-datasource/hudi-spark/src/test/scala-spark4.1/org/apache/spark/sql/connect/hudi/TestHoodieSparkConnectPipelines.scala index 5436d3efac97..3e1c87d4cffe 100644 --- a/hudi-spark-datasource/hudi-spark/src/test/scala-spark4.1/org/apache/spark/sql/connect/hudi/TestHoodieSparkConnectPipelines.scala +++ b/hudi-spark-datasource/hudi-spark/src/test/scala-spark4.1/org/apache/spark/sql/connect/hudi/TestHoodieSparkConnectPipelines.scala @@ -28,6 +28,8 @@ import java.nio.file.Files import java.util.UUID import java.util.concurrent.TimeUnit +import scala.jdk.CollectionConverters._ + /** Real pipelines CLI against a Connect service in the test JVM, without building a bundle. */ class TestHoodieSparkConnectPipelines extends FunSuite with BeforeAndAfterAll { private val python = sys.env.getOrElse("HUDI_SDP_PYTHON", "python3") @@ -120,6 +122,74 @@ class TestHoodieSparkConnectPipelines extends FunSuite with BeforeAndAfterAll { } } + Seq("cow", "mor").foreach { tableType => + test(s"$tableType streaming full refresh replays all input and resumes without duplicate commits") { + withPipeline { (dir, database) => + write(dir, "flows.sql", + s"""SET spark.hoodie.datasource.write.operation=insert; + |CREATE STREAMING TABLE events USING hudi + |TBLPROPERTIES ('type'='$tableType', 'primaryKey'='id', 'preCombineField'='ts') + |AS SELECT * FROM STREAM input_events; + |""".stripMargin) + val oldRows = Seq.fill(2)(Row(1, 1L, "old")) + assertSuccess(runPipeline(dir, database)) + assert(rows(database, "events") == oldRows) + write(new File(dir, "input"), "next.json", """{"id":2,"ts":2,"value":"new"}""") + assertSuccess(runPipeline(dir, database)) + val expected = oldRows :+ Row(2, 2L, "new") + assert(rows(database, "events") == expected) + + val before = completedCommits(database, "events") + val checkpoints = streamingCheckpoints(dir) + assert(before.size >= 2, before) + assert(checkpoints.size == 1, checkpoints) + assertSuccess(runPipeline(dir, database)) + assert(rows(database, "events") == expected) + assert(completedCommits(database, "events") == before) + assert(streamingCheckpoints(dir) == checkpoints) + + assertSuccess(runPipeline(dir, database, fullRefresh = true)) + assert(rows(database, "events") == expected) + val refreshed = completedCommits(database, "events") + assert(refreshed.nonEmpty && refreshed.intersect(before).isEmpty, refreshed) + val freshCheckpoints = streamingCheckpoints(dir).filter { case (path, metadata) => + !checkpoints.get(path).contains(metadata) + } + assert(freshCheckpoints.size == 1, freshCheckpoints) + assert(freshCheckpoints.values.toSet.intersect(checkpoints.values.toSet).isEmpty) + freshCheckpoints.keys.foreach { path => + assert(new File(path, "commits/0").isFile, s"Fresh checkpoint did not commit batch 0: $path") + } + val afterRefresh = streamingCheckpoints(dir) + assertSuccess(runPipeline(dir, database)) + assert(rows(database, "events") == expected) + assert(completedCommits(database, "events") == refreshed) + assert(streamingCheckpoints(dir) == afterRefresh) + + write(new File(dir, "input"), "after-refresh.json", """{"id":3,"ts":3,"value":"after"}""") + assertSuccess(runPipeline(dir, database)) + assert(rows(database, "events") == (expected :+ Row(3, 3L, "after"))) + assert(completedCommits(database, "events").size > refreshed.size) + assert(streamingCheckpoints(dir) == afterRefresh) + } + } + } + + test("invalid streaming table configuration fails before data commits") { + withPipeline { (dir, database) => + write(dir, "flows.sql", + """CREATE STREAMING TABLE bad_config USING hudi + |TBLPROPERTIES ('type'='cow', 'primaryKey'='missing_key', 'preCombineField'='ts') + |AS SELECT * FROM STREAM input_events; + |""".stripMargin) + val (exit, output) = runPipeline(dir, database) + assert(exit != 0, "The missing primary-key column unexpectedly succeeded") + assert(output.contains("Can't find primaryKey `missing_key`"), output.takeRight(12000)) + assert(completedCommits(database, "bad_config").isEmpty) + assert(spark.range(3).count() == 3) + } + } + private def remote: String = s"sc://127.0.0.1:${SparkConnectService.localPort}" private def withPipeline(f: (File, String) => Unit): Unit = { @@ -146,7 +216,7 @@ class TestHoodieSparkConnectPipelines extends FunSuite with BeforeAndAfterAll { } } - private def runPipeline(dir: File, database: String): (Int, String) = { + private def runPipeline(dir: File, database: String, fullRefresh: Boolean = false): (Int, String) = { def quoted(value: String): String = "'" + value.replace("'", "''") + "'" write(dir, "spark-pipeline.yml", s"""name: $database @@ -162,14 +232,36 @@ class TestHoodieSparkConnectPipelines extends FunSuite with BeforeAndAfterAll { | spark.sql.pipelines.maxFlowRetryAttempts: '0' | spark.hoodie.metadata.enable: 'true' |""".stripMargin) + val run = s"$database-${UUID.randomUUID()}" Seq("source.py", "flows.sql", "spark-pipeline.yml").foreach { name => - Files.copy(new File(dir, name).toPath, new File(logs, s"$database-$name").toPath) + Files.copy(new File(dir, name).toPath, new File(logs, s"$run-$name").toPath) } runPython(Seq("-m", "pyspark.pipelines.cli", "run", - "--spec", new File(dir, "spark-pipeline.yml").getAbsolutePath), database, 180) + "--spec", new File(dir, "spark-pipeline.yml").getAbsolutePath) ++ + (if (fullRefresh) Seq("--full-refresh-all") else Seq.empty), run, 180) + } + + private def completedCommits(database: String, table: String): Set[String] = { + val timeline = new File(root, s"warehouse/$database.db/$table/.hoodie/timeline") + Option(timeline.listFiles()).toSeq.flatten.map(_.getName) + .filter(name => Seq(".commit", ".deltacommit", ".replacecommit").exists(name.endsWith)).toSet + } + + private def streamingCheckpoints(dir: File): Map[String, String] = { + val paths = Files.walk(new File(dir, "checkpoints").toPath) + try { + paths.iterator().asScala.filter(path => path.getFileName.toString == "metadata") + .filter(Files.isRegularFile(_)).map { path => + path.getParent.toString -> new String(Files.readAllBytes(path), UTF_8) + }.toMap + } finally { + paths.close() + } } private def rows(database: String, table: String): Seq[Row] = { + // CLI writes use separate Connect sessions; invalidate this verifier's cached file listing. + spark.catalog.refreshTable(s"$database.$table") spark.table(s"$database.$table").select("id", "ts", "value").orderBy("id", "ts").collect().toSeq }
