gengliangwang commented on code in PR #55508:
URL: https://github.com/apache/spark/pull/55508#discussion_r3133150135


##########
common/utils/src/main/resources/error/error-conditions.json:
##########
@@ -3278,6 +3278,26 @@
         "message" : [
           "`startingVersion` is required when `endingVersion` is specified for 
CDC queries."
         ]
+      },
+      "NET_CHANGES_NOT_YET_SUPPORTED" : {
+        "message" : [
+          "The `deduplicationMode = netChanges` option on connector 
`<changelogName>` is not yet supported. Use `deduplicationMode = 
dropCarryovers` (default) or `deduplicationMode = none` instead."
+        ]
+      },
+      "STREAMING_POST_PROCESSING_NOT_SUPPORTED" : {
+        "message" : [
+          "Change Data Capture (CDC) streaming reads on connector 
`<changelogName>` do not yet support post-processing (carry-over removal, 
update detection, or net change computation). The requested combination of 
options would require post-processing, which is currently only available for 
batch reads. Use a batch read, or set `deduplicationMode = none` and 
`computeUpdates = false` to receive raw change rows in streaming."
+        ]
+      },
+      "UPDATE_DETECTION_REQUIRES_CARRY_OVER_REMOVAL" : {
+        "message" : [
+          "`computeUpdates` cannot be used with `deduplicationMode=none` on 
connector `<changelogName>` because the connector emits copy-on-write 
carry-over pairs (`containsCarryoverRows()` returns true) that would be 
silently mislabeled as updates. Set `deduplicationMode` to `dropCarryovers` or 
`netChanges`."
+        ]
+      },
+      "UNEXPECTED_MULTIPLE_CHANGES_PER_ROW_VERSION" : {
+        "message" : [
+          "Connector emitted multiple delete or insert rows for the same 
`(rowId, _commit_version)` partition. The `Changelog` contract requires at most 
one logical change per row identity per commit when 
`containsIntermediateChanges() = false`. Either fix the connector to 
deduplicate intermediate states, or set `containsIntermediateChanges() = true` 
and use `deduplicationMode = netChanges`."
+        ]
       }

Review Comment:
   `UNEXPECTED_MULTIPLE_CHANGES_PER_ROW_VERSION` is a runtime 
connector-contract violation raised via `RaiseError` at query execution, not an 
invalid CDC *option* the user set. Placing it under `INVALID_CDC_OPTION` 
(sqlState `42K03`, used by the other sub-conditions which are all analysis-time 
option errors) mixes two categories under one class. Consider a separate error 
class (e.g. `CHANGELOG_CONTRACT_VIOLATION`) with a runtime sqlState.



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/ResolveChangelogTable.scala:
##########
@@ -0,0 +1,315 @@
+/*
+ * 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.catalyst.analysis
+
+import org.apache.spark.sql.catalyst.expressions._
+import org.apache.spark.sql.catalyst.expressions.aggregate.{Count, Max, Min}
+import org.apache.spark.sql.catalyst.plans.logical._
+import org.apache.spark.sql.catalyst.rules.Rule
+import org.apache.spark.sql.catalyst.streaming.StreamingRelationV2
+import org.apache.spark.sql.catalyst.trees.TreeNodeTag
+import org.apache.spark.sql.connector.catalog.{Changelog, ChangelogInfo}
+import org.apache.spark.sql.errors.QueryCompilationErrors
+import org.apache.spark.sql.execution.datasources.v2.{ChangelogTable, 
DataSourceV2Relation}
+import org.apache.spark.sql.types.{IntegerType, StringType}
+
+/**
+ * Post-processes a resolved [[ChangelogTable]] read to apply CDC option 
semantics
+ * (carry-over removal, update detection) and to enforce supported option 
combinations.
+ *
+ * Fires after [[ResolveRelations]] has wrapped the connector's [[Changelog]] 
in a
+ * [[ChangelogTable]]. Both batch ([[DataSourceV2Relation]]) and streaming
+ * ([[StreamingRelationV2]]) reads are handled:
+ *   - Batch: the requested post-processing passes are injected as logical 
operators on top
+ *     of the relation. Carry-over removal and update detection are fused into 
a single
+ *     pass over a (rowId, _commit_version)-partitioned Window: the Filter 
drops CoW
+ *     carry-over pairs (same rowVersion on both sides) and the subsequent 
Project relabels
+ *     real delete+insert pairs as update_preimage / update_postimage.
+ *   - Streaming: post-processing is not yet supported. If the requested 
options would
+ *     require any post-processing, the rule throws an explicit 
[[AnalysisException]] to
+ *     prevent silent wrong results. Streams that don't require 
post-processing pass
+ *     through unchanged.
+ *
+ * Net change computation (`deduplicationMode = netChanges`) is not yet 
implemented and
+ * is rejected up-front for both batch and streaming.
+ */
+object ResolveChangelogTable extends Rule[LogicalPlan] {
+
+  private val CHANGELOG_TRANSFORMED_TAG =
+    TreeNodeTag[Boolean]("changelog_transformed")
+
+  private object HelperColumn {
+    final val DelCnt = "_del_cnt"
+    final val InsCnt = "_ins_cnt"
+    final val MinRv = "_min_rv"
+    final val MaxRv = "_max_rv"
+
+    val all: Set[String] = Set(DelCnt, InsCnt, MinRv, MaxRv)
+  }
+
+  override def apply(plan: LogicalPlan): LogicalPlan = {
+    if (isAlreadyTransformed(plan)) return plan
+    var updatedPlan = plan
+    updatedPlan = plan.resolveOperatorsUp {
+      case rel @ DataSourceV2Relation(table: ChangelogTable, _, _, _, _, _) =>
+        val changelog = table.changelog
+        val req = evaluateRequirements(changelog, table.changelogInfo)
+
+        var updatedRel: LogicalPlan = rel
+        if (req.requiresCarryOverRemoval || req.requiresUpdateDetection) {
+          updatedRel = addRowLevelPostProcessing(
+            rel, changelog, req.requiresCarryOverRemoval, 
req.requiresUpdateDetection)
+        }
+        if (req.requiresNetChanges) {
+          updatedRel = injectNetChangeComputation(updatedRel, changelog)
+        }
+        updatedRel
+
+      case rel @ StreamingRelationV2(_, _, table: ChangelogTable, _, _, _, _, 
_, _) =>
+        // Streaming CDC reads do not yet apply post-processing. Run the same 
option /
+        // capability validation as the batch path so silent wrong results are 
impossible:
+        // either no post-processing would be required (fall through, return 
raw stream),
+        // or we throw an explicit AnalysisException.
+        val changelog = table.changelog
+        val req = evaluateRequirements(changelog, table.changelogInfo)
+        if (req.needsAny) {
+          throw 
QueryCompilationErrors.cdcStreamingPostProcessingNotSupported(changelog.name())
+        }
+        rel
+    }
+    if (updatedPlan ne plan) {
+      updatedPlan.setTagValue(CHANGELOG_TRANSFORMED_TAG, true)
+    }
+    updatedPlan
+  }
+
+  // 
---------------------------------------------------------------------------
+  // Option validation & Requirement Computation
+  // 
---------------------------------------------------------------------------
+
+  /**
+   * Captures which post-processing passes a CDC query requires, derived from 
the
+   * user-provided [[ChangelogInfo]] options and the connector-declared 
[[Changelog]]
+   * capability flags.
+   */
+  private case class PostProcessingRequirements(
+      requiresCarryOverRemoval: Boolean,
+      requiresUpdateDetection: Boolean,
+      requiresNetChanges: Boolean) {
+    def needsAny: Boolean =
+      requiresCarryOverRemoval || requiresUpdateDetection || requiresNetChanges
+  }
+
+  /**
+   * Validates CDC option/capability combinations and computes which 
post-processing
+   * passes are required. Throws an [[org.apache.spark.sql.AnalysisException]] 
for
+   * unsupported or contradictory combinations (currently: `netChanges` 
deduplication,
+   * and `computeUpdates` with surfaced carry-overs but no carry-over removal).
+   */
+  private def evaluateRequirements(
+      changelog: Changelog,
+      options: ChangelogInfo): PostProcessingRequirements = {
+    // Net change computation is not yet implemented.
+    if (options.deduplicationMode() == 
ChangelogInfo.DeduplicationMode.NET_CHANGES) {
+      throw 
QueryCompilationErrors.cdcNetChangesNotYetSupported(changelog.name())
+    }
+
+    val requiresCarryOverRemoval =
+      options.deduplicationMode() != ChangelogInfo.DeduplicationMode.NONE &&
+        changelog.containsCarryoverRows()
+    val requiresUpdateDetection =
+      options.computeUpdates() && changelog.representsUpdateAsDeleteAndInsert()
+    val requiresNetChanges =
+      options.deduplicationMode() == 
ChangelogInfo.DeduplicationMode.NET_CHANGES &&
+        changelog.containsIntermediateChanges()
+
+    // If carry-overs are surfaced and update detection is enabled without 
carry-over
+    // removal, carry-overs would be falsely classified as updates, leading to 
wrong
+    // results. Hence we throw.
+    if (requiresUpdateDetection &&
+        changelog.containsCarryoverRows() &&
+        options.deduplicationMode() == ChangelogInfo.DeduplicationMode.NONE) {
+      throw QueryCompilationErrors.cdcUpdateDetectionRequiresCarryOverRemoval(
+        changelog.name())
+    }
+
+    PostProcessingRequirements(
+      requiresCarryOverRemoval, requiresUpdateDetection, requiresNetChanges)
+  }
+
+  // 
---------------------------------------------------------------------------
+  // Row Level Post Processing (Update Detection & Carry-over Removal)
+  // 
---------------------------------------------------------------------------
+
+  /**
+   * Adds row-level post-processing (carry-over removal and/or update 
detection) on top of
+   * the given plan:
+   *   - both active    -> Window(counts + rv bounds) -> Filter -> 
Project(relabel) -> Drop helpers
+   *   - carry-over only -> Window(counts + rv bounds) -> Filter -> Drop 
helpers
+   *   - update only    -> Window(counts only) -> Project(relabel) -> Drop 
helpers
+   *   - neither        -> not invoked (caller guards this case)
+   */
+  private def addRowLevelPostProcessing(
+      plan: LogicalPlan,
+      cl: Changelog,
+      requiresCarryOverRemoval: Boolean,
+      requiresUpdateDetection: Boolean): LogicalPlan = {
+    // Row-version bounds in the Window are needed iff we filter carry-over 
pairs.
+    var modifiedPlan = addPostProcessingWindow(plan, cl,
+      includeRowVersionBounds = requiresCarryOverRemoval)
+    if (requiresCarryOverRemoval) modifiedPlan = 
addCarryOverPairFilter(modifiedPlan)
+    if (requiresUpdateDetection) modifiedPlan = 
addUpdateRelabelProjection(modifiedPlan)
+    removeHelperColumns(modifiedPlan)
+  }
+
+  /**
+   * Adds a Window node partitioned by (rowId, _commit_version) that computes
+   * `_del_cnt` and `_ins_cnt` per partition, and, when 
`includeRowVersionBounds`
+   * is true, additionally `_min_rv` / `_max_rv` (min/max of 
`Changelog.rowVersion()`).
+   *
+   * `_del_cnt` / `_ins_cnt` drive update detection (1 each -> relabel as
+   * update_preimage / update_postimage). `_min_rv` / `_max_rv` drive 
carry-over
+   * detection (within a delete+insert pair, equal bounds signal a CoW 
carry-over).
+   */
+  private def addPostProcessingWindow(
+      plan: LogicalPlan,
+      cl: Changelog,
+      includeRowVersionBounds: Boolean): LogicalPlan = {
+    val changeTypeAttr = getAttribute(plan, "_change_type")
+    val rowIdExprs = 
V2ExpressionUtils.resolveRefs[NamedExpression](cl.rowId().toSeq, plan)

Review Comment:
   Two connector-contract failure modes surface as poor errors here:
   
   1. Connector reports `containsCarryoverRows = true` (or 
`representsUpdateAsDeleteAndInsert = true`) but never overrides `rowId()` / 
`rowVersion()`. The default impl on `Changelog` throws 
`UnsupportedOperationException("rowId is not supported.")`, which bubbles up as 
a non-`AnalysisException` with no CDC context.
   2. Connector *does* override `rowId()` but returns an empty array. 
`addPostProcessingWindow` then partitions only by `_commit_version` — unrelated 
row identities collapse into one partition, the window counts reflect 
cross-identity totals, and carry-over removal / update relabeling silently 
produce wrong results.
   
   Suggest validating at the top of `addPostProcessingWindow` (or in 
`evaluateRequirements`) that `cl.rowId()` is non-empty and that 
`cl.rowVersion()` is reachable when the capability flags require them, with a 
clear CDC error. Add two tests: empty `rowIdNames` + `containsCarryoverRows = 
true`; missing `rowVersion` override.



##########
sql/core/src/test/scala/org/apache/spark/sql/connector/ResolveChangelogTablePostProcessingSuite.scala:
##########
@@ -0,0 +1,945 @@
+/*
+ * 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.connector
+
+import java.util.Collections
+
+import org.scalatest.BeforeAndAfterEach
+
+import org.apache.spark.SparkRuntimeException
+import org.apache.spark.sql.{AnalysisException, QueryTest}
+import org.apache.spark.sql.catalyst.InternalRow
+import org.apache.spark.sql.connector.catalog.{
+  ChangelogProperties, Column, Identifier, InMemoryChangelogCatalog}
+import org.apache.spark.sql.connector.expressions.Transform
+import org.apache.spark.sql.test.SharedSparkSession
+import org.apache.spark.sql.types.{
+  BinaryType, BooleanType, DoubleType, LongType, StringType, StructField, 
StructType}
+import org.apache.spark.unsafe.types.UTF8String
+
+/**
+ * Tests for [[org.apache.spark.sql.catalyst.analysis.ResolveChangelogTable]] 
using the
+ * in-memory changelog catalog. These tests don't depend on Delta or any 
specific connector;
+ * they directly control what the connector "returns" by populating the 
in-memory changelog
+ * with hand-crafted change rows.
+ *
+ * Each test sets up [[ChangelogProperties]] on the catalog to enable specific 
post-processing
+ * paths (carry-over removal, update detection) and then verifies that Spark's 
analyzer rule
+ * correctly transforms the plan and produces the expected output.
+ */
+class ResolveChangelogTablePostProcessingSuite
+    extends QueryTest
+    with SharedSparkSession
+    with BeforeAndAfterEach {
+
+  private val catalogName = "cdc_test_catalog"
+  private val testTableName = "events"
+
+  override def beforeAll(): Unit = {
+    super.beforeAll()
+    spark.conf.set(
+      s"spark.sql.catalog.$catalogName",
+      classOf[InMemoryChangelogCatalog].getName)
+  }
+
+  override def beforeEach(): Unit = {
+    super.beforeEach()
+    val cat = catalog
+    val ident = Identifier.of(Array.empty, testTableName)
+    if (cat.tableExists(ident)) cat.dropTable(ident)
+    cat.clearChangeRows(ident)
+    cat.setChangelogProperties(ident, ChangelogProperties())
+    cat.createTable(
+      ident,
+      Array(
+        Column.create("id", LongType),
+        Column.create("name", StringType),
+        Column.create("row_commit_version", LongType, false)),
+      Array.empty[Transform],
+      Collections.emptyMap[String, String]())
+  }
+
+  private def catalog: InMemoryChangelogCatalog = {
+    spark.sessionState.catalogManager
+      .catalog(catalogName)
+      .asInstanceOf[InMemoryChangelogCatalog]
+  }
+
+  private def ident = Identifier.of(Array.empty, testTableName)
+
+  /**
+   * Helper to create a change row matching schema
+   * (id, name, row_commit_version, _change_type, _commit_version, 
_commit_timestamp).
+   *
+   * `rowCommitVersion` follows Delta row-tracking semantics: carry-over pairs 
(CoW-rewritten
+   * unchanged rows) share the same value on both sides; real updates carry 
the OLD value on
+   * the delete side and the NEW value on the insert side. Defaults to 
`commitVersion` for
+   * tests that don't exercise carry-over removal.
+   */
+  private def changeRow(
+      id: Long,
+      name: String,
+      changeType: String,
+      commitVersion: Long,
+      rowCommitVersion: Long = -1L,
+      commitTimestamp: Long = 0L): InternalRow = {
+    val rcv = if (rowCommitVersion == -1L) commitVersion else rowCommitVersion
+    InternalRow(
+      id,
+      UTF8String.fromString(name),
+      rcv,
+      UTF8String.fromString(changeType),
+      commitVersion,
+      commitTimestamp)
+  }
+
+  // 
===========================================================================
+  // Carry-Over Removal
+  // 
===========================================================================
+
+  test("carry-over removal drops identical delete+insert pairs") {
+    catalog.setChangelogProperties(ident, ChangelogProperties(
+      containsCarryoverRows = true,
+      rowIdNames = Seq("id"),
+      rowVersionName = Some("row_commit_version")))
+
+    // v1: insert Alice and Bob (rcv=1 each)
+    // v2: real delete Alice (preimage carries old rcv=1);
+    //     carry-over for Bob (CoW, rcv unchanged on both sides)
+    catalog.addChangeRows(ident, Seq(
+      changeRow(1L, "Alice", "insert", 1L, rowCommitVersion = 1L),
+      changeRow(2L, "Bob", "insert", 1L, rowCommitVersion = 1L),
+      changeRow(1L, "Alice", "delete", 2L, rowCommitVersion = 1L),
+      changeRow(2L, "Bob", "delete", 2L, rowCommitVersion = 1L),  // carry-over
+      changeRow(2L, "Bob", "insert", 2L, rowCommitVersion = 1L))) // 
carry-over (same rcv)
+
+    val rows = sql(
+      s"SELECT id, name, _change_type, _commit_version " +
+      s"FROM $catalogName.$testTableName CHANGES FROM VERSION 1 TO VERSION 2")
+      .orderBy("_commit_version", "id", "_change_type")
+      .collect()
+
+    val descs = rows.map(r =>
+      s"${r.getLong(0)}:${r.getString(1)}:${r.getString(2)}:v${r.getLong(3)}")
+
+    // v1 inserts kept
+    assert(descs.contains("1:Alice:insert:v1"))
+    assert(descs.contains("2:Bob:insert:v1"))
+    // Real Alice delete kept
+    assert(descs.contains("1:Alice:delete:v2"))
+    // Bob carry-over pair removed
+    assert(!descs.contains("2:Bob:delete:v2"),
+      s"Bob delete should be dropped. Got: ${descs.mkString(",")}")
+    assert(!descs.contains("2:Bob:insert:v2"),
+      s"Bob insert should be dropped. Got: ${descs.mkString(",")}")
+  }
+
+  test("deduplicationMode=none keeps all carry-over rows") {
+    catalog.setChangelogProperties(ident, ChangelogProperties(
+      containsCarryoverRows = true,
+      rowIdNames = Seq("id"),
+      rowVersionName = Some("row_commit_version")))
+
+    catalog.addChangeRows(ident, Seq(
+      changeRow(1L, "Alice", "insert", 1L, rowCommitVersion = 1L),
+      changeRow(2L, "Bob", "delete", 2L, rowCommitVersion = 1L),
+      changeRow(2L, "Bob", "insert", 2L, rowCommitVersion = 1L)))
+
+    val rows = sql(
+      s"SELECT id FROM $catalogName.$testTableName " +
+      s"CHANGES FROM VERSION 1 TO VERSION 2 WITH (deduplicationMode = 'none')")
+      .collect()
+
+    assert(rows.length == 3, "Without dedup, all 3 raw rows should be 
returned")
+  }
+
+  // 
===========================================================================
+  // Update Detection
+  // 
===========================================================================
+
+  test("update detection relabels delete+insert with different data as 
update") {
+    catalog.setChangelogProperties(ident, ChangelogProperties(
+      containsCarryoverRows = false,  // no carry-overs in this test
+      representsUpdateAsDeleteAndInsert = true,
+      rowIdNames = Seq("id"),
+      rowVersionName = Some("row_commit_version")))
+
+    catalog.addChangeRows(ident, Seq(
+      changeRow(1L, "Alice", "insert", 1L),
+      // v2: Alice -> Robert (delete old, insert new)
+      changeRow(1L, "Alice", "delete", 2L),
+      changeRow(1L, "Robert", "insert", 2L)))
+
+    val rows = sql(
+      s"SELECT id, name, _change_type, _commit_version " +
+      s"FROM $catalogName.$testTableName " +
+      s"CHANGES FROM VERSION 1 TO VERSION 2 WITH (computeUpdates = 'true')")
+      .orderBy("_commit_version", "_change_type")
+      .collect()
+
+    val descs = rows.map(r =>
+      s"${r.getLong(0)}:${r.getString(1)}:${r.getString(2)}")
+
+    assert(descs.contains("1:Alice:insert"), s"v1 insert. Got: 
${descs.mkString(",")}")
+    assert(descs.contains("1:Alice:update_preimage"))
+    assert(descs.contains("1:Robert:update_postimage"))
+    // No raw delete/insert at v2
+    assert(!descs.contains("1:Alice:delete"))
+    assert(!descs.contains("1:Robert:insert"))
+  }
+
+  test("delete and insert in different versions are NOT labeled as update") {
+    catalog.setChangelogProperties(ident, ChangelogProperties(
+      representsUpdateAsDeleteAndInsert = true,
+      rowIdNames = Seq("id"),
+      rowVersionName = Some("row_commit_version")))
+
+    catalog.addChangeRows(ident, Seq(
+      changeRow(1L, "Alice", "insert", 1L),
+      changeRow(1L, "Alice", "delete", 2L),
+      changeRow(1L, "Alice", "insert", 3L)))
+
+    val rows = sql(
+      s"SELECT _change_type, _commit_version FROM $catalogName.$testTableName 
" +
+      s"CHANGES FROM VERSION 1 TO VERSION 3 " +
+      s"WITH (computeUpdates = 'true', deduplicationMode = 'none')")
+      .collect()
+
+    assert(!rows.exists(_.getString(0).contains("update_")),
+      "Delete and insert in different versions should not be labeled as 
update")
+  }
+
+  // 
===========================================================================
+  // Composite rowId: partitioning uses every rowId column
+  // 
===========================================================================
+  //
+  // With a composite rowId such as Seq("id", "name"), the (rowId, 
_commit_version)
+  // window partition must include BOTH columns. A regression that drops one 
of the
+  // rowId columns would either falsely merge two different row identities 
into one
+  // partition (silently mislabeling unrelated delete/insert pairs as updates) 
or
+  // trip the UNEXPECTED_MULTIPLE_CHANGES_PER_ROW_VERSION runtime guard.
+
+  test("update detection with composite rowId keeps different (id, name) 
tuples raw") {
+    catalog.setChangelogProperties(ident, ChangelogProperties(
+      representsUpdateAsDeleteAndInsert = true,
+      rowIdNames = Seq("id", "name"),
+      rowVersionName = Some("row_commit_version")))
+
+    // delete (1, Alice) and insert (1, Bob) at v2. These are DIFFERENT 
composite
+    // rowIds; they must NOT be relabeled as update.
+    catalog.addChangeRows(ident, Seq(
+      changeRow(1L, "Alice", "delete", 2L),
+      changeRow(1L, "Bob", "insert", 2L)))
+
+    val rows = sql(
+      s"SELECT id, name, _change_type FROM $catalogName.$testTableName " +
+      s"CHANGES FROM VERSION 2 TO VERSION 2 WITH (computeUpdates = 'true')")
+      .collect()
+
+    val descs = rows.map(r =>
+      s"${r.getLong(0)}:${r.getString(1)}:${r.getString(2)}").toSet
+
+    assert(descs == Set("1:Alice:delete", "1:Bob:insert"),
+      s"Composite rowId must keep different (id, name) tuples raw. Got: 
$descs")
+  }
+
+  test("carry-over removal with composite rowId removes pairs per (id, name) 
tuple") {
+    catalog.setChangelogProperties(ident, ChangelogProperties(
+      containsCarryoverRows = true,
+      rowIdNames = Seq("id", "name"),
+      rowVersionName = Some("row_commit_version")))
+
+    // Two independent carry-over pairs at v2, both with id=1 but different 
names.
+    // With correct composite-rowId partitioning, each pair lives in its own
+    // (id, name, _commit_version) partition, has _del_cnt=1 / _ins_cnt=1 and 
equal
+    // _min_rv / _max_rv, and gets dropped. With broken (id-only) 
partitioning, the
+    // four rows would collapse into one partition with _del_cnt=2 / 
_ins_cnt=2 and
+    // the carry-over filter (which requires =1) would keep them all.
+    catalog.addChangeRows(ident, Seq(
+      changeRow(1L, "Alice", "insert", 1L, rowCommitVersion = 1L),
+      changeRow(1L, "Bob", "insert", 1L, rowCommitVersion = 1L),
+      changeRow(1L, "Alice", "delete", 2L, rowCommitVersion = 1L),
+      changeRow(1L, "Alice", "insert", 2L, rowCommitVersion = 1L),
+      changeRow(1L, "Bob", "delete", 2L, rowCommitVersion = 1L),
+      changeRow(1L, "Bob", "insert", 2L, rowCommitVersion = 1L)))
+
+    val rows = sql(
+      s"SELECT id, name, _change_type, _commit_version " +
+      s"FROM $catalogName.$testTableName CHANGES FROM VERSION 2 TO VERSION 2")
+      .collect()
+
+    val descs = rows.map(r =>
+      s"${r.getLong(0)}:${r.getString(1)}:${r.getString(2)}")
+    assert(rows.isEmpty,
+      s"Both Alice and Bob carry-over pairs at v2 should be removed. Got: 
${descs.mkString(",")}")
+  }
+
+  // 
===========================================================================
+  // No row identity: post-processing skipped
+  // 
===========================================================================
+
+  test("empty rowId skips post-processing in plan") {
+    // Default ChangelogProperties has no rowId; post-processing must not be 
injected
+    catalog.addChangeRows(ident, Seq(
+      changeRow(1L, "Alice", "insert", 1L),
+      changeRow(2L, "Bob", "delete", 2L),
+      changeRow(2L, "Bob", "insert", 2L)))
+
+    val df = sql(
+      s"SELECT * FROM $catalogName.$testTableName " +
+      s"CHANGES FROM VERSION 1 TO VERSION 2 WITH (computeUpdates = 'true')")
+
+    val plan = df.queryExecution.analyzed.treeString
+    assert(!plan.contains("_del_cnt"),
+      s"Plan must not contain post-processing window helpers without rowId. 
Plan:\n$plan")
+    assert(!plan.contains("_ins_cnt"),
+      s"Plan must not contain post-processing window helpers without rowId. 
Plan:\n$plan")
+  }

Review Comment:
   Both the test name and the inline comment (`// Default ChangelogProperties 
has no rowId; post-processing must not be injected`) claim empty rowId causes 
the skip, but the test uses `ChangelogProperties()` defaults which also have 
`containsCarryoverRows = false` and `representsUpdateAsDeleteAndInsert = false` 
— and those flags alone make `evaluateRequirements` return no-requirements. The 
rowId is never consulted on this path.
   
   Either rename to e.g. `"post-processing skipped when connector advertises no 
carry-overs or delete+insert updates"`, or keep the name and flip 
`containsCarryoverRows = true` so the test actually reaches the rowId 
resolution (which would then expose the gap raised in the comment on line 194 
of `ResolveChangelogTable.scala`).



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/ResolveChangelogTable.scala:
##########
@@ -0,0 +1,315 @@
+/*
+ * 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.catalyst.analysis
+
+import org.apache.spark.sql.catalyst.expressions._
+import org.apache.spark.sql.catalyst.expressions.aggregate.{Count, Max, Min}
+import org.apache.spark.sql.catalyst.plans.logical._
+import org.apache.spark.sql.catalyst.rules.Rule
+import org.apache.spark.sql.catalyst.streaming.StreamingRelationV2
+import org.apache.spark.sql.catalyst.trees.TreeNodeTag
+import org.apache.spark.sql.connector.catalog.{Changelog, ChangelogInfo}
+import org.apache.spark.sql.errors.QueryCompilationErrors
+import org.apache.spark.sql.execution.datasources.v2.{ChangelogTable, 
DataSourceV2Relation}
+import org.apache.spark.sql.types.{IntegerType, StringType}
+
+/**
+ * Post-processes a resolved [[ChangelogTable]] read to apply CDC option 
semantics
+ * (carry-over removal, update detection) and to enforce supported option 
combinations.
+ *
+ * Fires after [[ResolveRelations]] has wrapped the connector's [[Changelog]] 
in a
+ * [[ChangelogTable]]. Both batch ([[DataSourceV2Relation]]) and streaming
+ * ([[StreamingRelationV2]]) reads are handled:
+ *   - Batch: the requested post-processing passes are injected as logical 
operators on top
+ *     of the relation. Carry-over removal and update detection are fused into 
a single
+ *     pass over a (rowId, _commit_version)-partitioned Window: the Filter 
drops CoW
+ *     carry-over pairs (same rowVersion on both sides) and the subsequent 
Project relabels
+ *     real delete+insert pairs as update_preimage / update_postimage.
+ *   - Streaming: post-processing is not yet supported. If the requested 
options would
+ *     require any post-processing, the rule throws an explicit 
[[AnalysisException]] to
+ *     prevent silent wrong results. Streams that don't require 
post-processing pass
+ *     through unchanged.
+ *
+ * Net change computation (`deduplicationMode = netChanges`) is not yet 
implemented and
+ * is rejected up-front for both batch and streaming.
+ */
+object ResolveChangelogTable extends Rule[LogicalPlan] {
+
+  private val CHANGELOG_TRANSFORMED_TAG =
+    TreeNodeTag[Boolean]("changelog_transformed")
+
+  private object HelperColumn {
+    final val DelCnt = "_del_cnt"
+    final val InsCnt = "_ins_cnt"
+    final val MinRv = "_min_rv"
+    final val MaxRv = "_max_rv"
+
+    val all: Set[String] = Set(DelCnt, InsCnt, MinRv, MaxRv)
+  }

Review Comment:
   The helper names are unprefixed, so if a connector surfaces a user column 
literally named `_del_cnt`/`_ins_cnt`/`_min_rv`/`_max_rv`, `getAttribute` 
silently picks the user column (first name match on `plan.output`) and 
`removeHelperColumns` then drops that user column from the final output. Very 
unlikely, but the fix is free — a reserved prefix like `__spark_cdc_*` makes 
the collision structurally impossible. Complements @johanl-db's line-193 
suggestion to expose these as connector-facing constants: prefixing is the 
right shape regardless of whether they go public.



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