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


##########
sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/runtime/MicroBatchExecution.scala:
##########
@@ -466,6 +464,52 @@ 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(
+      enforceNamed: Boolean,
+      enforceNamedInCheckpoint: Option[Boolean]): 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):** `CANNOT_ENABLE_ON_EXISTING_CHECKPOINT`'s message was written 
for turning the config on over an offset log v1 checkpoint. It says the 
checkpoint "uses offset log format version <existingVersion>, which does not 
support the named source tracking required by streaming source evolution", and 
points only to a fresh checkpoint. This case now also raises it in two other 
situations:
   
   - a v2 positional checkpoint, where the new test expects `existingVersion` 
2, the version that named tracking actually uses;
   - a catalog table renamed against a `sources/<name>` layout with the config 
off (`IDENTIFIED BY other` in the new `sources/src` test), where nothing 
enabled source evolution.
   
   In both, the real cause is that the checkpoint tracks its sources by 
position, with their metadata in other directories. Starting fresh reprocesses 
the input. Restarting each source under the name the checkpoint was written 
with lets the query continue: `src` in that test, or no name for a checkpoint 
written without names.
   
   **Verification:**
   - **Behavior:** For a positional v2 checkpoint restarted with a new name 
under the config, and for a positional v1 checkpoint restarted with the config 
off and a name other than the one its metadata is under, assert the new 
condition and its parameters, that the message names the source and the option 
to restart each source under the name it had when the checkpoint was written, 
and that it does not offer removing the name as a remedy.
   - **Compatibility:** Enabling the config on an offset log v1 checkpoint 
still raises CANNOT_ENABLE_ON_EXISTING_CHECKPOINT with existingVersion 1 before 
any source is created.



##########
sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/runtime/MicroBatchExecution.scala:
##########
@@ -466,6 +464,52 @@ 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(
+      enforceNamed: Boolean,
+      enforceNamedInCheckpoint: Option[Boolean]): 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 =>

Review Comment:
   **Non-blocking (P2):** This case runs only when some source is named, and it 
only checks that each named source's `sources/<name>` exists. Several 
positional restarts still start with a source reading a directory that does not 
hold its metadata, which is the half-named run this PR sets out to stop:
   
   - **Dropped name.** A Spark 4.2/4.3 checkpoint of `STREAM t IDENTIFIED BY 
src`, with its metadata in `sources/src`, restarted as `STREAM t` has no named 
source. Nothing is checked, and `FileStreamSource` opens an empty `sources/0`.
   - **Unnamed source beside named ones.** It passes once the named directories 
exist, then opens an empty `sources/<n>`.
   - **Directory that holds no metadata for that source.** A name whose 
directory exists passes the existence test even when the directory holds 
nothing for that source. For example, Spark 4.3 rejects a v1 restart with the 
config on only after it has created the sources, so it leaves an empty 
`sources/x` behind. Likewise, a digit-only name such as `0` can equal another 
source's positional directory.
   - **Offset entry without a metadata line.** A v1 entry like this is parsed 
with no recorded tracking, so this case never matches.
   
   Reading the code, the dropped-name file source rebuilds its log from scratch 
and lists every file as its batch 0. If the committed offset is 0, that looks 
like no new data, and the files that arrived while the query was down are never 
read. If the committed offset is higher, the next batch ends at 0, and 
`getBatch` fails `assert(startOffset <= endOffset)` on that restart and every 
later one. The base branch runs these restarts the same way; they are the 
inputs this fix leaves out.
   
   **Recommended change:** In the positional-checkpoint case of 
checkSourceNames, compare the metadata directory each source of the run will 
open with what the checkpoint already holds under sources/, and check a 
checkpoint whose latest offset entry has no metadata line as a positional one.
   
   **Why this works:** Treat the run as positional when the latest offset entry 
records false for the source-evolution config or carries no metadata. Compute 
the directory each distinct source will open the way 
StreamingUtils.getMetadataPath assigns them, and list sources/ once through the 
checkpoint file manager. Before any source is created, reject the restart when 
two distinct sources would open the same directory, or when a source would open 
a directory that is missing or empty while sources/ holds a non-empty directory 
that no source of the run opens. Keep the existing rule that a named source 
whose sources/<name> is missing is rejected, and leave a TODO at the check 
naming the cases directory probes cannot tell apart and the offset log field 
that would close them.
   
   **Scope:** Extend the positional-checkpoint case of checkSourceNames with 
one listing of sources/ and a comparison against the directories the run's 
sources will open, and add restart tests for the layouts it now rejects and 
keeps.
   
   **Compatibility:** Restarts of positional checkpoints whose sources open the 
directories that hold their own metadata, or that keep no metadata under the 
checkpoint, start exactly as before, by position.
   
   **Risks:** Every restart of a positional checkpoint, which includes every 
query that never enabled source evolution, gains one listing of sources/ on the 
driver before its sources are created; nothing changes per batch. A positional 
restart now fails when a source that never writes its metadata path would open 
a missing directory while sources/ holds a non-empty directory no source opens, 
such as one left by an earlier run of a different source; the check adds no 
flag, so undoing that means reverting the change.
   
   **Constraints:** The new rejections report through the same error as the 
existing positional-checkpoint rejection, so they share its corrected message. 
The comparison runs before any source is created and creates no directory under 
sources/. Restarts whose sources open the directories that hold their own 
metadata, including Spark 4.2 checkpoints whose named sources keep it in 
sources/<name>, keep running by position.
   
   **Exclusions:**
   - Telling a non-empty directory left by a run that never committed from one 
written under that name, and digit-only names that swap positional directories, 
needs each source's metadata directory recorded in the offset log; the repair 
leaves a TODO at the check that names that migration.
   - Whether a named source whose sources/<name> is missing because it never 
writes there should still be rejected is the open question about such 
connectors, and this repair keeps the current rule.
   
   **Success:** Restarting without IDENTIFIED BY a positional checkpoint whose 
source keeps its metadata in sources/<name> fails before any source is created 
instead of starting an empty sources/0. A positional restart that leaves a 
source unnamed beside named ones while its metadata sits in another named 
directory fails before any source is created. A positional restart in which two 
sources would open the same metadata directory, such as a source named 0 beside 
an unnamed source, fails before either is created. A positional restart whose 
named source's sources/<name> exists but is empty while another directory under 
sources/ holds metadata no source opens, as Spark 4.3 left behind when it 
rejected a v1 restart with the config on, fails before any source is created. A 
checkpoint whose latest v1 offset entry has no metadata line is checked as a 
positional checkpoint. Restarts that keep the checkpoint's layout start as 
before, and a rejected restart creates no directory under sources/.
   
   **Verification:**
   - **Regression:** Build the Spark 4.2 layout by running a file-source 
catalog table and moving its sources/0 to sources/src, then restart it without 
IDENTIFIED BY and assert the restart fails before any source is created and 
that sources/0 is not created.
   - **Regression:** On a positional checkpoint whose two named sources keep 
their metadata in sources/a and sources/b, restart with the first still named 
and the second unnamed and assert it fails before any source is created.
   - **Regression:** On a positional checkpoint with a non-empty sources/0 and 
an empty sources/x, restart with the source named x and assert it fails before 
any source is created.
   - **Regression:** Restart a positional checkpoint with one source named 0 
beside an unnamed source and assert it fails before either source is created.
   - **Regression:** Restart a checkpoint whose latest v1 offset entry has an 
empty metadata line with a newly named source whose metadata is under sources/0 
and assert it is rejected like any positional checkpoint.
   - **Compatibility:** Restarts that keep the layout still run without 
reprocessing input: the Spark 4.2 layout restarted with its name, an unnamed 
positional checkpoint, a positional checkpoint whose unnamed source never 
writes its metadata path, and a positional checkpoint holding an empty leftover 
named directory beside the unnamed source's own directory.



##########
sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/runtime/MicroBatchExecution.scala:
##########
@@ -466,6 +464,52 @@ 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):** A rejected run still writes to the checkpoint. 
`StreamExecution`'s constructor reads `checkpointMetadata.streamMetadata`, 
which writes a new `metadata` file on a fresh checkpoint. `logicalPlan` then 
opens the offset log through `initialLatestOffsetSeq`, which creates 
`offsets/`, before it calls this check. So the new union test, rejected on a 
fresh directory, leaves `metadata` and `offsets/` behind.
   
   What the check does guarantee is that no source is created, so nothing is 
written under `sources/`. That narrower guarantee is the one the positional 
existence test depends on. Stating it instead keeps a later change from relying 
on an untouched checkpoint.
   
   **Verification:**
   - **Inspection:** The comment's guarantee matches the code: the checkpoint 
metadata file and the offset log directory are written before the check, and 
when the check throws no source and no directory under sources/ is created.



##########
sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/runtime/MicroBatchExecution.scala:
##########
@@ -466,6 +464,52 @@ 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(
+      enforceNamed: Boolean,
+      enforceNamedInCheckpoint: Option[Boolean]): 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 =>
+        throw unnamedSourcesError

Review Comment:
   **Nit (P3):** This case does not look at `enforceNamed`, so it also fires 
with the config off. Two examples: `SELECT * FROM STREAM t1 IDENTIFIED BY a 
UNION ALL SELECT * FROM STREAM t2` over session-catalog tables, or 
`spark.readStream.name("a").table("t1")` unioned with a `rate` source.
   
   The message says "All streaming sources must be named when 
spark.sql.streaming.queryEvolution.enableSourceEvolution is enabled", which is 
false for these users. Its advice to name every source sends the `rate` source 
into `SOURCE_NAMING_NOT_SUPPORTED`, which then asks them to enable the config. 
Whether this case should fire without the config at all is a separate question 
under Decision challenges.
   
   **Verification:**
   - **Behavior:** With the config off, start a union of a named and an unnamed 
session-catalog table on a new checkpoint and assert that any error it raises 
lists the unnamed source and does not say the config is enabled.
   - **Compatibility:** With the config on, a separately analyzed union of a 
named and an unnamed source still fails with 
UNNAMED_STREAMING_SOURCES_WITH_ENFORCEMENT and the same sourceInfo before any 
source is created.



##########
sql/core/src/test/scala/org/apache/spark/sql/streaming/test/StreamingSourceEvolutionSuite.scala:
##########
@@ -530,6 +532,119 @@ class StreamingSourceEvolutionSuite extends StreamTest {
       s"Expected default value 'false' for missing config in V2, but got: 
$valueV2")
   }
 
+  // ================================
+  // Checkpoint Source Tracking Tests

Review Comment:
   **Nit (P3):** Reading the code, each of these changes to `checkSourceNames` 
would leave every test green:
   
   1. **Deleting the `enforceNamed && unnamedSources.nonEmpty` case.** An 
unnamed session-catalog table read with the config on escapes analysis-time 
enforcement, because `FindDataSourceTable` unwraps it before 
`NameStreamingSources` runs. It would create `sources/0` and then hit the 
`IllegalStateException` in `sourceIdMap`. No test reaches this case; the only 
mixed test hits the mixed case first, with the same error.
   2. **Replacing `forall` with `exists`.** A checkpoint with `sources/a` and 
`sources/b`, restarted as `a` and `c`, would run `c` against an empty 
`sources/c`. Both tests that reach the existence check use a single named 
source.
   3. **Moving the mixed case above the positional one.** A Spark 4.2 
checkpoint of `t1 IDENTIFIED BY a UNION ALL t2` would stop restarting.
   4. **Moving the `CANNOT_DISABLE_ON_EXISTING_CHECKPOINT` case above the mixed 
one.** A named checkpoint restarted with some sources unnamed would report that 
no source in the query is named.
   
   **Verification:**
   - **Regression:** An unnamed session-catalog table started with the config 
on a new checkpoint fails with UNNAMED_STREAMING_SOURCES_WITH_ENFORCEMENT and 
no source is created.
   - **Regression:** A positional checkpoint whose named sources a and b keep 
their metadata only under sources/a, restarted as a and b, is rejected before 
any source is created.
   - **Compatibility:** A Spark 4.2 layout of a catalog table named a beside an 
unnamed one, with metadata in sources/a and sources/0, keeps running and does 
not reprocess its input.
   - **Regression:** A checkpoint that tracks sources by name, restarted with 
one source named and the other analyzed separately while the config is off, as 
the existing union test builds it, so that the unnamed source reaches the 
start-up check instead of failing analysis, fails with 
UNNAMED_STREAMING_SOURCES_WITH_ENFORCEMENT and not 
CANNOT_DISABLE_ON_EXISTING_CHECKPOINT before any source is created.



-- 
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