suhuruli commented on code in PR #60463:
URL: https://github.com/apache/spark/pull/60463#discussion_r4594029127


##########
docs/sql-migration-guide.md:
##########
@@ -100,6 +100,7 @@ license: |
 - Since Spark 4.4, a CHECK constraint that `ALTER TABLE ... ADD CONSTRAINT` 
adds to a Data Source V2 table, and whose condition reads the current time, 
date, catalog, user and the like, such as `ts <= current_timestamp()` or `db = 
current_database()`, is checked against their values at the time of each write. 
Previously, it was checked against their values at the time of the `ALTER 
TABLE`, unless a write could not read back a predicate for its condition, such 
as one with a lambda function or one that passes a column to `datediff`, `year` 
or `upper` (SPARK-60032). Such a constraint is stored without a predicate, so 
each write parses and analyzes its SQL text under the session of the write, as 
it does for a constraint without a predicate that `CREATE TABLE` adds. A 
setting of the write such as `spark.sql.ansi.enforceReservedKeywords`, which 
reserves `TIME`, or `spark.sql.ansi.doubleQuotedIdentifiers` can then make it 
fail to parse the text or read it differently. A row-level operation
  that copies unchanged rows, such as a `DELETE` or `UPDATE` on a copy-on-write 
table, fails with `CHECK_CONSTRAINT_VIOLATION` on a copied row that no longer 
satisfies the condition. For example, `ts >= current_timestamp() - INTERVAL 30 
DAYS` now fails such a `DELETE` once a copied row is older than 30 days. A 
condition that Spark detects a write could resolve differently is stored as 
before, so a write accepts and rejects the same rows for it as before. Examples 
are conditions that also read a variable, a `CHAR` column, a name with more 
than one part such as a column qualified by the table name, or a constant that 
depends on the session time zone, such as `'2024-01-01 00:00:00'` cast to a 
timestamp. So are conditions with a name such as `current_date` or `user` 
without parentheses, which a write can read as a column name, and conditions 
whose text the parser settings of the `ALTER TABLE`, such as 
`spark.sql.ansi.doubleQuotedIdentifiers` or 
`spark.sql.parser.escapedStringLiterals`, r
 ead differently from their default values. ANSI mode, 
`spark.sql.timestampType` and the session time zone are taken from the session 
for this comparison, as for a generation expression. A condition that reads the 
current date or time only through a typed literal such as `DATE 'today'` is 
also stored as before. An existing constraint keeps its stored predicate until 
it is dropped and added again. `Check.predicate()` is null for a constraint 
stored without a predicate, so a connector that validates or enforces it itself 
has to evaluate `Check.predicateSql()`. To restore the previous behavior, set 
`spark.sql.legacy.freezeCurrentValuesInCheckConstraint` to `true` before adding 
the constraint. A constraint added without it is not changed.
 - Since Spark 4.4, a function created by `CREATE FUNCTION ... AS 'class'` 
whose class implements 
`org.apache.spark.sql.connector.catalog.functions.UnboundFunction` and extends 
either a Hive UDF class (such as `UDF` or `GenericUDF`) or 
`org.apache.spark.sql.expressions.UserDefinedAggregateFunction` runs as a 
DataSource V2 function instead of a Hive UDF or Spark UDAF, including functions 
created in earlier versions. Its result type, argument coercion, and null 
handling are defined by the V2 implementation selected by 
`UnboundFunction.bind`. Hive's `@UDFType` and Spark UDAF's `deterministic` 
property do not control the V2 path. For scalar functions, determinism uses 
`BoundFunction.isDeterministic()` (default `true`) and the arguments' 
determinism. A call with constant arguments can therefore become eligible for 
constant folding during query planning instead of being evaluated per row.
 - Since Spark 4.4, `next_day` and `last_day` fail with `DATETIME_OVERFLOW` 
when the result is later than the maximum `DATE`, `+5881580-07-11`, and `trunc` 
fails with it when the result is earlier than the minimum `DATE`, 
`-5877641-06-23`, regardless of `spark.sql.ansi.enabled`. Previously, these 
functions silently returned a wrong date, in most cases one at the other end of 
the `DATE` range; for example, `last_day(DATE'+5881580-07-11')` returned 
`-5877641-07-12` and `trunc(DATE'-5877641-06-23', 'MONTH')` returned 
`+5881580-06-20`, while `trunc` to `QUARTER` failed with `ARITHMETIC_OVERFLOW`. 
`next_day` and `trunc` to `WEEK` also returned a wrong date for the first days 
of the `DATE` range; for example, `next_day(DATE'-5877641-06-23', 'MO')` and 
`trunc(DATE'-5877641-07-01', 'WEEK')` returned `-5877641-06-25`, a Thursday, 
and now return `-5877641-06-29`.
+- Since Spark 4.4, an incremental update of a [Declarative 
Pipelines](declarative-pipelines-programming-guide.html) streaming table 
applies the column comments of the pipeline's declared or inferred schema to 
the table, as a full refresh and an update of a materialized view already do: a 
changed comment is applied, and a comment that this schema lacks is removed, 
including a comment set directly on the table with `ALTER TABLE ... ALTER 
COLUMN ... COMMENT`. Previously, an incremental update kept the table's 
existing column comments and ignored the pipeline's. When such a comment change 
sits on a struct field nested under consecutive arrays or maps, for example in 
a column of type `ARRAY<ARRAY<STRUCT<a: INT COMMENT 'c'>>>`, the update now 
fails with `PIPELINE_NESTED_COMPLEX_TYPE_COMMENT_CHANGE_UNSUPPORTED` instead of 
ignoring the change. Declaring a comment in the table's schema in the pipeline 
keeps it.

Review Comment:
   Agreed, the sentence claimed more than the merge does. I reworded the bullet 
in `docs/sql-migration-guide.md` so that it says a comment that the pipeline's 
schema lacks on one of its columns or nested fields is removed, and that a 
column which remains on the table but is no longer in the pipeline's schema 
keeps its comment. The rest of the bullet is unchanged, including the `ALTER 
TABLE ... ALTER COLUMN ... COMMENT` case and the 
`PIPELINE_NESTED_COMPLEX_TYPE_COMMENT_CHANGE_UNSUPPORTED` error for a change 
under consecutive arrays or maps. This matches what 
`mergeSchemasWithDataMetadata` does: only fields present in both schemas take 
the declared metadata, which the `onlyInCurrent` assertion in 
`SchemaMergingUtilsSuite` already pins. I applied the same wording to the 
user-facing change section and the release note in the PR description.



##########
sql/pipelines/src/main/scala/org/apache/spark/sql/pipelines/util/SchemaMergingUtils.scala:
##########
@@ -40,8 +42,57 @@ object SchemaMergingUtils {
       tableSchema: StructType,
       dataSchema: StructType,
       caseSensitive: Boolean): StructType = {
-    // TODO (SPARK-59268): don't drop changes to comments and field metadata 
`desiredSchema`, or
-    // loudly reject changes to such fields.
     StructType.merge(tableSchema, dataSchema, 
caseSensitive).asInstanceOf[StructType]
   }
+
+  /**
+   * Like [[mergeSchemas]], but on a field present in both schemas (at any 
nesting level), the
+   * field's metadata (comment, default value, etc.) is taken from 
`dataSchema` rather than from
+   * `tableSchema`. Fields present only in `tableSchema` keep their metadata.
+   *
+   * Used for additive schema evolution of an existing streaming table, where 
`tableSchema` is the
+   * table's current schema and `dataSchema` is the declared or inferred one: 
column metadata
+   * changes in the desired schema (including a removed comment) must survive 
the merge so that
+   * they can be applied to the table, the same way they are when the desired 
schema is used as-is.
+   */
+  def mergeSchemasWithDataMetadata(
+      tableSchema: StructType,
+      dataSchema: StructType,
+      caseSensitive: Boolean): StructType = {
+    val merged = mergeSchemas(tableSchema, dataSchema, caseSensitive)
+    overlayFieldMetadata(merged, dataSchema, 
caseSensitive).asInstanceOf[StructType]
+  }
+
+  /**
+   * Returns `target` with the metadata of every struct field that also exists 
(by name, honoring
+   * `caseSensitive`) in `source` replaced by the metadata of the `source` 
field, recursing into
+   * nested structs, arrays, and maps. Names, types, and nullability are taken 
from `target`.
+   */
+  private def overlayFieldMetadata(
+      target: DataType,
+      source: DataType,
+      caseSensitive: Boolean): DataType = (target, source) match {
+    case (targetStruct: StructType, sourceStruct: StructType) =>
+      def normalize(name: String): String =
+        if (caseSensitive) name else name.toLowerCase(Locale.ROOT)

Review Comment:
   Good catch, no test exercised the case-sensitive branch of `normalize` with 
names that differ only in case. I added `SPARK-59268: 
mergeSchemasWithDataMetadata matches names exactly under case-sensitive merge` 
to `SchemaMergingUtilsSuite`: the table schema has `value` with comment 'old', 
the declared schema has `Value` with comment 'new', and with `caseSensitive = 
true` the result is `value` with 'old' followed by an added `Value` with 'new'. 
I checked that the test fails when `normalize` lower-cases the name regardless 
of `caseSensitive`, since `value` then takes the comment of `Value`. The 
production code is unchanged.



##########
sql/pipelines/src/main/scala/org/apache/spark/sql/pipelines/util/SchemaInferenceUtils.scala:
##########
@@ -455,6 +459,13 @@ object SchemaInferenceUtils extends Logging {
     if (typeChanges.nonEmpty) {
       (currentType, targetType) match {
         case (_: ArrayType | _: MapType, _: ArrayType | _: MapType) =>
+          val commentChanges = typeChanges.collect { case c: 
TableChange.UpdateColumnComment => c }
+          if (commentChanges.size == typeChanges.size) {

Review Comment:
   Right, nothing pinned the single-level side of this boundary. I added 
`SPARK-59268: diffSchemas - comment-only changes under a single array or map 
level are emitted at the leaf` to `SchemaInferenceUtilsSuite`, next to the DSv2 
catalog test. The two schemas differ only in the comment of a struct field 
inside `array<struct>` and of a struct field inside both the key and the value 
of `map<struct, struct>`, and the test asserts exactly the three 
`UpdateColumnComment` changes at `arr.element.a`, `m.key.x` and `m.value.x` 
with no exception. I checked that it fails when the comment-only rejection is 
moved above the `match` so that it applies to every array or map change. The 
production code is unchanged.



##########
sql/pipelines/src/main/scala/org/apache/spark/sql/pipelines/util/SchemaInferenceUtils.scala:
##########
@@ -455,6 +459,13 @@ object SchemaInferenceUtils extends Logging {
     if (typeChanges.nonEmpty) {
       (currentType, targetType) match {
         case (_: ArrayType | _: MapType, _: ArrayType | _: MapType) =>
+          val commentChanges = typeChanges.collect { case c: 
TableChange.UpdateColumnComment => c }
+          if (commentChanges.size == typeChanges.size) {
+            throw new SparkUnsupportedOperationException(
+              errorClass = 
"PIPELINE_NESTED_COMPLEX_TYPE_COMMENT_CHANGE_UNSUPPORTED",
+              messageParameters = Map(
+                "columnPath" -> 
commentChanges.map(_.fieldNames().mkString(".")).mkString(", ")))

Review Comment:
   Agreed, every existing expectation of this error had a single path, so the 
join was unobserved. I added `SPARK-59268: diffSchemas - several comment 
changes under array<array<struct>> are all named in the comment-specific error` 
to `SchemaInferenceUtilsSuite`: for `arr ARRAY<ARRAY<STRUCT<a: INT COMMENT 'x', 
b: INT COMMENT 'y'>>>` with both comments changed, it expects `columnPath` to 
be `arr.element.element.a, arr.element.element.b`, which is the separator the 
code already uses. I checked that it fails when only `commentChanges.head` is 
reported. The production code is unchanged.



##########
sql/pipelines/src/main/scala/org/apache/spark/sql/pipelines/graph/DatasetManager.scala:
##########
@@ -413,6 +413,10 @@ object DatasetManager extends Logging {
           desiredSchema = outputSchema,
           properties = mergedProperties,
           mergeWithExistingSchema = isTableIncrementallyUpdated,
+          // On the incremental path, shared columns take the declared or 
inferred schema's
+          // metadata, so that a changed or removed column comment reaches the 
table as it does on
+          // the non-merging paths (materialized views and full refreshes).
+          mergeWithDesiredMetadata = true,

Review Comment:
   I did not add a configuration for this. The change is documented in the 4.3 
to 4.4 section of `docs/sql-migration-guide.md`, which now also states the 
exact removal rule: a comment is removed only on a column or nested field that 
the pipeline's schema contains without it, and a column that stays on the table 
but left the pipeline's schema keeps its comment. For the nested case, a 
comment change beneath consecutive arrays or maps fails with 
`PIPELINE_NESTED_COMPLEX_TYPE_COMMENT_CHANGE_UNSUPPORTED` before any change is 
applied to the table, which `SPARK-59268: a comment change under consecutive 
arrays fails a streaming table update with a comment-specific error` in 
`MaterializeTablesSuite` checks together with the unchanged persisted columns. 
The error message says that declaring the comment the table currently has keeps 
it, and the migration note says that declaring a comment in the pipeline's 
schema keeps it, so a pipeline that relied on the previous behavior can keep 
updating by 
 stating its comments in the declared schema, which is also what a full refresh 
or a materialized view already requires.



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