spark-test commented on code in PR #60264:
URL: https://github.com/apache/spark/pull/60264#discussion_r4520317211


##########
sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/runtime/MicroBatchExecution.scala:
##########
@@ -466,6 +472,50 @@ class MicroBatchExecution(
     }
   }
 
+  /**
+   * Rejects source names that do not fit the source tracking of this run. 
Runs before any source is
+   * created, so that a rejected run leaves nothing behind in the checkpoint.
+   */
+  private def checkSourceNames(): Unit = {
+    val sources = StreamingSourceIdentifyingName.collectSources(analyzedPlan)
+    val namedSources = sources.map(_._2).filter(_.nameOpt.isDefined)
+    val unnamedSources = sources.zipWithIndex.collect {
+      case ((source, Unassigned), i) => s"Leaf position $i - $source"
+    }
+    def unnamedSourcesError: Throwable =
+      QueryCompilationErrors.unnamedStreamingSourcesWithEnforcementError(
+        unnamedSources.mkString("\n"))
+    val checkpointVersion = initialLatestOffsetSeq.map(_._2.version)
+    // Offset log VERSION_1 cannot track sources by name, so the config alone 
is rejected there.
+    checkpointVersion.filter(_ < OffsetSeqLog.VERSION_2).foreach { version =>
+      if 
(sparkSessionForStream.sessionState.conf.enableStreamingSourceEvolution) {
+        throw 
QueryCompilationErrors.cannotEnableSourceEvolutionOnExistingCheckpointError(version)
+      }
+    }
+    (enforceNamedInCheckpoint, checkpointVersion) match {
+      case (Some(false), Some(version)) if namedSources.nonEmpty =>
+        // A positional checkpoint cannot start tracking sources by name. 
Spark 4.2 ran the named
+        // sources of catalog tables by position, with their metadata in 
sources/<name>, and a
+        // checkpoint written that way keeps running as before.
+        val fileManager = CheckpointFileManager.create(
+          new Path(resolvedCheckpointRoot), 
sparkSession.sessionState.newHadoopConf())
+        val writtenUnderNames = namedSources.forall { name =>
+          fileManager.exists(new Path(
+            StreamingUtils.getMetadataPath(name, new AtomicLong(0L), 
resolvedCheckpointRoot)))
+        }
+        if (!writtenUnderNames) {
+          throw 
QueryCompilationErrors.cannotEnableSourceEvolutionOnExistingCheckpointError(version)
+        }
+      case _ if namedSources.nonEmpty && unnamedSources.nonEmpty =>

Review Comment:
   **Blocking (P1):** This case rejects every query that has both a named and 
an unnamed source, without looking at `enforceNamed`. With 
`spark.sql.streaming.queryEvolution.enableSourceEvolution` at its default 
`false`, a name on a V1 session-catalog table survives analysis. 
`FindDataSourceTable` rewrites top-down and consumes the 
`NamedStreamingRelation` wrapper before `NameStreamingSources` would reject the 
name. That is what lets the new test 'positional checkpoint written under 
source names keeps running with those names' restart with `IDENTIFIED BY src` 
while the config is off. So a new query on two parquet tables such as
   
   ```sql
   SELECT * FROM STREAM t1 IDENTIFIED BY a UNION ALL SELECT * FROM STREAM t2
   ```
   
   or 
`spark.readStream.name("a").table("t1").union(spark.readStream.table("t2"))`, 
which on master and in Spark 4.2.0 and 4.3.0 runs with positional tracking 
(`sources/a` and `sources/0`), would now fail at start with 
`UNNAMED_STREAMING_SOURCES_WITH_ENFORCEMENT`. Its message says the config is 
enabled when it is not. Its advice to name every source does not work for a 
`load()` source while the config is off, and no setting restores the old 
behavior. The same query restarted on an existing positional checkpoint still 
runs, because the case above matches first, so only fresh starts are refused.
   
   Only a run that tracks its sources by name needs every source named. 
Guarding this case with `enforceNamed` keeps the enforced behavior, including 
its precedence over `CANNOT_DISABLE_ON_EXISTING_CHECKPOINT` for a named 
checkpoint, and leaves positional runs as they are on master. Once SPARK-61311 
makes naming a source turn on named tracking, the guarded case rejects these 
queries there, where that change can weigh them. The only mixed-source test 
enables the config, so nothing exercises the config-off outcome today.
   
   **Verification:**
   - **Regression:** With the config at its default, a query on a fresh 
checkpoint that unions a session-catalog table named with IDENTIFIED BY, and 
separately one named with DataStreamReader.name().table(), with an unnamed 
session-catalog table processes data, keeps its metadata in sources/<name> and 
sources/0, and processes new data after an unchanged restart.
   - **Behavior:** A query that tracks its sources by name and mixes named and 
unnamed sources, such as a union of separately analyzed named and unnamed 
sources with the config on, still fails with 
UNNAMED_STREAMING_SOURCES_WITH_ENFORCEMENT and creates no source.



##########
sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/runtime/MicroBatchExecution.scala:
##########
@@ -466,6 +472,50 @@ class MicroBatchExecution(
     }
   }
 
+  /**
+   * Rejects source names that do not fit the source tracking of this run. 
Runs before any source is
+   * created, so that a rejected run leaves nothing behind in the checkpoint.
+   */
+  private def checkSourceNames(): Unit = {
+    val sources = StreamingSourceIdentifyingName.collectSources(analyzedPlan)
+    val namedSources = sources.map(_._2).filter(_.nameOpt.isDefined)
+    val unnamedSources = sources.zipWithIndex.collect {
+      case ((source, Unassigned), i) => s"Leaf position $i - $source"
+    }
+    def unnamedSourcesError: Throwable =
+      QueryCompilationErrors.unnamedStreamingSourcesWithEnforcementError(
+        unnamedSources.mkString("\n"))
+    val checkpointVersion = initialLatestOffsetSeq.map(_._2.version)
+    // Offset log VERSION_1 cannot track sources by name, so the config alone 
is rejected there.
+    checkpointVersion.filter(_ < OffsetSeqLog.VERSION_2).foreach { version =>
+      if 
(sparkSessionForStream.sessionState.conf.enableStreamingSourceEvolution) {
+        throw 
QueryCompilationErrors.cannotEnableSourceEvolutionOnExistingCheckpointError(version)
+      }
+    }
+    (enforceNamedInCheckpoint, checkpointVersion) match {
+      case (Some(false), Some(version)) if namedSources.nonEmpty =>
+        // A positional checkpoint cannot start tracking sources by name. 
Spark 4.2 ran the named
+        // sources of catalog tables by position, with their metadata in 
sources/<name>, and a
+        // checkpoint written that way keeps running as before.
+        val fileManager = CheckpointFileManager.create(
+          new Path(resolvedCheckpointRoot), 
sparkSession.sessionState.newHadoopConf())
+        val writtenUnderNames = namedSources.forall { name =>

Review Comment:
   **Non-blocking (P2):** For a positional checkpoint restarted with named 
sources, this requires `sources/<name>` to exist for every named source. 
Nothing in Spark creates that directory. `StreamingUtils.getMetadataPath` only 
builds the path, and `StreamSourceProvider.createSource` receives 
`metadataPath` without any obligation to write there. Take a source that keeps 
no metadata, such as a third-party V1 provider that tracks its position 
elsewhere, used as a session-catalog table and named with `IDENTIFIED BY` while 
the config is off. Its first start passes this check and records positional 
tracking. From the code, its unchanged restart would then fail here with 
`CANNOT_ENABLE_ON_EXISTING_CHECKPOINT`, and so would a checkpoint that Spark 
4.2 or 4.3 wrote for such a source. Master restarts both.
   
   File-format and Kafka sources create the directory through their 
`HDFSMetadataLog`, so only providers outside Spark are affected. The refusal is 
explicit, but users then have to drop the names or start a fresh checkpoint.
   
   See **Shared repair plan 1** in the review body.



##########
sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/runtime/MicroBatchExecution.scala:
##########
@@ -466,6 +472,50 @@ class MicroBatchExecution(
     }
   }
 
+  /**
+   * Rejects source names that do not fit the source tracking of this run. 
Runs before any source is
+   * created, so that a rejected run leaves nothing behind in the checkpoint.
+   */
+  private def checkSourceNames(): Unit = {
+    val sources = StreamingSourceIdentifyingName.collectSources(analyzedPlan)
+    val namedSources = sources.map(_._2).filter(_.nameOpt.isDefined)
+    val unnamedSources = sources.zipWithIndex.collect {
+      case ((source, Unassigned), i) => s"Leaf position $i - $source"
+    }
+    def unnamedSourcesError: Throwable =
+      QueryCompilationErrors.unnamedStreamingSourcesWithEnforcementError(
+        unnamedSources.mkString("\n"))
+    val checkpointVersion = initialLatestOffsetSeq.map(_._2.version)
+    // Offset log VERSION_1 cannot track sources by name, so the config alone 
is rejected there.
+    checkpointVersion.filter(_ < OffsetSeqLog.VERSION_2).foreach { version =>
+      if 
(sparkSessionForStream.sessionState.conf.enableStreamingSourceEvolution) {
+        throw 
QueryCompilationErrors.cannotEnableSourceEvolutionOnExistingCheckpointError(version)
+      }
+    }
+    (enforceNamedInCheckpoint, checkpointVersion) match {
+      case (Some(false), Some(version)) if namedSources.nonEmpty =>
+        // A positional checkpoint cannot start tracking sources by name. 
Spark 4.2 ran the named
+        // sources of catalog tables by position, with their metadata in 
sources/<name>, and a
+        // checkpoint written that way keeps running as before.
+        val fileManager = CheckpointFileManager.create(
+          new Path(resolvedCheckpointRoot), 
sparkSession.sessionState.newHadoopConf())
+        val writtenUnderNames = namedSources.forall { name =>
+          fileManager.exists(new Path(

Review Comment:
   **Non-blocking (P2):** This treats the existence of `sources/<name>` as 
proof that the positional checkpoint was written under that name, and then runs 
by position with the source reading that directory. The directory can exist 
without holding this source's metadata for the checkpoint's offsets:
   
   - `FileStreamSource` creates its metadata log, and so the directory, in its 
constructor. With the config off, `SELECT * FROM STREAM t IDENTIFIED BY src` 
stopped before any data arrives leaves an empty `sources/src` and no offset 
entry. A later unnamed `SELECT * FROM STREAM t` is a new positional query, 
because `verifyNewCheckpointDirectory` checks only offsets, commits and state, 
and it records its batches with metadata in `sources/0`. Restarting with 
`IDENTIFIED BY src` then passes this check. From the code, the source would 
read the empty log, report offset 0 against the committed offset and fail 
`assert(startOffset <= endOffset)` in `getBatch` on every restart.
   - Digit-only names are valid (`^[a-zA-Z0-9_]+$`), so the name `1` maps to 
the same `sources/1` as positional id 1. Two unnamed catalog sources renamed 
`1` and `0` in swapped order pass this check and read each other's metadata.
   
   Master behaves the same for these inputs, so this is the failure this change 
sets out to fix for a missing directory, left in place when the directory 
exists.
   
   See **Shared repair plan 1** in the review body.



##########
sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/runtime/MicroBatchExecution.scala:
##########
@@ -466,6 +472,50 @@ class MicroBatchExecution(
     }
   }
 
+  /**
+   * Rejects source names that do not fit the source tracking of this run. 
Runs before any source is
+   * created, so that a rejected run leaves nothing behind in the checkpoint.
+   */
+  private def checkSourceNames(): Unit = {
+    val sources = StreamingSourceIdentifyingName.collectSources(analyzedPlan)
+    val namedSources = sources.map(_._2).filter(_.nameOpt.isDefined)
+    val unnamedSources = sources.zipWithIndex.collect {
+      case ((source, Unassigned), i) => s"Leaf position $i - $source"
+    }
+    def unnamedSourcesError: Throwable =
+      QueryCompilationErrors.unnamedStreamingSourcesWithEnforcementError(
+        unnamedSources.mkString("\n"))
+    val checkpointVersion = initialLatestOffsetSeq.map(_._2.version)
+    // Offset log VERSION_1 cannot track sources by name, so the config alone 
is rejected there.
+    checkpointVersion.filter(_ < OffsetSeqLog.VERSION_2).foreach { version =>
+      if 
(sparkSessionForStream.sessionState.conf.enableStreamingSourceEvolution) {
+        throw 
QueryCompilationErrors.cannotEnableSourceEvolutionOnExistingCheckpointError(version)
+      }
+    }
+    (enforceNamedInCheckpoint, checkpointVersion) match {
+      case (Some(false), Some(version)) if namedSources.nonEmpty =>
+        // A positional checkpoint cannot start tracking sources by name. 
Spark 4.2 ran the named
+        // sources of catalog tables by position, with their metadata in 
sources/<name>, and a
+        // checkpoint written that way keeps running as before.
+        val fileManager = CheckpointFileManager.create(
+          new Path(resolvedCheckpointRoot), 
sparkSession.sessionState.newHadoopConf())
+        val writtenUnderNames = namedSources.forall { name =>
+          fileManager.exists(new Path(
+            StreamingUtils.getMetadataPath(name, new AtomicLong(0L), 
resolvedCheckpointRoot)))
+        }
+        if (!writtenUnderNames) {
+          throw 
QueryCompilationErrors.cannotEnableSourceEvolutionOnExistingCheckpointError(version)

Review Comment:
   **Nit (P3):** This reuses `CANNOT_ENABLE_ON_EXISTING_CHECKPOINT`, whose text 
says the checkpoint "uses offset log format version <existingVersion>, which 
does not support the named source tracking required by streaming source 
evolution" and offers only a fresh checkpoint. That was accurate for its only 
caller on master, the config turned on for an offset log below version 2. This 
case now raises it for two other causes:
   
   - A positional checkpoint at offset log version 2. That version is the 
`OffsetMap` format named tracking uses (`getMinRequiredOffsetLogVersion`), so 
the format version is not the problem; the new 'positional v2 checkpoint' test 
pins `existingVersion` 2.
   - A config-off restart that only changed a catalog source's `IDENTIFIED BY` 
name, as the new 4.2 compatibility test pins for `IDENTIFIED BY other`. The 
user enabled nothing, and restarting with the original name works, but the 
message points only at a fresh checkpoint, which discards the query's progress 
and state.
   
   A condition of its own for this case, saying that the checkpoint tracks its 
sources by position and naming the sources whose metadata does not match, would 
give users the real cause and remedy.
   
   **Verification:**
   - **Behavior:** The positional version-2 restart with names and the config 
on, and the config-off rename of a session-catalog source whose metadata sits 
under its old name, each fail with the new condition and parameters that name 
the mismatch, before any source is created.
   - **Compatibility:** Enabling the config on a version-1 positional 
checkpoint still raises CANNOT_ENABLE_ON_EXISTING_CHECKPOINT with 
existingVersion 1, and the error-condition registry accepts the new 
sub-condition under STREAMING_QUERY_EVOLUTION_ERROR with SQLSTATE 42KDE.



##########
sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/runtime/MicroBatchExecution.scala:
##########
@@ -466,6 +472,50 @@ class MicroBatchExecution(
     }
   }
 
+  /**
+   * Rejects source names that do not fit the source tracking of this run. 
Runs before any source is
+   * created, so that a rejected run leaves nothing behind in the checkpoint.

Review Comment:
   **Nit (P3):** For a fresh checkpoint location this does not hold. By the 
time `logicalPlan` runs, the `StreamExecution` constructor has evaluated 
`checkpointMetadata.streamMetadata`. That writes `<checkpoint>/metadata` with a 
new query id and, with 
`spark.sql.streaming.checkpoint.verifyMetadataExists.enabled` on (its default), 
creates `offsets/` and `commits/` through the `HDFSMetadataLog` constructor. 
`checkSourceNames` itself reads `initialLatestOffsetSeq`, which builds the 
offset log. Reading the code, the new test 'named and unnamed sources analyzed 
separately are rejected before creating sources' would therefore leave 
`metadata`, `offsets/` and `commits/` behind. Running first guarantees 
something narrower, which is what the `sources/<name>` check relies on: a 
rejected run creates no source, so nothing is written under `sources/`.
   
   ```suggestion
      * created, so that a rejected run writes nothing under the checkpoint's 
sources/ directory.
   ```
   
   **Verification:**
   - **Inspection:** The checkSourceNames comment states only the sources/ 
guarantee, which matches what the rejection tests assert: that a rejected run 
creates no source.



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

To unsubscribe, e-mail: [email protected]

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


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

Reply via email to