spark-test commented on code in PR #60463: URL: https://github.com/apache/spark/pull/60463#discussion_r4593350981
########## 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: **Nit (P3):** As written, this says an incremental update removes every comment the pipeline's schema lacks, the way a full refresh and a materialized-view update do. The code is narrower: `mergeSchemasWithDataMetadata` only replaces metadata on fields present in both schemas and keeps fields that only the table has (`case None => targetField`), and additive evolution keeps a column after the flow stops selecting it. Reading the code, for a streaming table `st(id, name, legacy)` whose flow no longer selects `legacy`, a comment set with `ALTER TABLE st ALTER COLUMN legacy COMMENT 'old'` stays after the next incremental update, as `SchemaMergingUtilsSuite` already asserts for `onlyInCurrent`, while a full refresh would drop the column. Wording along the lines of "a comment that this schema lacks on one of its columns or nested fields is removed, ...; a column that remains on the table but is no longer in the pipeline's schema keeps its comment" would match the behavior. This extends an [existing discussion](https://github.com/apache/spark/pull/60463#issuecomment-6925537948). **Verification:** - **Inspection:** Reading the entry, its removal rule matches the merge: comments are removed only on fields present in both the table and the pipeline's schema, and a column that only the table has keeps its comment, which the existing merge-helper test for a field present only on the table already asserts. ########## 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: **Non-blocking (P2):** Thanks for adding the migration note. It tells 4.3 users what changes, but it does not give them a way back: this line makes every incremental update of an existing streaming table, AutoCDC targets included, take its column metadata from the pipeline's declared or inferred schema. Reading the code, a comment set with `ALTER TABLE st ALTER COLUMN name COMMENT 'customer name'` on a table with an inferred schema is removed on the next incremental run, with no error or log line, and a table whose `ARRAY<ARRAY<STRUCT<a: INT COMMENT 'c1'>>>` comment drifted from its source now fails every incremental update. On 4.3 both tables keep updating with their comments in place, as the new note itself says. The only ways out are declaring each affected table's complete schema (a partial declaration fails validation) or, for the nested case, dropping and fully refreshing the table, which reprocesses the source and can lose history when the source's retention is limited; a d owngrade does not bring removed comments back. Please add a SQL configuration, versioned 4.4.0, whose default keeps this PR's behavior and whose other value makes `materializeTable` pass `mergeWithDesiredMetadata = false` here, read from the session's SQL configuration like the other pipeline settings, and name it in the 4.3-to-4.4 migration note as the way to restore the previous behavior. Materialized views, full refreshes, and the AutoCDC auxiliary table need no gate: they already ignore this argument or pass `false`, and the comment-specific error they can now raise replaces an error condition that no release has shipped. This extends an [existing discussion](https://github.com/apache/spark/pull/60463#issuecomment-6925537948). **Verification:** - **Behavior:** With the configuration set to restore the previous behavior, re-materializing a streaming table whose persisted column has a comment that the declared schema lacks, and whose other declared comment changed, issues no comment change and leaves both persisted comments in place. - **Behavior:** With the configuration set to restore the previous behavior, re-materializing a streaming table whose `array<array<struct>>` inner comment changed succeeds without an `alterTable` call, and the table keeps its persisted comment. - **Regression:** With the configuration at its default, the streaming-table comment tests this PR adds still observe the applied, removed, and nested comment changes and the comment-specific error for the `array<array<struct>>` case. - **Inspection:** Only `materializeTable`'s call into `evolveTable` reads the configuration, so materialized views and full refreshes, which ignore `mergeWithDesiredMetadata`, and the AutoCDC auxiliary table, which passes `false`, are unchanged, and the migration-guide entry names the configuration and the behavior it restores. ########## 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: **Nit (P3):** Nothing pins this branch for names that differ only in case. The `caseSensitive = true` cases in `SchemaMergingUtilsSuite` use names that stay distinct after lower-casing, the only case-differing case runs case-insensitively, and the case-sensitive `value`/`Value` test in `MaterializeTablesSuite` carries no comments and checks only the added column. If this line lower-cased regardless of `caseSensitive`, every test would still pass, yet in a case-sensitive pipeline whose table has `value COMMENT 'v'` and whose declared schema adds `Value COMMENT 'V'`, `value` would take 'V' and the incremental update would rewrite the wrong column's comment. A case-sensitive `mergeSchemasWithDataMetadata` case with a table `value` and a declared `Value`, each with its own comment, would cover it. **Verification:** - **Regression:** With case sensitivity on, merging a table schema that has `value` with comment 'old' and a declared schema that has `Value` with comment 'new' yields `value` with 'old' and an added `Value` with 'new', and the assertion fails when the overlay lower-cases names regardless of case sensitivity. ########## 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: **Nit (P3):** This check is only reached for an element, key, or value that is itself an array or map, and nothing tests the other side of that boundary. The single-level case in "diffSchemas - DSv2 catalog respects emitted nested changes" mixes the comment change with an added field and a nullability change, and the new `MaterializeTablesSuite` test covers top-level and struct-in-struct comments only. So hoisting this check above the `match` would pass every test while rejecting comment-only updates of `array<struct>` and `map<_, struct>` fields, which this PR now lets incremental streaming-table updates apply. A `diffSchemas` case with only comment changes under `array<struct>` and under a map's struct key and value, expecting the comment updates and no exception, would pin it. **Verification:** - **Regression:** Diffing schemas that differ only in the comment of a struct field inside `array<struct>` and inside both the key and the value of `map<struct, struct>` returns exactly the comment updates at `arr.element.a`, `m.key.x`, and `m.value.x` and raises nothing, and the assertion fails when the all-comments rejection is applied outside the case of consecutive arrays or maps. ########## 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: **Nit (P3):** Every test that expects `PIPELINE_NESTED_COMPLEX_TYPE_COMMENT_CHANGE_UNSUPPORTED` rejects exactly one comment change (the `array<array<struct>>` and `map<string, array<struct>>` cases in `SchemaInferenceUtilsSuite` and the consecutive-array case in `MaterializeTablesSuite`), so replacing this map-and-join with `commentChanges.head` would still pass. For `arr ARRAY<ARRAY<STRUCT<a: INT COMMENT 'x', b: INT COMMENT 'y'>>>` with both comments changed, the error would then name only `arr.element.element.a`, and a user who declares that comment fails again on `b`. Giving the `array<array<struct>>` case a second field whose comment also changes would cover the join. **Verification:** - **Regression:** Diffing `array<array<struct<a, b>>>` schemas in which the comments of both `a` and `b` change raises the comment-specific condition with columnPath `arr.element.element.a, arr.element.element.b`, and the assertion fails when only the first path is reported. -- 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]
