spark-test commented on code in PR #60265:
URL: https://github.com/apache/spark/pull/60265#discussion_r4520704188
##########
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):** Counting names that are already on relations here also
rejects statements that Spark 4.2 and 4.3 ran by position without the config.
Take `SELECT * FROM STREAM events IDENTIFIED BY ev UNION ALL SELECT * FROM
STREAM clicks_view`, where `events` is a Parquet session-catalog table and
`clicks_view` is a streaming temp view. On the base branch, FindDataSourceTable
moves `ev` onto the table's StreamingRelation, this rule unwraps the view's
Unassigned wrapper, and the query runs by position with source metadata in
`sources/ev` and `sources/0`. With this change, `hasUserProvidedName` finds
`ev` on the relation and `checkSourceNamingEnforcement` rejects the view's
wrapper with UNNAMED_STREAMING_SOURCES_WITH_ENFORCEMENT while `spark.sql`
analyzes the statement, before `checkSourceNames` could accept the existing
`sources/ev`. A V2-catalog table, CDC changes, or a table-valued function in
place of the view fails the same way; DataFrame-API unions are not affected
because
each side is analyzed on its own. Renaming within the statement does not
recover the checkpoint: naming the view leaves an unresolved wrapper, naming a
V2-catalog table fails the start-time probe, and dropping `ev` moves `events`
onto the view's `sources/0`. This rule is byte-identical in v4.2.0, v4.2.1,
v4.3.0 and the base branch, so released checkpoints of this shape exist.
Relatedly, no test restarts a positional checkpoint that has both a named and
an unnamed source, so nothing fails if the case order in `checkSourceNames`
that keeps the two-catalog-table version of this statement restarting changes.
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)
+ }
+
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):** This case was the only clear error, without the
config, for a name the rule cannot attach. A streaming temp view resolves to
`SubqueryAlias` over `View` (`SessionCatalog.getTempViewRelation`), which none
of the `propagateSourceNames` cases match, and `NamedStreamingRelation` is
never resolved on its own. So `spark.readStream.name("x").table("v")` now fails
with the internal error 'Found the unresolved operator' from CheckAnalysis, and
`SELECT * FROM STREAM v IDENTIFIED BY x` fails with
INVALID_USAGE_OF_STAR_OR_REGEX, where the base branch reported
SOURCE_NAMING_NOT_SUPPORTED. Streaming table-valued functions named with
IDENTIFIED BY take the same path, since the fallback comment in
`propagateSourceNames` notes that they do not resolve to a nameable relation.
**Verification:**
- **Regression:** spark.readStream.name(...).table on a streaming temp view
and SELECT * FROM STREAM view IDENTIFIED BY ... fail during analysis with the
new error instead of an internal unresolved-operator error or a star error,
with and without the config.
- **Compatibility:** Names on format sources, session-catalog and V2-catalog
tables, and CDC changes still reach their relations, with and without the
config.
##########
sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/runtime/MicroBatchExecution.scala:
##########
@@ -224,14 +243,9 @@ class MicroBatchExecution(
val disabledSources =
Utils.stringToSeq(sparkSession.sessionState.conf.disabledV2StreamingMicroBatchReaders)
- // Read the source evolution enforcement from the last written offset log
entry. If no entries
- // are found, use the session config value.
- val enforceNamed = initialLatestOffsetSeq.flatMap { case (_, offsetSeq) =>
- offsetSeq.metadataOpt.flatMap { metadata =>
- OffsetSeqMetadata.readValueOpt(metadata,
SQLConf.ENABLE_STREAMING_SOURCE_EVOLUTION)
- .map(_.toBoolean)
- }
-
}.getOrElse(sparkSessionForStream.sessionState.conf.enableStreamingSourceEvolution)
+ checkSourceNames()
+ // Every offset log entry records the decision from the query's session.
+
sparkSessionForStream.conf.set(SQLConf.ENABLE_STREAMING_SOURCE_EVOLUTION.key,
enforceNamed)
Review Comment:
**Nit (P3):** This write happens before `populateStartOffsets` calls
`OffsetSeqMetadata.setSessionConf`, which warns only when the session value
differs from the recorded one, so the warning never fires for this config. On
the base branch, restarting a positional v2 checkpoint with
`spark.sql.streaming.queryEvolution.enableSourceEvolution=true` logged
"Updating the value of conf ... from 'true' to 'false'", and a positional v1
checkpoint failed with CANNOT_ENABLE_ON_EXISTING_CHECKPOINT. Now both restart
by position with no signal, so an operator who turned the config on to make
queries evolvable does not learn that a restarted positional query keeps
positional tracking. The commit that moved this write (SPARK-61310) describes
itself as no behavior change.
**Verification:**
- **Behavior:** Restart a positional v1 and a positional v2 checkpoint with
the config on and check that each logs one warning naming the config and the
kept positional tracking; restart a checkpoint that tracks sources by name, and
a positional checkpoint, with the config off and check that neither logs it.
##########
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:
**Nit (P3):** `collectSources` visits every node down to the sources and
builds a sequence at each one, and this runs for every streaming plan while the
config is off, including the re-analysis of each micro-batch for the life of
the query. The base branch's config-off path was pruned on
NAMED_STREAMING_RELATION and did no work once no wrapper was left. Queries that
name a source also run `checkSourceNamingEnforcement`'s unpruned `collect` on
every batch, because their session now has the config on. When the plan has no
`NamedStreamingRelation`, every branch of `apply` returns it unchanged, so
returning early on `!plan.containsPattern(NAMED_STREAMING_RELATION)` gives the
same result without the walk. The cost has not been measured and is likely
small next to the rest of analysis.
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
+ * `spark.sql.streaming.queryEvolution.enableSourceEvolution` is enabled, all
sources must be
+ * explicitly named (throws error if any Unassigned sources found).
Review Comment:
**Nit (P3):** The rule only sees sources that are still wrapped when it
runs. Session-catalog tables, whose wrappers FindDataSourceTable consumes
first, and DataFrames analyzed separately pass it and are rejected later by
`MicroBatchExecution.checkSourceNames`, as the new SQL IDENTIFIED BY test
expects, so "throws error if any Unassigned sources found" overstates what this
rule enforces. Its 'Leaf position' also counts wrappers only: for a named
relation unioned with a wrapped unnamed source it reports position 0 for the
second source, which the new test at NameStreamingSourcesSuite.scala:382 pins,
while `checkSourceNames` reports position 1 for the same shape.
UNNAMED_STREAMING_SOURCES_WITH_ENFORCEMENT therefore identifies one source two
ways.
**Verification:**
- **Regression:** With the config on, a union of an already named relation
and a wrapped unnamed source fails with
UNNAMED_STREAMING_SOURCES_WITH_ENFORCEMENT whose sourceInfo is exactly Leaf
position 1 for the second source.
- **Inspection:** The class doc's enforcement statement matches the rule: it
rejects only wrapped unnamed sources and points to the start-time check for the
rest.
##########
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(
Review Comment:
**Nit (P3):** This decision narrows what
`spark.sql.streaming.queryEvolution.enableSourceEvolution` means: a
user-provided name from `name()` or IDENTIFIED BY turns on source evolution
without it, and with it on a restarted positional checkpoint, v1 included,
keeps its recorded positional tracking. The entry's doc in SQLConf.scala (lines
4047-4049) still says "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." A
reader concludes that evolution needs the config and that turning it on makes
existing queries evolvable, and neither holds now. The entry is internal, so
this misleads code readers rather than the generated user docs.
**Verification:**
- **Inspection:** The doc's statements match
MicroBatchExecution.enforceNamed and NameStreamingSources.apply: names opt in
without the config, the config forces evolution for new queries, and the
checkpoint's recorded tracking wins on restart.
##########
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):** `exists` on `sources/<name>` cannot tell whether the
positional runs wrote that directory for this source. By our reading of the
code it goes wrong two ways. First, all-digit names are valid
(`^[a-zA-Z0-9_]+$`), and `getMetadataPath` maps the name `1` to `sources/1`,
the directory an unnamed run gives its second source. Run `a.union(b)` once
over two Parquet file sources without names, then restart it as
`a.name("1").union(b.name("0"))`: the probe finds both directories,
`enforceNamed` stays the recorded false, and each FileStreamSource is created
on the other's log while it receives its own positional offset. Each restores
the other's seen files, lists its own already-read files as new, appends them
as batch 1 of the other log, and `getBatch(0, 1)` reads them again, so batch 1
writes the rows of both files a second time with no error. Second, a source
creates its directory when it is constructed, so a named run stopped before its
first batch, or a base-branch r
un that `resolveOffsetLogVersion` rejected after creating its sources, leaves
an empty `sources/<name>`. A later named restart passes the probe and runs the
positional offsets against that empty log, which reprocesses files or fails the
`getBatch` assertion after the regressed offset is logged. On the base branch
`.name("1")` on these sources fails at `load()` without the config, so the
default config now reaches a crossed layout that the base branch reached only
with the config on and a v2 checkpoint.
**Recommended change:** In the positional-checkpoint case of
checkSourceNames, count a named source as written under its name only when its
name is not made of digits alone and sources/<name> exists and holds at least
one file; otherwise throw CANNOT_ENABLE_ON_EXISTING_CHECKPOINT as now. Rewrite
the comment there to say why (positional sources use decimal directory names
that all-digit names collide with, and a directory a source created but never
wrote to is empty), and add a TODO naming the case this cannot detect, a
directory with content left by a named run that never logged an offset, and the
record of metadata-path names in offset metadata it would need. Add streaming
source evolution restart tests for both rejections.
**Why this works:** All-digit names are the only names getMetadataPath can
map onto a positional source's directory, so refusing to attribute such a
directory to a name removes every collision; a directory that a source created
but never wrote to is empty, so requiring content removes the leftovers of
rejected runs and of named runs stopped before their first batch, while the
directories released Spark wrote for named catalog tables hold metadata under
non-numeric names and keep passing.
**Scope:** Tighten which directories the start-time check attributes to a
source name, and test both rejections.
**Compatibility:** Positional checkpoints that released Spark wrote for
named catalog tables, whose named directories hold metadata under non-numeric
names, keep restarting by position.
**Risks:** A checkpoint that released Spark wrote for a catalog table named
with digits only, or whose named source never wrote metadata, now fails with
CANNOT_ENABLE_ON_EXISTING_CHECKPOINT instead of running; both fail before any
source is created. A positional checkpoint restarted with all-digit names that
match the directories its sources used while unnamed, which keeps each source
on its own metadata and runs correctly without this rule, fails the same way;
restarting it without the names keeps it running.
**Constraints:** The rule must keep accepting the checkpoints the exemption
exists for, including those of SQL statements that mix a named catalog table
with an unnamed source, which reach this check once the analyzer stops
rejecting them.
**Exclusions:**
- A directory with content left by a named run that never logged an offset
is still accepted; detecting it needs offset metadata that records which names
positional runs used for metadata paths, which released checkpoints do not have.
**Success:** Restarting a positional checkpoint with all-digit source names
fails with CANNOT_ENABLE_ON_EXISTING_CHECKPOINT before any source is created.
Restarting a positional checkpoint whose sources/<name> directory is empty
fails the same way. A positional checkpoint whose named sources keep metadata
under non-numeric names restarts by position as before.
**Verification:**
- **Regression:** Run two unnamed file sources once, restart them named 1
and 0 in swapped order, and check that the start fails with
CANNOT_ENABLE_ON_EXISTING_CHECKPOINT, creates no source, and leaves both
sources' metadata logs unchanged.
- **Regression:** Start a named file source that stops before its first
batch, restart the query without the name until it commits a batch, then
restart it with the name, and check that the start fails with
CANNOT_ENABLE_ON_EXISTING_CHECKPOINT before any source is created.
- **Compatibility:** A positional checkpoint laid out as released Spark
writes it for a named catalog table, alone and together with an unnamed source,
still restarts with the same names, reads its existing metadata, and writes no
duplicate output.
##########
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):** This case is the only guard for a new query that tracks by
name only because the config is on and whose sources all reach query start
unnamed: `SELECT * FROM STREAM t` over a session-catalog table, whose wrapper
FindDataSourceTable consumes before the analyzer's check, a memory stream, or a
DataFrame analyzed before the config was set. No test reaches it: the
start-time UNNAMED_STREAMING_SOURCES_WITH_ENFORCEMENT tests all mix a named and
an unnamed source, which the earlier mixed case rejects, and the all-unnamed
enforcement test fails at `load()` in the analyzer. Without this case such a
query would create its source and then fail with the IllegalStateException from
the name-keyed `sourceIdMap` build, and every test would still pass.
**Verification:**
- **Regression:** With the config on, a new query over one session-catalog
table streamed without a name fails at start with
UNNAMED_STREAMING_SOURCES_WITH_ENFORCEMENT and leaves no sources directory in
the checkpoint.
--
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]