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-20516-d200119883d592ecd5c53ad91e1c9aa86aa93d87 in repository https://gitbox.apache.org/repos/asf/hudi.git
commit 70b7a10c0d1e5f0a84cb678e925e7566b8e6b298 Author: Danny Chan <[email protected]> AuthorDate: Fri Nov 20 07:03:31 2026 +0000 feat(spark)!: define streaming source recovery strategies (#20516) * feat(spark): guard streaming reads against resets and expired history * fix(spark): address streaming source safety review and Spark 3 compatibility * feat(spark)!: define explicit streaming source recovery strategies * fix(spark): address streaming source recovery review * fix(spark): preserve streaming scan plans and defer only safety rejections * fix(spark): clarify streaming recovery scope and defer schema lookup * fix(spark): validate recovery snapshots and checkpoint write offsets * test(spark): isolate recovery settings across restart scenarios --- hudi-integ-test/spark-pipelines/ACCEPTANCE.md | 5 + hudi-integ-test/spark-pipelines/SOURCE_SAFETY.md | 167 ++++++++ .../spark-pipelines/source_safety_acceptance.py | 209 ++++++++++ .../scala/org/apache/hudi/DataSourceOptions.scala | 22 + .../sql/hudi/streaming/HoodieStreamSourceV1.scala | 130 +++--- .../sql/hudi/streaming/HoodieStreamSourceV2.scala | 134 +++--- .../streaming/HoodieStreamingSourceSafety.scala | 212 ++++++++++ .../hudi/functional/TestStreamingSource.scala | 457 ++++++++++++++++++++- release/streaming-source-recovery-1.3.0.md | 64 +++ 9 files changed, 1287 insertions(+), 113 deletions(-) diff --git a/hudi-integ-test/spark-pipelines/ACCEPTANCE.md b/hudi-integ-test/spark-pipelines/ACCEPTANCE.md index 02df1cc4551b..dc6391efc7fe 100644 --- a/hudi-integ-test/spark-pipelines/ACCEPTANCE.md +++ b/hudi-integ-test/spark-pipelines/ACCEPTANCE.md @@ -281,3 +281,8 @@ exercising the enabled default. Both tables passed metadata initialization/write exact-row, two-partition, and unchanged-restart checks. MOR completed upstream compaction; in this run its catch-up needed no additional downstream commit. The bundle package build skipped unit-test execution. + +## Source reset and expired-history safeguards + +See [streaming source recovery](SOURCE_SAFETY.md) for the default failure +policy, explicit recovery strategies, and `source_safety_acceptance.py` scenario. diff --git a/hudi-integ-test/spark-pipelines/SOURCE_SAFETY.md b/hudi-integ-test/spark-pipelines/SOURCE_SAFETY.md new file mode 100644 index 000000000000..006826c3b39c --- /dev/null +++ b/hudi-integ-test/spark-pipelines/SOURCE_SAFETY.md @@ -0,0 +1,167 @@ +<!-- +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. +--> + +# Hudi streaming source recovery + +The streaming source supports insert/upsert/delete plus compaction and clustering. +`INSERT OVERWRITE` (table or partition), `delete_partition` writes and partition +TTL on an upstream table require recovery for downstream consumers and fail by +default. This includes TTL run inline with `hoodie.partition.ttl.inline`, which +writes `DELETE_PARTITION` replace commits. `READ_LATEST` drops the overwrite's +new rows along with the unread range; `READ_UPTO_LATEST_COMMIT` replays the whole +table, including unaffected partitions. Latest-state reads do not propagate hard +deletes to downstream tables. + +`hoodie.datasource.read.streaming.recovery.strategy` defaults to `FAIL` for +latest-state structured-streaming readers, including SDP. It replaces the +unreleased boolean guard. An unreadable saved offset (archived or cleaned +history), logical overwrite/truncate, or physical recreation produces an +error naming the strategy config and the coordinated rebuild procedure. + +| Strategy | Recovery batch | Consequence | +| --- | --- | --- | +| `FAIL` (default) | Stop before executing an unsafe batch | Rebuild downstream tables and checkpoints together | +| `READ_UPTO_LATEST_COMMIT` | One full snapshot bounded by Spark's recorded batch end, then resume increments | Append targets may duplicate rows; upsert targets may retain keys deleted upstream | +| `READ_LATEST` | Empty batch acknowledging Spark's recorded latest end, then resume increments | Deliberately skip the unread range, accepting data loss | + +These are recovery policies, not alternate settings for every healthy batch. +An explicit choice takes precedence over +`hoodie.datasource.read.incr.fallback.fulltablescan.enable`; latest-state +streaming incremental reads disable that legacy silent fallback after the initial +earliest offset. Fresh earliest starts retain the configured fallback so a +coordinated rebuild can read tables with cleaned, replaced files. The strategy +is captured at source construction. Restart the query to change it. Initial +startup still uses `hoodie.datasource.streaming.startOffset` (earliest, latest, +or an explicit instant); a fresh earliest checkpoint can read the current state. +CDC behavior is unchanged. Validation runs during batch planning, but safety +rejections are raised only when the batch executes. Spark may therefore re-plan +and discard the last committed batch on restart without failing on that +already-delivered range. + +For direct readers: + +```python +spark.readStream.option( + "hoodie.datasource.read.streaming.recovery.strategy", "FAIL" +).table("sdp_test.upstream").select("id", "ts", "value") +``` + +For SDP graph-internal reads, Spark 4.1.1 discards explicit reader options. +Use pipeline configuration or the flow's SQLConf to select recovery: + +```yaml +configuration: + spark.hoodie.datasource.read.streaming.recovery.strategy: READ_UPTO_LATEST_COMMIT +``` + +Direct reader options take precedence when Spark forwards them. There is no +need to set the configuration merely to obtain the default `FAIL` behavior. + +## Recovery boundaries and limits + +Stop consumers and rebuild affected downstream tables **and** checkpoints in +upstream-to-downstream order. Merely discarding a checkpoint can duplicate rows +or retain stale rows. Snapshot recovery is explicit permission to accept those +risks; it does not truncate or reconcile the downstream table. Every external +source must retain enough data for a complete coordinated rebuild. + +Spark owns each batch end and checkpoint. Recovery never reads a newer snapshot +while acknowledging an older end. Snapshot recovery uses a time-travel snapshot +at that batch's last included write. If that snapshot cannot be reconstructed +(for example, recreation removed it, cleaning expired its files, or completion +ordering cannot be represented by the requested-time snapshot), rebuild tables +and checkpoints together. Concurrent destructive operations must still be +coordinated: validation and execution are not atomic. + +If an overwrite completes after a restarted uncommitted batch's recorded end, +`READ_UPTO_LATEST_COMMIT` can replay two full snapshots: the pre-reset snapshot +for that batch (if reconstructible), then the post-reset snapshot when the next +batch includes the replace commit. Append targets can therefore receive the +whole table twice. + +Keep consumer lag within the cleaner retention window (`hoodie.clean.commits.retained`, +formerly `hoodie.cleaner.commits.retained`) as well as the archival window. +`READ_UPTO_LATEST_COMMIT` uses the failed batch end already recorded by Spark; +it only works while that end remains readable. Once cleaning passes that end, +use `READ_LATEST` (accepting data loss) or rebuild. Pending non-clustering writes +at or before the snapshot bound must complete before snapshot replay can proceed. +After a successful recovery, restart with `FAIL` again. Leaving snapshot recovery +on with daily partition TTL can replay the entire table every day. + +Retain sufficient active history for the slowest consumer with +`hoodie.keep.min.commits` / `hoodie.keep.max.commits`. An archived checkpoint +requires recovery even if some data files remain. With +`hoodie.cleaner.policy=KEEP_LATEST_FILE_VERSIONS`, a clean after the checkpoint +that deletes any files requires recovery, even when those files were not needed: +that policy records no earliest retained commit. Choose a policy with a retention +boundary when incremental continuity must be established. + +Non-clustering replace commits are logical resets; clustering and compaction +remain readable. This includes the timeline-preserving `TRUNCATE TABLE` proposed +in #20378. Physical recreation is detected at the next resumed batch, not while +an empty source produces no batch. Copying identical timeline history does not +establish a new table identity. + +Snapshot recovery is a single unbounded batch. Chunked bootstrap and source +admission control remain follow-ups; size the backlog and snapshot accordingly. +Latest-state chaining does not propagate hard deletes or every intermediate +change. CLI full-refresh acceptance remains separate from this recovery policy. + +## Verification + +`TestStreamingSource` covers both offset versions and COW/MOR: default failure, +explicit strategy precedence, reset/recreation, cleaner boundaries, clustering, +exact snapshot rows, bounded recovery after a newer write, and incremental +continuation after recovery. + +`source_safety_acceptance.py` uses the #20453 Spark 4.1.1 CLI/Connect harness. +It verifies exact two-stage rows, unchanged restarts, recreation rejection before +any downstream commit, and explicit coordinated rebuild of both tables with new +checkpoints. It does not validate the CLI full-refresh path. + +```sh +python hudi-integ-test/spark-pipelines/source_safety_acceptance.py \ + --harness-dir /path/to/harness-checkout/hudi-integ-test/spark-pipelines \ + --bundle /path/to/candidate-hudi-spark4.1-bundle.jar \ + --table-type cow +# Repeat with --table-type mor. +``` + +`FAIL` requires the sink to propagate batch execution errors. Safety rejections +are deferred until execution so Spark can discard the last committed batch plan +on restart. For Hudi sinks, keep +`hoodie.datasource.write.streaming.ignore.failed.batch=false` (the default). +Setting it to `true`, or swallowing errors in a custom sink, can acknowledge a +rejected batch and advance the checkpoint past unread data even under `FAIL`. +Healthy batches retain their scan relations for column pruning and filter pushdown. + +## Table upgrades and legacy checkpoints + +Before upgrading a source table from v6 to v8 or newer, pin existing requested-time +(`BLOCK`/`FAIL` hollow-commit mode) readers with +`.option("hoodie.datasource.read.streaming.table.version", "6")` and keep that +option on every restart using the same checkpoint. Offsets have no version marker; +automatically selecting V2 after the table upgrade interprets an old requested +time as a completion time and fails validation. Do not change offset semantics +in place. To adopt V2, coordinate a downstream/checkpoint rebuild. Readers already +using `USE_TRANSITION_TIME` use completion times and do not need this conversion. + +New offsets come only from completed writes, so rolling back a checkpointed write +via restore requires recovery. Existing service-time checkpoints remain supported: +on restart, an active legacy clean/rollback offset is retained until a later write +arrives. Such legacy positions cannot prove that earlier writes survived a restore; +coordinate restore with downstream rebuilding even when a legacy position survives. diff --git a/hudi-integ-test/spark-pipelines/source_safety_acceptance.py b/hudi-integ-test/spark-pipelines/source_safety_acceptance.py new file mode 100644 index 000000000000..6132bb2ad398 --- /dev/null +++ b/hudi-integ-test/spark-pipelines/source_safety_acceptance.py @@ -0,0 +1,209 @@ +# 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. + +"""Run guarded Hudi source reset and coordinated rebuild acceptance using the #20453 Spark CLI/Connect harness.""" + +import argparse +import json +from pathlib import Path +import signal +import sys +import tempfile + + +SOURCE = '''from pyspark import pipelines as dp +from pyspark.sql import SparkSession + +spark = SparkSession.active() + [email protected]_view(name="input_events") +def input_events(): + return spark.readStream.schema("id INT, ts LONG, value STRING").json(spark.conf.get("hudi.test.input")) + [email protected]_view(name="guarded_upstream") +def guarded_upstream(): + # SDP discards explicit options on graph-internal reads; the pipeline SQLConf enables safety. + return (spark.readStream + .table("sdp_test.upsert_events") + .select("id", "ts", "value")) +''' + +# The downstream insert operation makes replay visible as duplicate business rows. +# Explicit projection excludes the upstream table's reserved Hudi metadata fields. +FLOWS = '''SET spark.hoodie.datasource.write.operation=upsert; +CREATE STREAMING TABLE upsert_events USING hudi +TBLPROPERTIES ('type'='{table_type}', 'primaryKey'='id', 'preCombineField'='ts') +AS SELECT id, ts, value FROM STREAM input_events; + +SET spark.hoodie.datasource.write.operation=insert; +CREATE STREAMING TABLE downstream_events USING hudi +TBLPROPERTIES ('type'='{table_type}', 'primaryKey'='id', 'preCombineField'='ts') +AS SELECT id, ts, value FROM STREAM guarded_upstream; +''' + + +def verify(mode, remote, root): + from pyspark.sql import SparkSession + + spark = SparkSession.builder.remote(remote).getOrCreate() + try: + assert spark.conf.get("spark.hudi.test.run.id") == root.name + if mode == "truncate-upstream": + spark.sql("TRUNCATE TABLE sdp_test.upsert_events") + return + if mode == "truncate-graph": + for table in ("upsert_events", "downstream_events"): + spark.sql(f"TRUNCATE TABLE sdp_test.{table}") + return + if mode == "rebuilt": + for table in ("upsert_events", "downstream_events"): + actual = [tuple(row) for row in spark.table(f"sdp_test.{table}") + .select("id", "ts", "value").collect()] + assert actual == [(1, 3, "reset")], (table, actual) + return + old = (1, 1, "old") + new = (1, 2, "new") + for table, expected in ( + ("upsert_events", [old] if mode == "first" else [new]), + ("downstream_events", [old] if mode == "first" else [old, new]), + ): + if mode == "failed-reset" and table == "upsert_events": + continue + actual = [tuple(row) for row in spark.table(f"sdp_test.{table}") + .select("id", "ts", "value").orderBy("ts").collect()] + assert actual == expected, (table, actual, expected) + properties = dict(spark.sql(f"SHOW TBLPROPERTIES sdp_test.{table}").collect()) + assert not any("write.operation" in key for key in properties), properties + print(f"Verified {mode}: incremental upstream-to-downstream rows through Spark Connect") + finally: + spark.stop() + + +def scenario(harness, table_type, metadata): + flows = FLOWS.format(table_type=table_type) + input_dir = harness.root / "input" + input_dir.mkdir() + (harness.root / "source.py").write_text(SOURCE) + (harness.root / "flows.sql").write_text(flows) + spec = { + "name": "hudi_chaining", + "storage": (harness.root / "checkpoints").as_uri(), + "catalog": "spark_catalog", + "database": "sdp_test", + "libraries": [{"glob": {"include": "source.py"}}, {"glob": {"include": "flows.sql"}}], + "configuration": { + "hudi.test.input": input_dir.as_uri(), + "spark.hoodie.datasource.read.streaming.recovery.strategy": "FAIL", + "spark.sql.shuffle.partitions": "2", + "spark.sql.pipelines.maxFlowRetryAttempts": "0", + "spark.hoodie.metadata.enable": str(metadata).lower(), + "spark.hoodie.datasource.compaction.async.enable": str(table_type == "mor").lower(), + "spark.hoodie.compact.inline.max.delta.commits": "1", + }, + } + spec_path = harness.root / "spark-pipeline.yml" + spec_path.write_text(json.dumps(spec, indent=2)) + for name in ("source.py", "flows.sql", "spark-pipeline.yml"): + (harness.logs / name).write_text((harness.root / name).read_text()) + for name, timestamp, value in (("first", 1, "old"), ("second", 2, "new")): + row = json.dumps({"id": 1, "ts": timestamp, "value": value}) + "\n" + (input_dir / f"{name}.json").write_text(row * (2 if name == "first" else 1)) + harness.run_pipeline(spec_path, name=f"pipeline-{name}") + harness.client(Path(__file__).resolve(), name) + def commits(): + result = {} + for table in ("upsert_events", "downstream_events"): + timeline = harness.root / "warehouse" / "sdp_test.db" / table / ".hoodie" / "timeline" + result[table] = sorted(p.name for p in timeline.iterdir() + if p.suffix in (".commit", ".deltacommit", ".replacecommit")) + assert result[table], f"No completed commits found for {table}" + return result + + before = commits() + if table_type == "mor": + # The upsert update creates a log file and must actually exercise async compaction. + assert any(name.endswith(".commit") for name in before["upsert_events"]), before + # AvailableNow may capture its end offset before async compaction completes. + # Drain that maintenance instant before asserting a quiescent restart. + harness.run_pipeline(spec_path, name="pipeline-compaction-catchup") + harness.client(Path(__file__).resolve(), "restart") + caught_up = commits() + assert before["upsert_events"] == caught_up["upsert_events"], (before, caught_up) + (harness.logs / "compaction-catchup.json").write_text( + json.dumps({"before": before, "after": caught_up}, indent=2)) + before = caught_up + + # Restart with no new input must leave both outputs and the completed timeline unchanged. + harness.run_pipeline(spec_path, name="pipeline-restart") + harness.client(Path(__file__).resolve(), "restart") + after = commits() + assert before == after, (before, after) + (harness.logs / "restart-commits.json").write_text(json.dumps({"before": before, "after": after}, indent=2)) + downstream_before = commits()["downstream_events"] + harness.client(Path(__file__).resolve(), "truncate-upstream") + (input_dir / "third.json").write_text('{"id": 1, "ts": 3, "value": "reset"}\n') + try: + harness.run_pipeline(spec_path, name="pipeline-expected-reset-failure") + except RuntimeError: + log = (harness.logs / "pipeline-expected-reset-failure.log").read_text() + assert "rebuild required" in log, log[-4000:] + assert harness.server.poll() is None, "Source failure killed the Connect server" + else: + raise AssertionError("A recreated upstream table was accepted with the old checkpoint") + assert commits()["downstream_events"] == downstream_before + harness.client(Path(__file__).resolve(), "failed-reset") + # All flows are stopped. Rebuild every affected table and start with fresh checkpoints. + # The full-refresh CLI path separately depends on catalog DeleteColumn support (#20492). + harness.client(Path(__file__).resolve(), "truncate-graph") + spec["storage"] = (harness.root / "rebuild-checkpoints").as_uri() + spec_path.write_text(json.dumps(spec, indent=2)) + (harness.logs / "rebuild-spec.json").write_text(spec_path.read_text()) + harness.run_pipeline(spec_path, name="pipeline-rebuild") + harness.client(Path(__file__).resolve(), "rebuilt") + print("PASS: guarded restart, reset rejection before downstream commit, and coordinated rebuild") + + +def main(): + if len(sys.argv) == 4 and sys.argv[1] in ("first", "second", "restart", "truncate-upstream", "truncate-graph", "rebuilt", "failed-reset"): + verify(sys.argv[1], sys.argv[2], Path(sys.argv[3])) + return + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--harness-dir", type=Path, default=Path(__file__).resolve().parent) + parser.add_argument("--bundle", type=Path, required=True) + parser.add_argument("--logs", type=Path, default=Path("target/source-safety-acceptance-logs")) + parser.add_argument("--table-type", choices=("cow", "mor"), default="cow") + parser.add_argument("--metadata", choices=("enabled", "disabled"), default="disabled") + args = parser.parse_args() + if not (args.harness_dir / "harness.py").is_file(): + parser.error("The #20453 harness is required; pass its spark-pipelines directory with --harness-dir") + sys.path.insert(0, str(args.harness_dir.resolve())) + from harness import ConnectHarness + + args.logs.mkdir(parents=True, exist_ok=True) + logs = Path(tempfile.mkdtemp(prefix="run-", dir=args.logs.resolve())) + print(f"Source safety acceptance logs: {logs}", flush=True) + + def interrupted(signum, frame): + raise KeyboardInterrupt(f"Received signal {signum}") + + signal.signal(signal.SIGTERM, interrupted) + with ConnectHarness(args.bundle, logs) as harness: + scenario(harness, args.table_type, args.metadata == "enabled") + + +if __name__ == "__main__": + main() diff --git a/hudi-spark-datasource/hudi-spark-common/src/main/scala/org/apache/hudi/DataSourceOptions.scala b/hudi-spark-datasource/hudi-spark-common/src/main/scala/org/apache/hudi/DataSourceOptions.scala index ffdd58f85c6d..76881d8ec128 100644 --- a/hudi-spark-datasource/hudi-spark-common/src/main/scala/org/apache/hudi/DataSourceOptions.scala +++ b/hudi-spark-datasource/hudi-spark-common/src/main/scala/org/apache/hudi/DataSourceOptions.scala @@ -130,6 +130,28 @@ object DataSourceReadOptions { + "completion_time <= END_COMMIT are fetched out. " + "Point in time type queries make more sense with begin and end completion times specified.") + val STREAMING_READ_RECOVERY_STRATEGY: ConfigProperty[String] = ConfigProperty + .key("hoodie.datasource.read.streaming.recovery.strategy") + .defaultValue("FAIL") + .withValidValues("FAIL", "READ_UPTO_LATEST_COMMIT", "READ_LATEST") + .sinceVersion("1.3.0") + .withDocumentation("Recovery when a saved latest-state streaming offset is archived, cleaned, or reset. " + + "The source supports insert/upsert/delete plus compaction and clustering. INSERT OVERWRITE (table or partition), " + + "delete_partition writes and partition TTL (including hoodie.partition.ttl.inline) on an upstream table " + + "require recovery for downstream consumers. READ_LATEST drops the overwrite's new rows; " + + "READ_UPTO_LATEST_COMMIT replays the whole table, including unaffected partitions. " + + "FAIL stops with an actionable error and requires sinks to propagate execution errors; keep " + + "hoodie.datasource.write.streaming.ignore.failed.batch=false for Hudi sinks. " + + "READ_UPTO_LATEST_COMMIT reads a single full snapshot at the " + + "batch end, then resumes increments; this may duplicate append rows or retain stale downstream upsert keys. " + + "READ_LATEST skips the unread range, accepting data loss. Rebuilding downstream tables and checkpoints " + + "together is the safe reset recovery. This strategy overrides incremental full-table-scan fallback after the initial earliest offset. " + + "Initial earliest/latest/instant selection still uses hoodie.datasource.streaming.startOffset. " + + "Tune hoodie.keep.min.commits and hoodie.keep.max.commits for consumer lag. " + + "KEEP_LATEST_FILE_VERSIONS cleaning records no retention boundary, so any new clean deleting files " + + "requires recovery even if those files were not needed. For SDP internal reads set " + + "spark.hoodie.datasource.read.streaming.recovery.strategy in flow SQLConf. CDC is unchanged.") + val STREAMING_READ_TABLE_VERSION: ConfigProperty[String] = ConfigProperty .key("hoodie.datasource.read.streaming.table.version") .noDefaultValue() diff --git a/hudi-spark-datasource/hudi-spark-common/src/main/scala/org/apache/spark/sql/hudi/streaming/HoodieStreamSourceV1.scala b/hudi-spark-datasource/hudi-spark-common/src/main/scala/org/apache/spark/sql/hudi/streaming/HoodieStreamSourceV1.scala index ca2492967d72..0343d5abf602 100644 --- a/hudi-spark-datasource/hudi-spark-common/src/main/scala/org/apache/spark/sql/hudi/streaming/HoodieStreamSourceV1.scala +++ b/hudi-spark-datasource/hudi-spark-common/src/main/scala/org/apache/spark/sql/hudi/streaming/HoodieStreamSourceV1.scala @@ -19,7 +19,7 @@ package org.apache.spark.sql.hudi.streaming -import org.apache.hudi.{DataSourceReadOptions, HoodieCopyOnWriteCDCHadoopFsRelationFactory, HoodieCopyOnWriteIncrementalHadoopFsRelationFactoryV1, HoodieMergeOnReadCDCHadoopFsRelationFactory, HoodieMergeOnReadIncrementalHadoopFsRelationFactoryV1, HoodieSchemaConversionUtils, HoodieSparkUtils, IncrementalRelationV1, MergeOnReadIncrementalRelationV1, SparkAdapterSupport} +import org.apache.hudi.{DataSourceOptionsHelper, DataSourceReadOptions, HoodieCopyOnWriteCDCHadoopFsRelationFactory, HoodieCopyOnWriteIncrementalHadoopFsRelationFactoryV1, HoodieMergeOnReadCDCHadoopFsRelationFactory, HoodieMergeOnReadIncrementalHadoopFsRelationFactoryV1, HoodieSchemaConversionUtils, HoodieSparkUtils, IncrementalRelationV1, MergeOnReadIncrementalRelationV1, SparkAdapterSupport} import org.apache.hudi.DataSourceReadOptions.INCREMENTAL_READ_HANDLE_HOLLOW_COMMIT import org.apache.hudi.cdc.HoodieCDCFileIndex import org.apache.hudi.common.config.HoodieReaderConfig @@ -59,6 +59,10 @@ class HoodieStreamSourceV1(sqlContext: SQLContext, .getStringWithAltKeys(parameters, HoodieReaderConfig.FILE_GROUP_READER_ENABLED).toBoolean + // Capture flow-scoped SQLConf once; explicit reader options take precedence. + private val recoveryStrategy = HoodieStreamingSourceSafety.strategy( + DataSourceOptionsHelper.collectHoodieAndSparkHoodieConfs(sqlContext, parameters)) + private lazy val tableType = metaClient.getTableType private lazy val isBootstrappedTable = metaClient.getTableConfig.getBootstrapBasePath.isPresent @@ -108,10 +112,12 @@ class HoodieStreamSourceV1(sqlContext: SQLContext, } } + private var legacyEnd: Option[HoodieSourceOffset] = None + private def getLatestOffset: Option[HoodieSourceOffset] = { metaClient.reloadActiveTimeline() val filteredTimeline = handleHollowCommitIfNeeded( - metaClient.getActiveTimeline.filterCompletedInstants(), metaClient, hollowCommitHandlingMode) + metaClient.getActiveTimeline.getWriteTimeline.filterCompletedInstants(), metaClient, hollowCommitHandlingMode) filteredTimeline match { case activeInstants if !activeInstants.empty() => val timestamp = if (hollowCommitHandlingMode == USE_TRANSITION_TIME) { @@ -130,69 +136,85 @@ class HoodieStreamSourceV1(sqlContext: SQLContext, * @return */ override def getOffset: Option[Offset] = { - getLatestOffset + val latest = getLatestOffset + legacyEnd.filter(old => latest.forall(_.offsetCommitTime <= old.offsetCommitTime)).orElse(latest) } override def getBatch(start: Option[Offset], end: Offset): DataFrame = { - var startOffset = start.map(HoodieSourceOffset(_)) - .getOrElse(initialOffsets) - var endOffset = HoodieSourceOffset(end) + legacyEnd = HoodieStreamingSourceSafety.legacyOffset(metaClient, HoodieSourceOffset(end), + completionTime = hollowCommitHandlingMode == USE_TRANSITION_TIME) + val batchStart = start.map(HoodieSourceOffset(_)).getOrElse(initialOffsets) + if (isCDCQuery) buildBatch(start, end, batchStart) else { + HoodieStreamingSourceSafety.deferRejection(sqlContext, schema) { buildBatch(start, end, batchStart) } + } + } - // We update the offsets here since until this point the latest offsets have been - // calculated no matter if it is in the expected version. - // We translate them here, then the rest logic should be intact. - startOffset = HoodieSourceOffset(translateCheckpoint(startOffset.offsetCommitTime)) - endOffset = HoodieSourceOffset(translateCheckpoint(endOffset.offsetCommitTime)) + private def buildBatch(start: Option[Offset], end: Offset, batchStart: HoodieSourceOffset): DataFrame = { + var startOffset = batchStart + var endOffset = HoodieSourceOffset(end) - if (startOffset == endOffset) { - sparkAdapter.internalCreateDataFrame(sqlContext.sparkSession, - sqlContext.sparkContext.emptyRDD[InternalRow].setName("empty"), schema, isStreaming = true) - } else { - if (isCDCQuery) { - val cdcOptions = Map( - DataSourceReadOptions.START_COMMIT.key()-> startCommitTime(startOffset), - DataSourceReadOptions.END_COMMIT.key() -> endOffset.offsetCommitTime - ) - val relation = if (tableType == HoodieTableType.COPY_ON_WRITE) { - new HoodieCopyOnWriteCDCHadoopFsRelationFactory( - sqlContext, metaClient, parameters ++ cdcOptions, schemaOption, isBootstrappedTable).build() - } else { - new HoodieMergeOnReadCDCHadoopFsRelationFactory( - sqlContext, metaClient, parameters ++ cdcOptions, schemaOption, isBootstrappedTable).build() - } - sparkAdapter.createStreamingDataFrame(sqlContext, relation, HoodieCDCFileIndex.FULL_CDC_SPARK_SCHEMA) + val recovery = if (isCDCQuery) None else HoodieStreamingSourceSafety.recover( + sqlContext, metaClient, schema, parameters, recoveryStrategy, startOffset.offsetCommitTime, + endOffset.offsetCommitTime, completionTime = hollowCommitHandlingMode == USE_TRANSITION_TIME, resumed = start.isDefined) + recovery.getOrElse { + // We update the offsets here since until this point the latest offsets have been + // calculated no matter if it is in the expected version. + // We translate them here, then the rest logic should be intact. + startOffset = HoodieSourceOffset(translateCheckpoint(startOffset.offsetCommitTime)) + endOffset = HoodieSourceOffset(translateCheckpoint(endOffset.offsetCommitTime)) + + if (startOffset == endOffset) { + sparkAdapter.internalCreateDataFrame(sqlContext.sparkSession, + sqlContext.sparkContext.emptyRDD[InternalRow].setName("empty"), schema, isStreaming = true) } else { - // Consume the data between (startCommitTime, endCommitTime] - val incParams = parameters ++ Map( - DataSourceReadOptions.QUERY_TYPE.key -> DataSourceReadOptions.QUERY_TYPE_INCREMENTAL_OPT_VAL, - DataSourceReadOptions.START_COMMIT.key -> startCommitTime(startOffset), - DataSourceReadOptions.END_COMMIT.key -> endOffset.offsetCommitTime, - INCREMENTAL_READ_HANDLE_HOLLOW_COMMIT.key -> hollowCommitHandlingMode.name - ) - if (enableFileGroupReader) { + if (isCDCQuery) { + val cdcOptions = Map( + DataSourceReadOptions.START_COMMIT.key()-> startCommitTime(startOffset), + DataSourceReadOptions.END_COMMIT.key() -> endOffset.offsetCommitTime + ) val relation = if (tableType == HoodieTableType.COPY_ON_WRITE) { - new HoodieCopyOnWriteIncrementalHadoopFsRelationFactoryV1(sqlContext, metaClient, incParams, Option(schema), isBootstrappedTable) - .build() + new HoodieCopyOnWriteCDCHadoopFsRelationFactory( + sqlContext, metaClient, parameters ++ cdcOptions, schemaOption, isBootstrappedTable).build() } else { - new HoodieMergeOnReadIncrementalHadoopFsRelationFactoryV1(sqlContext, metaClient, incParams, Option(schema), isBootstrappedTable) - .build() + new HoodieMergeOnReadCDCHadoopFsRelationFactory( + sqlContext, metaClient, parameters ++ cdcOptions, schemaOption, isBootstrappedTable).build() } - sparkAdapter.createStreamingDataFrame(sqlContext, relation, schema) + sparkAdapter.createStreamingDataFrame(sqlContext, relation, HoodieCDCFileIndex.FULL_CDC_SPARK_SCHEMA) } else { - val requiredColumns = schema.fields.map(_.name) - val rdd = tableType match { - case HoodieTableType.COPY_ON_WRITE => - val serDe = HoodieSparkUtils.getCatalystRowSerDe(schema) - new IncrementalRelationV1(sqlContext, incParams, Some(schema), metaClient) - .buildScan(requiredColumns) - .map(serDe.serializeRow) - case HoodieTableType.MERGE_ON_READ => - new MergeOnReadIncrementalRelationV1(sqlContext, incParams, metaClient, Some(schema)) - .buildScan(requiredColumns, Array.empty[Filter]) - .asInstanceOf[RDD[InternalRow]] - case _ => throw new IllegalArgumentException(s"UnSupport tableType: $tableType") + // Consume the data between (startCommitTime, endCommitTime] + val fallbackOptions = if (startOffset == INIT_OFFSET) Map.empty[String, String] else Map( + DataSourceReadOptions.INCREMENTAL_FALLBACK_TO_FULL_TABLE_SCAN.key() -> "false") + val incParams = parameters ++ fallbackOptions ++ Map( + DataSourceReadOptions.QUERY_TYPE.key -> DataSourceReadOptions.QUERY_TYPE_INCREMENTAL_OPT_VAL, + DataSourceReadOptions.START_COMMIT.key -> startCommitTime(startOffset), + DataSourceReadOptions.END_COMMIT.key -> endOffset.offsetCommitTime, + INCREMENTAL_READ_HANDLE_HOLLOW_COMMIT.key -> hollowCommitHandlingMode.name + ) + if (enableFileGroupReader) { + val relation = if (tableType == HoodieTableType.COPY_ON_WRITE) { + new HoodieCopyOnWriteIncrementalHadoopFsRelationFactoryV1(sqlContext, metaClient, incParams, Option(schema), isBootstrappedTable) + .build() + } else { + new HoodieMergeOnReadIncrementalHadoopFsRelationFactoryV1(sqlContext, metaClient, incParams, Option(schema), isBootstrappedTable) + .build() + } + sparkAdapter.createStreamingDataFrame(sqlContext, relation, schema) + } else { + val requiredColumns = schema.fields.map(_.name) + val rdd = tableType match { + case HoodieTableType.COPY_ON_WRITE => + val serDe = HoodieSparkUtils.getCatalystRowSerDe(schema) + new IncrementalRelationV1(sqlContext, incParams, Some(schema), metaClient) + .buildScan(requiredColumns) + .map(serDe.serializeRow) + case HoodieTableType.MERGE_ON_READ => + new MergeOnReadIncrementalRelationV1(sqlContext, incParams, metaClient, Some(schema)) + .buildScan(requiredColumns, Array.empty[Filter]) + .asInstanceOf[RDD[InternalRow]] + case _ => throw new IllegalArgumentException(s"UnSupport tableType: $tableType") + } + sparkAdapter.internalCreateDataFrame(sqlContext.sparkSession,rdd, schema, isStreaming = true) } - sparkAdapter.internalCreateDataFrame(sqlContext.sparkSession,rdd, schema, isStreaming = true) } } } diff --git a/hudi-spark-datasource/hudi-spark-common/src/main/scala/org/apache/spark/sql/hudi/streaming/HoodieStreamSourceV2.scala b/hudi-spark-datasource/hudi-spark-common/src/main/scala/org/apache/spark/sql/hudi/streaming/HoodieStreamSourceV2.scala index 11a44f58a0b6..ff5824100d1a 100644 --- a/hudi-spark-datasource/hudi-spark-common/src/main/scala/org/apache/spark/sql/hudi/streaming/HoodieStreamSourceV2.scala +++ b/hudi-spark-datasource/hudi-spark-common/src/main/scala/org/apache/spark/sql/hudi/streaming/HoodieStreamSourceV2.scala @@ -17,7 +17,7 @@ package org.apache.spark.sql.hudi.streaming -import org.apache.hudi.{DataSourceReadOptions, HoodieCopyOnWriteCDCHadoopFsRelationFactory, HoodieCopyOnWriteIncrementalHadoopFsRelationFactoryV2, HoodieMergeOnReadCDCHadoopFsRelationFactory, HoodieMergeOnReadIncrementalHadoopFsRelationFactoryV2, HoodieSchemaConversionUtils, HoodieSparkUtils, IncrementalRelationV2, MergeOnReadIncrementalRelationV2, SparkAdapterSupport} +import org.apache.hudi.{DataSourceOptionsHelper, DataSourceReadOptions, HoodieCopyOnWriteCDCHadoopFsRelationFactory, HoodieCopyOnWriteIncrementalHadoopFsRelationFactoryV2, HoodieMergeOnReadCDCHadoopFsRelationFactory, HoodieMergeOnReadIncrementalHadoopFsRelationFactoryV2, HoodieSchemaConversionUtils, HoodieSparkUtils, IncrementalRelationV2, MergeOnReadIncrementalRelationV2, SparkAdapterSupport} import org.apache.hudi.cdc.HoodieCDCFileIndex import org.apache.hudi.common.config.HoodieReaderConfig import org.apache.hudi.common.model.HoodieTableType @@ -51,6 +51,10 @@ class HoodieStreamSourceV2(sqlContext: SQLContext, writeTableVersion: HoodieTableVersion) extends Source with Logging with Serializable with SparkAdapterSupport { + // Capture flow-scoped SQLConf once; explicit reader options take precedence. + private val recoveryStrategy = HoodieStreamingSourceSafety.strategy( + DataSourceOptionsHelper.collectHoodieAndSparkHoodieConfs(sqlContext, parameters)) + private lazy val tableType = metaClient.getTableType private lazy val isBootstrappedTable = metaClient.getTableConfig.getBootstrapBasePath.isPresent @@ -90,9 +94,11 @@ class HoodieStreamSourceV2(sqlContext: SQLContext, } } + private var legacyEnd: Option[HoodieSourceOffset] = None + private def getLatestOffset: Option[HoodieSourceOffset] = { metaClient.reloadActiveTimeline() - val latestCompletionTime = metaClient.getActiveTimeline.filterCompletedInstants.getLatestCompletionTime + val latestCompletionTime = metaClient.getActiveTimeline.getWriteTimeline.filterCompletedInstants.getLatestCompletionTime if (latestCompletionTime.isPresent) { Some(HoodieSourceOffset(latestCompletionTime.get)) } else { @@ -105,70 +111,86 @@ class HoodieStreamSourceV2(sqlContext: SQLContext, * @return */ override def getOffset: Option[Offset] = { - getLatestOffset + val latest = getLatestOffset + legacyEnd.filter(old => latest.forall(_.offsetCommitTime <= old.offsetCommitTime)).orElse(latest) } override def getBatch(start: Option[Offset], end: Offset): DataFrame = { - var startOffset = start.map(HoodieSourceOffset(_)) - .getOrElse(initialOffsets) - var endOffset = HoodieSourceOffset(end) + legacyEnd = HoodieStreamingSourceSafety.legacyOffset(metaClient, HoodieSourceOffset(end), + completionTime = true) + val batchStart = start.map(HoodieSourceOffset(_)).getOrElse(initialOffsets) + if (isCDCQuery) buildBatch(start, end, batchStart) else { + HoodieStreamingSourceSafety.deferRejection(sqlContext, schema) { buildBatch(start, end, batchStart) } + } + } - // We update the offsets here since until this point the latest offsets have been - // calculated no matter if it is in the expected version. - // We translate them here, then the rest logic should be intact. - startOffset = HoodieSourceOffset(translateCheckpoint(startOffset.offsetCommitTime)) - endOffset = HoodieSourceOffset(translateCheckpoint(endOffset.offsetCommitTime)) + private def buildBatch(start: Option[Offset], end: Offset, batchStart: HoodieSourceOffset): DataFrame = { + var startOffset = batchStart + var endOffset = HoodieSourceOffset(end) - if (startOffset == endOffset) { - sparkAdapter.internalCreateDataFrame(sqlContext.sparkSession, - sqlContext.sparkContext.emptyRDD[InternalRow].setName("empty"), schema, isStreaming = true) - } else { - val (startCompletionTime, rangeType) = getStartCompletionTimeAndRangeType(startOffset) - if (isCDCQuery) { - val cdcOptions = Map( - DataSourceReadOptions.START_COMMIT.key() -> startCompletionTime, - DataSourceReadOptions.END_COMMIT.key() -> endOffset.offsetCommitTime - ) - val relation = if (tableType == HoodieTableType.COPY_ON_WRITE) { - new HoodieCopyOnWriteCDCHadoopFsRelationFactory( - sqlContext, metaClient, parameters ++ cdcOptions, schemaOption, isBootstrappedTable, rangeType).build() - } else { - new HoodieMergeOnReadCDCHadoopFsRelationFactory( - sqlContext, metaClient, parameters ++ cdcOptions, schemaOption, isBootstrappedTable, rangeType).build() - } - sparkAdapter.createStreamingDataFrame(sqlContext, relation, HoodieCDCFileIndex.FULL_CDC_SPARK_SCHEMA) + val recovery = if (isCDCQuery) None else HoodieStreamingSourceSafety.recover( + sqlContext, metaClient, schema, parameters, recoveryStrategy, startOffset.offsetCommitTime, + endOffset.offsetCommitTime, completionTime = true, resumed = start.isDefined) + recovery.getOrElse { + // We update the offsets here since until this point the latest offsets have been + // calculated no matter if it is in the expected version. + // We translate them here, then the rest logic should be intact. + startOffset = HoodieSourceOffset(translateCheckpoint(startOffset.offsetCommitTime)) + endOffset = HoodieSourceOffset(translateCheckpoint(endOffset.offsetCommitTime)) + + if (startOffset == endOffset) { + sparkAdapter.internalCreateDataFrame(sqlContext.sparkSession, + sqlContext.sparkContext.emptyRDD[InternalRow].setName("empty"), schema, isStreaming = true) } else { - // Consume the data between (startCommitTime, endCommitTime] - val incParams = parameters ++ Map( - DataSourceReadOptions.QUERY_TYPE.key -> DataSourceReadOptions.QUERY_TYPE_INCREMENTAL_OPT_VAL, - DataSourceReadOptions.START_COMMIT.key -> startCompletionTime, - DataSourceReadOptions.END_COMMIT.key -> endOffset.offsetCommitTime - ) - - if (enableFileGroupReader) { + val (startCompletionTime, rangeType) = getStartCompletionTimeAndRangeType(startOffset) + if (isCDCQuery) { + val cdcOptions = Map( + DataSourceReadOptions.START_COMMIT.key() -> startCompletionTime, + DataSourceReadOptions.END_COMMIT.key() -> endOffset.offsetCommitTime + ) val relation = if (tableType == HoodieTableType.COPY_ON_WRITE) { - new HoodieCopyOnWriteIncrementalHadoopFsRelationFactoryV2(sqlContext, metaClient, incParams, Option(schema), isBootstrappedTable, rangeType) - .build() + new HoodieCopyOnWriteCDCHadoopFsRelationFactory( + sqlContext, metaClient, parameters ++ cdcOptions, schemaOption, isBootstrappedTable, rangeType).build() } else { - new HoodieMergeOnReadIncrementalHadoopFsRelationFactoryV2(sqlContext, metaClient, incParams, Option(schema), isBootstrappedTable, rangeType) - .build() + new HoodieMergeOnReadCDCHadoopFsRelationFactory( + sqlContext, metaClient, parameters ++ cdcOptions, schemaOption, isBootstrappedTable, rangeType).build() } - sparkAdapter.createStreamingDataFrame(sqlContext, relation, schema) + sparkAdapter.createStreamingDataFrame(sqlContext, relation, HoodieCDCFileIndex.FULL_CDC_SPARK_SCHEMA) } else { - val requiredColumns = schema.fields.map(_.name) - val rdd = tableType match { - case HoodieTableType.COPY_ON_WRITE => - val serDe = HoodieSparkUtils.getCatalystRowSerDe(schema) - new IncrementalRelationV2(sqlContext, incParams, Some(schema), metaClient, rangeType) - .buildScan(requiredColumns) - .map(serDe.serializeRow) - case HoodieTableType.MERGE_ON_READ => - MergeOnReadIncrementalRelationV2(sqlContext, incParams, metaClient, Some(schema), rangeType = rangeType) - .buildScan(requiredColumns, Array.empty[Filter]) - .asInstanceOf[RDD[InternalRow]] - case _ => throw new IllegalArgumentException(s"UnSupport tableType: $tableType") - } - sparkAdapter.internalCreateDataFrame(sqlContext.sparkSession, rdd, schema, isStreaming = true)} + // Consume the data between (startCommitTime, endCommitTime] + val fallbackOptions = if (startOffset == INIT_OFFSET) Map.empty[String, String] else Map( + DataSourceReadOptions.INCREMENTAL_FALLBACK_TO_FULL_TABLE_SCAN.key() -> "false") + val incParams = parameters ++ fallbackOptions ++ Map( + DataSourceReadOptions.QUERY_TYPE.key -> DataSourceReadOptions.QUERY_TYPE_INCREMENTAL_OPT_VAL, + DataSourceReadOptions.START_COMMIT.key -> startCompletionTime, + DataSourceReadOptions.END_COMMIT.key -> endOffset.offsetCommitTime + ) + + if (enableFileGroupReader) { + val relation = if (tableType == HoodieTableType.COPY_ON_WRITE) { + new HoodieCopyOnWriteIncrementalHadoopFsRelationFactoryV2(sqlContext, metaClient, incParams, Option(schema), isBootstrappedTable, rangeType) + .build() + } else { + new HoodieMergeOnReadIncrementalHadoopFsRelationFactoryV2(sqlContext, metaClient, incParams, Option(schema), isBootstrappedTable, rangeType) + .build() + } + sparkAdapter.createStreamingDataFrame(sqlContext, relation, schema) + } else { + val requiredColumns = schema.fields.map(_.name) + val rdd = tableType match { + case HoodieTableType.COPY_ON_WRITE => + val serDe = HoodieSparkUtils.getCatalystRowSerDe(schema) + new IncrementalRelationV2(sqlContext, incParams, Some(schema), metaClient, rangeType) + .buildScan(requiredColumns) + .map(serDe.serializeRow) + case HoodieTableType.MERGE_ON_READ => + MergeOnReadIncrementalRelationV2(sqlContext, incParams, metaClient, Some(schema), rangeType = rangeType) + .buildScan(requiredColumns, Array.empty[Filter]) + .asInstanceOf[RDD[InternalRow]] + case _ => throw new IllegalArgumentException(s"UnSupport tableType: $tableType") + } + sparkAdapter.internalCreateDataFrame(sqlContext.sparkSession, rdd, schema, isStreaming = true)} + } } } } diff --git a/hudi-spark-datasource/hudi-spark-common/src/main/scala/org/apache/spark/sql/hudi/streaming/HoodieStreamingSourceSafety.scala b/hudi-spark-datasource/hudi-spark-common/src/main/scala/org/apache/spark/sql/hudi/streaming/HoodieStreamingSourceSafety.scala new file mode 100644 index 000000000000..66700dfc456e --- /dev/null +++ b/hudi-spark-datasource/hudi-spark-common/src/main/scala/org/apache/spark/sql/hudi/streaming/HoodieStreamingSourceSafety.scala @@ -0,0 +1,212 @@ +/* + * 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, TimelineUtils} +import org.apache.hudi.common.util.CleanerUtils +import org.apache.hudi.exception.{HoodieException, HoodieTimeTravelException} + +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) + } + } + + // Spark supplies the last committed end through its discarded restart getBatch call. + // Preserve legacy service offsets until a write catches up, without masking removed writes. + def legacyOffset(metaClient: HoodieTableMetaClient, end: HoodieSourceOffset, + completionTime: Boolean): Option[HoodieSourceOffset] = { + val timeline = metaClient.reloadActiveTimeline() + def matches(i: HoodieInstant): Boolean = + (if (completionTime) i.getCompletionTime else i.requestedTime()) == end.offsetCommitTime + val isWrite = timeline.getWriteTimeline.filterCompletedInstants().getInstants.asScala.exists(matches) + if (!isWrite && timeline.filterCompletedInstants().getInstants.asScala.exists(matches)) Some(end) else None + } + + 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) + } + try { + TimelineUtils.validateTimestampAsOf(metaClient, bound.get) + } catch { + case cause: IllegalArgumentException => + throw new RebuildRequired("Cannot reconstruct the recovery snapshot: recorded batch end is outside cleaner retention. " + + "Use READ_LATEST to skip the gap or rebuild downstream tables and checkpoints together.", cause) + case cause: HoodieTimeTravelException => + throw new RebuildRequired("Cannot reconstruct the recovery snapshot at the recorded batch end: " + + "a pending write or unavailable cleaner history prevents time travel. Wait for pending writes to complete, " + + "use READ_LATEST to skip the gap, or rebuild downstream tables and checkpoints together.", cause) + } + 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).") + } + + val checkpointInstant = completed.find(i => offset(i) == start) + if (resumed && checkpointInstant.isEmpty) { + fail(s"saved offset $start is absent from the active timeline; history expired or the source table was recreated") + } + if (end < start) { + fail(s"source offset moved backwards from $start to $end") + } + + val firstWrite = timeline.getWriteTimeline.filterCompletedInstants().firstInstant() + val requestedStart = checkpointInstant.map(_.requestedTime()) + val unreadWrites = timeline.getCommitsTimeline.filterCompletedInstants().getInstants.asScala + .filter(i => offset(i) > start && offset(i) <= end).toSeq + val earliestUnread = unreadWrites.map(_.requestedTime()).reduceOption((a, b) => if (a < b) a else b) + val completedByRequestedTime = completed.map(i => i.requestedTime() -> i).toMap + // Usually only new cleans matter. Retain earlier cleans for late-completing writes, + // or a user-specified initial offset whose requested-time boundary is unknown. + timeline.getCleanerTimeline.filterCompletedInstants().getInstants.asScala + .filter(clean => offset(clean) > start || requestedStart.isEmpty || + requestedStart.exists(_ < clean.requestedTime()) || earliestUnread.exists(_ < clean.requestedTime())) + .foreach { clean => + val metadata = CleanerUtils.getCleanerMetadata(metaClient, clean) + val retained = metadata.getEarliestCommitToRetain + // File-version cleaning does not expose a retention boundary. Refuse to infer safety. + if ((retained == null || retained.isEmpty) && metadata.getTotalFilesDeleted > 0 && offset(clean) > start) { + fail("the cleaner did not record an earliest retained commit; KEEP_LATEST_FILE_VERSIONS " + + "cannot prove incremental safety after deleting files") + } + val boundary = Option(retained).filter(_.nonEmpty) + val retainedInstant = completedByRequestedTime.get(retained) + val expired = boundary.exists { floor => + earliestUnread.exists(_ < floor) || + (requestedStart.isEmpty && retainedInstant.exists(i => start < offset(i))) || + (requestedStart.isEmpty && retainedInstant.isEmpty && firstWrite.isPresent && start < offset(firstWrite.get)) + } + if (expired) { + fail(s"history after offset $start has been cleaned (earliest retained commit $retained)") + } + } + + completed.filter(i => i.getAction == HoodieTimeline.REPLACE_COMMIT_ACTION && + offset(i) > start).foreach { instant => + val operation = timeline.readReplaceCommitMetadata(instant).getOperationType + if (operation != WriteOperationType.CLUSTER) { + fail(s"logical reset $operation at ${instant.requestedTime()} follows offset $start") + } + } + } +} diff --git a/hudi-spark-datasource/hudi-spark/src/test/scala/org/apache/hudi/functional/TestStreamingSource.scala b/hudi-spark-datasource/hudi-spark/src/test/scala/org/apache/hudi/functional/TestStreamingSource.scala index 4fa1113b0261..4746706fdfb0 100644 --- a/hudi-spark-datasource/hudi-spark/src/test/scala/org/apache/hudi/functional/TestStreamingSource.scala +++ b/hudi-spark-datasource/hudi-spark/src/test/scala/org/apache/hudi/functional/TestStreamingSource.scala @@ -17,9 +17,9 @@ package org.apache.hudi.functional -import org.apache.hudi.{DataSourceReadOptions, HoodieSparkUtils} +import org.apache.hudi.{DataSourceReadOptions, HoodieSparkUtils, SparkAdapterSupport} import org.apache.hudi.DataSourceReadOptions.{START_OFFSET, STREAMING_READ_TABLE_VERSION} -import org.apache.hudi.DataSourceWriteOptions.{ORDERING_FIELDS, RECORDKEY_FIELD, TABLE_TYPE} +import org.apache.hudi.DataSourceWriteOptions.{ORDERING_FIELDS, PARTITIONPATH_FIELD, RECORDKEY_FIELD, TABLE_TYPE} import org.apache.hudi.common.config.HoodieReaderConfig import org.apache.hudi.common.fs.FSUtils import org.apache.hudi.common.model.HoodieTableType @@ -38,7 +38,7 @@ import org.apache.spark.sql.{DataFrame, Row, SaveMode} import org.apache.spark.sql.streaming.StreamTest import org.junit.jupiter.api.Assertions.{assertEquals, assertTrue} -class TestStreamingSource extends StreamTest { +class TestStreamingSource extends StreamTest with SparkAdapterSupport { import testImplicits._ protected val commonOptions: Map[String, String] = Map( @@ -651,6 +651,457 @@ class TestStreamingSource extends StreamTest { ) } + test("pin requested-time source version across a v6 to v8 upgrade") { + withTempDir { dir => + val tablePath = s"${dir.getCanonicalPath}/upgrade" + addData(tablePath, Seq(("1", "old", "10", "001")), tableVersion = HoodieTableVersion.SIX) + def source(version: Option[String]): org.apache.spark.sql.execution.streaming.Source = { + val options = Map("path" -> tablePath) ++ version.map(STREAMING_READ_TABLE_VERSION.key() -> _) + new org.apache.hudi.DefaultSource().createSource(spark.sqlContext, + s"${dir.getCanonicalPath}/checkpoint", None, "hudi", options) + } + val saved = source(Some("6")).getOffset.get + addData(tablePath, Seq(("2", "new", "20", "002")), tableVersion = HoodieTableVersion.EIGHT) + val switched = source(None) + assert(intercept[org.apache.hudi.exception.HoodieException] { + batchIds(switched.getBatch(Some(saved), switched.getOffset.get)) + }.getMessage.contains("saved offset")) + val pinned = source(Some("6")) + assert(batchIds(pinned.getBatch(Some(saved), pinned.getOffset.get)) == Seq("2")) + } + } + + Seq("6", "8").foreach { readVersion => + test(s"restored write checkpoint is rejected: readVersion=$readVersion") { + withTempDir { dir => + val tablePath = s"${dir.getCanonicalPath}/restore" + addData(tablePath, Seq(("1", "kept", "10", "001"))) + val metaClient = HoodieTableMetaClient.builder() + .setConf(HadoopFSUtils.getStorageConf(spark.sessionState.newHadoopConf())) + .setBasePath(tablePath).build() + val restoreTime = metaClient.getActiveTimeline.getWriteTimeline.filterCompletedInstants().lastInstant().get().requestedTime() + addData(tablePath, Seq(("2", "removed", "20", "002"))) + val reader = new org.apache.hudi.DefaultSource().createSource(spark.sqlContext, + s"${dir.getCanonicalPath}/checkpoint", None, "hudi", + Map("path" -> tablePath, STREAMING_READ_TABLE_VERSION.key() -> readVersion)) + val saved = reader.getOffset.get + spark.sql(s"call restore_to_instant(path => '$tablePath', instant_time => '$restoreTime')").collect() + addData(tablePath, Seq(("3", "next", "30", "003"))) + assert(intercept[org.apache.hudi.exception.HoodieException] { + batchIds(reader.getBatch(Some(saved), reader.getOffset.get)) + }.getMessage.contains("saved offset")) + } + } + } + + Seq("READ_UPTO_LATEST_COMMIT", "READ_LATEST").foreach { recoveryStrategy => + test(s"restart failed batch with $recoveryStrategy then return to FAIL") { + withSQLConf(DataSourceReadOptions.STREAMING_READ_RECOVERY_STRATEGY.key() -> "FAIL") { + withTempDir { dir => + val tablePath = s"${dir.getCanonicalPath}/restart" + addData(tablePath, Seq(("1", "old", "10", "001"))) + val df = spark.readStream.format("hudi").load(tablePath).select("id") + val recoveryRows = if (recoveryStrategy == "READ_LATEST") Seq(Row("1")) else Seq(Row("1"), Row("2")) + testStream(df)( + StartStream(additionalConfs = Map(DataSourceReadOptions.STREAMING_READ_RECOVERY_STRATEGY.key() -> "FAIL")), + AssertOnQuery { q => q.processAllAvailable(); true }, + CheckAnswerRows(Seq(Row("1")), lastOnly = false, isSorted = false), + StopStream, + AssertOnQuery { _ => + Seq(("2", "replacement", "20", "002")).toDF(columns: _*).write.format("hudi") + .options(commonOptions).option(TBL_NAME.key, "restart") + .option("hoodie.datasource.write.operation", "insert_overwrite_table") + .mode(SaveMode.Append).save(tablePath) + true + }, + StartStream(additionalConfs = Map(DataSourceReadOptions.STREAMING_READ_RECOVERY_STRATEGY.key() -> "FAIL")), + // StreamTest checks exact classes; the safety exception is intentionally private. + ExpectFailure[Throwable]()(scala.reflect.ClassTag( + Class.forName("org.apache.spark.sql.hudi.streaming.HoodieStreamingSourceSafety$RebuildRequired"))), + StartStream(additionalConfs = Map(DataSourceReadOptions.STREAMING_READ_RECOVERY_STRATEGY.key() -> recoveryStrategy)), + AssertOnQuery { q => q.processAllAvailable(); true }, + CheckAnswerRows(recoveryRows, lastOnly = false, isSorted = false), + StopStream, + addDataToQuery(tablePath, Seq(("3", "next", "30", "003"))), + StartStream(additionalConfs = Map(DataSourceReadOptions.STREAMING_READ_RECOVERY_STRATEGY.key() -> "FAIL")), + AssertOnQuery { q => q.processAllAvailable(); true }, + CheckAnswerRows(recoveryRows :+ Row("3"), lastOnly = false, isSorted = false) + ) + } + } + } + } + + Seq(COPY_ON_WRITE, MERGE_ON_READ).foreach { tableType => + Seq(false, true).foreach { completionTime => + test(s"guarded source requires recovery after partition overwrite: $tableType completionTime=$completionTime") { + withTempDir { dir => + val tablePath = s"${dir.getCanonicalPath}/partitioned" + val options = commonOptions ++ Map( + PARTITIONPATH_FIELD.key -> "name", TBL_NAME.key -> "partitioned", + TABLE_TYPE.key -> tableType.name()) + Seq(("1", "reloaded", "10", "001"), ("2", "retained", "20", "001")) + .toDF(columns: _*).write.format("hudi").options(options).mode(SaveMode.Append).save(tablePath) + val metaClient = HoodieTableMetaClient.builder() + .setConf(HadoopFSUtils.getStorageConf(spark.sessionState.newHadoopConf())) + .setBasePath(tablePath).build() + def source(strategy: String = "FAIL"): org.apache.spark.sql.execution.streaming.Source = { + val readOptions = options ++ Map("path" -> tablePath, + DataSourceReadOptions.STREAMING_READ_RECOVERY_STRATEGY.key() -> strategy) + val checkpoint = s"${dir.getCanonicalPath}/checkpoint" + if (completionTime) { + new org.apache.spark.sql.hudi.streaming.HoodieStreamSourceV2(spark.sqlContext, + metaClient, checkpoint, None, readOptions, + org.apache.spark.sql.hudi.streaming.HoodieEarliestOffsetRangeLimit, HoodieTableVersion.current()) + } else { + new org.apache.spark.sql.hudi.streaming.HoodieStreamSourceV1(spark.sqlContext, + metaClient, checkpoint, None, readOptions, + org.apache.spark.sql.hudi.streaming.HoodieEarliestOffsetRangeLimit, HoodieTableVersion.current()) + } + } + val reader = source() + val saved = reader.getOffset.get + Seq(("3", "reloaded", "30", "002")).toDF(columns: _*).write.format("hudi") + .options(options).option("hoodie.datasource.write.operation", "insert_overwrite") + .mode(SaveMode.Append).save(tablePath) + val end = reader.getOffset.get + val error = intercept[org.apache.hudi.exception.HoodieException] { + batchIds(reader.getBatch(Some(saved), end)) + } + assert(error.getMessage.contains("logical reset")) + // Snapshot recovery includes the untouched partition; skip recovery drops the new row too. + assert(batchIds(source("READ_UPTO_LATEST_COMMIT").getBatch(Some(saved), end)) == Seq("2", "3")) + assert(batchIds(source("READ_LATEST").getBatch(Some(saved), end)).isEmpty) + val pending = metaClient.getInstantGenerator.createNewInstant( + org.apache.hudi.common.table.timeline.HoodieInstant.State.INFLIGHT, + HoodieTimeline.COMMIT_ACTION, "20000101000000000") + metaClient.getActiveTimeline.createNewInstant(pending) + val pendingPlan = source("READ_UPTO_LATEST_COMMIT").getBatch(Some(saved), end) + assert(pendingPlan.isStreaming) + assert(intercept[org.apache.hudi.exception.HoodieException] { + batchIds(pendingPlan) + }.getMessage.contains("pending write")) + val pendingPath = new Path(metaClient.getTimelinePath.toString, + metaClient.getInstantFileNameGenerator.getFileName(pending)) + assert(pendingPath.getFileSystem(spark.sessionState.newHadoopConf()).delete(pendingPath, false)) + val cleanTime = "20990101000000000" + val clean = metaClient.getInstantGenerator.createNewInstant( + org.apache.hudi.common.table.timeline.HoodieInstant.State.INFLIGHT, HoodieTimeline.CLEAN_ACTION, cleanTime) + val metadata = org.apache.hudi.avro.model.HoodieCleanMetadata.newBuilder() + .setVersion(1).setTimeTakenInMillis(1).setTotalFilesDeleted(1).setStartCleanTime(cleanTime) + .setEarliestCommitToRetain(cleanTime).setPartitionMetadata(new java.util.HashMap()).build() + metaClient.reloadActiveTimeline().createNewInstant(clean) + val completedClean = completeTestInstant(metaClient, clean, metadata, "20990101000000001") + // Service completion cannot advance newly produced offsets. + assert(source().getOffset.get == end) + val legacyEnd = org.apache.spark.sql.hudi.streaming.HoodieSourceOffset( + if (completionTime) completedClean.getCompletionTime else completedClean.requestedTime()) + val legacyReader = source() + assert(legacyReader.getBatch(Some(end), legacyEnd).isStreaming) + assert(legacyReader.getOffset.get == legacyEnd) + assert(batchIds(legacyReader.getBatch(Some(legacyEnd), legacyEnd)).isEmpty) + val cleanedPlan = source("READ_UPTO_LATEST_COMMIT").getBatch(Some(saved), end) + assert(cleanedPlan.isStreaming) + assert(intercept[org.apache.hudi.exception.HoodieException] { + batchIds(cleanedPlan) + }.getMessage.contains("recorded batch end is outside cleaner retention")) + assert(batchIds(source("READ_LATEST").getBatch(Some(saved), end)).isEmpty) + } + } + + test(s"guarded source rejects resets and recreation: $tableType completionTime=$completionTime") { + withTempDir { dir => + val tablePath = s"${dir.getCanonicalPath}/guarded" + val conf = HadoopFSUtils.getStorageConf(spark.sessionState.newHadoopConf()) + def initialize(): HoodieTableMetaClient = HoodieTableMetaClient.newTableBuilder() + .setTableType(tableType).setTableName("guarded").setRecordKeyFields("id") + .setOrderingFields("ts").initTable(conf, tablePath) + val metaClient = initialize() + addData(tablePath, Seq(("1", "old", "10", "001"))) + def source(strategy: Option[String] = None): org.apache.spark.sql.execution.streaming.Source = { + val options = commonOptions + ("path" -> tablePath) ++ strategy.map { value => + DataSourceReadOptions.STREAMING_READ_RECOVERY_STRATEGY.key() -> value + } + val checkpoint = s"${dir.getCanonicalPath}/checkpoint" + if (completionTime) { + new org.apache.spark.sql.hudi.streaming.HoodieStreamSourceV2(spark.sqlContext, + metaClient, checkpoint, None, options, + org.apache.spark.sql.hudi.streaming.HoodieEarliestOffsetRangeLimit, + HoodieTableVersion.current()) + } else { + new org.apache.spark.sql.hudi.streaming.HoodieStreamSourceV1(spark.sqlContext, + metaClient, checkpoint, None, options, + org.apache.spark.sql.hudi.streaming.HoodieEarliestOffsetRangeLimit, + HoodieTableVersion.current()) + } + } + val reader = source() + val saved = reader.getOffset.get + addData(tablePath, Seq(("2", "new", "20", "002")), enableInlineCluster = true) + val healthyBatch = reader.getBatch(Some(saved), reader.getOffset.get) + assert(healthyBatch.queryExecution.logical.exists { + case _: org.apache.spark.sql.execution.datasources.LogicalRelation => true + case _ => false + }, "Healthy batches must expose the scan to pruning and predicate pushdown") + assert(batchIds(healthyBatch) == Seq("2")) + assert(metaClient.reloadActiveTimeline().getCompletedReplaceTimeline.countInstants() > 0) + val beforeResetEnd = reader.getOffset.get + Seq(("3", "replacement", "30", "003")).toDF(columns: _*).write.format("hudi") + .options(commonOptions).option(TBL_NAME.key, "guarded") + .option("hoodie.datasource.write.operation", "insert_overwrite_table") + .mode(SaveMode.Append).save(tablePath) + val resetEnd = reader.getOffset.get + val resetError = intercept[org.apache.hudi.exception.HoodieException] { + batchIds(reader.getBatch(Some(saved), resetEnd)) + } + assert(resetError.getMessage.contains("rebuild required")) + assert(resetError.getMessage.contains("logical reset")) + val concurrentResetError = intercept[org.apache.hudi.exception.HoodieException] { + batchIds(reader.getBatch(Some(saved), beforeResetEnd)) + } + assert(concurrentResetError.getMessage.contains("logical reset")) + Seq("hoodie.", "spark.hoodie.").foreach { prefix => + var sessionReader: org.apache.spark.sql.execution.streaming.Source = null + withSQLConf(prefix + "datasource.read.streaming.recovery.strategy" -> "READ_LATEST") { + sessionReader = source(strategy = None) + val explicitReader = source(strategy = Some("FAIL")) + intercept[org.apache.hudi.exception.HoodieException] { + batchIds(explicitReader.getBatch(Some(saved), resetEnd)) + } + } + assert(batchIds(sessionReader.getBatch(Some(saved), resetEnd)).isEmpty) + } + // Re-planning a committed recovery batch under FAIL must not execute its validation. + assert(source().getBatch(Some(saved), resetEnd).isStreaming) + val snapshotReader = source(Some("READ_UPTO_LATEST_COMMIT")) + assert(batchIds(snapshotReader.getBatch(Some(saved), resetEnd)) == Seq("3")) + if (completionTime) { + // A service requested before the snapshot bound may finish after Spark pinned end. + import org.apache.hudi.common.model.{HoodieCommitMetadata, HoodieReplaceCommitMetadata, WriteOperationType} + Seq(WriteOperationType.COMPACT, WriteOperationType.LOG_COMPACT, WriteOperationType.CLUSTER, + WriteOperationType.UPSERT).zipWithIndex.foreach { case (operation, index) => + val action = if (operation == WriteOperationType.CLUSTER) HoodieTimeline.REPLACE_COMMIT_ACTION + else if (operation == WriteOperationType.LOG_COMPACT) HoodieTimeline.DELTA_COMMIT_ACTION + else HoodieTimeline.COMMIT_ACTION + val metadata = if (operation == WriteOperationType.CLUSTER) new HoodieReplaceCommitMetadata() + else new HoodieCommitMetadata() + metadata.setOperationType(operation) + val instant = metaClient.getInstantGenerator.createNewInstant( + org.apache.hudi.common.table.timeline.HoodieInstant.State.INFLIGHT, action, s"2000010100000000$index") + val timeline = metaClient.reloadActiveTimeline() + timeline.createNewInstant(instant) + val completed = completeTestInstant(metaClient, instant, metadata, s"2099010100000000$index") + if (operation == WriteOperationType.UPSERT) { + val error = intercept[org.apache.hudi.exception.HoodieException] { + batchIds(snapshotReader.getBatch(Some(saved), resetEnd)) + } + assert(error.getMessage.contains("Cannot reconstruct")) + } else { + assert(batchIds(snapshotReader.getBatch(Some(saved), resetEnd)) == Seq("3")) + } + val path = new Path(metaClient.getTimelinePath.toString, + metaClient.getInstantFileNameGenerator.getFileName(completed)) + assert(path.getFileSystem(spark.sessionState.newHadoopConf()).delete(path, false)) + } + } + addData(tablePath, Seq(("5", "after-recovery", "50", "005"))) + // Recovery must remain bounded by Spark's end even if another commit has arrived. + assert(batchIds(snapshotReader.getBatch(Some(saved), resetEnd)) == Seq("3")) + assert(batchIds(snapshotReader.getBatch(Some(resetEnd), snapshotReader.getOffset.get)) == Seq("5")) + val skipped = source(Some("READ_LATEST")).getBatch(Some(saved), resetEnd) + assert(skipped.queryExecution.logical.collectFirst { + case relation: org.apache.spark.sql.execution.LogicalRDD => relation.rdd.count() + }.contains(0L)) + intercept[IllegalArgumentException] { source(Some("invalid")) } + // A fresh checkpoint rebuilds from the current snapshot instead of rejecting old resets. + assert(source().getBatch(None, resetEnd).isStreaming) + + val fs = new Path(tablePath).getFileSystem(spark.sessionState.newHadoopConf()) + val savedTime = org.apache.spark.sql.hudi.streaming.HoodieSourceOffset(resetEnd).offsetCommitTime + val completedReset = metaClient.reloadActiveTimeline().filterCompletedInstants().getInstantsAsStream + .filter(i => (if (completionTime) i.getCompletionTime else i.requestedTime()) == savedTime) + .findFirst().get() + val resetFile = new Path(metaClient.getTimelinePath.toString, + metaClient.getInstantFileNameGenerator.getFileName(completedReset)) + assert(fs.delete(resetFile, false)) + val expiredError = intercept[org.apache.hudi.exception.HoodieException] { + batchIds(source().getBatch(Some(resetEnd), resetEnd)) + } + assert(expiredError.getMessage.contains("history expired")) + fs.delete(new Path(tablePath), true) + initialize() + addData(tablePath, Seq(("4", "recreated", "40", "004"))) + val recreationError = intercept[org.apache.hudi.exception.HoodieException] { + batchIds(source().getBatch(Some(saved), source().getOffset.get)) + } + assert(recreationError.getMessage.contains("rebuild required")) + assert(recreationError.getMessage.contains("recreated")) + val recreatedReader = source(Some("READ_UPTO_LATEST_COMMIT")) + assert(batchIds(recreatedReader.getBatch(Some(saved), recreatedReader.getOffset.get)) == Seq("4")) + } + } + } + } + + Seq(COPY_ON_WRITE, MERGE_ON_READ).foreach { tableType => + Seq(false, true).foreach { completionTime => + test(s"caught-up source resumes after real cleaning: $tableType completionTime=$completionTime") { + withTempDir { dir => + val tablePath = s"${dir.getCanonicalPath}/cleaned" + val metaClient = HoodieTableMetaClient.newTableBuilder() + .setTableType(tableType).setTableName("cleaned").setRecordKeyFields("id").setOrderingFields("ts") + .initTable(HadoopFSUtils.getStorageConf(spark.sessionState.newHadoopConf()), tablePath) + def write(value: Int): Unit = { + Seq(("1", s"value$value", value.toString, "001")).toDF(columns: _*).write.format("hudi") + .options(commonOptions).option(TBL_NAME.key, "cleaned") + .option("hoodie.clean.commits.retained", "2") + .option("hoodie.clean.automatic", "true") + .option("hoodie.clean.async", "false") + .option(HoodieCompactionConfig.INLINE_COMPACT.key(), (tableType == MERGE_ON_READ).toString) + .option(HoodieCompactionConfig.INLINE_COMPACT_NUM_DELTA_COMMITS.key(), "1") + .mode(SaveMode.Append).save(tablePath) + } + write(1) + val options = commonOptions + ("path" -> tablePath) + val reader = if (completionTime) { + new org.apache.spark.sql.hudi.streaming.HoodieStreamSourceV2(spark.sqlContext, + metaClient, s"${dir.getCanonicalPath}/checkpoint", None, options, + org.apache.spark.sql.hudi.streaming.HoodieEarliestOffsetRangeLimit, HoodieTableVersion.current()) + } else { + new org.apache.spark.sql.hudi.streaming.HoodieStreamSourceV1(spark.sqlContext, + metaClient, s"${dir.getCanonicalPath}/checkpoint", None, options, + org.apache.spark.sql.hudi.streaming.HoodieEarliestOffsetRangeLimit, HoodieTableVersion.current()) + } + val oldStart = reader.getOffset.get + write(2) + val oldEnd = reader.getOffset.get + (3 to 7).foreach(write) + val cleans = metaClient.reloadActiveTimeline().getCleanerTimeline.filterCompletedInstants() + assert(cleans.getInstantsAsStream.anyMatch(i => + org.apache.hudi.common.util.CleanerUtils.getCleanerMetadata(metaClient, i).getTotalFilesDeleted > 0)) + // Spark discards this plan on restart, even though its range is now cleaned. + assert(reader.getBatch(Some(oldStart), oldEnd).isStreaming) + val saved = reader.getOffset.get + val lastClean = cleans.lastInstant().get() + val legacySaved = org.apache.spark.sql.hudi.streaming.HoodieSourceOffset( + if (completionTime) lastClean.getCompletionTime else lastClean.requestedTime()) + assert(reader.getBatch(Some(oldStart), legacySaved).isStreaming) + val latestWrite = org.apache.spark.sql.hudi.streaming.HoodieSourceOffset(saved) + assert(reader.getOffset.get == (if (legacySaved.offsetCommitTime > latestWrite.offsetCommitTime) legacySaved else latestWrite)) + write(8) + assert(batchIds(reader.getBatch(Some(legacySaved), reader.getOffset.get)) == Seq("1")) + assert(batchIds(reader.getBatch(Some(saved), reader.getOffset.get)) == Seq("1")) + assert(batchIds(reader.getBatch(None, reader.getOffset.get)) == Seq("1")) + if (completionTime) { + val savedTime = org.apache.spark.sql.hudi.streaming.HoodieSourceOffset(saved).offsetCommitTime + val timeline = metaClient.reloadActiveTimeline() + val service = metaClient.getInstantGenerator.createNewInstant( + org.apache.hudi.common.table.timeline.HoodieInstant.State.INFLIGHT, + HoodieTimeline.COMMIT_ACTION, "20000101000000000") + val serviceMetadata = new org.apache.hudi.common.model.HoodieCommitMetadata() + serviceMetadata.setOperationType(org.apache.hudi.common.model.WriteOperationType.COMPACT) + timeline.createNewInstant(service) + completeTestInstant(metaClient, service, serviceMetadata, savedTime) + // The delivered service's requested time is below the cleaner floor; unread rows are retained. + assert(batchIds(reader.getBatch(Some(saved), reader.getOffset.get)) == Seq("1")) + val oldClean = metaClient.getInstantGenerator.createNewInstant( + org.apache.hudi.common.table.timeline.HoodieInstant.State.INFLIGHT, + HoodieTimeline.CLEAN_ACTION, "20000101000000001") + val cleanMetadata = org.apache.hudi.avro.model.HoodieCleanMetadata.newBuilder() + .setVersion(1).setTimeTakenInMillis(1).setTotalFilesDeleted(1).setStartCleanTime("20000101000000001") + .setEarliestCommitToRetain("19990101000000000").setLastCompletedCommitTimestamp("19990101000000000") + .setPartitionMetadata(new java.util.HashMap[String, org.apache.hudi.avro.model.HoodieCleanPartitionMetadata]()) + .build() + timeline.createNewInstant(oldClean) + completeTestInstant(metaClient, oldClean, cleanMetadata, "20000101000000002") + val recentStart = (BigInt(savedTime) + 1).toString + val specifiedReader = new org.apache.spark.sql.hudi.streaming.HoodieStreamSourceV2(spark.sqlContext, + metaClient, s"${dir.getCanonicalPath}/specified-checkpoint", None, options, + org.apache.spark.sql.hudi.streaming.HoodieSpecifiedOffsetRangeLimit(recentStart), HoodieTableVersion.current()) + assert(batchIds(specifiedReader.getBatch(None, reader.getOffset.get)) == Seq("1")) + } + + } + } + } + } + + Seq(false, true).foreach { unknownBoundary => + test(s"guarded source rejects cleaned history: unknownBoundary=$unknownBoundary") { + withTempDir { dir => + val tablePath = s"${dir.getCanonicalPath}/cleaned" + val metaClient = HoodieTableMetaClient.newTableBuilder() + .setTableType(COPY_ON_WRITE).setTableName("cleaned").setRecordKeyFields("id") + .setOrderingFields("ts") + .initTable(HadoopFSUtils.getStorageConf(spark.sessionState.newHadoopConf()), tablePath) + addData(tablePath, Seq(("1", "old", "10", "001"))) + val reader = new org.apache.spark.sql.hudi.streaming.HoodieStreamSourceV2(spark.sqlContext, + metaClient, s"${dir.getCanonicalPath}/checkpoint", None, + commonOptions ++ Map("path" -> tablePath, + DataSourceReadOptions.STREAMING_READ_RECOVERY_STRATEGY.key() -> "FAIL"), + org.apache.spark.sql.hudi.streaming.HoodieEarliestOffsetRangeLimit, HoodieTableVersion.current()) + val saved = reader.getOffset.get + addData(tablePath, Seq(("1", "new", "20", "002"))) + val end = reader.getOffset.get + val timeline = metaClient.reloadActiveTimeline() + assert(batchIds(reader.getBatch(Some(saved), end)) == Seq("1")) + addData(tablePath, Seq(("1", "latest", "30", "003"))) + val retained = metaClient.reloadActiveTimeline().getCommitsTimeline.lastInstant().get().requestedTime() + val cleanTime = "20990101000000000" + val clean = metaClient.getInstantGenerator.createNewInstant( + org.apache.hudi.common.table.timeline.HoodieInstant.State.INFLIGHT, + HoodieTimeline.CLEAN_ACTION, cleanTime) + val metadata = org.apache.hudi.avro.model.HoodieCleanMetadata.newBuilder() + .setVersion(1).setTimeTakenInMillis(1).setTotalFilesDeleted(1).setStartCleanTime(cleanTime) + .setEarliestCommitToRetain(if (unknownBoundary) "" else retained) + .setLastCompletedCommitTimestamp(retained) + .setPartitionMetadata(new java.util.HashMap[String, org.apache.hudi.avro.model.HoodieCleanPartitionMetadata]()) + .build() + timeline.createNewInstant(clean) + timeline.saveAsComplete(false, clean, org.apache.hudi.common.util.Option.of(metadata)) + val error = intercept[org.apache.hudi.exception.HoodieException] { + batchIds(reader.getBatch(Some(saved), end)) + } + assert(error.getMessage.contains("rebuild required")) + assert(error.getMessage.contains(if (unknownBoundary) "earliest retained commit" else "has been cleaned")) + } + } + } + + // V2 saveAsComplete generates its own completion time; rename the synthetic fixture + // explicitly and remove its pending marker to model an already-completed service. + private def completeTestInstant[T](metaClient: HoodieTableMetaClient, + instant: org.apache.hudi.common.table.timeline.HoodieInstant, + metadata: T, + completionTime: String): org.apache.hudi.common.table.timeline.HoodieInstant = { + val actual = metaClient.getActiveTimeline.saveAsComplete(false, instant, org.apache.hudi.common.util.Option.of(metadata)) + val completed = metaClient.getInstantGenerator.createNewInstant( + org.apache.hudi.common.table.timeline.HoodieInstant.State.COMPLETED, + instant.getAction, instant.requestedTime(), completionTime) + def path(i: org.apache.hudi.common.table.timeline.HoodieInstant): Path = + new Path(metaClient.getTimelinePath.toString, metaClient.getInstantFileNameGenerator.getFileName(i)) + val fs = path(actual).getFileSystem(spark.sessionState.newHadoopConf()) + assert(fs.rename(path(actual), path(completed))) + assert(fs.delete(path(instant), false)) + metaClient.reloadActiveTimeline() + completed + } + + private def batchIds(batch: org.apache.spark.sql.DataFrame): Seq[String] = { + batch.queryExecution.logical match { + case relation: org.apache.spark.sql.execution.LogicalRDD => + val idIndex = batch.schema.fieldIndex("id") + relation.rdd.collect().map(_.getUTF8String(idIndex).toString).toSeq.sorted + case plan => + // Keep incremental filters and projection; the base relation alone reads extra clustered rows. + val boundedPlan = plan.transform { + case relation: org.apache.spark.sql.execution.datasources.LogicalRelation => relation.copy(isStreaming = false) + } + sparkAdapter.getUnsafeUtils.createDataFrameFrom(spark, boundedPlan) + .select("id").collect().map(_.getString(0)).toSeq.sorted + } + } + private def addData(inputPath: String, rows: Seq[(String, String, String, String)], enableInlineCompaction: Boolean = false, diff --git a/release/streaming-source-recovery-1.3.0.md b/release/streaming-source-recovery-1.3.0.md new file mode 100644 index 000000000000..9cb7b22a0a01 --- /dev/null +++ b/release/streaming-source-recovery-1.3.0.md @@ -0,0 +1,64 @@ +<!-- +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. +--> + +# Structured-streaming source recovery: 1.3.0 migration note + +The streaming source supports insert/upsert/delete plus compaction and clustering. +`INSERT OVERWRITE` (table or partition), `delete_partition` writes and partition +TTL on an upstream table require recovery for downstream consumers and fail by +default. This includes TTL run inline with `hoodie.partition.ttl.inline`, which +writes `DELETE_PARTITION` replace commits. `READ_LATEST` drops the overwrite's +new rows along with the unread range; `READ_UPTO_LATEST_COMMIT` replays the whole +table, including unaffected partitions. Latest-state reads do not propagate hard +deletes to downstream tables. + +Latest-state Hudi structured-streaming readers now default to **failing** when a +saved offset cannot be read safely because history was archived/cleaned or the +upstream table was reset/recreated. This affects plain `readStream` users as well +as Spark Declarative Pipelines. Previously incremental full-table-scan fallback +could silently scan after history loss. + +The new `hoodie.datasource.read.streaming.recovery.strategy` takes precedence +over `hoodie.datasource.read.incr.fallback.fulltablescan.enable` on resumed incremental reads. Fresh earliest starts retain the configured +full-scan fallback for rebuilding from retained table state: + +- `FAIL` (default): stop with an actionable error; coordinate rebuilding the + downstream tables and checkpoints. +- `READ_UPTO_LATEST_COMMIT`: explicitly recover with one full snapshot batch, + then resume increments. Append targets can duplicate rows and upsert targets + can retain keys deleted upstream. It is not downstream reconciliation. +- `READ_LATEST`: explicitly skip the unread range and accept data loss. + +Initial start-offset selection and CDC reads are unchanged. Restart queries to +change the strategy. SDP internal sources must pass explicit recovery through +`spark.hoodie.datasource.read.streaming.recovery.strategy` in flow SQLConf. +See [source recovery and operational limits](../hudi-integ-test/spark-pipelines/SOURCE_SAFETY.md). + +`FAIL` requires the sink to propagate batch execution errors. Safety rejections +are deferred until execution so Spark can discard the last committed batch plan +on restart. For Hudi sinks, keep +`hoodie.datasource.write.streaming.ignore.failed.batch=false` (the default). +Setting it to `true`, or swallowing errors in a custom sink, can acknowledge a +rejected batch and advance the checkpoint past unread data even under `FAIL`. +Healthy batches retain their scan relations for column pruning and filter pushdown. + +Before a v6 to v8+ source-table upgrade, pin existing requested-time readers with +`hoodie.datasource.read.streaming.table.version=6` on every restart of the existing +checkpoint. The unversioned offset cannot safely switch to V2 completion-time +semantics automatically. `USE_TRANSITION_TIME` readers already use completion times. +See the operational guide's table-upgrade section for migration and legacy +service-checkpoint limitations. Return to `FAIL` after explicit recovery.
