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


##########
sql/pipelines/src/main/scala/org/apache/spark/sql/pipelines/graph/DatasetManager.scala:
##########
@@ -682,7 +682,9 @@ object DatasetManager extends Logging {
       caseSensitive: Boolean): Unit = {
     val currentSchema = v2ColumnsToStructType(existingTable.columns())
     val targetSchema = if (mergeWithExistingSchema) {
-      SchemaMergingUtils.mergeSchemas(currentSchema, desiredSchema, 
caseSensitive)
+      // Column metadata (e.g. comments) of columns present in both schemas 
comes from the desired
+      // schema, so that metadata changes are diffed and applied below rather 
than dropped.
+      SchemaMergingUtils.mergeSchemasWithDataMetadata(currentSchema, 
desiredSchema, caseSensitive)

Review Comment:
   **Blocking (P1):** This merge now takes desired-schema metadata for every 
caller that passes `mergeWithExistingSchema = true`, and that includes 
`materializeAuxiliaryTable` for AutoCDC auxiliary tables. Their desired schema 
is derived from the inferred target schema (`DataflowGraph.inferSchemas` passes 
`userSpecifiedSchema = None`, and the SCD2 auxiliary schema mirrors every 
target field with its metadata), not from the declaration.
   
   Reading the code, this sequence now fails where the base branch succeeds: an 
SCD2 AutoCDC target declares its full schema, including the reserved AutoCDC 
columns, and its change feed has `arr ARRAY<ARRAY<STRUCT<a: INT COMMENT 
'c1'>>>`. After the source comment on `a` becomes `'c2'`, validation still 
passes (the declared side's metadata wins `mergeSchemas`), and the target diffs 
against its unchanged declaration and finds nothing to change. The auxiliary 
evolve then overlays `'c2'`, `diffSchemas` emits 
`UpdateColumnComment(arr.element.element.a)` inside the outer element diff, and 
`rejectUnsupportedNestedTypeChanges` throws 
`PIPELINE_NESTED_COMPLEX_TYPE_SCHEMA_EVOLUTION_UNSUPPORTED`, showing 
`array<struct<a:int>>` as both types.
   
   The update fails with `TableMaterializationException` after the target may 
already have been altered, and every later incremental run fails the same way 
until a full refresh re-creates the auxiliary table or the source comment is 
reverted; the declared target schema cannot pin the auxiliary comment. SCD1 
auxiliary tables hold only the key and CDC metadata columns, so they hit this 
only when a key column has such nesting. Nothing reads auxiliary-table 
comments, so applying them buys nothing, and at shallower nesting the overlay 
also adds a metadata-only `alterTable` on the auxiliary table whenever source 
comments change.
   
   **Recommended change:** Keep the base branch's merge for the AutoCDC 
auxiliary table: let evolveTable's caller choose whether shared fields take the 
desired schema's metadata, with materializeTable choosing it for streaming 
tables and materializeAuxiliaryTable keeping the plain additive merge 
(mergeSchemas), which keeps the auxiliary table's persisted metadata. Add an 
AutoCDC auxiliary-table materialization test for an SCD type 2 target that 
declares its schema and whose change feed has a commented struct field under an 
array of arrays, changing that comment between runs.
   
   **Why this works:** With the auxiliary table's own metadata kept on shared 
fields, its diff finds no comment difference, so no comment change is built for 
it and the nested-type check has nothing to reject. Added columns, type 
widening, and nullability still come from the same merge as before.
   
   **Scope:** Let each evolveTable caller choose the merge, so only streaming 
tables take desired-schema metadata, and cover the auxiliary-table path with a 
test.
   
   **Compatibility:** Streaming tables keep this PR's behavior: on 
non-full-refresh runs their shared fields take metadata from the declared or 
inferred schema.
   
   **Risks:** Auxiliary-table column comments stop following the inferred 
target schema, as on the base branch; nothing reads them, and a full refresh 
still re-creates the auxiliary table from the current derived schema.
   
   **Constraints:** Streaming tables on non-full-refresh runs must keep taking 
shared-field metadata from the desired schema, including removed comments. The 
auxiliary table's merge must keep folding names under the target's effective 
case sensitivity.
   
   **Exclusions:**
   - Comment changes under consecutive arrays or maps on the streaming tables 
themselves, which now fail the update, stay as they are; how to handle them is 
the separate open question about those comment changes.
   
   **Success:** An incremental run of an AutoCDC target whose derived auxiliary 
schema differs from the persisted auxiliary table only in field comments, at 
any nesting depth, issues no column change for the auxiliary table and 
succeeds. Existing streaming tables on non-full-refresh runs still apply added, 
changed, and removed column comments from their declared schema.
   
   **Verification:**
   - **Regression:** An SCD type 2 AutoCDC target that declares its schema, 
with a change feed whose commented struct field sits under an array of arrays, 
runs incrementally after that source comment changes: the run succeeds, and the 
auxiliary table keeps its persisted columns with no alterTable issued for it.
   - **Compatibility:** When only a top-level or single-level nested comment 
changes in the derived auxiliary schema, an incremental run issues no 
alterTable for the auxiliary table, as on the base branch.



##########
sql/pipelines/src/test/scala/org/apache/spark/sql/pipelines/util/SchemaMergingUtilsSuite.scala:
##########
@@ -54,4 +53,59 @@ class SchemaMergingUtilsSuite extends SparkFunSuite {
     assert(
       mergedDefaults("score").getCurrentDefaultValue() === Some("0"))
   }
+
+  test("SPARK-59268: mergeSchemasWithDataMetadata takes data-side metadata on 
shared fields") {
+    val currentSchema = new StructType()
+      .add("id", IntegerType, nullable = false, "id comment")
+      .add("changed", StringType, nullable = true, "old comment")
+      .add("removed", StringType, nullable = true, "removed comment")
+      .add("added", StringType)
+      .add(StructField("score", IntegerType).withCurrentDefaultValue("0"))
+      .add("onlyInCurrent", StringType, nullable = true, "kept comment")
+    val desiredSchema = new StructType()
+      .add("id", IntegerType, nullable = false, "id comment")
+      .add("changed", StringType, nullable = true, "new comment")
+      .add("removed", StringType)
+      .add("added", StringType, nullable = true, "added comment")
+      .add(StructField("score", IntegerType).withCurrentDefaultValue("42"))
+      .add("onlyInDesired", StringType, nullable = true, "new column comment")
+
+    val merged = SchemaMergingUtils.mergeSchemasWithDataMetadata(
+      currentSchema, desiredSchema, caseSensitive = true)
+    assert(merged.fieldNames.toSeq ===
+      Seq("id", "changed", "removed", "added", "score", "onlyInCurrent", 
"onlyInDesired"))
+    assert(merged("id").getComment() === Some("id comment"))
+    assert(merged("changed").getComment() === Some("new comment"))
+    assert(merged("removed").getComment() === None)
+    assert(merged("added").getComment() === Some("added comment"))
+    assert(merged("score").getCurrentDefaultValue() === Some("42"))
+    assert(merged("onlyInCurrent").getComment() === Some("kept comment"))
+    assert(merged("onlyInDesired").getComment() === Some("new column comment"))
+  }
+
+  test("SPARK-59268: mergeSchemasWithDataMetadata takes data-side metadata on 
nested fields") {
+    def schema(comment: String): StructType = {
+      val inner = new StructType().add("a", IntegerType, nullable = true, 
comment)
+      new StructType()
+        .add("s", inner)
+        .add("arr", ArrayType(inner))
+        .add("m", MapType(StringType, inner))

Review Comment:
   **Nit (P3):** With a `StringType` key, the key recursion in 
`overlayFieldMetadata` only ever reaches `case _ => target`, and the only 
`caseSensitive = false` case is top-level, while the end-to-end test uses 
identically cased nested names. Reading the code, replacing the key recursion 
with `keyType = targetMap.keyType`, or recursing with `caseSensitive = true`, 
would leave every assertion in both suites passing. Both inputs are supported: 
`diffSchemas` and `CatalogV2Util.replace` handle comment changes on fields of a 
struct key, and `StructType.merge` folds nested names that differ only in case 
under the default case-insensitive session. Either regression would silently 
bring back the dropped comment change for those fields. Using a struct key here 
(for example `MapType(inner, inner)`) and adding a nested field whose declared 
name differs only in case (table `s.a`, declared `s.A`, with a changed comment) 
to the case-insensitive test would cover both.
   
   **Verification:**
   - **Behavior:** For a map column whose key is a struct with a commented 
field, merging with a desired schema that changes that comment yields the 
desired comment on the key's field.
   - **Behavior:** Under case-insensitive merging, a nested struct field whose 
declared name differs from the table's only in case, with a changed comment, 
keeps the table's name and takes the declared comment.



##########
sql/pipelines/src/main/scala/org/apache/spark/sql/pipelines/graph/DatasetManager.scala:
##########
@@ -682,7 +682,9 @@ object DatasetManager extends Logging {
       caseSensitive: Boolean): Unit = {
     val currentSchema = v2ColumnsToStructType(existingTable.columns())
     val targetSchema = if (mergeWithExistingSchema) {
-      SchemaMergingUtils.mergeSchemas(currentSchema, desiredSchema, 
caseSensitive)
+      // Column metadata (e.g. comments) of columns present in both schemas 
comes from the desired
+      // schema, so that metadata changes are diffed and applied below rather 
than dropped.

Review Comment:
   **Nit (P3):** `diffSchemas` below emits only type, nullability, and comment 
changes; `warnOnFieldMetadataDrift` just logs that any other metadata 
difference, such as a changed default value (still the SPARK-59269 TODO), will 
be ignored. As written, this comment tells the next reader that default values 
and other metadata are synchronized here. Suggested wording:
   
   ```suggestion
         // Shared columns take their metadata from the desired schema, so 
comment changes are diffed
         // and applied below; other metadata changes (e.g. defaults, 
SPARK-59269) are only logged.
   ```
   
   **Verification:**
   - **Inspection:** The comment that explains why the incremental merge takes 
desired-schema metadata no longer claims that metadata changes in general are 
applied, and it says that non-comment differences such as default values are 
only logged.



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