cloud-fan commented on code in PR #59596:
URL: https://github.com/apache/spark/pull/59596#discussion_r4642218377


##########
sql/catalyst/src/main/java/org/apache/spark/sql/connector/catalog/Changelog.java:
##########
@@ -218,4 +218,15 @@ default NamedReference[] rowId() {
   default NamedReference rowVersion() {
     throw new UnsupportedOperationException("rowVersion is not supported.");
   }
+
+  /**
+   * Returns metadata columns exposed when scanning this Changelog.

Review Comment:
   **Nit (P3):** The interface already uses "metadata columns" for the required 
`_change_type`, `_commit_version` and `_commit_timestamp` columns (the class 
Javadoc at line 37 and `columns()` at line 132), so a connector author can read 
this method as the place for them. `ChangelogTable.validateSchema` reads only 
`columns()`, so that fails with a missing-column error. The Javadoc also does 
not tell implementors how Spark uses these columns: `rowId()` (line 188) and 
`rowVersion()` (line 216) may reference a column returned here, and that column 
must then be non-nullable, while `MetadataColumn.isNullable()` defaults to 
`true`. Because `ChangelogTable` now implements `SupportsMetadataColumns` by 
forwarding this method, the scan builder receives these fields in 
`pruneColumns`, and a column whose name matches a data column is suppressed, 
but nothing points to those rules. Keeping your first sentence, wording like 
this would close the gap without saying what the columns are for:
   
   ```java
      * Returns metadata columns exposed when scanning this Changelog.
      * <p>
      * These are additional columns in the sense of {@link 
SupportsMetadataColumns}, separate
      * from the required {@code _change_type}, {@code _commit_version} and
      * {@code _commit_timestamp} columns, which {@link #columns()} must 
return. See
      * {@link SupportsMetadataColumns} for how they are requested from the 
scan and how name
      * conflicts with data columns are handled.
   ```
   
   Then add a sentence to `rowId()` and `rowVersion()` saying that a reference 
may name a column from `metadataColumns()`, which must then be non-nullable.
   
   **Verification:**
   - **Inspection:** Check that the Javadoc of Changelog.metadataColumns() 
keeps its opening sentence, distinguishes these columns from the required 
_change_type, _commit_version and _commit_timestamp columns of columns(), and 
points to SupportsMetadataColumns for scan pruning and name conflicts, and that 
the rowId() and rowVersion() Javadoc says a reference may name a non-nullable 
column from metadataColumns().
   - **Compile:** Check that the links to SupportsMetadataColumns and 
metadataColumns() in the Javadoc of the Changelog interface resolve when the 
Java API documentation is generated.



##########
sql/core/src/test/scala/org/apache/spark/sql/connector/ChangelogEndToEndSuite.scala:
##########
@@ -685,6 +687,127 @@ class ChangelogEndToEndSuite extends SharedSparkSession {
     }
   }
 
+  test("named streaming changelogs preserve source names through 
post-processing") {
+    val metadataColumn = new MetadataColumn {
+      override def name(): String = "_metadata"
+      override def dataType(): StructType = new StructType()
+        .add("row_id", LongType, nullable = false)
+      override def isNullable(): Boolean = false
+    }
+    val postProcessing = ChangelogProperties(
+      containsCarryoverRows = true,
+      containsIntermediateChanges = true,
+      representsUpdateAsDeleteAndInsert = true,
+      rowIdPaths = Seq(Seq("_metadata", "row_id")),
+      rowVersionName = Some("_commit_version"),
+      metadataColumns = Seq(metadataColumn))
+
+    withSQLConf(SQLConf.ENABLE_STREAMING_SOURCE_EVOLUTION.key -> "true") {
+      val cases = Seq(
+        (ChangelogProperties(), "none"),
+        (postProcessing, "none"),
+        (postProcessing, "dropCarryovers"),
+        (postProcessing, "netChanges"))
+      cases.zipWithIndex.foreach { case ((properties, mode), i) =>
+        catalog.setChangelogProperties(ident, properties)
+        val computeUpdates = mode != "none"
+        val sqlText = s"SELECT * FROM STREAM $fullTableName CHANGES FROM 
VERSION 1 " +
+          s"WITH (deduplicationMode = '$mode', computeUpdates = 
'$computeUpdates') " +
+          "IDENTIFIED BY cdc"
+        val streams = Seq(
+          spark.readStream.name("cdc").option("startingVersion", "1")
+            .option("deduplicationMode", mode).option("computeUpdates", 
computeUpdates.toString)
+            .changes(fullTableName),
+          sql(sqlText))
+        streams.zipWithIndex.foreach { case (stream, api) =>
+          val analyzed = stream.queryExecution.analyzed
+          assert(analyzed.collect {
+            case source: StreamingRelationV2 => source.sourceIdentifyingName
+          } == Seq(UserProvided("cdc")))
+          assert(stream.schema.fieldNames.toSeq ==
+            Seq("id", "data", "_change_type", "_commit_version", 
"_commit_timestamp"))
+          assert(analyzed.metadataOutput.isEmpty)
+          checkError(
+            intercept[AnalysisException] {
+              stream.select(stream.metadataColumn("_metadata")).schema
+            },
+            condition = "UNRESOLVED_COLUMN.WITHOUT_SUGGESTION",
+            parameters = Map("objectName" -> "`_metadata`"),
+            queryContext = if (api == 1) {
+              Array(ExpectedContext(sqlText, 0, sqlText.length - 1))
+            } else {
+              Array.empty
+            })
+
+          // Execute the basic named read as well as checking all rewritten 
plan shapes.
+          if (i == 0) {
+            catalog.addChangeRows(ident, Seq(
+              makeChangeRow(1L, "a", CHANGE_TYPE_INSERT, 1L, 1000000L)))
+            val queryName = s"cdc_named_boundary_$api"
+            val query = 
stream.writeStream.format("memory").queryName(queryName).start()
+            try {
+              query.processAllAvailable()
+              checkAnswer(spark.table(queryName),
+                Seq(Row(1L, "a", CHANGE_TYPE_INSERT, 1L, new 
Timestamp(1000L))))
+            } finally {
+              query.stop()
+              catalog.clearChangeRows(ident)
+            }
+          }
+        }
+      }
+    }
+  }
+
+  for {
+    hasInitialState <- Seq(false, true)
+    streamingInitialState <- Seq(false, true)
+  } {
+    test(s"source naming preserves initial-state inputs: 
hasInitialState=$hasInitialState, " +
+        s"streamingInitialState=$streamingInitialState") {
+      catalog.setChangelogProperties(ident, ChangelogProperties(
+        containsIntermediateChanges = true,
+        rowIdNames = Seq("id")))
+      withSQLConf(SQLConf.ENABLE_STREAMING_SOURCE_EVOLUTION.key -> "true") {
+        val stream = spark.readStream.name("original")
+          .option("deduplicationMode", "netChanges").changes(fullTableName)
+        val stateful = stream.queryExecution.analyzed.collectFirst {
+          case tws: TransformWithState => tws
+        }.get
+        val initialState = if (streamingInitialState) stateful.child else 
stateful.initialState
+        val withInitialState = stateful.copy(
+          hasInitialState = hasInitialState, initialState = initialState)
+        val wrapper = NamedStreamingRelation(withInitialState, 
UserProvided("replacement"))
+        val result = NameStreamingSources(wrapper)
+        val resultStateful = result.collectFirst { case tws: 
TransformWithState => tws }.get
+        assert(resultStateful.initialState eq initialState)
+        if (streamingInitialState) {
+          assert(result.fastEquals(wrapper))
+        } else {
+          assert(result.collect { case n: NamedStreamingRelation => n 
}.isEmpty)
+          assert(result.collect {
+            case source: StreamingRelationV2 => source.sourceIdentifyingName
+          } == Seq(UserProvided("replacement")))
+        }
+      }
+    }
+  }
+
+  test("source naming remains attached to the changelog input of a 
stream-static join") {

Review Comment:
   **Nit (P3):** `beforeEach` (lines 68-81) drops and recreates the table and 
clears its change rows, but `InMemoryChangelogCatalog` keeps changelog 
properties in a per-identifier map that `dropTable` does not touch. In suite 
order, this test therefore analyzes the read with the properties the last 
initial-state test left (`containsIntermediateChanges = true`, `rowIdNames = 
Seq("id")`), while run alone with `-z` it uses the defaults. It passes either 
way only because the default `dropCarryovers` mode selects no post-processing 
for those properties. By this review's reading, a test placed right after the 
named post-processing test above would instead inherit its `_metadata` column 
and carry-over removal, which rows built with the plain `makeChangeRow` helper 
cannot satisfy. Resetting the properties in `beforeEach` with 
`cat.setChangelogProperties(ident, ChangelogProperties())`, as 
`ChangelogResolutionSuite.beforeEach` already does, makes every test start from 
the defaults.
   
   **Verification:**
   - **Regression:** Check that the end-to-end test of a named streaming 
changelog read joined with a static range analyzes the read with default 
changelog properties, both when it runs alone and when it runs after the tests 
that set post-processing and hidden-metadata properties.
   - **Behavior:** Check that the full end-to-end changelog suite passes with 
the per-test reset, so no existing test depended on properties left by an 
earlier test.



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/NameStreamingSources.scala:
##########
@@ -105,6 +105,22 @@ object NameStreamingSources extends Rule[LogicalPlan] {
           sourceIdentifyingName) =>
         sa.copy(child = h.withSourceIdentifyingName(sourceIdentifyingName))
 
+      // Wait for an unresolved inner naming wrapper instead of swapping the 
two names.
+      case named @ NamedStreamingRelation(_: NamedStreamingRelation, _) =>
+        named
+
+      // Follow the unary operators inserted by changelog resolution.

Review Comment:
   **Nit (P3):** The case below has no guard, so it matches any unary child, 
not only the changelog operators. With source evolution enabled, a named read 
of a streaming temporary view, for example, recurses through the view's 
`SubqueryAlias` and `View` and renames its source. The case also has to stay 
after the nested-wrapper case above, because `NamedStreamingRelation` is itself 
a `UnaryNode`. Suggested wording:
   
   ```suggestion
         // Propagate the name through any unary operator above the source, 
such as the ones
         // changelog resolution inserts. A node with several children stops 
propagation, except
         // the TransformWithState case below. Must follow the nested-wrapper 
case, because
         // NamedStreamingRelation is itself a UnaryNode.
   ```
   
   **Verification:**
   - **Inspection:** Check that the comment on the unary-operator case of 
NameStreamingSources.propagateSourceNames no longer limits it to changelog 
operators, says multi-child nodes stop propagation, and notes that the case 
must follow the nested-wrapper case.



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/ResolveChangelogTable.scala:
##########
@@ -278,13 +296,13 @@ object ResolveChangelogTable extends Rule[LogicalPlan] {
    *     the batch path -- groups with `_del_cnt = 1 AND _ins_cnt = 1 AND 
_rv_cnt = 2 AND
    *     _min_rv = _max_rv` are dropped wholesale.
    *  4. [[Generate]] using `Inline(events)` to re-emit one output row per 
buffered input
-   *     row. `unrequiredChildIndex` drops the duplicate grouping columns and 
the events
-   *     buffer; the helper count columns flow through.
+   *     row. A Project selects the generated columns and preserves scalar 
rowId helpers

Review Comment:
   **Nit (P3):** The method now builds `Generate`, then a `Project` that keeps 
the rowId helpers, the count and row-version helpers, and the generated columns 
(lines 398-402), then the optional relabel `Project`. The diagram at lines 
250-253 still goes from `Generate` straight to the relabel `Project` and says 
the helper-drop `Project` removes the helper columns, although 
`removeHelperColumns` keeps the `__spark_cdc_rowid_<i>` helpers. This step and 
the inline comment at lines 384-385 mention only the rowId helpers, but the 
relabel step reads the count and row-version helpers that the new `Project` 
also keeps. Step 6 (lines 304-305) says the rowId helpers stay until the final 
changelog output projection. When net changes follow, though, 
`addStreamingNetChangeComputation` drops them (line 673) and removes its own 
copies at the end (line 720). While updating the diagram, you could also list 
the watermark-strip and helper-drop Projects in the order the code builds them: 
the strip comes 
 first (lines 412-413).
   
   **Verification:**
   - **Inspection:** Check that the scaladoc of 
addStreamingRowLevelPostProcessing lists the operators in the order the method 
builds them, including the Project after Generate, and that its text names 
every helper column that each step keeps or drops, including where the rowId 
helpers are dropped when net changes follow.



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