AnishMahto commented on code in PR #60462:
URL: https://github.com/apache/spark/pull/60462#discussion_r4610770423


##########
sql/core/src/main/scala/org/apache/spark/sql/execution/datasources/v2/V2SessionCatalog.scala:
##########
@@ -294,8 +294,16 @@ class V2SessionCatalog(catalog: SessionCatalog)
     val properties = 
CatalogV2Util.applyPropertiesChanges(catalogTable.properties, changes)
     val schema = CatalogV2Util.applySchemaChanges(
       catalogTable.schema, changes, catalogTable.provider, "ALTER TABLE")
-    val comment = properties.get(TableCatalog.PROP_COMMENT)
-    val collation = properties.get(TableCatalog.PROP_COLLATION)
+    // The comment and collation live in dedicated fields of the catalog table 
and are not mirrored
+    // in its properties: the in-memory catalog drops the `comment` key from 
the stored properties,
+    // the Hive catalog moves `comment` and `collation` out of the table 
parameters when it reads a
+    // table, and a table created by DDL never had them there. Keep the 
existing values unless the
+    // changes set or remove the corresponding property, as the v1 SET/UNSET 
TBLPROPERTIES commands
+    // do.
+    val comment = properties.get(TableCatalog.PROP_COMMENT).orElse(
+      if (removesProperty(changes, TableCatalog.PROP_COMMENT)) None else 
catalogTable.comment)
+    val collation = properties.get(TableCatalog.PROP_COLLATION).orElse(
+      if (removesProperty(changes, TableCatalog.PROP_COLLATION)) None else 
catalogTable.collation)

Review Comment:
   This fixes a separate SQL bug: on spark_catalog, `COMMENT ON TABLE` 
currently clears the default collation, and `ALTER TABLE ... DEFAULT COLLATION` 
clears the comment. It changes `alterTable` for every session-catalog caller, 
so could it go in its own [SQL] JIRA/PR, with SQL-level tests for both commands 
and a SQL reviewer? The comment could also be shorter: "Comment and collation 
live in dedicated fields, not `properties`; keep them unless a change sets or 
removes them, as the v1 SET/UNSET commands do."



##########
sql/core/src/test/scala/org/apache/spark/sql/execution/datasources/v2/V2SessionCatalogSuite.scala:
##########
@@ -379,6 +379,77 @@ class V2SessionCatalogTableSuite extends 
V2SessionCatalogBaseSuite {
     assert(filterV2TableProperties(table.properties) == Map())
   }
 
+  test("SPARK-57670: alterTable keeps the comment and collation when no change 
names them") {
+    val catalog = newCatalog()
+    // A table created by DDL keeps its comment and default collation only in 
the dedicated fields
+    // of the catalog table, not in its properties.
+    spark.sql(s"CREATE TABLE $testIdentQuoted (id INT, data STRING) USING 
parquet " +
+      "COMMENT 'table comment' DEFAULT COLLATION UTF8_LCASE")
+    val created = 
catalog.loadTable(testIdent).asInstanceOf[V1Table].catalogTable
+    assert(created.comment.contains("table comment"))
+    assert(created.collation.contains("UTF8_LCASE"))
+    assert(!created.properties.contains(TableCatalog.PROP_COMMENT))
+    assert(!created.properties.contains(TableCatalog.PROP_COLLATION))
+
+    catalog.alterTable(testIdent, TableChange.setProperty("prop-1", "1"))
+    val afterSet = 
catalog.loadTable(testIdent).asInstanceOf[V1Table].catalogTable
+    assert(afterSet.properties.get("prop-1").contains("1"))
+    assert(afterSet.comment.contains("table comment"))
+    assert(afterSet.collation.contains("UTF8_LCASE"))
+
+    catalog.alterTable(testIdent, TableChange.removeProperty("prop-1"))
+    val afterRemove = 
catalog.loadTable(testIdent).asInstanceOf[V1Table].catalogTable
+    assert(!afterRemove.properties.contains("prop-1"))
+    assert(afterRemove.comment.contains("table comment"))
+    assert(afterRemove.collation.contains("UTF8_LCASE"))
+  }
+
+  test("SPARK-57670: alterTable sets or removes the comment and collation a 
change names") {
+    val catalog = newCatalog()
+    spark.sql(s"CREATE TABLE $testIdentQuoted (id INT, data STRING) USING 
parquet " +
+      "COMMENT 'table comment' DEFAULT COLLATION UTF8_LCASE")
+
+    catalog.alterTable(testIdent, 
TableChange.setProperty(TableCatalog.PROP_COMMENT, "new comment"))
+    val afterComment = 
catalog.loadTable(testIdent).asInstanceOf[V1Table].catalogTable
+    assert(afterComment.comment.contains("new comment"))
+    assert(afterComment.collation.contains("UTF8_LCASE"))
+
+    catalog.alterTable(testIdent, 
TableChange.setProperty(TableCatalog.PROP_COLLATION, "UNICODE"))
+    val afterCollation = 
catalog.loadTable(testIdent).asInstanceOf[V1Table].catalogTable
+    assert(afterCollation.comment.contains("new comment"))
+    assert(afterCollation.collation.contains("UNICODE"))
+
+    catalog.alterTable(testIdent,
+      TableChange.removeProperty(TableCatalog.PROP_COMMENT),
+      TableChange.removeProperty(TableCatalog.PROP_COLLATION))
+    val afterRemove = 
catalog.loadTable(testIdent).asInstanceOf[V1Table].catalogTable
+    assert(afterRemove.comment.isEmpty)
+    assert(afterRemove.collation.isEmpty)
+  }
+
+  test("SPARK-57670: alterTable that removes only the comment keeps the 
collation") {

Review Comment:
   Nit: this test, the next one, and the one above are near-duplicates. Could 
they be one table-driven test?



##########
sql/pipelines/src/main/scala/org/apache/spark/sql/pipelines/graph/DatasetManager.scala:
##########
@@ -694,31 +705,73 @@ object DatasetManager extends Logging {
 
     val existingProperties = existingTable.properties()
 
-    // TODO (SPARK-57670): Property removal is intentionally not handled here: 
a property dropped
-    // from the table definition between runs is left in place rather than 
actually removed from the
-    // corresponding catalog table entry. Removing it reliably is hard because 
we cannot distinguish
-    // a user-declared property the user dropped from a catalog/engine-managed 
property (e.g. the
-    // non-reserved `clusteringColumns`, or arbitrary catalog-internal keys) 
that must never be
-    // removed, and there is no record of which keys the pipeline previously 
set.
+    // Property removal is driven by the declared-keys record a previous 
materialization left on
+    // the table (see PipelinesTableProperties.declaredPropertyKeys). A 
recorded key is removed when
+    // all of these hold:
+    //   - `properties` no longer contains it, i.e. the definition dropped it;
+    //   - it is still present on the table;
+    //   - it is not a reserved catalog property other than `comment` (see
+    //     `nonRemovableReservedProperties`).
+    // Ownership follows declaration, not who first set the property: a key a 
definition declared is
+    // removable once dropped, even if the catalog had already set it to the 
same value and no
+    // SetProperty was ever issued for it. Every property outside the record 
may be catalog-managed
+    // (e.g. the non-reserved `clusteringColumns`, or arbitrary 
catalog-internal keys) or set
+    // outside the pipeline, and is left alone. A table without a record (e.g. 
one materialized
+    // before the record was introduced), or whose record is not a JSON string 
array, has nothing
+    // removed. The record itself is removed once `properties` no longer 
carries one, i.e. the
+    // definition no longer declares any table property. Only graph datasets 
pass the record in
+    // `properties`; auxiliary tables never carry it (see 
`materializeAuxiliaryTable`).
+    val recordKey = PipelinesTableProperties.declaredPropertyKeys
+    val previouslyDeclaredKeys = Option(existingProperties.get(recordKey))
+      .flatMap(JsonStringArrayCodec.parse)
+      .getOrElse(Seq.empty)
+      .filterNot(nonRemovableReservedProperties.contains)
+    val propertiesToRemove = (previouslyDeclaredKeys :+ 
recordKey).distinct.collect {
+      case k if !properties.contains(k) && existingProperties.containsKey(k) =>
+        TableChange.removeProperty(k)
+    }
+
     val propertiesToSet = properties.collect {
       case (k, v) if !Option(existingProperties.get(k)).contains(v) =>
         TableChange.setProperty(k, v)
     }
 
-    val allTableChanges = columnChanges ++ propertiesToSet
+    val allTableChanges = columnChanges ++ propertiesToRemove ++ 
propertiesToSet
 
     // If there are no table changes to evolve with, avoid the no-op 
round-trip alter altogether.
     if (allTableChanges.nonEmpty) {

Review Comment:
   Could we `logInfo` the removed keys? Also, a `logWarning` for a malformed 
record: this run overwrites it, so its keys are never removed and nothing says 
why.



##########
sql/pipelines/src/main/scala/org/apache/spark/sql/pipelines/graph/DatasetManager.scala:
##########
@@ -656,9 +657,19 @@ object DatasetManager extends Logging {
    *                                schema; for auxiliary tables, the derived 
schema). This is the
    *                                "incoming" side and may differ from 
`existingTable`'s recorded
    *                                schema due to schema evolution across runs.
-   * @param properties              the declared table properties to (re)set 
on the table. Note
-   *                                that properties absent here are NOT 
removed from the table (see
-   *                                the TODO in the body).
+   * @param properties              the table properties to (re)set on the 
table. For graph

Review Comment:
   This `@param` now describes the JDBC rule in `resolveTableProperties`. 
Suggest just: "the desired table properties; see 
[[PipelinesTableProperties.declaredPropertyKeys]] for which absent keys are 
removed."



##########
sql/hive/src/test/scala/org/apache/spark/sql/hive/execution/HiveDDLSuite.scala:
##########
@@ -3643,6 +3643,37 @@ class HiveDDLSuite
     }
   }
 
+  test("SPARK-57670: V2SessionCatalog alterTable keeps the table comment on a 
Hive catalog") {

Review Comment:
   Nit: Hive also moves `collation` out of the table parameters. Worth covering 
it here too.



##########
sql/pipelines/src/main/scala/org/apache/spark/sql/pipelines/graph/PipelinesTableProperties.scala:
##########
@@ -37,6 +37,33 @@ object PipelinesTableProperties {
   val resetAllowed: PipelineTableProperty[Boolean] =
     buildProp("pipelines.reset.allowed", default = true)
 
+  /**
+   * Internal table property recording, as a sorted JSON string array (see
+   * [[JsonStringArrayCodec]]), the keys of the table properties declared in 
the dataset definition
+   * (SQL `TBLPROPERTIES`, Python `table_properties`) as of the latest 
materialization.
+   *
+   * `DatasetManager` writes it, through `resolveTableProperties`, only when 
the definition declares
+   * at least one table property, and never for a table in a JDBC catalog, 
which appends every
+   * non-reserved table property to its `CREATE TABLE` statement as a DDL 
option. It covers those
+   * declared keys, not the `comment` and `provider` entries derived from the 
dataset's comment and
+   * format. On the next materialization, `evolveTable` removes a recorded key 
when the resolved
+   * table properties of the definition no longer contain it, it is still on 
the table, and it is
+   * not a reserved catalog property other than `comment` (the keys the SQL 
parser rejects in
+   * `TBLPROPERTIES`). The resolved properties include the `comment` and 
`provider` derived from the
+   * definition, so a comment moved from the table properties to the dataset's 
comment field stays.
+   * A dropped reserved key such as `owner`, which Python `table_properties` 
passes through, is
+   * recorded but never removed. Ownership follows declaration: a key is 
removable once a definition
+   * declared it, even if the catalog had already set it to the same value. 
Properties the
+   * definition never declared, e.g. catalog-managed ones, are never removed. 
A table without the
+   * record, or with one that is not a JSON string array, has nothing removed. 
The record itself is
+   * removed once the definition declares no table property, whether or not 
the keys it listed are
+   * removed with it. Auxiliary tables never carry it.
+   *
+   * This key is not registered as a user-settable property, so 
[[validateAndCanonicalize]] drops
+   * it if a user declares it.
+   */
+  val declaredPropertyKeys: String = s"${pipelinesPrefix}declaredPropertyKeys"

Review Comment:
   This key will be stored on user tables and shown in `SHOW TBLPROPERTIES`, so 
renaming it later means migrating tables. Worth settling the name now, e.g. 
adding an `internal` segment to discourage hand edits? Nit: the AutoCDC 
internal keys use a `...Property` suffix and live with the code that owns them. 
At minimum, a section header would separate this from the user-settable 
properties.



##########
sql/pipelines/src/main/scala/org/apache/spark/sql/pipelines/graph/DatasetManager.scala:
##########
@@ -694,31 +705,73 @@ object DatasetManager extends Logging {
 
     val existingProperties = existingTable.properties()
 
-    // TODO (SPARK-57670): Property removal is intentionally not handled here: 
a property dropped
-    // from the table definition between runs is left in place rather than 
actually removed from the
-    // corresponding catalog table entry. Removing it reliably is hard because 
we cannot distinguish
-    // a user-declared property the user dropped from a catalog/engine-managed 
property (e.g. the
-    // non-reserved `clusteringColumns`, or arbitrary catalog-internal keys) 
that must never be
-    // removed, and there is no record of which keys the pipeline previously 
set.
+    // Property removal is driven by the declared-keys record a previous 
materialization left on
+    // the table (see PipelinesTableProperties.declaredPropertyKeys). A 
recorded key is removed when
+    // all of these hold:
+    //   - `properties` no longer contains it, i.e. the definition dropped it;
+    //   - it is still present on the table;
+    //   - it is not a reserved catalog property other than `comment` (see
+    //     `nonRemovableReservedProperties`).
+    // Ownership follows declaration, not who first set the property: a key a 
definition declared is
+    // removable once dropped, even if the catalog had already set it to the 
same value and no
+    // SetProperty was ever issued for it. Every property outside the record 
may be catalog-managed
+    // (e.g. the non-reserved `clusteringColumns`, or arbitrary 
catalog-internal keys) or set
+    // outside the pipeline, and is left alone. A table without a record (e.g. 
one materialized
+    // before the record was introduced), or whose record is not a JSON string 
array, has nothing
+    // removed. The record itself is removed once `properties` no longer 
carries one, i.e. the
+    // definition no longer declares any table property. Only graph datasets 
pass the record in
+    // `properties`; auxiliary tables never carry it (see 
`materializeAuxiliaryTable`).
+    val recordKey = PipelinesTableProperties.declaredPropertyKeys
+    val previouslyDeclaredKeys = Option(existingProperties.get(recordKey))
+      .flatMap(JsonStringArrayCodec.parse)
+      .getOrElse(Seq.empty)
+      .filterNot(nonRemovableReservedProperties.contains)
+    val propertiesToRemove = (previouslyDeclaredKeys :+ 
recordKey).distinct.collect {

Review Comment:
   Nit: appending `recordKey` mixes the record's own removal into the user 
keys, and `.distinct` only matters for a hand-edited record. Handling the 
record in a separate expression would read more clearly.



##########
sql/pipelines/src/main/scala/org/apache/spark/sql/pipelines/graph/DatasetManager.scala:
##########
@@ -742,7 +795,16 @@ object DatasetManager extends Logging {
       }
       .collect { case (key, Some(value)) => key -> value }
 
-    validatedAndCanonicalizedProps ++ specialProps
+    val recordsDeclaredKeys =

Review Comment:
   `JDBCTable` reports no properties, and the JDBC dialect rejects 
`SetProperty`/`RemoveProperty`. So a JDBC table with any property already fails 
on its second run, before and after this PR. This check only keeps the first 
run working. The cost is that `sql/pipelines` depends on a concrete connector 
class, and a catalog that wraps a JDBC catalog gets past the check. Fine as the 
least invasive option, but could the doc state the re-run limitation, with a 
follow-up JIRA?



##########
python/pyspark/pipelines/api.py:
##########
@@ -152,7 +152,11 @@ def table(
         These confs will be set when the query for the dataset is executed and 
they can override \
         confs set for the pipeline or on the cluster.
     :param table_properties: A dict where the keys are the property names and 
the values are the \
-        property values. These properties will be set on the table.
+        property values. These properties will be set on the table. A property 
removed from \
+        this dict is removed from the table on the next pipeline run, provided 
an earlier run \
+        recorded it in the ``pipelines.declaredPropertyKeys`` table property. 
A property \

Review Comment:
   Suggest trimming all 4 copies (here, L265, L447, `output.py` L48) to: "A 
property removed from this dict is removed from the table on a later run; see 
the migration guide for exceptions." The API docs don't need the internal key 
name.



##########
sql/pipelines/src/main/scala/org/apache/spark/sql/pipelines/graph/DatasetManager.scala:
##########
@@ -694,31 +705,73 @@ object DatasetManager extends Logging {
 
     val existingProperties = existingTable.properties()
 
-    // TODO (SPARK-57670): Property removal is intentionally not handled here: 
a property dropped
-    // from the table definition between runs is left in place rather than 
actually removed from the
-    // corresponding catalog table entry. Removing it reliably is hard because 
we cannot distinguish
-    // a user-declared property the user dropped from a catalog/engine-managed 
property (e.g. the
-    // non-reserved `clusteringColumns`, or arbitrary catalog-internal keys) 
that must never be
-    // removed, and there is no record of which keys the pipeline previously 
set.
+    // Property removal is driven by the declared-keys record a previous 
materialization left on

Review Comment:
   This rule is written out in about 10 places: here, `@param properties`, the 
`declaredPropertyKeys` Scaladoc, `resolveTableProperties`, the JDBC suite, the 
migration guide, and 4 Python docstrings. Earlier revisions already had copies 
disagree. Could we keep one canonical statement (the `declaredPropertyKeys` 
doc) and point to it? Here I'd keep only the why: ownership follows 
declaration, undeclared keys may be catalog-managed, and no record means 
nothing is removed.



##########
sql/pipelines/src/main/scala/org/apache/spark/sql/pipelines/graph/DatasetManager.scala:
##########
@@ -742,7 +795,16 @@ object DatasetManager extends Logging {
       }
       .collect { case (key, Some(value)) => key -> value }
 
-    validatedAndCanonicalizedProps ++ specialProps
+    val recordsDeclaredKeys =
+      validatedAndCanonicalizedProps.nonEmpty && 
!catalog.isInstanceOf[JDBCTableCatalog]
+    val declaredPropertyKeys = if (recordsDeclaredKeys) {
+      Map(PipelinesTableProperties.declaredPropertyKeys ->
+        
JsonStringArrayCodec.serialize(validatedAndCanonicalizedProps.keys.toSeq.sorted))

Review Comment:
   Nit: reserved keys like `owner` are recorded but never removed. Leaving them 
out of the record here (keeping the read-side filter as a safeguard) would let 
the docs drop that case.



##########
sql/pipelines/src/test/scala/org/apache/spark/sql/pipelines/graph/MaterializeTablesInJdbcCatalogSuite.scala:
##########
@@ -0,0 +1,118 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.spark.sql.pipelines.graph
+
+import java.sql.DriverManager
+import java.util.Properties
+
+import scala.collection.mutable
+import scala.jdk.CollectionConverters._
+
+import org.apache.spark.SparkConf
+import org.apache.spark.sql.connector.catalog.{Column, Identifier, Table => 
V2Table}
+import org.apache.spark.sql.connector.expressions.Transform
+import org.apache.spark.sql.execution.datasources.v2.jdbc.JDBCTableCatalog
+import org.apache.spark.sql.pipelines.utils.{BaseCoreExecutionTest, 
TestGraphRegistrationContext}
+import org.apache.spark.sql.test.SharedSparkSession
+import org.apache.spark.util.Utils
+
+/**
+ * Materialization tests against an H2-backed [[JDBCTableCatalog]]. That 
catalog appends every
+ * table property other than the reserved ones to the `CREATE TABLE` statement 
as a DDL option, so
+ * the declared-keys record must not reach it (see
+ * [[PipelinesTableProperties.declaredPropertyKeys]]).
+ */
+class MaterializeTablesInJdbcCatalogSuite extends BaseCoreExecutionTest with 
SharedSparkSession {
+  import testImplicits._
+
+  private val catalogName = "h2_cat"
+  private val namespace = "ns"
+  private val tempDir = Utils.createTempDir()
+  private val url = 
s"jdbc:h2:${tempDir.getCanonicalPath};user=testUser;password=testPass"
+
+  override def sparkConf: SparkConf = super.sparkConf
+    .set(s"spark.sql.catalog.$catalogName", 
classOf[RecordingJDBCTableCatalog].getName)
+    .set(s"spark.sql.catalog.$catalogName.url", url)
+    .set(s"spark.sql.catalog.$catalogName.driver", "org.h2.Driver")
+
+  override def beforeAll(): Unit = {
+    super.beforeAll()
+    Utils.classForName("org.h2.Driver")
+    spark.sql(s"CREATE NAMESPACE $catalogName.$namespace")
+  }
+
+  override def afterAll(): Unit = {
+    try {
+      Utils.deleteRecursively(tempDir)
+    } finally {
+      super.afterAll()
+    }
+  }
+
+  private def jdbcCatalog: RecordingJDBCTableCatalog =
+    
spark.sessionState.catalogManager.catalog(catalogName).asInstanceOf[RecordingJDBCTableCatalog]
+
+  /** The comment H2 stores for a table in `namespace`. */
+  private def h2TableComment(table: String): Option[String] = {
+    val conn = DriverManager.getConnection(url, new Properties())
+    try {
+      val rs = conn.createStatement().executeQuery(
+        "SELECT REMARKS FROM INFORMATION_SCHEMA.TABLES " +
+        s"WHERE TABLE_SCHEMA = '$namespace' AND TABLE_NAME = '$table'")
+      if (rs.next()) Option(rs.getString(1)) else None
+    } finally {
+      conn.close()
+    }
+  }
+
+  test("SPARK-57670: a materialized view that declares a table property is 
created without the " +

Review Comment:
   Could this note that re-runs aren't supported on JDBC? The second run fails 
on `SetProperty`, with or without this PR, so the test shouldn't imply JDBC 
tables are fully supported.



##########
sql/pipelines/src/test/scala/org/apache/spark/sql/pipelines/graph/MaterializeTablesSuite.scala:
##########
@@ -1610,17 +1626,321 @@ abstract class MaterializeTablesSuite extends 
BaseCoreExecutionTest {
     }
   }
 
-  test("re-materializing with a dropped property neither removes it nor issues 
an alterTable") {
+  test("SPARK-57670: re-materializing with a dropped property removes it") {
     withRecordingCatalog {
       val schema = new StructType().add("id", IntegerType)
-      // This test locks in the current buggy behavior where dropped 
properties do not materialize
-      // against the catalog table entity. See SPARK-57670.
       materializeStreamingTable("t", schema, Map("p.keep" -> "v", "p.stale" -> 
"old"))
       assert(recordingCatalog.recordedAlters.isEmpty)
+      // A property the pipeline never declared, e.g. one managed by the 
catalog.
+      spark.sql(
+        s"ALTER TABLE $recordingCatalogName.$recordingNamespace.t " +
+        "SET TBLPROPERTIES ('p.external' = 'e')")
+      recordingCatalog.recordedAlters.clear()
+
       materializeStreamingTable("t", schema, Map("p.keep" -> "v"))
+      assert(recordingCatalog.recordedAlters.size == 1)
+      val changes = recordingCatalog.recordedAlters.flatten
+      assert(changes.collect { case r: TableChange.RemoveProperty => 
r.property() } ==
+        Seq("p.stale"))
+
+      val props = loadTableFromRecordingCatalog("t").properties()
+      assert(!props.containsKey("p.stale"))
+      assert(props.get("p.keep") == "v")
+      assert(props.get("p.external") == "e")
+      assert(props.get(PipelinesTableProperties.declaredPropertyKeys) == 
"""["p.keep"]""")
+    }
+  }
+
+  test("SPARK-57670: re-materializing with all properties dropped removes them 
and the record " +
+    "in one alterTable") {
+    withRecordingCatalog {
+      val schema = new StructType().add("id", IntegerType)
+      materializeStreamingTable("t", schema, Map("p.a" -> "1", "p.b" -> "2"))
+      recordingCatalog.recordedAlters.clear()
+
+      materializeStreamingTable("t", schema, Map.empty)
+      assert(recordingCatalog.recordedAlters.size == 1)
+      val changes = recordingCatalog.recordedAlters.head
+      assert(changes.forall(_.isInstanceOf[TableChange.RemoveProperty]))
+      assert(changes.collect { case r: TableChange.RemoveProperty => 
r.property() }.toSet ==
+        Set("p.a", "p.b", PipelinesTableProperties.declaredPropertyKeys))
+
+      val props = loadTableFromRecordingCatalog("t").properties()
+      assert(!props.containsKey("p.a"))
+      assert(!props.containsKey("p.b"))
+      assert(!props.containsKey(PipelinesTableProperties.declaredPropertyKeys))
+
+      // The table is now in sync with its definition, so re-materializing is 
a no-op.
+      recordingCatalog.recordedAlters.clear()
+      materializeStreamingTable("t", schema, Map.empty)
       assert(recordingCatalog.recordedAlters.isEmpty)
+    }
+  }
+
+  test("SPARK-57670: a definition without table properties writes no 
declared-keys record") {
+    withRecordingCatalog {
+      val schema = new StructType().add("id", IntegerType)
+      materializeStreamingTable("t", schema, Map.empty)
+      assert(!loadTableFromRecordingCatalog("t").properties()
+        .containsKey(PipelinesTableProperties.declaredPropertyKeys))
+    }
+  }
+
+  test("SPARK-57670: a table without properties and without a record is 
re-materialized " +

Review Comment:
   A definition with no properties never writes a record, so this `UNSET IF 
EXISTS` does nothing, and the "stand in" comment is misleading. The test 
repeats the previous one; merge them?



##########
sql/pipelines/src/test/scala/org/apache/spark/sql/pipelines/graph/MaterializeTablesSuite.scala:
##########
@@ -1610,17 +1626,321 @@ abstract class MaterializeTablesSuite extends 
BaseCoreExecutionTest {
     }
   }
 
-  test("re-materializing with a dropped property neither removes it nor issues 
an alterTable") {
+  test("SPARK-57670: re-materializing with a dropped property removes it") {
     withRecordingCatalog {
       val schema = new StructType().add("id", IntegerType)
-      // This test locks in the current buggy behavior where dropped 
properties do not materialize
-      // against the catalog table entity. See SPARK-57670.
       materializeStreamingTable("t", schema, Map("p.keep" -> "v", "p.stale" -> 
"old"))
       assert(recordingCatalog.recordedAlters.isEmpty)
+      // A property the pipeline never declared, e.g. one managed by the 
catalog.
+      spark.sql(
+        s"ALTER TABLE $recordingCatalogName.$recordingNamespace.t " +
+        "SET TBLPROPERTIES ('p.external' = 'e')")
+      recordingCatalog.recordedAlters.clear()
+
       materializeStreamingTable("t", schema, Map("p.keep" -> "v"))
+      assert(recordingCatalog.recordedAlters.size == 1)
+      val changes = recordingCatalog.recordedAlters.flatten
+      assert(changes.collect { case r: TableChange.RemoveProperty => 
r.property() } ==
+        Seq("p.stale"))
+
+      val props = loadTableFromRecordingCatalog("t").properties()
+      assert(!props.containsKey("p.stale"))
+      assert(props.get("p.keep") == "v")
+      assert(props.get("p.external") == "e")
+      assert(props.get(PipelinesTableProperties.declaredPropertyKeys) == 
"""["p.keep"]""")
+    }
+  }
+
+  test("SPARK-57670: re-materializing with all properties dropped removes them 
and the record " +
+    "in one alterTable") {
+    withRecordingCatalog {
+      val schema = new StructType().add("id", IntegerType)
+      materializeStreamingTable("t", schema, Map("p.a" -> "1", "p.b" -> "2"))
+      recordingCatalog.recordedAlters.clear()
+
+      materializeStreamingTable("t", schema, Map.empty)
+      assert(recordingCatalog.recordedAlters.size == 1)
+      val changes = recordingCatalog.recordedAlters.head
+      assert(changes.forall(_.isInstanceOf[TableChange.RemoveProperty]))
+      assert(changes.collect { case r: TableChange.RemoveProperty => 
r.property() }.toSet ==
+        Set("p.a", "p.b", PipelinesTableProperties.declaredPropertyKeys))
+
+      val props = loadTableFromRecordingCatalog("t").properties()
+      assert(!props.containsKey("p.a"))
+      assert(!props.containsKey("p.b"))
+      assert(!props.containsKey(PipelinesTableProperties.declaredPropertyKeys))
+
+      // The table is now in sync with its definition, so re-materializing is 
a no-op.
+      recordingCatalog.recordedAlters.clear()
+      materializeStreamingTable("t", schema, Map.empty)
       assert(recordingCatalog.recordedAlters.isEmpty)
+    }
+  }
+
+  test("SPARK-57670: a definition without table properties writes no 
declared-keys record") {
+    withRecordingCatalog {
+      val schema = new StructType().add("id", IntegerType)
+      materializeStreamingTable("t", schema, Map.empty)
+      assert(!loadTableFromRecordingCatalog("t").properties()
+        .containsKey(PipelinesTableProperties.declaredPropertyKeys))
+    }
+  }
+
+  test("SPARK-57670: a table without properties and without a record is 
re-materialized " +
+    "without an alterTable") {
+    withRecordingCatalog {
+      val schema = new StructType().add("id", IntegerType)
+      materializeStreamingTable("t", schema, Map.empty)
+      // Stand in for a table materialized before the record was introduced.
+      spark.sql(
+        s"ALTER TABLE $recordingCatalogName.$recordingNamespace.t UNSET 
TBLPROPERTIES IF EXISTS " +
+        s"('${PipelinesTableProperties.declaredPropertyKeys}')")
+      recordingCatalog.recordedAlters.clear()
+
+      materializeStreamingTable("t", schema, Map.empty)
+      assert(recordingCatalog.recordedAlters.isEmpty)
+      assert(!loadTableFromRecordingCatalog("t").properties()
+        .containsKey(PipelinesTableProperties.declaredPropertyKeys))
+    }
+  }
 
-      assert(loadTableFromRecordingCatalog("t").properties().get("p.stale") == 
"old")
+  test("SPARK-57670: dropped properties are not removed from a table without a 
declared-keys " +
+    "record") {
+    withRecordingCatalog {
+      val schema = new StructType().add("id", IntegerType)
+      materializeStreamingTable("t", schema, Map("p.keep" -> "v", "p.stale" -> 
"old"))
+      // Simulate a table materialized before the declared-keys record was 
introduced.
+      spark.sql(
+        s"ALTER TABLE $recordingCatalogName.$recordingNamespace.t " +
+        s"UNSET TBLPROPERTIES 
('${PipelinesTableProperties.declaredPropertyKeys}')")
+
+      materializeStreamingTable("t", schema, Map("p.keep" -> "v"))
+      val props = loadTableFromRecordingCatalog("t").properties()
+      assert(props.get("p.stale") == "old")
+      assert(props.get(PipelinesTableProperties.declaredPropertyKeys) == 
"""["p.keep"]""")
+    }
+  }
+
+  test("SPARK-57670: a user-declared value for the declared-keys property is 
ignored") {
+    withRecordingCatalog {
+      val schema = new StructType().add("id", IntegerType)
+      materializeStreamingTable("t", schema, Map(
+        "p.a" -> "1",
+        PipelinesTableProperties.declaredPropertyKeys -> """["p.other"]"""))
+      assert(loadTableFromRecordingCatalog("t").properties()
+        .get(PipelinesTableProperties.declaredPropertyKeys) == """["p.a"]""")
+    }
+  }
+
+  test("SPARK-57670: a dropped property is removed from a materialized view") {
+    materializeGraph(new TestGraphRegistrationContext(spark) {
+      registerMaterializedView(
+        "mv",
+        query = dfFlowFunc(Seq(1).toDF("id")),
+        properties = Map("p.keep" -> "v", "p.stale" -> "old"))
+    }.resolveToDataflowGraph(), storageRoot = storageRoot)
+
+    materializeGraph(new TestGraphRegistrationContext(spark) {
+      registerMaterializedView(
+        "mv",
+        query = dfFlowFunc(Seq(1).toDF("id")),
+        properties = Map("p.keep" -> "v"))
+    }.resolveToDataflowGraph(), storageRoot = storageRoot)
+
+    val props = 
spark.sessionState.catalogManager.currentCatalog.asInstanceOf[TableCatalog]
+      
.loadTable(Identifier.of(Array(TestGraphRegistrationContext.DEFAULT_DATABASE), 
"mv"))
+      .properties()
+    assert(!props.containsKey("p.stale"))
+    assert(props.get("p.keep") == "v")
+  }
+
+  test("SPARK-57670: a dropped comment declared as a table property is 
removed") {
+    withRecordingCatalog {
+      val schema = new StructType().add("id", IntegerType)
+      materializeStreamingTable(
+        "t", schema, Map("p.a" -> "1", TableCatalog.PROP_COMMENT -> "old"))
+      assert(
+        
loadTableFromRecordingCatalog("t").properties().get(TableCatalog.PROP_COMMENT) 
== "old")
+
+      materializeStreamingTable("t", schema, Map("p.a" -> "1"))
+      val props = loadTableFromRecordingCatalog("t").properties()
+      assert(!props.containsKey(TableCatalog.PROP_COMMENT))
+      assert(props.get("p.a") == "1")
+      assert(props.get(PipelinesTableProperties.declaredPropertyKeys) == 
"""["p.a"]""")
+    }
+  }
+
+  test("SPARK-57670: a comment moved from the table properties to the comment 
field stays") {
+    withRecordingCatalog {
+      val schema = new StructType().add("id", IntegerType)
+      materializeStreamingTable("t", schema, Map(TableCatalog.PROP_COMMENT -> 
"kept"))
+      recordingCatalog.recordedAlters.clear()
+
+      materializeStreamingTable("t", schema, Map.empty, comment = 
Option("kept"))
+      // The definition still supplies the comment, so only the record goes 
away.
+      assert(recordingCatalog.recordedAlters.flatten.map {
+        case r: TableChange.RemoveProperty => r.property()
+        case other => other.toString
+      } == Seq(PipelinesTableProperties.declaredPropertyKeys))
+      val props = loadTableFromRecordingCatalog("t").properties()
+      assert(props.get(TableCatalog.PROP_COMMENT) == "kept")
+      assert(!props.containsKey(PipelinesTableProperties.declaredPropertyKeys))
+    }
+  }
+
+  test("SPARK-57670: a dropped reserved key other than comment declared as a 
table property " +
+    "stays on the table") {
+    withRecordingCatalog {
+      val schema = new StructType().add("id", IntegerType)
+      materializeStreamingTable(
+        "t", schema, Map("p.a" -> "1", TableCatalog.PROP_OWNER -> "someone"))
+      assert(loadTableFromRecordingCatalog("t").properties()
+        .get(PipelinesTableProperties.declaredPropertyKeys) == 
"""["owner","p.a"]""")
+
+      materializeStreamingTable("t", schema, Map("p.a" -> "1"))
+      val props = loadTableFromRecordingCatalog("t").properties()
+      assert(props.get(TableCatalog.PROP_OWNER) == "someone")
+      assert(props.get(PipelinesTableProperties.declaredPropertyKeys) == 
"""["p.a"]""")
+    }
+  }
+
+  test("SPARK-57670: a dropped comment declared as a table property is removed 
on the session " +
+    "catalog") {
+    val schema = new StructType().add("id", IntegerType)
+    materializeStreamingTable(
+      "t", schema, Map(TableCatalog.PROP_COMMENT -> "old"), catalog = None, 
database = None)
+    assert(sessionCatalogTable("t").comment.contains("old"))
+
+    materializeStreamingTable("t", schema, Map.empty, catalog = None, database 
= None)
+    assert(sessionCatalogTable("t").comment.isEmpty)
+    
assert(!sessionCatalogTable("t").properties.contains(TableCatalog.PROP_COMMENT))
+
+    // A comment the definition keeps supplying through its comment field 
stays.
+    materializeStreamingTable(
+      "t", schema, Map(TableCatalog.PROP_COMMENT -> "again"), catalog = None, 
database = None)
+    assert(sessionCatalogTable("t").comment.contains("again"))
+    materializeStreamingTable(
+      "t", schema, Map.empty, comment = Option("again"), catalog = None, 
database = None)
+    assert(sessionCatalogTable("t").comment.contains("again"))
+  }
+
+  test("SPARK-57670: table comments survive the declared-keys bootstrap and 
removal alters") {
+    val schema = new StructType().add("id", IntegerType)
+    def materialize(properties: Map[String, String]): Unit = {
+      materializeStreamingTable(
+        "declared", schema, properties, comment = Option("declared comment"),
+        catalog = None, database = None)
+      materializeStreamingTable("external", schema, properties, catalog = 
None, database = None)
+    }
+    def checkComments(): Unit = {
+      assert(sessionCatalogTable("declared").comment.contains("declared 
comment"))
+      assert(sessionCatalogTable("external").comment.contains("external 
comment"))
+    }
+    val db = s"${TestGraphRegistrationContext.DEFAULT_CATALOG}." +
+      TestGraphRegistrationContext.DEFAULT_DATABASE
+
+    materialize(Map("p.keep" -> "v", "p.stale" -> "old"))
+    // A comment set outside the pipeline.
+    spark.sql(s"COMMENT ON TABLE $db.external IS 'external comment'")
+    // Stand in for tables materialized before the record was introduced.
+    Seq("declared", "external").foreach { name =>
+      spark.sql(
+        s"ALTER TABLE $db.$name UNSET TBLPROPERTIES " +
+        s"('${PipelinesTableProperties.declaredPropertyKeys}')")
+    }
+    checkComments()
+
+    // The run whose only change is writing the record on the otherwise 
unchanged tables.
+    materialize(Map("p.keep" -> "v", "p.stale" -> "old"))
+    checkComments()
+    assert(sessionCatalogTable("declared").properties
+      
.get(PipelinesTableProperties.declaredPropertyKeys).contains("""["p.keep","p.stale"]"""))
+
+    // The run whose only change is dropping a recorded key.
+    materialize(Map("p.keep" -> "v"))
+    checkComments()
+    assert(!sessionCatalogTable("declared").properties.contains("p.stale"))
+    assert(!sessionCatalogTable("external").properties.contains("p.stale"))
+    
assert(sessionCatalogTable("external").properties.get("p.keep").contains("v"))
+  }
+
+  test("SPARK-57670: a malformed declared-keys record removes nothing and is 
rewritten") {
+    withRecordingCatalog {
+      val schema = new StructType().add("id", IntegerType)
+      Seq("t1" -> "not-json", "t2" -> """["p.stale", 1]""").foreach { case 
(name, malformed) =>
+        materializeStreamingTable(name, schema, Map("p.a" -> "1", "p.stale" -> 
"old"))
+        spark.sql(
+          s"ALTER TABLE $recordingCatalogName.$recordingNamespace.$name SET 
TBLPROPERTIES " +
+          s"('${PipelinesTableProperties.declaredPropertyKeys}' = 
'$malformed')")
+
+        materializeStreamingTable(name, schema, Map("p.a" -> "1"))
+        val props = loadTableFromRecordingCatalog(name).properties()
+        assert(props.get("p.stale") == "old", s"record: $malformed")
+        assert(props.get(PipelinesTableProperties.declaredPropertyKeys) == 
"""["p.a"]""",
+          s"record: $malformed")
+      }
+    }
+  }
+
+  test("SPARK-57670: a declared-keys record with trailing content is malformed 
and removes " +

Review Comment:
   Nit: this has the same body as the malformed-record test above; make them 
one table-driven test? Small helpers such as `declaredKeysRecord(name)` and 
`setRecord(name, value)` would also cut the 26 references to the record key and 
the 8 `ALTER` snippets.



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