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


##########
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:
   `evolveTable` now logs one INFO line with the table identifier and the 
sorted removed keys, without values. When the table has a record that 
`JsonStringArrayCodec.parse` cannot read, it logs a warning that the record is 
not a JSON string array, that its keys are not removed, and that this run 
replaces the record or removes it if the definition declares no removable 
property. The merged malformed-record test in `MaterializeTablesSuite` asserts 
the warning for every malformed input through `withLogAppender`; that assertion 
fails without the change.



##########
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:
   The `resolveTableProperties` Scaladoc now states the limitation: a JDBC 
table with any table property fails on its second run, with or without the 
record, because `JDBCTable` reports no properties and the JDBC dialect rejects 
`SetProperty`, so leaving out the record only lets the first run succeed. It 
also says that a catalog wrapping a JDBC catalog is not detected by the check. 
`MaterializeTablesInJdbcCatalogSuite` carries the same note. Re-run support for 
JDBC tables is a separate problem from this change; I can file a JIRA for it if 
that helps.



##########
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:
   `resolveTableProperties` now leaves the `nonRemovableReservedProperties` 
keys out of the recorded list and writes the record only when the list is 
non-empty, so a definition whose only declared property is `owner` gets no 
record. The read-side filter in `evolveTable` stays as a safeguard for a 
hand-edited record, and the `declaredPropertyKeys` Scaladoc no longer needs a 
separate reserved-key case. The new test "SPARK-57670: a reserved key passed as 
a table property is not recorded" checks both cases and fails on the previous 
code, where the record listed `owner`. The existing reserved-key test now sets 
a record that lists `owner` to keep covering the read-side filter.



##########
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:
   Good point, renaming it after a release would mean migrating tables. Would 
`pipelines.internal.declaredPropertyKeys` work for you? The other option I see 
is keeping the stored string and only moving the Scala constant next to the 
code that owns it, with a `...Property` suffix like the AutoCDC internal keys. 
I kept `pipelines.declaredPropertyKeys` unchanged in this push so the rename 
happens once, in one place, after we agree on the name.



##########
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:
   All four `table_properties` docstrings (the three in `api.py` and the one in 
`output.py`) now say "A property removed from this dict is removed from the 
table on a later run; see the migration guide for exceptions." The rest of each 
docstring is unchanged, and the internal key name is no longer mentioned. 
`dev/lint-python --ruff` and `ruff format --diff` pass on both files.



##########
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:
   The test now has a comment saying that it covers only the first run: re-runs 
are not supported for a JDBC table with table properties, because the second 
run fails on `SetProperty`, with or without the record, as the JDBC dialect 
rejects it and `JDBCTable` reports no properties. The suite still passes.



##########
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:
   I deleted that test and its "stand in" comment. The one check it added, that 
re-materializing a table without properties and without a record issues no 
`alterTable`, is now part of "SPARK-57670: a definition without table 
properties writes no declared-keys record".



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