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


##########
sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/runtime/MicroBatchExecution.scala:
##########
@@ -466,6 +475,43 @@ 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"))
+    enforceNamedInCheckpoint match {
+      case Some(false) if namedSources.nonEmpty =>

Review Comment:
   **Non-blocking (P2):** This arm checks only the sources that the restart 
still names, so dropping names from the layout it admits goes unchecked: a 
fully unnamed restart matches no arm, and in a partly named one the unnamed 
sources are not checked. Take a checkpoint of
   
   ```sql
   SELECT * FROM STREAM a IDENTIFIED BY src UNION ALL SELECT * FROM STREAM b
   ```
   
   on parquet tables, written with the config off by the base branch or Spark 
4.2: positional offsets, `a`'s file log in `sources/src`, and `b`'s in 
`sources/0`. Restarted without `IDENTIFIED BY`, `enforceNamedInCheckpoint` is 
`Some(false)` and no source is named, so by the code this check passes; `a` 
opens `sources/0`, which holds `b`'s file log, and `b` opens an empty 
`sources/1`, each keeping its positional offset. `a` then reads `b`'s file 
lists for its own offset range and treats its own table's files as new, so 
`b`'s rows and duplicates reach the sink, while `b` fails `verifyBatchIds` or 
restarts from its empty log.
   
   The base branch runs this restart the same way, but it is the misread that 
this check now prevents when names are added to a positional checkpoint or 
dropped from a named one, and nothing here marks this case as deferred.
   
   See **Shared repair plan 2** in the review body.



##########
sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/runtime/MicroBatchExecution.scala:
##########
@@ -466,6 +475,43 @@ 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"))
+    enforceNamedInCheckpoint match {
+      case Some(false) 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:
   **Blocking (P1):** `fileManager.exists` only shows that a directory named 
after each source exists, not that a positional run wrote that source's 
metadata into it, so this check admits restarts in which a source opens another 
source's metadata:
   
   - `name()` accepts digit-only names (`^[a-zA-Z0-9_]+$` in 
`StreamingNameValidator`), and a positional run creates `sources/0`, 
`sources/1`, and so on. Take two parquet file sources run unnamed as 
`a.union(b)` on `cp`, with `a`'s file log in `sources/0` and `b`'s in 
`sources/1`, and restart them as `a.name("1").union(b.name("0"))` with the 
config off. Following the code, this check finds both directories and accepts 
the restart, and the run keeps positional tracking: `a` keeps position 0 and 
its own offsets but opens `sources/1`, which is `b`'s `FileStreamSourceLog`, 
restores `b`'s seen files, and reads `b`'s file lists for its own batch range 
in `getBatch`; `b` does the same with `a`'s log. Naming them `0` and `1` in 
position order also passes and keeps positional tracking, so a later reorder, 
which the new `name()` docs say naming allows, gives each source the other's 
offsets.
   - A named run that created its sources and failed before writing its first 
offset entry leaves `sources/<name>` behind, because 
`verifyNewCheckpointDirectory` checks only offsets, commits, and state. That 
includes a run that the base branch rejected with 
CANNOT_ENABLE_ON_EXISTING_CHECKPOINT in `initializeExecution`, after its named 
sources were created; Spark 4.3.0 ships the same `CheckpointVersionManager` 
check, though this review could not check its `StreamExecution` ordering. An 
empty leftover directory usually makes the restart fail in `verifyBatchIds` 
instead of misreading.
   
   File sources then send the other table's rows to the sink and treat their 
own table's files as new, re-sending files already processed, with no error 
when the misdirected log holds the requested batch ids, as it does for two file 
sources that each log a batch per micro-batch; otherwise 
`HDFSMetadataLog.verifyBatchIds` fails with an IllegalStateException instead of 
CANNOT_ENABLE_ON_EXISTING_CHECKPOINT. Other sources resume from another 
source's offsets or metadata. The base branch rejected these restarts for named 
`load()` sources (SOURCE_NAMING_NOT_SUPPORTED at analysis with the config off, 
CANNOT_ENABLE_ON_EXISTING_CHECKPOINT for a v1 log with it on), so for them the 
misread is new. Named V1 catalog tables already ran such restarts by position 
with no check, and for them this check leaves the digit-name and 
leftover-directory cases as they were.
   
   See **Shared repair plan 2** in the review body.



##########
sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/runtime/MicroBatchExecution.scala:
##########
@@ -197,14 +197,33 @@ class MicroBatchExecution(
 
   /**
    * Cached result of the first `offsetLog.getLatest()` call. Reused by both
-   * `logicalPlan` (to determine `enforceNamed`) and `initializeExecution` (to 
seed
+   * `logicalPlan` (to determine `enforceNamedInCheckpoint`) and 
`initializeExecution` (to seed
    * `latestStartedBatch`). This avoids a redundant `ListStatus` on the 
checkpoint's
    * `offsets/` directory during stream startup. Safe to cache: between 
construction
    * and `initializeExecution`, nothing else writes the offset log on the 
query thread.
    */
   private lazy val initialLatestOffsetSeq: Option[(Long, OffsetSeqBase)] =
     offsetLog.getLatest()
 
+  /** Whether the last written offset log entry tracks sources by name, if 
there is one. */
+  private lazy val enforceNamedInCheckpoint: Option[Boolean] =

Review Comment:
   **Nit (P3):** An existing offset entry without metadata maps to `None` here, 
the same value as a checkpoint with no offset entry, so `enforceNamed` and 
`checkSourceNames` treat the restart as a new query. `ContinuousExecution` 
writes every entry as `OffsetSeq.fill(globalOffset)` without metadata.
   
   Reading the code, with the config off: a Kafka query run with 
`Trigger.Continuous` on `cp`, then restarted on `cp` with the default trigger 
and its source named with `.name("k")`, passes `checkSourceNames`, creates its 
source under `sources/k`, and then fails with a NullPointerException on 
`watermarkTracker` in `populateStartOffsets` or, when the last epoch was not 
committed, in `markMicroBatchEnd` after re-running that epoch into the sink. 
The base branch rejected this restart before any batch ran, with 
SOURCE_NAMING_NOT_SUPPORTED at `load()` when the config is off and with 
CANNOT_ENABLE_ON_EXISTING_CHECKPOINT in `resolveOffsetLogVersion` when it is on.
   
   No offset entry is written, so the checkpoint is not mislabeled, and unnamed 
micro-batch restarts of continuous checkpoints already fail this way on the 
base branch.
   
   See **Shared repair plan 2** in the review body.



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/NameStreamingSources.scala:
##########
@@ -117,23 +118,25 @@ object NameStreamingSources extends Rule[LogicalPlan] {
     }
   }
 
+  private def hasUserProvidedName(plan: LogicalPlan): Boolean = {
+    
StreamingSourceIdentifyingName.collectSources(plan).exists(_._2.toUserProvided.isDefined)
+  }
+
   override def apply(plan: LogicalPlan): LogicalPlan = {
     if (!plan.isStreaming) {
       plan
-    } else if (conf.enableStreamingSourceEvolution) {
+    } else if (conf.enableStreamingSourceEvolution || 
hasUserProvidedName(plan)) {

Review Comment:
   **Blocking (P1):** With the config off, `hasUserProvidedName(plan)` now runs 
on every streaming plan before the pruned branch, and `collectSources` is an 
unpruned recursion that pattern-matches every node and builds a `Seq` per node 
until it meets a `NamedStreamingRelation` or a 
`HasStreamingSourceIdentifyingName`. This rule is the last of the fixed-point 
Resolution batch, and each micro-batch analyzes a fresh `withNewBatchId` copy 
of the plan through a new `IncrementalExecution` (`MicroBatchExecution.scala` 
lines 1392-1410). The leaves of that copy are batch data rather than 
`StreamingRelation` or `StreamingRelationV2`, the only implementors of 
`HasStreamingSourceIdentifyingName`, so nothing ends the walk early.
   
   By the code, for a query that names no source on the default config, which 
covers most streaming queries, this rule now traverses the whole logical plan, 
including any static join side, in every Resolution iteration of each 
micro-batch's analysis and of each analysis while the DataFrame is built 
through chained transformations. On the base branch, and in Spark 4.2.0 and 
4.3.0, which ship the same `NameStreamingSources`, this branch was 
`resolveOperatorsWithPruning(_.containsPattern(NAMED_STREAMING_RELATION))`: one 
pattern check at the root of a plan without wrappers.
   
   The walk cannot change the outcome: when a plan contains no 
`NamedStreamingRelation`, both branches return it unchanged and neither throws. 
It changes no result, executor work, I/O, or state, and the cost of each pass 
was not measured and is probably small next to per-batch planning, but it grows 
with plan size (many unioned sources, long transformation chains, large static 
join sides) and with the number of micro-batches, and these are queries that 
this change is not meant to affect. Named and config-on queries also run the 
unpruned `plan.collect` in `checkSourceNamingEnforcement` on every batch.
   
   See **Shared repair plan 1** in the review body.



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/NameStreamingSources.scala:
##########
@@ -117,23 +118,25 @@ object NameStreamingSources extends Rule[LogicalPlan] {
     }
   }
 
+  private def hasUserProvidedName(plan: LogicalPlan): Boolean = {
+    
StreamingSourceIdentifyingName.collectSources(plan).exists(_._2.toUserProvided.isDefined)

Review Comment:
   **Blocking (P1):** With the config off, this finds a name that 
`FindDataSourceTable` has already moved into a V1 table's `StreamingRelation`, 
after that table's wrapper is gone, and the name then sends the plan to 
`checkSourceNamingEnforcement`, which rejects any surviving unnamed wrapper 
without being able to read the checkpoint. In one SQL statement, an unnamed V2 
catalog table, `CHANGES` relation, or streaming TVF keeps its wrapper until 
this rule. So, following the code, a base-branch checkpoint of
   
   ```sql
   SELECT * FROM STREAM a IDENTIFIED BY src UNION ALL SELECT * FROM STREAM 
v2cat.db.t
   ```
   
   (with `a` a parquet table in the session catalog and `t` a table in the V2 
catalog `v2cat`; positional offsets, `a`'s file log in `sources/src`, and `t`'s 
metadata in `sources/0`) can no longer be restarted with the unchanged 
statement: `spark.sql` fails with UNNAMED_STREAMING_SOURCES_WITH_ENFORCEMENT 
before `start()` reaches `checkSourceNames`, whose `Some(false)` arm would 
accept this checkpoint because `sources/src` exists. The new 
`NameStreamingSourcesSuite` test 'config disabled - already named source 
requires every source to be named' pins this rejection for the plan shape.
   
   Changing the statement does not help either. Naming `t` anything but `` `0` 
`` passes analysis but fails at start with 
CANNOT_ENABLE_ON_EXISTING_CHECKPOINT, whose message sends users to a fresh 
checkpoint that loses the query's progress and state. Naming it `` `0` `` 
restarts correctly only because `sources/0` happens to hold `t`'s metadata; 
that depends on an undocumented checkpoint layout and on accepting digit-only 
names, which another comment in this review flags as unsafe. Dropping 
`IDENTIFIED BY` passes both checks but makes `a` open `sources/0`, which holds 
`t`'s metadata, and `t` open an empty `sources/1`.
   
   `NameStreamingSources`, `NamedStreamingRelation`, and `RelationResolution` 
are byte-identical at v4.3.0 and the base branch, and the `IDENTIFIED BY`, 
`CHANGES`, and name-propagation commits (SPARK-55039, SPARK-55948, SPARK-55029) 
are in v4.2.0 and v4.3.0, so released checkpoints can have this layout; this 
review could not check `FindDataSourceTable` at those tags. Queries built with 
the DataFrame API are unaffected, because each side is analyzed alone and loses 
its wrapper before the union is analyzed, and the same statement with two V1 
tables keeps running by position.
   
   See **Shared repair plan 1** in the review body.



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/NameStreamingSources.scala:
##########
@@ -41,8 +41,9 @@ import org.apache.spark.sql.errors.QueryCompilationErrors
  * - Flow-assigned names (from DLT context) are preserved
  * - Unassigned sources remain unassigned and will be auto-numbered later in 
MicroBatchExecution
  *
- * When `spark.sql.streaming.queryEvolution.enableSourceEvolution` is enabled,
- * all sources must be explicitly named (throws error if any Unassigned 
sources found).
+ * When any source has a user-provided name, or

Review Comment:
   **Nit (P3):** `checkSourceNamingEnforcement` only inspects sources that are 
still wrapped in `NamedStreamingRelation`. An unnamed source analyzed on its 
own, such as the other side of `named.union(unnamed)`, or a V1 catalog table 
that `FindDataSourceTable` has already resolved, has no wrapper left and passes 
this rule. For example, with the config off, 
`spark.readStream.format("rate").name("a").load().union(spark.readStream.format("rate").load())`
 switches this rule to its enforcing branch, but by the code nothing is thrown 
here, because neither side has a wrapper left; the query fails only at start, 
in `MicroBatchExecution.checkSourceNames`, with 
UNNAMED_STREAMING_SOURCES_WITH_ENFORCEMENT, which the new 
`StreamingSourceEvolutionSuite` tests rely on (their comment: 'no 
NamedStreamingRelation is left to check').
   
   With the new user-provided-name trigger, that is the ordinary DataFrame 
union, so a maintainer reading this doc can conclude that analysis already 
guarantees every source is named and that the start-time check is redundant. 
The base-branch doc made the same claim for the config-on case.
   
   See **Shared repair plan 1** in the review body.



##########
sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/runtime/MicroBatchExecution.scala:
##########
@@ -197,14 +197,33 @@ class MicroBatchExecution(
 
   /**
    * Cached result of the first `offsetLog.getLatest()` call. Reused by both
-   * `logicalPlan` (to determine `enforceNamed`) and `initializeExecution` (to 
seed
+   * `logicalPlan` (to determine `enforceNamedInCheckpoint`) and 
`initializeExecution` (to seed
    * `latestStartedBatch`). This avoids a redundant `ListStatus` on the 
checkpoint's
    * `offsets/` directory during stream startup. Safe to cache: between 
construction
    * and `initializeExecution`, nothing else writes the offset log on the 
query thread.
    */
   private lazy val initialLatestOffsetSeq: Option[(Long, OffsetSeqBase)] =
     offsetLog.getLatest()
 
+  /** Whether the last written offset log entry tracks sources by name, if 
there is one. */
+  private lazy val enforceNamedInCheckpoint: Option[Boolean] =
+    initialLatestOffsetSeq.flatMap { case (_, offsetSeq) =>
+      offsetSeq.metadataOpt.flatMap { metadata =>
+        OffsetSeqMetadata.readValueOpt(metadata, 
SQLConf.ENABLE_STREAMING_SOURCE_EVOLUTION)
+          .map(_.toBoolean)
+      }
+    }
+
+  /**
+   * Whether this run tracks sources by name (source evolution), decided once 
per run: the
+   * checkpoint's recorded tracking wins, and a new query tracks by name when 
the session config is
+   * on or any source has a user-provided name.
+   */
+  private lazy val enforceNamed: Boolean = enforceNamedInCheckpoint.getOrElse(
+    sparkSessionForStream.sessionState.conf.enableStreamingSourceEvolution ||
+      StreamingSourceIdentifyingName.collectSources(analyzedPlan)

Review Comment:
   **Non-blocking (P2):** This makes a SQL `IDENTIFIED BY` name an `OffsetMap` 
key on the default config, but SQL names skip the rule `name()` applies. 
`name()` limits names to `^[a-zA-Z0-9_]+$` through `StreamingNameValidator`, 
and its new docs say a name must contain only ASCII letters, digits, and 
underscores. On the SQL path, `AstBuilder.extractSourceName` takes the 
identifier text, the parser strips backquotes, and 
`NamedStreamingRelation.withUserProvidedName` and `FindDataSourceTable` pass 
the name through; `QueryCompilationErrors.invalidStreamingSourceNameError` has 
no caller. `OffsetSeqLog.serialize` writes each `OffsetMap` entry as 
`<sourceId>:<offset json>`, and `deserialize` splits each line at the first `:`.
   
   Following the code, for
   
   ```sql
   SELECT * FROM STREAM t IDENTIFIED BY `orders:v1`
   ```
   
   on a session-catalog parquet table with the config off and a new checkpoint, 
batch 0 writes the line `orders:v1:{"logOffset":0}`. On restart it reads back 
as source `orders` with offset `v1:{"logOffset":0}`, 
`OffsetSeqBase.toStreamProgress` drops the entry because `orders` is not a 
known source, as it does for a removed source, and the source restarts with no 
start offset. A file source then re-reads every file in its log and a Kafka 
source restarts from its initial offsets, so the sink receives duplicated or 
skipped data with no error. On the base branch without the config, the same 
query ran by position on a v1 log, where the name appears only in the 
`sources/orders:v1` path, and its offsets round-tripped; with the config on, 
the base branch already had this problem.
   
   Whether a query gets this far depends on the checkpoint file system 
accepting `:` in the `sources/orders:v1` directory that file and Kafka sources 
create at start, which this review could not check.
   
   **Recommended change:** In checkSourceNames, when the run will track its 
sources by name and its checkpoint does not yet record that tracking, validate 
every user-provided source name with the StreamingNameValidator rule that 
DataStreamReader.name() applies and fail with INVALID_SOURCE_NAME before 
creating sources; when a checkpoint already tracks its sources by name, fail 
the same way for a name containing ':', which its offset log cannot read back. 
Positional runs keep accepting any SQL name. Add streaming tests for SQL names 
in each case.
   
   **Why this works:** Names become OffsetMap keys only when the run tracks 
sources by name, which checkSourceNames knows before any offset or source 
directory is written, so validating there gives SQL the name() rule for every 
new name-tracked checkpoint and turns the silent offset loss on existing ones 
into an error.
   
   **Scope:** Validate source names that become offset log keys at the 
start-time naming check.
   
   **Risks:** New name-tracked SQL queries whose names contain characters other 
than ASCII letters, digits, and underscores, which the stack accepts today, 
fail to start with INVALID_SOURCE_NAME; checkpoints that already track by name 
keep running unless a name contains ':'.
   
   **Constraints:** Positional runs, including released checkpoints whose SQL 
names appear only in sources/<name>, keep accepting their names.
   
   **Exclusions:**
   - Name characters other than ':' in checkpoints that already track sources 
by name keep working, since their offsets round-trip.
   
   **Success:** A new SQL query named with IDENTIFIED BY `orders:v1` fails with 
INVALID_SOURCE_NAME before any source is created. A checkpoint that already 
tracks a source whose name contains ':' fails with INVALID_SOURCE_NAME on 
restart instead of losing that source's offset. SQL names on positional runs 
behave as before.
   
   **Verification:**
   - **Regression:** Starting a new SQL query whose IDENTIFIED BY name contains 
':' fails with INVALID_SOURCE_NAME and creates no source.
   - **Behavior:** SQL names that name() accepts track by name on a new 
checkpoint and resume from their offsets after a restart.
   - **Compatibility:** A positional checkpoint written with a SQL name that 
name() rejects, such as one containing '-', restarts by position with the same 
name.



##########
sql/api/src/main/scala/org/apache/spark/sql/streaming/DataStreamReader.scala:
##########
@@ -107,8 +107,14 @@ abstract class DataStreamReader {
    * Specifies a name for the streaming source. This name is used to identify 
the source in
    * checkpoint metadata and enables stable checkpoint locations for source 
evolution.
    *
+   * Naming a source enables source evolution for its query: every source in 
the query must be

Review Comment:
   **Non-blocking (P2):** This paragraph does not hold for the positional 
checkpoints that the base branch, Spark 4.2, and Spark 4.3 wrote for catalog 
tables named with `IDENTIFIED BY` or `name().table()` without the config, with 
each named source's metadata under `sources/<name>`. For those, 
`checkSourceNames` keeps positional tracking (the legacy arm in 
`MicroBatchExecution`): naming enables no evolution, named and unnamed sources 
are accepted together, offsets are matched to sources by position 
(`OffsetSeqBase.toStreamProgress` zips them behind an assert that only compares 
counts), and dropping the names is not rejected.
   
   For example, a Spark 4.3 query
   
   ```sql
   SELECT * FROM STREAM a IDENTIFIED BY x UNION ALL SELECT * FROM STREAM b 
IDENTIFIED BY y
   ```
   
   on parquet tables, run with the config off, has such a checkpoint, with 
`sources/x` and `sources/y`. By the code, if the user then reorders the 
sources, as this doc says naming allows, the restart is accepted because both 
directories exist, and positional tracking gives `b`, now at position 0, `a`'s 
offset against `b`'s own log, so each source skips or reprocesses its own 
files. Adding or removing a source fails the source-count assertion ('... 
Cannot continue.') instead of evolving.
   
   The code comment on the legacy arm states this exception, but this doc, the 
PySpark docstring in `python/pyspark/sql/streaming/readwriter.py`, and the 
Spark Connect docstring that copies it do not.
   
   **Verification:**
   - **Inspection:** The Scala, PySpark, and Spark Connect name() docs state 
the positional-checkpoint exception and no longer promise add, remove, or 
reorder for every named query.



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/internal/SQLConf.scala:
##########
@@ -4044,9 +4044,10 @@ object SQLConf {
   val ENABLE_STREAMING_SOURCE_EVOLUTION =
     buildConf("spark.sql.streaming.queryEvolution.enableSourceEvolution")
       .internal()
-      .doc("When true, enforces that all streaming sources must be explicitly 
named via " +
-        "the .name() API. This enables streaming source evolution, allowing 
sources to be " +
-        "added, removed, or reordered without losing state.")
+      .doc("When true, enables streaming source evolution for every streaming 
query in the " +

Review Comment:
   **Nit (P3):** On restart, the tracking recorded in the checkpoint wins 
(`enforceNamed = enforceNamedInCheckpoint.getOrElse(...)` in 
`MicroBatchExecution`), so this config only affects queries whose checkpoint 
has no offset entry yet. With it on, a positional checkpoint's unnamed sources 
keep running by position, as the renamed `OffsetSeqLogSuite` test 'source 
evolution config does not change an existing V1 checkpoint' asserts, and its 
named sources fail with CANNOT_ENABLE_ON_EXISTING_CHECKPOINT. For example, by 
the code, a `MemoryStream` query restarted with the config on from a checkpoint 
created without source evolution runs by position and records the config as 
false in its query session.
   
   A maintainer or user who sets this internal config to move existing queries 
to source evolution is told that it does so, but it applies to them only on a 
new checkpoint.
   
   **Verification:**
   - **Inspection:** The config's doc describes new-query and restart behavior 
consistently with the tracking recorded in the checkpoint.



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/NameStreamingSources.scala:
##########
@@ -117,23 +118,25 @@ object NameStreamingSources extends Rule[LogicalPlan] {
     }
   }
 
+  private def hasUserProvidedName(plan: LogicalPlan): Boolean = {
+    
StreamingSourceIdentifyingName.collectSources(plan).exists(_._2.toUserProvided.isDefined)
+  }
+
   override def apply(plan: LogicalPlan): LogicalPlan = {
     if (!plan.isStreaming) {
       plan
-    } else if (conf.enableStreamingSourceEvolution) {
+    } else if (conf.enableStreamingSourceEvolution || 
hasUserProvidedName(plan)) {
       // Feature enabled - propagate names to streaming sources.
       checkSourceNamingEnforcement(plan)
       propagateSourceNames(plan)
     } else {
       // Feature disabled - unwrap NamedStreamingRelation nodes without 
propagating names.
-      // Error if any source has an explicitly assigned name since the feature 
is disabled.
+      // Error if any source has a flow-assigned name since the feature is 
disabled.
       // Only unwrap when child is resolved - this allows FindDataSourceTable 
to resolve
       // UnresolvedCatalogRelation to StreamingRelation before we unwrap.
       
plan.resolveOperatorsWithPruning(_.containsPattern(NAMED_STREAMING_RELATION)) {
         case NamedStreamingRelation(child, Unassigned) if child.resolved =>
           child
-        case NamedStreamingRelation(_, UserProvided(name)) =>

Review Comment:
   **Non-blocking (P2):** Without this case, a user-provided name on the 
default config also reaches `ContinuousExecution`, but only 
`MicroBatchExecution` implements name-based tracking. `ContinuousExecution`, 
unchanged, matches `StreamingRelationV2` without looking at its 
`sourceIdentifyingName`, puts source metadata under `sources/$nextSourceId`, 
writes `OffsetSeq.fill(globalOffset)` entries without metadata, and on restart 
casts the latest offset entry to `OffsetSeq` (`ContinuousExecution.scala` lines 
84-93, 197-200, and 370). Reading the code, with the config off:
   
   - 
`spark.readStream.format("rate").name("r").load().writeStream.format("console").trigger(Trigger.Continuous("1
 second")).option("checkpointLocation", cp).start()` failed at `load()` with 
SOURCE_NAMING_NOT_SUPPORTED on the base branch. With the stack it runs with its 
source under `sources/0` and positional offsets, so the name has no effect, 
although the new `name()` docs say the checkpoint tracks the sources by name.
   - The same named query run on a fresh `cp2` with the default trigger now 
writes `OffsetMap` entries. Restarting it on `cp2` with `Trigger.Continuous`, a 
switch that `docs/streaming/performance-tips.md` documents as supported, throws 
a ClassCastException in `ContinuousExecution.getStartOffsets` instead of an 
error saying that continuous processing does not support source evolution.
   
   The sibling sink-evolution feature rejects continuous processing explicitly 
in `StreamingQueryManager.createQuery`, with 
STREAMING_QUERY_EVOLUTION_ERROR.CONTINUOUS_PROCESSING_NOT_SUPPORTED, instead of 
silently dropping the setting. No wrong result is established, since continuous 
processing reads a single source by position, and with the internal config on, 
the base branch already behaved this way.
   
   **Recommended change:** In StreamingQueryManager.createQuery, when the 
trigger is continuous, reject a plan in which any source has a user-provided or 
flow-assigned name with a new STREAMING_QUERY_EVOLUTION_ERROR condition, as 
sink evolution does; in ContinuousExecution.getStartOffsets, fail with a clear 
error when the committed epoch's offset entry tracks sources by name instead of 
casting it to OffsetSeq; and say in the Scala and Python name() docs that 
naming a source requires a micro-batch trigger. Cover both rejections in 
continuous processing tests.
   
   **Why this works:** Every supported start goes through createQuery, which 
already has the analyzed plan and the trigger, so a name check there fails 
before ContinuousExecution is built; the recovery check turns the type mismatch 
into an error that says the checkpoint tracks its sources by name.
   
   **Scope:** Reject source names for continuous processing at engine selection 
and make continuous recovery fail clearly on checkpoints that track sources by 
name.
   
   **Risks:** Continuous queries that name their source now fail to start; on 
the base branch they ran with the name ignored when the internal config was on, 
and they recover by dropping the name.
   
   **Constraints:** Unnamed continuous queries, and continuous restarts of 
checkpoints that do not track sources by name, keep starting unchanged.
   
   **Success:** A continuous-trigger query whose source has a user-provided 
name fails at start with a source-evolution error saying that continuous 
processing does not support source names. Restarting with a continuous trigger 
a checkpoint that tracks its sources by name fails with an error that names the 
cause instead of a ClassCastException. The Scala and Python name() docs say 
that naming a source requires a micro-batch trigger.
   
   **Verification:**
   - **Regression:** Starting a continuous-trigger query with a named source 
fails at start with the new error, for a name given through the DataFrame API 
and through SQL IDENTIFIED BY.
   - **Regression:** Restarting with a continuous trigger a checkpoint that a 
named micro-batch query wrote fails with the new recovery error rather than a 
ClassCastException.
   - **Compatibility:** Unnamed continuous queries start and restart as before, 
including on checkpoints written by unnamed micro-batch runs.



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/NameStreamingSources.scala:
##########
@@ -117,23 +118,25 @@ object NameStreamingSources extends Rule[LogicalPlan] {
     }
   }
 
+  private def hasUserProvidedName(plan: LogicalPlan): Boolean = {
+    
StreamingSourceIdentifyingName.collectSources(plan).exists(_._2.toUserProvided.isDefined)
+  }
+
   override def apply(plan: LogicalPlan): LogicalPlan = {
     if (!plan.isStreaming) {
       plan
-    } else if (conf.enableStreamingSourceEvolution) {
+    } else if (conf.enableStreamingSourceEvolution || 
hasUserProvidedName(plan)) {

Review Comment:
   **Nit (P3):** A user-provided name now always takes this branch to 
`propagateSourceNames`, which unwraps a `NamedStreamingRelation` only when its 
child carries a source name or is a `SubqueryAlias` over one, or when the name 
is `Unassigned`. A name on any other resolved child, such as a streaming 
temporary view (`resolveTempView` returns `SubqueryAlias(View(...))`) or a 
streaming table-valued function, leaves the always-unresolved wrapper in the 
plan.
   
   Reading the code, after 
`spark.readStream.format("rate").load().createOrReplaceTempView("events")`, 
both `SELECT * FROM STREAM events IDENTIFIED BY e` and 
`spark.readStream.name("e").table("events")` fail analysis with INTERNAL_ERROR 
'Found the unresolved operator' from `CheckAnalysis`, where the base branch 
raised SOURCE_NAMING_NOT_SUPPORTED with the config off; a named streaming TVF 
fails the same way. `common/utils/src/main/resources/error/README.md` reserves 
INTERNAL_ERROR for bugs that users are not expected to encounter, which does 
not include unsupported operations, so users who name a view or TVF, as the new 
docs suggest for turning on source evolution, get an error that reads like a 
Spark bug. With the config on, the base branch already failed this way.
   
   **Verification:**
   - **Regression:** Naming a streaming temporary view, through SQL IDENTIFIED 
BY and through readStream.name().table(), fails analysis with the new error 
condition, with or without the source evolution config.
   - **Regression:** Naming a streaming table-valued function fails analysis 
with the same condition.
   - **Compatibility:** Unnamed streaming views and table-valued functions 
still analyze, and named streaming source relations still receive their names.



##########
sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/runtime/MicroBatchExecution.scala:
##########
@@ -466,6 +475,43 @@ 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"))
+    enforceNamedInCheckpoint match {
+      case Some(false) 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()
+        }
+      case _ if namedSources.nonEmpty && unnamedSources.nonEmpty =>
+        throw unnamedSourcesError
+      case Some(true) if unnamedSources.nonEmpty =>
+        throw 
QueryCompilationErrors.cannotDisableSourceEvolutionOnExistingCheckpointError()
+      case _ if enforceNamed && unnamedSources.nonEmpty =>

Review Comment:
   **Nit (P3):** Two of the contracts this method now carries have no test that 
fails when they regress. By the review's reading of 
`NameStreamingSourcesSuite`, `OffsetSeqLogSuite`, and 
`StreamingSourceEvolutionSuite`, each edit below passes all three suites:
   
   - The config-on rejection of a new query whose sources reach 
`MicroBatchExecution` unnamed and without a naming wrapper. Deleting this arm 
lets a config-on `MemoryStream` or `STREAM` catalog-table query on a new 
checkpoint create its sources and then fail with IllegalStateException 
'Unassigned sources should not exist when enforcement is enabled'; dropping the 
config disjunct of `enforceNamed` (line 223) lets it run by position and record 
the config as false. Every config-on test names its sources, fails earlier at 
`load()`, mixes named and unnamed sources (the arm at line 505), or restarts a 
positional checkpoint, where the checkpoint's value wins.
   - The legacy arm's requirement that every name have a directory, and its 
acceptance of named and unnamed sources together (lines 492-504). Replacing 
`forall` with `exists` at line 498 accepts a two-source legacy checkpoint 
restarted with one source renamed, which then resumes that source's positional 
offset against a new metadata directory; moving the mixed-names arm above the 
legacy arm rejects legacy checkpoints that mix named and unnamed sources. The 
only tests that reach this arm, 'positional v$version checkpoint - restart with 
names is rejected before creating sources' and 'positional checkpoint written 
under source names keeps running with those names', use one named source and no 
unnamed one.
   
   The stack relies on these checks to reject mismatched restarts before 
creating sources, and the multi-source and mixed legacy cases are also the 
shapes whose behavior the fixes for other comments in this review would change.
   
   **Verification:**
   - **Regression:** With the config on, starting a new query whose unnamed 
source has no naming wrapper fails with 
UNNAMED_STREAMING_SOURCES_WITH_ENFORCEMENT before any source is created.
   - **Regression:** Restarting a positional checkpoint written under two 
source names with one of them changed fails before any source is created.
   - **Compatibility:** Restarting unchanged a positional checkpoint that keeps 
one named source under sources/<name> beside an unnamed source keeps running by 
position.



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