You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@datafusion.apache.org by gi...@apache.org on 2026/10/04 19:10:25 UTC
(datafusion-comet) branch gh-readonly-queue/main/pr-5318-e7760c027d3167f764eccf4d12d7995f88dd078c created (now 207fb6f4b9)
This is an automated email from the ASF dual-hosted git repository.
github-merge-queue[bot] pushed a change to branch gh-readonly-queue/main/pr-5318-e7760c027d3167f764eccf4d12d7995f88dd078c
in repository https://gitbox.apache.org/repos/asf/datafusion-comet.git
at 207fb6f4b9 feat: add native support for MergeRowsExec (row-level MERGE INTO) (#5318)
This branch includes the following new commits:
new 207fb6f4b9 feat: add native support for MergeRowsExec (row-level MERGE INTO) (#5318)
The 1 revisions listed above as "new" are entirely new to this
repository and will be described in separate emails. The revisions
listed as "add" were already present in the repository and have only
been added to this reference.
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@datafusion.apache.org
For additional commands, e-mail: commits-help@datafusion.apache.org
(datafusion-comet) 01/01: feat: add native support for MergeRowsExec (row-level MERGE INTO) (#5318)
Posted by gi...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
github-merge-queue[bot] pushed a commit to branch gh-readonly-queue/main/pr-5318-e7760c027d3167f764eccf4d12d7995f88dd078c
in repository https://gitbox.apache.org/repos/asf/datafusion-comet.git
commit 207fb6f4b9801adea9f270e816c3fa33da4b1534
Author: Unik Dahal <61...@users.noreply.github.com>
AuthorDate: Sun Oct 4 19:10:03 2026 +0000
feat: add native support for MergeRowsExec (row-level MERGE INTO) (#5318)
* feat: add native MergeRows execution
* Address MergeRows review feedback
* Review Comments Addressed
* Address Review Feedback
---
.github/workflows/ci.yml | 3 +
.github/workflows/pr_build_linux.yml | 1 +
.github/workflows/pr_build_macos.yml | 1 +
dev/ci/check-versioned-source-parity.py | 59 +
.../user-guide/latest/compatibility/operators.md | 46 +
docs/source/user-guide/latest/iceberg-writes.md | 6 +
docs/source/user-guide/latest/operators.md | 1 +
.../user-guide/latest/understanding-comet-plans.md | 1 +
native/common/src/error.rs | 13 +-
native/core/src/execution/jni_api.rs | 1 +
native/core/src/execution/operators/merge_rows.rs | 1486 ++++++++++++++++++++
native/core/src/execution/operators/mod.rs | 2 +
native/core/src/execution/planner.rs | 171 ++-
.../src/execution/planner/operator_registry.rs | 3 +-
native/proto/src/proto/operator.proto | 34 +
.../main/scala/org/apache/comet/CometConf.scala | 8 +
.../org/apache/comet/rules/CometExecRule.scala | 8 +-
.../org/apache/spark/sql/comet/operators.scala | 83 ++
.../apache/comet/shims/ShimCometMergeRows.scala | 32 +
.../comet/serde/operator/CometMergeRows.scala | 242 ++++
.../apache/comet/shims/ShimCometMergeRows.scala | 35 +
.../sql/comet/shims/ShimSparkErrorConverter.scala | 3 +
.../comet/serde/operator/CometMergeRows.scala | 242 ++++
.../apache/comet/shims/ShimCometMergeRows.scala | 35 +
.../apache/comet/shims/ShimCometMergeRows.scala | 33 +
.../sql/comet/shims/ShimSparkErrorConverter.scala | 3 +
.../comet/CometIcebergWriteActionSuite.scala | 277 +++-
.../comet/exec/CometMergeRowsNativeSuiteBase.scala | 493 +++++++
.../apache/comet/exec/CometMergeRowsSuite.scala | 31 +
.../apache/comet/exec/CometMergeRowsSuite.scala | 23 +
.../apache/comet/exec/CometMergeRowsSuite.scala | 23 +
.../apache/comet/exec/CometMergeRowsSuite.scala | 109 ++
32 files changed, 3481 insertions(+), 27 deletions(-)
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index 03a38831de..2a63cb153b 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -190,6 +190,9 @@ jobs:
- name: Check missing suites
run: python3 dev/ci/check-suites.py
+ - name: Check versioned source parity
+ run: python3 dev/ci/check-versioned-source-parity.py
+
- name: Check micro benchmark runner
run: python3 dev/ci/check-benchmark-runner.py
diff --git a/.github/workflows/pr_build_linux.yml b/.github/workflows/pr_build_linux.yml
index 9e51cf03e2..2360d7a5a4 100644
--- a/.github/workflows/pr_build_linux.yml
+++ b/.github/workflows/pr_build_linux.yml
@@ -510,6 +510,7 @@ jobs:
org.apache.comet.exec.CometAggregateSuite
org.apache.comet.exec.CometExec3_4PlusSuite
org.apache.comet.exec.CometExecSuite
+ org.apache.comet.exec.CometMergeRowsSuite
org.apache.comet.exec.CometTopKSuite
org.apache.comet.exec.CometEmptyRelationExecSuite
org.apache.comet.exec.CometRangeExecSuite
diff --git a/.github/workflows/pr_build_macos.yml b/.github/workflows/pr_build_macos.yml
index 5d759d0b64..0a8254bff8 100644
--- a/.github/workflows/pr_build_macos.yml
+++ b/.github/workflows/pr_build_macos.yml
@@ -214,6 +214,7 @@ jobs:
org.apache.comet.exec.CometAggregateSuite
org.apache.comet.exec.CometExec3_4PlusSuite
org.apache.comet.exec.CometExecSuite
+ org.apache.comet.exec.CometMergeRowsSuite
org.apache.comet.exec.CometTopKSuite
org.apache.comet.exec.CometEmptyRelationExecSuite
org.apache.comet.exec.CometRangeExecSuite
diff --git a/dev/ci/check-versioned-source-parity.py b/dev/ci/check-versioned-source-parity.py
new file mode 100644
index 0000000000..1b21794fba
--- /dev/null
+++ b/dev/ci/check-versioned-source-parity.py
@@ -0,0 +1,59 @@
+# 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.
+
+from pathlib import Path
+
+PARITY_GROUPS = [
+ (
+ "MergeRows serializer",
+ [
+ Path("spark/src/main/spark-3.5/org/apache/comet/serde/operator/CometMergeRows.scala"),
+ Path("spark/src/main/spark-4.0/org/apache/comet/serde/operator/CometMergeRows.scala"),
+ ],
+ "Spark 3.5 and 4.0 intentionally share the same MergeRows serialization contract.",
+ ),
+ (
+ "MergeRows registration shim",
+ [
+ Path("spark/src/main/spark-3.5/org/apache/comet/shims/ShimCometMergeRows.scala"),
+ Path("spark/src/main/spark-4.0/org/apache/comet/shims/ShimCometMergeRows.scala"),
+ ],
+ "Spark 3.5 and 4.0 intentionally register MergeRows through identical shims.",
+ ),
+]
+
+
+def main() -> int:
+ failed = False
+ for name, paths, reason in PARITY_GROUPS:
+ reference = paths[0].read_bytes()
+ for path in paths[1:]:
+ if path.read_bytes() != reference:
+ failed = True
+ print(f"{name} files must remain byte-identical.")
+ print(f"Reason: {reason}")
+ print(f"Reference: {paths[0]}")
+ print(f"Different: {path}")
+ if failed:
+ return 1
+
+ print("Versioned source parity checks passed.")
+ return 0
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())
diff --git a/docs/source/user-guide/latest/compatibility/operators.md b/docs/source/user-guide/latest/compatibility/operators.md
index 657a32de53..08883edaef 100644
--- a/docs/source/user-guide/latest/compatibility/operators.md
+++ b/docs/source/user-guide/latest/compatibility/operators.md
@@ -111,6 +111,52 @@ Floating-point `ORDER BY` keys, including floats nested in arrays and structs, a
and match Spark's ranks; see [floating-point ordering](./floating-point.md), which also covers
strict floating-point mode.
+## MERGE INTO (MergeRowsExec)
+
+Spark `MergeRowsExec` appears as `CometMergeRows` when native execution is enabled.
+
+Comet can run `MergeRowsExec` (Spark's row-level `MERGE INTO` dispatch operator) natively on
+Spark 3.5.x and Spark 4.0.x, but it is disabled by default. Enable it with
+`spark.comet.exec.mergeRows.enabled=true`.
+
+Spark 4.1+ intentionally falls back to Spark even when that flag is enabled. Starting in Spark
+4.1, the V2 existing-table writer locates the concrete Spark `MergeRowsExec`, builds a
+`MergeSummary` from its row-level metrics, and passes that summary to the summary-aware
+`BatchWrite.commit` overload. Replacing the node with `CometMergeRowsExec` would make summary
+discovery fail and silently switch the data source to the legacy summary-less commit overload.
+Comet will keep Spark 4.1+ `MERGE` on the JVM until it can preserve that writer contract end-to-end.
+See [#6606](https://github.com/apache/datafusion-comet/issues/6606).
+
+**Cardinality validation memory use can exceed Spark's:** native MERGE cardinality validation
+currently stores matched target row IDs in an unspillable hash set. For MERGEs with many matched
+rows per task, this can use more memory than Spark's compressed bitmap and may reach the native
+memory limit earlier than Spark. See
+[#6608](https://github.com/apache/datafusion-comet/issues/6608).
+
+**Undeclared physical output order can differ from Spark:** native execution is set-at-a-time. Within
+an input batch it emits rows grouped by the MERGE instruction that produced them, and it processes
+the MATCHED, NOT MATCHED, then NOT MATCHED BY SOURCE groups. Spark's row-at-a-time implementation
+emits rows in input order. This is not a MERGE row-value semantic difference: an unordered table
+scan has no row-order guarantee. Downstream V2 write planning still enforces every distribution or
+ordering requirement declared by the writer; only a writer that declares no ordering requirement
+can persist the same rows in a different physical sequence.
+
+**Failure precedence can differ from Spark on rare inputs:** Spark consumes joined rows one at a
+time. For each row it determines the MERGE group, validates cardinality when required, and walks
+that row's instruction list until the first clause fires. Comet intentionally vectorizes this work:
+it validates cardinality for the input batch, then evaluates each instruction over the remaining
+rows of the MATCHED, NOT MATCHED, and NOT MATCHED BY SOURCE groups. Successful deterministic row
+results preserve Spark semantics, including first-match-wins within a row, but the two evaluation
+orders are not identical when more than one row in the same Arrow batch would fail.
+
+For example, Spark may encounter an ANSI cast failure on an earlier input row before reaching a
+later row whose earlier MERGE clause divides by zero, while Comet can evaluate that earlier clause
+across the whole group and report `DIVIDE_BY_ZERO` first. The same ordering difference can occur
+between different MERGE groups, between the two projections of a `Split`, or between a cardinality
+violation and an unrelated clause-evaluation error. In these cases both engines reject the query,
+but the surfaced Spark error condition can differ. This limitation only applies to Spark versions
+where native `MergeRowsExec` is enabled.
+
## Round-Robin Partitioning
Comet's native shuffle implementation of round-robin partitioning (`df.repartition(n)`) is not compatible with
diff --git a/docs/source/user-guide/latest/iceberg-writes.md b/docs/source/user-guide/latest/iceberg-writes.md
index d1b14c1e71..52e0eb7715 100644
--- a/docs/source/user-guide/latest/iceberg-writes.md
+++ b/docs/source/user-guide/latest/iceberg-writes.md
@@ -100,6 +100,12 @@ supports:
`OverwritePartitionsDynamic`)
- Copy-on-write `DELETE` / `UPDATE` / `MERGE` (`ReplaceData`)
+For an unpartitioned copy-on-write `MERGE`, the native Iceberg writer is reachable on Spark
+3.5.x and 4.0.x only when `spark.comet.exec.mergeRows.enabled=true`. With the flag disabled,
+the JVM `MergeRowsExec` breaks the fully-native child chain required by `CometIcebergWriteExec`.
+Spark 4.1+ keeps `MergeRowsExec` on the JVM even when the flag is set, so this unpartitioned
+shape continues through the JVM writer there.
+
The mechanism behind row-level DML differs by Spark version: on Spark 4.0+ the analyzer emits
operation-coded rows that Comet's writer dispatches through `ReplaceData`'s projections, while
on Spark 3.4/3.5 the rewritten rows are written as a plain row stream. The supported set of
diff --git a/docs/source/user-guide/latest/operators.md b/docs/source/user-guide/latest/operators.md
index 676f295ccf..9f2e485c50 100644
--- a/docs/source/user-guide/latest/operators.md
+++ b/docs/source/user-guide/latest/operators.md
@@ -136,6 +136,7 @@ natively on `BroadcastHashJoinExec` and `ShuffledHashJoinExec`. Existence sort-m
| `WriteFilesExec` | ⚠️ | Spark 4.0+. Experimental native Parquet writes, disabled by default (opt-in). Non-partitioned, non-bucketed writes only, and not when `spark.sql.files.maxRecordsPerFile` is set. [...]
| `DataWritingCommandExec` | ⚠️ | Spark 3.4/3.5 only. Experimental native Parquet writes, disabled by default (opt-in). Replaced by `WriteFilesExec` on Spark 4.0+ and removed with Spark 3.x support. [...]
| Iceberg writes: `AppendDataExec`, `OverwriteByExpressionExec`, `OverwritePartitionsDynamicExec`, `ReplaceDataExec` | ⚠️ | Experimental, disabled by default. `spark.comet.write.iceberg.splitOperator.enabled=true` plans the write as `IcebergWrite` and `IcebergCommit`, and Iceberg's Java writer still writes the data files. `spark.comet.write.iceberg.enabled=true` then writes eligible data files natively (`CometIcebergWrite`). Covers `INSERT INTO`, `INSERT OVERWRITE`, and copy-on-write [...]
+| `MergeRowsExec` | ⚠️ | Spark 3.5 and 4.0 only. Experimental, disabled by default (`spark.comet.exec.mergeRows.enabled`). See [MERGE INTO](compatibility/operators.md#merge-into-mergerowsexec). [...]
## Python and UDF
diff --git a/docs/source/user-guide/latest/understanding-comet-plans.md b/docs/source/user-guide/latest/understanding-comet-plans.md
index fcbd995a79..579cd16670 100644
--- a/docs/source/user-guide/latest/understanding-comet-plans.md
+++ b/docs/source/user-guide/latest/understanding-comet-plans.md
@@ -322,6 +322,7 @@ consecutively in a plan, they execute as a single fused block.
| `CometBroadcastHashJoin` | `BroadcastHashJoinExec` |
| `CometBroadcastNestedLoopJoin` | `BroadcastNestedLoopJoinExec` |
| `CometSortMergeJoin` | `SortMergeJoinExec` |
+| `CometMergeRows` | `MergeRowsExec` (Spark 3.5.x / 4.0.x; opt-in) |
| `CometWindowExec` | `WindowExec` |
| `CometWindowGroupLimitExec` | `WindowGroupLimitExec` (Spark 3.5 and later) |
| `CometSample` | `SampleExec` (sampling without replacement) |
diff --git a/native/common/src/error.rs b/native/common/src/error.rs
index c78b063426..77716e5414 100644
--- a/native/common/src/error.rs
+++ b/native/common/src/error.rs
@@ -215,6 +215,12 @@ pub enum SparkError {
#[error("[SCALAR_SUBQUERY_TOO_MANY_ROWS] Scalar subquery returned more than one row.")]
ScalarSubqueryTooManyRows,
+ /// Mirrors Spark's `QueryExecutionErrors.mergeCardinalityViolationError()`, raised by
+ /// `MergeRowsExec.BitmapCardinalityValidator` when a MERGE's ON condition matches a single
+ /// target row against more than one source row.
+ #[error("[MERGE_CARDINALITY_VIOLATION] The ON search condition of the MERGE statement matched a single row from the target table with multiple rows of the source table. This could result in the target row being operated on more than once with an update or delete operation and is not allowed.")]
+ MergeCardinalityViolation,
+
#[error("{message}")]
FileNotFound { message: String },
@@ -369,6 +375,7 @@ impl SparkError {
SparkError::InvalidRegexGroupIndex { .. } => "InvalidRegexGroupIndex",
SparkError::DatatypeCannotOrder { .. } => "DatatypeCannotOrder",
SparkError::ScalarSubqueryTooManyRows => "ScalarSubqueryTooManyRows",
+ SparkError::MergeCardinalityViolation => "MergeCardinalityViolation",
SparkError::FileNotFound { .. } => "FileNotFound",
SparkError::DuplicateFieldCaseInsensitive { .. } => "DuplicateFieldCaseInsensitive",
SparkError::DuplicateFieldByFieldId { .. } => "DuplicateFieldByFieldId",
@@ -712,7 +719,8 @@ impl SparkError {
| SparkError::UnexpectedPositiveValue { .. }
| SparkError::UnexpectedNegativeValue { .. }
| SparkError::InvalidRegexGroupIndex { .. }
- | SparkError::ScalarSubqueryTooManyRows => "org/apache/spark/SparkRuntimeException",
+ | SparkError::ScalarSubqueryTooManyRows
+ | SparkError::MergeCardinalityViolation => "org/apache/spark/SparkRuntimeException",
// DateTimeException
SparkError::InvalidInputInCastToDatetime { .. }
@@ -841,6 +849,9 @@ impl SparkError {
// Subquery errors
SparkError::ScalarSubqueryTooManyRows => Some("SCALAR_SUBQUERY_TOO_MANY_ROWS"),
+ // MERGE INTO errors
+ SparkError::MergeCardinalityViolation => Some("MERGE_CARDINALITY_VIOLATION"),
+
// File not found
SparkError::FileNotFound { .. } => Some("_LEGACY_ERROR_TEMP_2055"),
diff --git a/native/core/src/execution/jni_api.rs b/native/core/src/execution/jni_api.rs
index 44d2cab14d..5b1bf96699 100644
--- a/native/core/src/execution/jni_api.rs
+++ b/native/core/src/execution/jni_api.rs
@@ -486,6 +486,7 @@ fn op_name(op: &OpStruct) -> &'static str {
OpStruct::ShuffleScan(_) => "ShuffleScan",
OpStruct::BroadcastNestedLoopJoin(_) => "BroadcastNestedLoopJoin",
OpStruct::Sample(_) => "Sample",
+ OpStruct::MergeRows(_) => "MergeRows",
OpStruct::RangeScan(_) => "RangeScan",
OpStruct::ContribScan(_) => "ContribScan",
OpStruct::WindowGroupLimit(_) => "WindowGroupLimit",
diff --git a/native/core/src/execution/operators/merge_rows.rs b/native/core/src/execution/operators/merge_rows.rs
new file mode 100644
index 0000000000..97ba954241
--- /dev/null
+++ b/native/core/src/execution/operators/merge_rows.rs
@@ -0,0 +1,1486 @@
+// 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.
+
+use arrow::array::{Array, ArrayRef, BooleanArray, Int64Array, RecordBatch};
+use arrow::compute::kernels::boolean::{and, and_not, not};
+use arrow::compute::{filter_record_batch, prep_null_mask_filter};
+use arrow::datatypes::{DataType, SchemaRef};
+use datafusion::common::tree_node::TreeNodeRecursion;
+use datafusion::common::utils::memory::estimate_memory_size;
+use datafusion::common::{DataFusionError, HashSet, ScalarValue};
+use datafusion::execution::memory_pool::{MemoryConsumer, MemoryReservation};
+use datafusion::logical_expr::ColumnarValue;
+use datafusion::physical_expr::{EquivalenceProperties, PhysicalExpr};
+use datafusion::physical_plan::execution_plan::{Boundedness, EmissionType};
+use datafusion::physical_plan::metrics::{BaselineMetrics, ExecutionPlanMetricsSet, MetricsSet};
+use datafusion::{
+ execution::TaskContext,
+ physical_plan::{
+ apply_expression_roots, ChildrenPropertiesMode, DisplayAs, DisplayFormatType,
+ ExecutionPlan, Partitioning, PlanProperties, RecordBatchStream, ReplaceChildrenOptions,
+ SendableRecordBatchStream,
+ },
+};
+use datafusion_comet_common::{cast_and_stamp_schema, SparkError};
+use futures::{Stream, StreamExt};
+use std::{
+ pin::Pin,
+ sync::Arc,
+ task::{Context, Poll},
+};
+
+/// A MergeRows instruction: condition plus zero (Discard), one (Keep), or two (Split)
+/// output row projections.
+#[derive(Debug, Clone)]
+pub struct MergeInstructionExec {
+ pub condition: Arc<dyn PhysicalExpr>,
+ pub outputs: Vec<Vec<Arc<dyn PhysicalExpr>>>,
+}
+
+#[derive(Debug)]
+struct MergeConfig {
+ is_source_row_present: Arc<dyn PhysicalExpr>,
+ is_target_row_present: Arc<dyn PhysicalExpr>,
+ matched_instructions: Vec<MergeInstructionExec>,
+ not_matched_instructions: Vec<MergeInstructionExec>,
+ not_matched_by_source_instructions: Vec<MergeInstructionExec>,
+ row_id_ordinal: Option<usize>,
+}
+
+impl MergeConfig {
+ fn validate(
+ &self,
+ child: &Arc<dyn ExecutionPlan>,
+ output_schema: &SchemaRef,
+ ) -> Result<(), DataFusionError> {
+ if let Some(ordinal) = self.row_id_ordinal {
+ let child_schema = child.schema();
+ let child_fields = child_schema.fields().len();
+ if ordinal >= child_fields {
+ return Err(DataFusionError::Internal(format!(
+ "MergeRows: row id ordinal {ordinal} is out of range for a child with \
+ {child_fields} columns"
+ )));
+ }
+ let data_type = child_schema.field(ordinal).data_type();
+ if data_type != &DataType::Int64 {
+ return Err(DataFusionError::Internal(format!(
+ "MergeRows: row id column at ordinal {ordinal} must be Int64, got {data_type}"
+ )));
+ }
+ }
+
+ let output_width = output_schema.fields().len();
+ for (group, instructions) in [
+ ("matched", &self.matched_instructions),
+ ("not matched", &self.not_matched_instructions),
+ (
+ "not matched by source",
+ &self.not_matched_by_source_instructions,
+ ),
+ ] {
+ for (instruction_index, instruction) in instructions.iter().enumerate() {
+ if instruction.outputs.len() > 2 {
+ return Err(DataFusionError::Internal(format!(
+ "MergeRows: {group} instruction {instruction_index} has {} output rows; expected at most 2",
+ instruction.outputs.len()
+ )));
+ }
+ for (output_index, output) in instruction.outputs.iter().enumerate() {
+ if output.len() != output_width {
+ return Err(DataFusionError::Internal(format!(
+ "MergeRows: {group} instruction {instruction_index} output {output_index} has {} expressions; expected {output_width}",
+ output.len()
+ )));
+ }
+ }
+ }
+ }
+ Ok(())
+ }
+}
+
+#[derive(Debug)]
+pub struct MergeRowsExec {
+ config: Arc<MergeConfig>,
+ child: Arc<dyn ExecutionPlan>,
+ schema: SchemaRef,
+ cache: Arc<PlanProperties>,
+ metrics: ExecutionPlanMetricsSet,
+}
+
+impl MergeRowsExec {
+ #[allow(clippy::too_many_arguments)]
+ pub fn try_new(
+ is_source_row_present: Arc<dyn PhysicalExpr>,
+ is_target_row_present: Arc<dyn PhysicalExpr>,
+ matched_instructions: Vec<MergeInstructionExec>,
+ not_matched_instructions: Vec<MergeInstructionExec>,
+ not_matched_by_source_instructions: Vec<MergeInstructionExec>,
+ row_id_ordinal: Option<usize>,
+ child: Arc<dyn ExecutionPlan>,
+ schema: SchemaRef,
+ ) -> Result<Self, DataFusionError> {
+ let config = Arc::new(MergeConfig {
+ is_source_row_present,
+ is_target_row_present,
+ matched_instructions,
+ not_matched_instructions,
+ not_matched_by_source_instructions,
+ row_id_ordinal,
+ });
+ config.validate(&child, &schema)?;
+
+ let cache = Arc::new(PlanProperties::new(
+ EquivalenceProperties::new(Arc::clone(&schema)),
+ Partitioning::UnknownPartitioning(1),
+ EmissionType::Incremental,
+ Boundedness::Bounded,
+ ));
+
+ Ok(Self {
+ config,
+ child,
+ schema,
+ cache,
+ metrics: ExecutionPlanMetricsSet::new(),
+ })
+ }
+}
+
+impl DisplayAs for MergeRowsExec {
+ fn fmt_as(&self, t: DisplayFormatType, f: &mut std::fmt::Formatter) -> std::fmt::Result {
+ match t {
+ DisplayFormatType::Default | DisplayFormatType::Verbose => {
+ write!(f, "CometMergeRowsExec")
+ }
+ DisplayFormatType::TreeRender => unimplemented!(),
+ }
+ }
+}
+
+impl ExecutionPlan for MergeRowsExec {
+ fn schema(&self) -> SchemaRef {
+ Arc::clone(&self.schema)
+ }
+
+ fn children(&self) -> Vec<&Arc<dyn ExecutionPlan>> {
+ vec![&self.child]
+ }
+
+ fn replace_children(
+ self: Arc<Self>,
+ children: Vec<Arc<dyn ExecutionPlan>>,
+ _options: ReplaceChildrenOptions,
+ ) -> datafusion::common::Result<Arc<dyn ExecutionPlan>> {
+ let [child] = children.as_slice() else {
+ return Err(DataFusionError::Internal(format!(
+ "MergeRows expects exactly one child, got {}",
+ children.len()
+ )));
+ };
+ let child = Arc::clone(child);
+ self.config.validate(&child, &self.schema)?;
+ Ok(Arc::new(MergeRowsExec {
+ config: Arc::clone(&self.config),
+ child,
+ schema: Arc::clone(&self.schema),
+ cache: Arc::clone(&self.cache),
+ metrics: self.metrics.clone(),
+ }))
+ }
+
+ fn apply_expressions(
+ &self,
+ f: &mut dyn FnMut(&Arc<dyn PhysicalExpr>) -> datafusion::common::Result<TreeNodeRecursion>,
+ ) -> datafusion::common::Result<TreeNodeRecursion> {
+ let instructions = self
+ .config
+ .matched_instructions
+ .iter()
+ .chain(self.config.not_matched_instructions.iter())
+ .chain(self.config.not_matched_by_source_instructions.iter());
+ let instruction_expressions = instructions.flat_map(|instruction| {
+ std::iter::once(&instruction.condition)
+ .chain(instruction.outputs.iter().flat_map(|output| output.iter()))
+ });
+
+ apply_expression_roots(
+ [
+ &self.config.is_source_row_present,
+ &self.config.is_target_row_present,
+ ]
+ .into_iter()
+ .chain(instruction_expressions),
+ f,
+ )
+ }
+
+ fn with_new_children(
+ self: Arc<Self>,
+ children: Vec<Arc<dyn ExecutionPlan>>,
+ ) -> datafusion::common::Result<Arc<dyn ExecutionPlan>> {
+ self.replace_children(
+ children,
+ ReplaceChildrenOptions::new(ChildrenPropertiesMode::Recompute),
+ )
+ }
+
+ fn execute(
+ &self,
+ partition: usize,
+ context: Arc<TaskContext>,
+ ) -> datafusion::common::Result<SendableRecordBatchStream> {
+ let reservation = self.config.row_id_ordinal.map(|_| {
+ MemoryConsumer::new(format!("CometMergeRowsExec[{partition}]"))
+ .register(&context.runtime_env().memory_pool)
+ });
+ let child_stream = self.child.execute(partition, Arc::clone(&context))?;
+ Ok(Box::pin(MergeRowsStream {
+ config: Arc::clone(&self.config),
+ child_stream,
+ schema: Arc::clone(&self.schema),
+ seen: HashSet::new(),
+ reservation,
+ baseline: BaselineMetrics::new(&self.metrics, partition),
+ }))
+ }
+
+ fn properties(&self) -> &Arc<PlanProperties> {
+ &self.cache
+ }
+
+ fn metrics(&self) -> Option<MetricsSet> {
+ Some(self.metrics.clone_inner())
+ }
+
+ fn name(&self) -> &str {
+ "CometMergeRowsExec"
+ }
+}
+
+pub struct MergeRowsStream {
+ config: Arc<MergeConfig>,
+ child_stream: SendableRecordBatchStream,
+ schema: SchemaRef,
+ // Partition-scoped so duplicate matches across Arrow batches are still detected.
+ seen: HashSet<i64>,
+ reservation: Option<MemoryReservation>,
+ baseline: BaselineMetrics,
+}
+
+const SEEN_FIXED_BYTES: usize = std::mem::size_of::<HashSet<i64>>();
+// Covers hashbrown's mirrored control group and minimum small-table allocation.
+const SEEN_HASH_TABLE_SLACK_BYTES: usize = 64;
+
+fn estimate_seen_memory_size(num_elements: usize) -> Result<usize, DataFusionError> {
+ estimate_memory_size::<i64>(num_elements, SEEN_FIXED_BYTES)?
+ .checked_add(SEEN_HASH_TABLE_SLACK_BYTES)
+ .ok_or_else(|| {
+ DataFusionError::ResourcesExhausted(
+ "MergeRows: cardinality memory estimate overflow".to_string(),
+ )
+ })
+}
+
+/// Spark predicates treat NULL as false; Arrow boolean kernels preserve NULL.
+fn null_to_false(array: &BooleanArray) -> BooleanArray {
+ if array.null_count() == 0 {
+ array.clone()
+ } else {
+ prep_null_mask_filter(array)
+ }
+}
+
+fn eval_bool(
+ expr: &Arc<dyn PhysicalExpr>,
+ batch: &RecordBatch,
+) -> Result<BooleanArray, DataFusionError> {
+ let array: ArrayRef = expr.evaluate(batch)?.into_array(batch.num_rows())?;
+ array
+ .as_any()
+ .downcast_ref::<BooleanArray>()
+ .map(null_to_false)
+ .ok_or_else(|| DataFusionError::Internal("MergeRows: expected boolean array".to_string()))
+}
+
+fn project(
+ batch: &RecordBatch,
+ exprs: &[Arc<dyn PhysicalExpr>],
+ schema: &SchemaRef,
+) -> Result<RecordBatch, DataFusionError> {
+ let mut columns = Vec::with_capacity(exprs.len());
+ for expr in exprs {
+ columns.push(expr.evaluate(batch)?.into_array(batch.num_rows())?);
+ }
+ // Different instructions can infer different nested nullability for the same output column.
+ cast_and_stamp_schema("MergeRows", schema, columns, batch.num_rows())
+}
+
+fn filter_or_pass_through(
+ batch: &RecordBatch,
+ mask: &BooleanArray,
+) -> Result<RecordBatch, DataFusionError> {
+ if mask.true_count() == batch.num_rows() {
+ Ok(batch.clone())
+ } else {
+ filter_record_batch(batch, mask).map_err(|e| e.into())
+ }
+}
+
+/// Applies an ordered instruction group with Spark's first-match-wins semantics.
+/// Output is grouped by the producing instruction; no physical row ordering is advertised.
+fn run_group(
+ batch: &RecordBatch,
+ group_mask: &BooleanArray,
+ instructions: &[MergeInstructionExec],
+ schema: &SchemaRef,
+) -> Result<Vec<RecordBatch>, DataFusionError> {
+ if instructions.is_empty() || group_mask.true_count() == 0 {
+ return Ok(vec![]);
+ }
+
+ // Only rows routed to this group may evaluate its clause predicates.
+ let mut current = filter_or_pass_through(batch, group_mask)?;
+ let mut out = Vec::new();
+ let last = instructions.len() - 1;
+
+ for (idx, instr) in instructions.iter().enumerate() {
+ if current.num_rows() == 0 {
+ break;
+ }
+
+ // Remove claimed rows before evaluating later clauses. This matters for ANSI errors in
+ // predicates that Spark would never evaluate after an earlier clause matched.
+ let fire = match instr.condition.evaluate(¤t)? {
+ ColumnarValue::Scalar(ScalarValue::Boolean(Some(true))) => {
+ BooleanArray::from(vec![true; current.num_rows()])
+ }
+ ColumnarValue::Scalar(ScalarValue::Boolean(Some(false) | None)) => continue,
+ value => value
+ .into_array(current.num_rows())?
+ .as_any()
+ .downcast_ref::<BooleanArray>()
+ .map(null_to_false)
+ .ok_or_else(|| {
+ DataFusionError::Internal("MergeRows: expected boolean array".to_string())
+ })?,
+ };
+
+ if fire.true_count() == 0 {
+ continue;
+ }
+
+ let filtered = filter_or_pass_through(¤t, &fire)?;
+ for output_exprs in &instr.outputs {
+ out.push(project(&filtered, output_exprs, schema)?);
+ }
+
+ if idx != last {
+ current = if fire.true_count() == current.num_rows() {
+ current.slice(0, 0)
+ } else {
+ filter_record_batch(¤t, ¬(&fire)?)?
+ };
+ }
+ }
+
+ Ok(out)
+}
+
+fn cardinality_violation() -> DataFusionError {
+ DataFusionError::External(Box::new(SparkError::MergeCardinalityViolation))
+}
+
+fn reserve_seen_growth(
+ seen: &mut HashSet<i64>,
+ reservation: &mut MemoryReservation,
+) -> Result<(), DataFusionError> {
+ let next_len = seen.len().checked_add(1).ok_or_else(|| {
+ DataFusionError::ResourcesExhausted(
+ "MergeRows: cardinality set length overflow".to_string(),
+ )
+ })?;
+ let projected_bytes = estimate_seen_memory_size(next_len)?;
+ let additional = projected_bytes.saturating_sub(reservation.size());
+ reservation.try_grow(additional)?;
+
+ if let Err(e) = seen.try_reserve(1) {
+ if additional != 0 {
+ reservation.shrink(additional);
+ }
+ return Err(DataFusionError::ResourcesExhausted(format!(
+ "MergeRows: failed to allocate cardinality set: {e}"
+ )));
+ }
+ Ok(())
+}
+
+/// Detects a target row matched by more than one source row.
+fn check_cardinality(
+ batch: &RecordBatch,
+ matched_mask: &BooleanArray,
+ row_id_ordinal: usize,
+ seen: &mut HashSet<i64>,
+ reservation: &mut MemoryReservation,
+) -> Result<(), DataFusionError> {
+ let row_ids = batch
+ .column(row_id_ordinal)
+ .as_any()
+ .downcast_ref::<Int64Array>()
+ .ok_or_else(|| {
+ DataFusionError::Internal("MergeRows: row id column must be Int64".to_string())
+ })?;
+
+ for i in matched_mask.values().set_indices() {
+ // Spark's row-id read treats a null long slot as zero.
+ let id = if row_ids.is_null(i) {
+ 0
+ } else {
+ row_ids.value(i)
+ };
+
+ if seen.len() < seen.capacity() {
+ if !seen.insert(id) {
+ return Err(cardinality_violation());
+ }
+ } else {
+ // Preserve Spark's error precedence: detect duplicates before memory admission.
+ if seen.contains(&id) {
+ return Err(cardinality_violation());
+ }
+ reserve_seen_growth(seen, reservation)?;
+ seen.insert(id);
+ }
+ }
+ Ok(())
+}
+
+fn process_batch(
+ batch: RecordBatch,
+ config: &MergeConfig,
+ seen: &mut HashSet<i64>,
+ reservation: Option<&mut MemoryReservation>,
+ schema: &SchemaRef,
+) -> Result<RecordBatch, DataFusionError> {
+ let source_present = eval_bool(&config.is_source_row_present, &batch)?;
+ let target_present = eval_bool(&config.is_target_row_present, &batch)?;
+
+ let matched_mask = and(&target_present, &source_present)?;
+ let not_matched_mask = and_not(&source_present, &target_present)?;
+ let not_matched_by_source_mask = and_not(&target_present, &source_present)?;
+
+ // Vectorized cardinality validation can surface before an unrelated per-row expression error;
+ // both paths fail the query, but the error selected can differ from Spark in that rare case.
+ if let Some(row_id_ordinal) = config.row_id_ordinal {
+ let reservation = reservation.ok_or_else(|| {
+ DataFusionError::Internal(
+ "MergeRows: cardinality checking requires a memory reservation".to_string(),
+ )
+ })?;
+ check_cardinality(&batch, &matched_mask, row_id_ordinal, seen, reservation)?;
+ }
+
+ let mut batches = Vec::new();
+ for (mask, instructions) in [
+ (&matched_mask, &config.matched_instructions),
+ (¬_matched_mask, &config.not_matched_instructions),
+ (
+ ¬_matched_by_source_mask,
+ &config.not_matched_by_source_instructions,
+ ),
+ ] {
+ batches.extend(run_group(&batch, mask, instructions, schema)?);
+ }
+
+ if batches.is_empty() {
+ return Ok(RecordBatch::new_empty(Arc::clone(schema)));
+ }
+
+ arrow::compute::concat_batches(schema, &batches).map_err(|e| e.into())
+}
+
+// Bound synchronous all-discard processing so a delete-heavy stream yields cooperatively.
+const MAX_DISCARDED_BATCHES_PER_POLL: u32 = 128;
+
+impl Stream for MergeRowsStream {
+ type Item = datafusion::common::Result<RecordBatch>;
+
+ fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
+ let this = self.get_mut();
+ let mut discarded_budget = MAX_DISCARDED_BATCHES_PER_POLL;
+ loop {
+ let poll = match this.child_stream.poll_next_unpin(cx) {
+ Poll::Ready(Some(Ok(batch))) => {
+ // Keep elapsed_compute scoped to this operator, not the upstream poll.
+ let _timer = this.baseline.elapsed_compute().timer();
+ let result = process_batch(
+ batch,
+ &this.config,
+ &mut this.seen,
+ this.reservation.as_mut(),
+ &this.schema,
+ );
+ match result {
+ Ok(batch) if batch.num_rows() == 0 => {
+ discarded_budget -= 1;
+ if discarded_budget == 0 {
+ cx.waker().wake_by_ref();
+ return Poll::Pending;
+ }
+ continue;
+ }
+ other => Poll::Ready(Some(other)),
+ }
+ }
+ other => other,
+ };
+ return this.baseline.record_poll(poll);
+ }
+ }
+}
+
+impl RecordBatchStream for MergeRowsStream {
+ fn schema(&self) -> SchemaRef {
+ Arc::clone(&self.schema)
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use arrow::array::{Int32Array, StructArray};
+ use arrow::datatypes::{Field, Schema};
+ use datafusion::execution::memory_pool::{GreedyMemoryPool, MemoryPool, UnboundedMemoryPool};
+ use datafusion::execution::runtime_env::RuntimeEnvBuilder;
+ use datafusion::logical_expr::Operator as DFOperator;
+ use datafusion::physical_expr::expressions::{binary, col, lit};
+ use std::sync::atomic::{AtomicUsize, Ordering};
+
+ #[derive(Debug, Default)]
+ struct RegistrationCountingPool {
+ inner: UnboundedMemoryPool,
+ merge_rows_registrations: AtomicUsize,
+ }
+
+ impl std::fmt::Display for RegistrationCountingPool {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ write!(f, "RegistrationCountingPool")
+ }
+ }
+
+ impl MemoryPool for RegistrationCountingPool {
+ fn name(&self) -> &str {
+ "RegistrationCountingPool"
+ }
+
+ fn register(&self, consumer: &MemoryConsumer) {
+ if consumer.name().starts_with("CometMergeRowsExec[") {
+ self.merge_rows_registrations.fetch_add(1, Ordering::SeqCst);
+ }
+ self.inner.register(consumer);
+ }
+
+ fn unregister(&self, consumer: &MemoryConsumer) {
+ self.inner.unregister(consumer);
+ if consumer.name().starts_with("CometMergeRowsExec[") {
+ self.merge_rows_registrations.fetch_sub(1, Ordering::SeqCst);
+ }
+ }
+
+ fn grow(&self, reservation: &MemoryReservation, additional: usize) {
+ self.inner.grow(reservation, additional);
+ }
+
+ fn shrink(&self, reservation: &MemoryReservation, subtractive: usize) {
+ self.inner.shrink(reservation, subtractive);
+ }
+
+ fn try_grow(
+ &self,
+ reservation: &MemoryReservation,
+ additional: usize,
+ ) -> Result<(), DataFusionError> {
+ self.inner.try_grow(reservation, additional)
+ }
+
+ fn reserved(&self) -> usize {
+ self.inner.reserved()
+ }
+ }
+
+ fn task_context_with_registration_counter(
+ pool: &Arc<RegistrationCountingPool>,
+ ) -> Arc<TaskContext> {
+ let memory_pool = Arc::clone(pool) as Arc<dyn MemoryPool>;
+ let runtime = RuntimeEnvBuilder::new()
+ .with_memory_pool(memory_pool)
+ .build_arc()
+ .unwrap();
+ Arc::new(TaskContext::default().with_runtime(runtime))
+ }
+
+ fn test_schema() -> SchemaRef {
+ Arc::new(Schema::new(vec![
+ Field::new("row_id", DataType::Int64, true),
+ Field::new("val", DataType::Int32, true),
+ Field::new("target_present", DataType::Boolean, false),
+ Field::new("source_present", DataType::Boolean, false),
+ ]))
+ }
+
+ fn test_batch(
+ row_ids: Vec<i64>,
+ vals: Vec<i32>,
+ target: Vec<bool>,
+ source: Vec<bool>,
+ ) -> RecordBatch {
+ RecordBatch::try_new(
+ test_schema(),
+ vec![
+ Arc::new(Int64Array::from(row_ids)),
+ Arc::new(Int32Array::from(vals)),
+ Arc::new(BooleanArray::from(target)),
+ Arc::new(BooleanArray::from(source)),
+ ],
+ )
+ .unwrap()
+ }
+
+ fn test_reservation() -> MemoryReservation {
+ let pool: Arc<dyn MemoryPool> = Arc::new(UnboundedMemoryPool::default());
+ MemoryConsumer::new("test").register(&pool)
+ }
+
+ fn out_schema() -> SchemaRef {
+ Arc::new(Schema::new(vec![Field::new("val", DataType::Int32, true)]))
+ }
+
+ fn keep_all() -> MergeInstructionExec {
+ MergeInstructionExec {
+ condition: lit(true),
+ outputs: vec![vec![col("val", &test_schema()).unwrap()]],
+ }
+ }
+
+ fn discard_all() -> MergeInstructionExec {
+ MergeInstructionExec {
+ condition: lit(true),
+ outputs: vec![],
+ }
+ }
+
+ fn test_config(
+ matched_instructions: Vec<MergeInstructionExec>,
+ not_matched_instructions: Vec<MergeInstructionExec>,
+ not_matched_by_source_instructions: Vec<MergeInstructionExec>,
+ row_id_ordinal: Option<usize>,
+ ) -> MergeConfig {
+ MergeConfig {
+ is_source_row_present: col("source_present", &test_schema()).unwrap(),
+ is_target_row_present: col("target_present", &test_schema()).unwrap(),
+ matched_instructions,
+ not_matched_instructions,
+ not_matched_by_source_instructions,
+ row_id_ordinal,
+ }
+ }
+
+ #[test]
+ fn keep_matched_discard_rest() {
+ let batch = test_batch(
+ vec![1, 2, 3],
+ vec![10, 20, 30],
+ vec![true, false, true],
+ vec![true, true, false],
+ );
+ let config = test_config(
+ vec![keep_all()],
+ vec![keep_all()],
+ vec![discard_all()],
+ None,
+ );
+ let out = process_batch(
+ batch,
+ &config,
+ &mut HashSet::new(),
+ Some(&mut test_reservation()),
+ &out_schema(),
+ )
+ .unwrap();
+ let vals = out.column(0).as_any().downcast_ref::<Int32Array>().unwrap();
+ let mut got: Vec<i32> = vals.iter().flatten().collect();
+ got.sort();
+ assert_eq!(got, vec![10, 20]);
+ }
+
+ #[test]
+ fn first_match_wins_ordering() {
+ let batch = test_batch(vec![1], vec![5], vec![true], vec![true]);
+ let cond_false = MergeInstructionExec {
+ condition: binary(
+ col("val", &test_schema()).unwrap(),
+ DFOperator::Gt,
+ lit(100i32),
+ &test_schema(),
+ )
+ .unwrap(),
+ outputs: vec![vec![lit(1i32)]],
+ };
+ let cond_true = MergeInstructionExec {
+ condition: lit(true),
+ outputs: vec![vec![lit(2i32)]],
+ };
+ let config = test_config(vec![cond_false, cond_true], vec![], vec![], None);
+ let out = process_batch(
+ batch,
+ &config,
+ &mut HashSet::new(),
+ Some(&mut test_reservation()),
+ &out_schema(),
+ )
+ .unwrap();
+ let vals = out.column(0).as_any().downcast_ref::<Int32Array>().unwrap();
+ assert_eq!(vals.value(0), 2);
+ }
+
+ #[test]
+ fn later_condition_is_not_evaluated_on_an_already_claimed_row() {
+ let batch = test_batch(vec![1, 2], vec![0, 2], vec![true, true], vec![true, true]);
+ let claims_zero = MergeInstructionExec {
+ condition: binary(
+ col("val", &test_schema()).unwrap(),
+ DFOperator::Eq,
+ lit(0i32),
+ &test_schema(),
+ )
+ .unwrap(),
+ outputs: vec![vec![lit(111i32)]],
+ };
+ let divides_by_val = MergeInstructionExec {
+ condition: binary(
+ binary(
+ lit(2i32),
+ DFOperator::Divide,
+ col("val", &test_schema()).unwrap(),
+ &test_schema(),
+ )
+ .unwrap(),
+ DFOperator::Gt,
+ lit(0i32),
+ &test_schema(),
+ )
+ .unwrap(),
+ outputs: vec![vec![lit(222i32)]],
+ };
+ let config = test_config(vec![claims_zero, divides_by_val], vec![], vec![], None);
+ let out = process_batch(
+ batch,
+ &config,
+ &mut HashSet::new(),
+ Some(&mut test_reservation()),
+ &out_schema(),
+ )
+ .unwrap();
+ let vals = out.column(0).as_any().downcast_ref::<Int32Array>().unwrap();
+ let mut got: Vec<i32> = vals.iter().flatten().collect();
+ got.sort();
+ assert_eq!(got, vec![111, 222]);
+ }
+
+ #[test]
+ fn null_condition_falls_through_to_next_instruction() {
+ let batch = RecordBatch::try_new(
+ test_schema(),
+ vec![
+ Arc::new(Int64Array::from(vec![1i64])),
+ Arc::new(Int32Array::from(vec![None::<i32>])),
+ Arc::new(BooleanArray::from(vec![true])),
+ Arc::new(BooleanArray::from(vec![true])),
+ ],
+ )
+ .unwrap();
+ let cond_null = MergeInstructionExec {
+ condition: binary(
+ col("val", &test_schema()).unwrap(),
+ DFOperator::Gt,
+ lit(100i32),
+ &test_schema(),
+ )
+ .unwrap(),
+ outputs: vec![vec![lit(1i32)]],
+ };
+ let keep_catch_all = MergeInstructionExec {
+ condition: lit(true),
+ outputs: vec![vec![lit(2i32)]],
+ };
+ let config = test_config(vec![cond_null, keep_catch_all], vec![], vec![], None);
+ let out = process_batch(
+ batch,
+ &config,
+ &mut HashSet::new(),
+ Some(&mut test_reservation()),
+ &out_schema(),
+ )
+ .unwrap();
+ assert_eq!(
+ out.num_rows(),
+ 1,
+ "row with a NULL clause condition must fall through to the catch-all Keep, not \
+ disappear from the rewritten data file"
+ );
+ let vals = out.column(0).as_any().downcast_ref::<Int32Array>().unwrap();
+ assert_eq!(vals.value(0), 2);
+ }
+
+ #[test]
+ fn null_row_presence_flag_treated_as_false() {
+ let schema = Arc::new(Schema::new(vec![
+ Field::new("row_id", DataType::Int64, true),
+ Field::new("val", DataType::Int32, true),
+ Field::new("target_present", DataType::Boolean, true),
+ Field::new("source_present", DataType::Boolean, true),
+ ]));
+ let batch = RecordBatch::try_new(
+ Arc::clone(&schema),
+ vec![
+ Arc::new(Int64Array::from(vec![1i64])),
+ Arc::new(Int32Array::from(vec![10])),
+ Arc::new(BooleanArray::from(vec![Some(true)])),
+ Arc::new(BooleanArray::from(vec![None::<bool>])),
+ ],
+ )
+ .unwrap();
+ let config = MergeConfig {
+ is_source_row_present: col("source_present", &schema).unwrap(),
+ is_target_row_present: col("target_present", &schema).unwrap(),
+ matched_instructions: vec![],
+ not_matched_instructions: vec![],
+ not_matched_by_source_instructions: vec![MergeInstructionExec {
+ condition: lit(true),
+ outputs: vec![vec![col("val", &schema).unwrap()]],
+ }],
+ row_id_ordinal: None,
+ };
+ let out = process_batch(
+ batch,
+ &config,
+ &mut HashSet::new(),
+ Some(&mut test_reservation()),
+ &out_schema(),
+ )
+ .unwrap();
+ assert_eq!(out.num_rows(), 1);
+ let vals = out.column(0).as_any().downcast_ref::<Int32Array>().unwrap();
+ assert_eq!(vals.value(0), 10);
+ }
+
+ #[test]
+ fn condition_not_evaluated_outside_its_group() {
+ let batch = test_batch(vec![1, 2], vec![0, 5], vec![true, false], vec![true, true]);
+ let div_cond = MergeInstructionExec {
+ condition: binary(
+ binary(
+ lit(10i32),
+ DFOperator::Divide,
+ col("val", &test_schema()).unwrap(),
+ &test_schema(),
+ )
+ .unwrap(),
+ DFOperator::Gt,
+ lit(1i32),
+ &test_schema(),
+ )
+ .unwrap(),
+ outputs: vec![vec![col("val", &test_schema()).unwrap()]],
+ };
+ assert!(
+ eval_bool(&div_cond.condition, &batch).is_err(),
+ "test is only meaningful if batch-wide evaluation of this condition errors"
+ );
+ let config = test_config(vec![keep_all()], vec![div_cond], vec![], None);
+ let out = process_batch(
+ batch,
+ &config,
+ &mut HashSet::new(),
+ Some(&mut test_reservation()),
+ &out_schema(),
+ )
+ .expect("not-matched condition must not be evaluated against the matched row");
+ let vals = out.column(0).as_any().downcast_ref::<Int32Array>().unwrap();
+ let mut got: Vec<i32> = vals.iter().flatten().collect();
+ got.sort();
+ assert_eq!(got, vec![0, 5]);
+ }
+
+ fn bounded_reservation(limit: usize) -> MemoryReservation {
+ let pool: Arc<dyn MemoryPool> = Arc::new(GreedyMemoryPool::new(limit));
+ MemoryConsumer::new("test").register(&pool)
+ }
+
+ fn run_cardinality(
+ n: usize,
+ batch_rows: usize,
+ reservation: &mut MemoryReservation,
+ ) -> Result<HashSet<i64>, DataFusionError> {
+ let mut seen = HashSet::new();
+ let mut next = 0i64;
+ while (next as usize) < n {
+ let end = ((next as usize) + batch_rows).min(n) as i64;
+ let ids: Vec<i64> = (next..end).collect();
+ let len = ids.len();
+ let batch = test_batch(ids, vec![0; len], vec![true; len], vec![true; len]);
+ let mask = BooleanArray::from(vec![true; len]);
+ check_cardinality(&batch, &mask, 0, &mut seen, reservation)?;
+ next = end;
+ }
+ Ok(seen)
+ }
+
+ fn assert_seen_fully_reserved(seen: &HashSet<i64>, reservation: &MemoryReservation) {
+ let actual = seen.allocation_size().saturating_add(SEEN_FIXED_BYTES);
+ assert!(
+ reservation.size() >= actual,
+ "reserved {} bytes < actual HashSet footprint {} bytes (len={}, capacity={})",
+ reservation.size(),
+ actual,
+ seen.len(),
+ seen.capacity()
+ );
+ }
+
+ #[test]
+ fn insert_only_merge_does_not_register_memory_consumer() {
+ use datafusion::datasource::memory::MemorySourceConfig;
+
+ let source = MemorySourceConfig::try_new_exec(&[vec![]], test_schema(), None).unwrap();
+ let exec = MergeRowsExec::try_new(
+ col("source_present", &test_schema()).unwrap(),
+ col("target_present", &test_schema()).unwrap(),
+ vec![],
+ vec![keep_all()],
+ vec![],
+ None,
+ source,
+ out_schema(),
+ )
+ .unwrap();
+ let pool = Arc::new(RegistrationCountingPool::default());
+ let stream = exec
+ .execute(0, task_context_with_registration_counter(&pool))
+ .unwrap();
+
+ assert_eq!(
+ pool.merge_rows_registrations.load(Ordering::SeqCst),
+ 0,
+ "insert-only MERGE must not register an unused memory consumer"
+ );
+ drop(stream);
+ assert_eq!(pool.merge_rows_registrations.load(Ordering::SeqCst), 0);
+ }
+
+ #[test]
+ fn cardinality_merge_registers_memory_consumer() {
+ use datafusion::datasource::memory::MemorySourceConfig;
+
+ let source = MemorySourceConfig::try_new_exec(&[vec![]], test_schema(), None).unwrap();
+ let exec = MergeRowsExec::try_new(
+ col("source_present", &test_schema()).unwrap(),
+ col("target_present", &test_schema()).unwrap(),
+ vec![keep_all()],
+ vec![],
+ vec![],
+ Some(0),
+ source,
+ out_schema(),
+ )
+ .unwrap();
+ let pool = Arc::new(RegistrationCountingPool::default());
+ let stream = exec
+ .execute(0, task_context_with_registration_counter(&pool))
+ .unwrap();
+
+ assert_eq!(pool.merge_rows_registrations.load(Ordering::SeqCst), 1);
+ drop(stream);
+ assert_eq!(
+ pool.merge_rows_registrations.load(Ordering::SeqCst),
+ 0,
+ "dropping the stream must unregister the memory consumer"
+ );
+ }
+
+ #[test]
+ fn cardinality_state_is_accounted_to_the_memory_pool() {
+ let mut reservation = test_reservation();
+ let seen = run_cardinality(9, 4, &mut reservation).unwrap();
+ assert!(
+ reservation.size() > 0,
+ "`seen` must be visible to the memory pool"
+ );
+ assert_seen_fully_reserved(&seen, &reservation);
+ }
+
+ #[test]
+ fn cardinality_reservation_covers_actual_hashbrown_allocations() {
+ for &(n, batch_rows) in &[
+ (1usize, 1usize),
+ (2, 1),
+ (3, 1),
+ (7, 1),
+ (8, 1),
+ (9, 1),
+ (17, 1),
+ (64, 8),
+ (200, 16),
+ ] {
+ let mut reservation = test_reservation();
+ let seen = run_cardinality(n, batch_rows, &mut reservation).unwrap();
+ assert_seen_fully_reserved(&seen, &reservation);
+ }
+ }
+
+ #[test]
+ fn cardinality_state_cannot_exceed_a_bounded_pool() {
+ let n = 917_505;
+ let mut reservation = bounded_reservation(16 * 1024 * 1024);
+ let err = run_cardinality(n, 4096, &mut reservation).unwrap_err();
+ assert!(
+ matches!(err, DataFusionError::ResourcesExhausted(_)),
+ "expected the pool to reject the oversized cardinality table, got {err}"
+ );
+
+ let needed = estimate_seen_memory_size(n).unwrap();
+ let mut ok_reservation = bounded_reservation(needed + 8 * 1024 * 1024);
+ let seen = run_cardinality(n, 4096, &mut ok_reservation).unwrap();
+ assert_eq!(seen.len(), n);
+ assert_seen_fully_reserved(&seen, &ok_reservation);
+ }
+
+ #[test]
+ fn cardinality_violation_wins_over_memory_exhaustion() {
+ let mut seen = HashSet::new();
+ let mut warmup_reservation = test_reservation();
+ let mut next_id = 1i64;
+
+ while seen.len() < seen.capacity().max(1) {
+ let batch = test_batch(vec![next_id], vec![0], vec![true], vec![true]);
+ check_cardinality(
+ &batch,
+ &BooleanArray::from(vec![true]),
+ 0,
+ &mut seen,
+ &mut warmup_reservation,
+ )
+ .unwrap();
+ next_id += 1;
+ }
+ assert_eq!(seen.len(), seen.capacity(), "table must be full");
+
+ let duplicate = test_batch(vec![1], vec![0], vec![true], vec![true]);
+ let mut zero_budget = bounded_reservation(0);
+ let duplicate_err = check_cardinality(
+ &duplicate,
+ &BooleanArray::from(vec![true]),
+ 0,
+ &mut seen,
+ &mut zero_budget,
+ )
+ .unwrap_err();
+ assert!(
+ duplicate_err
+ .to_string()
+ .contains("MERGE_CARDINALITY_VIOLATION"),
+ "expected cardinality violation before pool admission, got {duplicate_err}"
+ );
+
+ let new_id = test_batch(vec![next_id], vec![0], vec![true], vec![true]);
+ let memory_err = check_cardinality(
+ &new_id,
+ &BooleanArray::from(vec![true]),
+ 0,
+ &mut seen,
+ &mut zero_budget,
+ )
+ .unwrap_err();
+ assert!(
+ matches!(memory_err, DataFusionError::ResourcesExhausted(_)),
+ "expected memory exhaustion for a new id at capacity, got {memory_err}"
+ );
+ }
+
+ #[test]
+ fn cardinality_violation_detected() {
+ let batch = test_batch(vec![1, 1], vec![10, 20], vec![true, true], vec![true, true]);
+ let matched_mask = BooleanArray::from(vec![true, true]);
+ let mut seen = HashSet::new();
+ let result =
+ check_cardinality(&batch, &matched_mask, 0, &mut seen, &mut test_reservation());
+ assert!(result.is_err());
+ assert!(result
+ .unwrap_err()
+ .to_string()
+ .contains("MERGE_CARDINALITY_VIOLATION"));
+ }
+
+ #[test]
+ fn split_produces_two_rows() {
+ let batch = test_batch(vec![1], vec![7], vec![true], vec![true]);
+ let split = MergeInstructionExec {
+ condition: lit(true),
+ outputs: vec![vec![lit(1i32)], vec![lit(2i32)]],
+ };
+ let config = test_config(vec![split], vec![], vec![], None);
+ let out = process_batch(
+ batch,
+ &config,
+ &mut HashSet::new(),
+ Some(&mut test_reservation()),
+ &out_schema(),
+ )
+ .unwrap();
+ let vals = out.column(0).as_any().downcast_ref::<Int32Array>().unwrap();
+ let got: Vec<i32> = vals.iter().flatten().collect();
+ assert_eq!(got, vec![1, 2]);
+ }
+
+ #[test]
+ fn cardinality_violation_detected_for_null_row_ids() {
+ let batch = RecordBatch::try_new(
+ test_schema(),
+ vec![
+ Arc::new(Int64Array::from(vec![None, None])),
+ Arc::new(Int32Array::from(vec![10, 20])),
+ Arc::new(BooleanArray::from(vec![true, true])),
+ Arc::new(BooleanArray::from(vec![true, true])),
+ ],
+ )
+ .unwrap();
+ let matched_mask = BooleanArray::from(vec![true, true]);
+ let result = check_cardinality(
+ &batch,
+ &matched_mask,
+ 0,
+ &mut HashSet::new(),
+ &mut test_reservation(),
+ );
+ assert!(result.is_err());
+ assert!(result
+ .unwrap_err()
+ .to_string()
+ .contains("MERGE_CARDINALITY_VIOLATION"));
+ }
+
+ #[tokio::test]
+ async fn all_discarded_batch_is_not_emitted() {
+ use datafusion::datasource::memory::MemorySourceConfig;
+ use datafusion::prelude::SessionContext;
+
+ let discarded = test_batch(vec![1], vec![10], vec![true], vec![true]);
+ let kept = test_batch(vec![2], vec![20], vec![false], vec![true]);
+ let source =
+ MemorySourceConfig::try_new_exec(&[vec![discarded, kept]], test_schema(), None)
+ .unwrap();
+
+ let exec = MergeRowsExec::try_new(
+ col("source_present", &test_schema()).unwrap(),
+ col("target_present", &test_schema()).unwrap(),
+ vec![discard_all()],
+ vec![keep_all()],
+ vec![],
+ None,
+ source,
+ out_schema(),
+ )
+ .unwrap();
+
+ let ctx = SessionContext::new();
+ let mut stream = exec.execute(0, ctx.task_ctx()).unwrap();
+ let mut batches = Vec::new();
+ while let Some(batch) = stream.next().await {
+ batches.push(batch.unwrap());
+ }
+ assert_eq!(batches.len(), 1);
+ assert_eq!(batches[0].num_rows(), 1);
+ }
+
+ #[test]
+ fn instruction_with_more_than_two_outputs_is_rejected() {
+ use datafusion::datasource::memory::MemorySourceConfig;
+ let source = MemorySourceConfig::try_new_exec(&[vec![]], test_schema(), None).unwrap();
+ let invalid = MergeInstructionExec {
+ condition: lit(true),
+ outputs: vec![vec![lit(1i32)], vec![lit(2i32)], vec![lit(3i32)]],
+ };
+ let err = MergeRowsExec::try_new(
+ col("source_present", &test_schema()).unwrap(),
+ col("target_present", &test_schema()).unwrap(),
+ vec![invalid],
+ vec![],
+ vec![],
+ None,
+ source,
+ out_schema(),
+ )
+ .unwrap_err();
+ assert!(err.to_string().contains("expected at most 2"));
+ }
+
+ #[test]
+ fn instruction_output_width_must_match_operator_schema() {
+ use datafusion::datasource::memory::MemorySourceConfig;
+ let source = MemorySourceConfig::try_new_exec(&[vec![]], test_schema(), None).unwrap();
+ let invalid = MergeInstructionExec {
+ condition: lit(true),
+ outputs: vec![vec![lit(1i32), lit(2i32)]],
+ };
+ let err = MergeRowsExec::try_new(
+ col("source_present", &test_schema()).unwrap(),
+ col("target_present", &test_schema()).unwrap(),
+ vec![invalid],
+ vec![],
+ vec![],
+ None,
+ source,
+ out_schema(),
+ )
+ .unwrap_err();
+ assert!(err.to_string().contains("expected 1"));
+ }
+
+ #[test]
+ fn out_of_range_row_id_ordinal_is_rejected() {
+ use datafusion::datasource::memory::MemorySourceConfig;
+ let source = MemorySourceConfig::try_new_exec(&[vec![]], test_schema(), None).unwrap();
+ let err = MergeRowsExec::try_new(
+ col("source_present", &test_schema()).unwrap(),
+ col("target_present", &test_schema()).unwrap(),
+ vec![keep_all()],
+ vec![],
+ vec![],
+ Some(99),
+ source,
+ out_schema(),
+ )
+ .unwrap_err();
+ assert!(err.to_string().contains("row id ordinal"));
+ }
+
+ #[test]
+ fn non_int64_row_id_is_rejected_at_plan_construction() {
+ use datafusion::datasource::memory::MemorySourceConfig;
+ let wrong_schema = Arc::new(Schema::new(vec![
+ Field::new("row_id", DataType::Int32, true),
+ Field::new("val", DataType::Int32, true),
+ Field::new("target_present", DataType::Boolean, false),
+ Field::new("source_present", DataType::Boolean, false),
+ ]));
+ let source =
+ MemorySourceConfig::try_new_exec(&[vec![]], Arc::clone(&wrong_schema), None).unwrap();
+ let err = MergeRowsExec::try_new(
+ col("source_present", &wrong_schema).unwrap(),
+ col("target_present", &wrong_schema).unwrap(),
+ vec![],
+ vec![],
+ vec![],
+ Some(0),
+ source,
+ out_schema(),
+ )
+ .unwrap_err();
+ assert!(err.to_string().contains("must be Int64"));
+ }
+
+ #[test]
+ fn replace_children_rejects_ordinal_out_of_range_for_new_child() {
+ use datafusion::datasource::memory::MemorySourceConfig;
+ let original_schema = Arc::new(Schema::new(vec![
+ Field::new("a", DataType::Int32, true),
+ Field::new("b", DataType::Int32, true),
+ Field::new("c", DataType::Int32, true),
+ Field::new("row_id", DataType::Int64, true),
+ ]));
+ let source =
+ MemorySourceConfig::try_new_exec(&[vec![]], Arc::clone(&original_schema), None)
+ .unwrap();
+ let exec = Arc::new(
+ MergeRowsExec::try_new(
+ lit(true),
+ lit(true),
+ vec![],
+ vec![],
+ vec![],
+ Some(3),
+ source,
+ out_schema(),
+ )
+ .unwrap(),
+ );
+
+ let narrow_schema = Arc::new(Schema::new(vec![Field::new(
+ "row_id",
+ DataType::Int64,
+ true,
+ )]));
+ let narrow_child =
+ MemorySourceConfig::try_new_exec(&[vec![]], narrow_schema, None).unwrap();
+ let err = exec
+ .replace_children(
+ vec![narrow_child],
+ ReplaceChildrenOptions::new(ChildrenPropertiesMode::Recompute),
+ )
+ .unwrap_err();
+ assert!(
+ err.to_string().contains("out of range"),
+ "expected an out-of-range ordinal error, got: {err}"
+ );
+ }
+
+ #[test]
+ fn replace_children_rejects_wrong_arity() {
+ use datafusion::datasource::memory::MemorySourceConfig;
+ let source = MemorySourceConfig::try_new_exec(&[vec![]], test_schema(), None).unwrap();
+ let exec = Arc::new(
+ MergeRowsExec::try_new(
+ col("source_present", &test_schema()).unwrap(),
+ col("target_present", &test_schema()).unwrap(),
+ vec![keep_all()],
+ vec![],
+ vec![],
+ Some(0),
+ source,
+ out_schema(),
+ )
+ .unwrap(),
+ );
+ let no_children = Arc::clone(&exec)
+ .replace_children(
+ vec![],
+ ReplaceChildrenOptions::new(ChildrenPropertiesMode::Recompute),
+ )
+ .unwrap_err();
+ assert!(no_children.to_string().contains("exactly one child"));
+
+ let child_a = MemorySourceConfig::try_new_exec(&[vec![]], test_schema(), None).unwrap();
+ let child_b = MemorySourceConfig::try_new_exec(&[vec![]], test_schema(), None).unwrap();
+ let two_children = exec
+ .replace_children(
+ vec![child_a, child_b],
+ ReplaceChildrenOptions::new(ChildrenPropertiesMode::Recompute),
+ )
+ .unwrap_err();
+ assert!(two_children.to_string().contains("exactly one child"));
+ }
+
+ #[test]
+ fn replace_children_revalidates_row_id_schema() {
+ use datafusion::datasource::memory::MemorySourceConfig;
+ let source = MemorySourceConfig::try_new_exec(&[vec![]], test_schema(), None).unwrap();
+ let exec = Arc::new(
+ MergeRowsExec::try_new(
+ col("source_present", &test_schema()).unwrap(),
+ col("target_present", &test_schema()).unwrap(),
+ vec![keep_all()],
+ vec![],
+ vec![],
+ Some(0),
+ source,
+ out_schema(),
+ )
+ .unwrap(),
+ );
+
+ let narrow_schema = Arc::new(Schema::new(vec![Field::new(
+ "only_col",
+ DataType::Int32,
+ true,
+ )]));
+ let narrow_child =
+ MemorySourceConfig::try_new_exec(&[vec![]], narrow_schema, None).unwrap();
+ let err = exec
+ .replace_children(
+ vec![narrow_child],
+ ReplaceChildrenOptions::new(ChildrenPropertiesMode::Recompute),
+ )
+ .unwrap_err();
+ assert!(err.to_string().contains("must be Int64"));
+ }
+
+ #[test]
+ fn cardinality_violation_detected_across_batches() {
+ let mut seen = HashSet::new();
+ let batch1 = test_batch(vec![1], vec![10], vec![true], vec![true]);
+ let batch2 = test_batch(vec![1], vec![20], vec![true], vec![true]);
+ let config = test_config(vec![keep_all()], vec![], vec![], Some(0));
+
+ let first = process_batch(
+ batch1,
+ &config,
+ &mut seen,
+ Some(&mut test_reservation()),
+ &out_schema(),
+ );
+ assert!(first.is_ok());
+
+ let second = process_batch(
+ batch2,
+ &config,
+ &mut seen,
+ Some(&mut test_reservation()),
+ &out_schema(),
+ );
+ assert!(second.is_err());
+ assert!(second
+ .unwrap_err()
+ .to_string()
+ .contains("MERGE_CARDINALITY_VIOLATION"));
+ }
+
+ #[test]
+ fn project_reconciles_nested_struct_nullability_with_declared_schema() {
+ let source_field = Field::new("n", DataType::Boolean, false);
+ let source_schema = Arc::new(Schema::new(vec![Field::new(
+ "payload",
+ DataType::Struct(vec![source_field.clone()].into()),
+ true,
+ )]));
+ let inner_values: ArrayRef = Arc::new(BooleanArray::from(vec![true]));
+ let payload_array: ArrayRef = Arc::new(StructArray::new(
+ vec![source_field].into(),
+ vec![inner_values],
+ None,
+ ));
+ let batch = RecordBatch::try_new(Arc::clone(&source_schema), vec![payload_array]).unwrap();
+
+ let target_field = Field::new("n", DataType::Boolean, true);
+ let out_schema = Arc::new(Schema::new(vec![Field::new(
+ "payload",
+ DataType::Struct(vec![target_field].into()),
+ true,
+ )]));
+
+ let out = project(
+ &batch,
+ &[col("payload", &source_schema).unwrap()],
+ &out_schema,
+ )
+ .expect("project must reconcile projected nested nullability with the declared schema");
+ assert_eq!(
+ out.schema().field(0).data_type(),
+ out_schema.field(0).data_type()
+ );
+ }
+}
diff --git a/native/core/src/execution/operators/mod.rs b/native/core/src/execution/operators/mod.rs
index a57fb693f2..a51d921444 100644
--- a/native/core/src/execution/operators/mod.rs
+++ b/native/core/src/execution/operators/mod.rs
@@ -32,6 +32,8 @@ mod iceberg_partition_value;
mod iceberg_scan;
mod iceberg_write;
pub use iceberg_write::IcebergWriteExec;
+mod merge_rows;
+pub use merge_rows::{MergeInstructionExec, MergeRowsExec};
mod parquet_writer;
pub use parquet_writer::{ParquetCompression, ParquetWriterExec};
mod csv_scan;
diff --git a/native/core/src/execution/planner.rs b/native/core/src/execution/planner.rs
index 756ece3f93..56cdb142eb 100644
--- a/native/core/src/execution/planner.rs
+++ b/native/core/src/execution/planner.rs
@@ -39,7 +39,7 @@ use crate::execution::operators::DynamicFilterJoinExec;
use crate::execution::operators::IcebergScanExec;
use crate::execution::operators::TopKReaderFilterExec;
use crate::execution::{
- operators::{ExecutionError, ScanExec, ShuffleScanExec},
+ operators::{ExecutionError, MergeInstructionExec, MergeRowsExec, ScanExec, ShuffleScanExec},
planner::expression_registry::ExpressionRegistry,
planner::operator_registry::OperatorRegistry,
serde::{to_arrow_datatype, to_arrow_field},
@@ -215,6 +215,51 @@ fn make_all_fields_nullable(data_type: &DataType) -> DataType {
}
}
+/// Returns true when `actual` and `expected` have the same nested shape and leaf types.
+/// Nested field nullability is intentionally ignored: MergeRows normalizes runtime batches to
+/// Spark's declared output schema, validating any nullability narrowing against the actual data.
+fn merge_output_type_compatible(actual: &DataType, expected: &DataType) -> bool {
+ match (actual, expected) {
+ (DataType::Struct(actual_fields), DataType::Struct(expected_fields)) => {
+ actual_fields.len() == expected_fields.len()
+ && actual_fields.iter().zip(expected_fields.iter()).all(
+ |(actual_field, expected_field)| {
+ actual_field.name() == expected_field.name()
+ && merge_output_type_compatible(
+ actual_field.data_type(),
+ expected_field.data_type(),
+ )
+ },
+ )
+ }
+ (DataType::List(actual_field), DataType::List(expected_field))
+ | (DataType::LargeList(actual_field), DataType::LargeList(expected_field)) => {
+ merge_output_type_compatible(actual_field.data_type(), expected_field.data_type())
+ }
+ (
+ DataType::FixedSizeList(actual_field, actual_size),
+ DataType::FixedSizeList(expected_field, expected_size),
+ ) => {
+ actual_size == expected_size
+ && merge_output_type_compatible(
+ actual_field.data_type(),
+ expected_field.data_type(),
+ )
+ }
+ (
+ DataType::Map(actual_entries, actual_sorted),
+ DataType::Map(expected_entries, expected_sorted),
+ ) => {
+ actual_sorted == expected_sorted
+ && merge_output_type_compatible(
+ actual_entries.data_type(),
+ expected_entries.data_type(),
+ )
+ }
+ _ => actual == expected,
+ }
+}
+
/// Return a copy of a `Map` type with only the outer entries `value` field marked nullable, keeping
/// the key field non-nullable and every nested key/value type byte-for-byte unchanged. Any non-`Map`
/// type is returned unchanged.
@@ -2010,6 +2055,130 @@ impl PhysicalPlanner {
Arc::new(SparkPlan::new(spark_plan.plan_id, expand, vec![child])),
))
}
+ OpStruct::MergeRows(merge) => {
+ let [child] = children.as_slice() else {
+ return Err(ExecutionError::GeneralError(format!(
+ "MergeRows expects exactly one child, got {}",
+ children.len()
+ )));
+ };
+ let (scans, shuffle_scans, child) =
+ self.create_plan(child, inputs, partition_count)?;
+
+ let missing_field = |name: &str| {
+ ExecutionError::GeneralError(format!("MergeRows proto missing `{name}`"))
+ };
+ let is_source_row_present = self.create_expr(
+ merge
+ .is_source_row_present
+ .as_ref()
+ .ok_or_else(|| missing_field("is_source_row_present"))?,
+ child.schema(),
+ )?;
+ let is_target_row_present = self.create_expr(
+ merge
+ .is_target_row_present
+ .as_ref()
+ .ok_or_else(|| missing_field("is_target_row_present"))?,
+ child.schema(),
+ )?;
+
+ let compile_instructions = |instrs: &[spark_operator::MergeInstruction]| -> Result<
+ Vec<MergeInstructionExec>,
+ ExecutionError,
+ > {
+ instrs
+ .iter()
+ .map(|instr| {
+ let condition = self.create_expr(
+ instr
+ .condition
+ .as_ref()
+ .ok_or_else(|| missing_field("instruction condition"))?,
+ child.schema(),
+ )?;
+ let outputs = instr
+ .outputs
+ .iter()
+ .map(|row| {
+ row.exprs
+ .iter()
+ .map(|e| self.create_expr(e, child.schema()))
+ .collect::<Result<Vec<_>, _>>()
+ })
+ .collect::<Result<Vec<_>, _>>()?;
+ Ok(MergeInstructionExec { condition, outputs })
+ })
+ .collect()
+ };
+
+ let matched_instructions = compile_instructions(&merge.matched_instructions)?;
+ let not_matched_instructions =
+ compile_instructions(&merge.not_matched_instructions)?;
+ let not_matched_by_source_instructions =
+ compile_instructions(&merge.not_matched_by_source_instructions)?;
+
+ // Spark's declared MergeRows output is the contract presented to the downstream
+ // V2 write. Derive the expression schema as an independent check, then stamp native
+ // batches with Spark's declared types so compatible nested-nullability widening does
+ // not leak a narrower physical schema across the JVM/native boundary.
+ let output_rows: Vec<Vec<Arc<dyn PhysicalExpr>>> = matched_instructions
+ .iter()
+ .chain(¬_matched_instructions)
+ .chain(¬_matched_by_source_instructions)
+ .flat_map(|instr| instr.outputs.iter().cloned())
+ .collect();
+ let expected_fields: Vec<Field> = merge
+ .output_types
+ .iter()
+ .map(to_arrow_datatype)
+ .enumerate()
+ .map(|(idx, dt)| Field::new(format!("col_{idx}"), dt, true))
+ .collect();
+ let schema = Arc::new(Schema::new(expected_fields));
+
+ if !output_rows.is_empty() {
+ let derived_schema = ExpandExec::build_schema(&output_rows, &child.schema())?;
+ if derived_schema.fields().len() != schema.fields().len() {
+ return Err(ExecutionError::GeneralError(format!(
+ "MergeRows projected {} columns but Spark declared {}",
+ derived_schema.fields().len(),
+ schema.fields().len()
+ )));
+ }
+ for (idx, (actual, expected)) in derived_schema
+ .fields()
+ .iter()
+ .zip(schema.fields().iter())
+ .enumerate()
+ {
+ if !merge_output_type_compatible(actual.data_type(), expected.data_type()) {
+ return Err(ExecutionError::GeneralError(format!(
+ "MergeRows output column {idx} has projected type {:?}, incompatible with Spark output type {:?}",
+ actual.data_type(),
+ expected.data_type()
+ )));
+ }
+ }
+ }
+
+ let exec = Arc::new(MergeRowsExec::try_new(
+ is_source_row_present,
+ is_target_row_present,
+ matched_instructions,
+ not_matched_instructions,
+ not_matched_by_source_instructions,
+ merge.row_id_ordinal.map(|ord| ord as usize),
+ Arc::clone(&child.native_plan),
+ schema,
+ )?);
+
+ Ok((
+ scans,
+ shuffle_scans,
+ Arc::new(SparkPlan::new(spark_plan.plan_id, exec, vec![child])),
+ ))
+ }
OpStruct::Explode(explode) => {
assert_eq!(children.len(), 1);
let (scans, shuffle_scans, child) =
diff --git a/native/core/src/execution/planner/operator_registry.rs b/native/core/src/execution/planner/operator_registry.rs
index b8f05ba48b..70ed309ebe 100644
--- a/native/core/src/execution/planner/operator_registry.rs
+++ b/native/core/src/execution/planner/operator_registry.rs
@@ -178,7 +178,8 @@ fn get_operator_type(spark_operator: &Operator) -> Option<OperatorType> {
OpStruct::ShuffleScan(_) => Some(OperatorType::ShuffleScan),
OpStruct::BroadcastNestedLoopJoin(_) => None,
OpStruct::RangeScan(_) => None,
- OpStruct::Sample(_) => None, // Not yet in OperatorType enum
+ OpStruct::Sample(_) => None, // Not yet in OperatorType enum
+ OpStruct::MergeRows(_) => None, // Not yet in OperatorType enum
// Generic extension point for out-of-tree contrib scans (Delta, Lance, ...); not in
// OperatorType enum. The arm stays unconditional even in non-contrib builds because the
// proto enum is generated regardless of cargo features and Rust requires an exhaustive
diff --git a/native/proto/src/proto/operator.proto b/native/proto/src/proto/operator.proto
index 1901b59655..213536b040 100644
--- a/native/proto/src/proto/operator.proto
+++ b/native/proto/src/proto/operator.proto
@@ -69,6 +69,7 @@ message Operator {
WindowGroupLimit window_group_limit = 119;
IcebergWrite iceberg_write = 120;
RangeScan range_scan = 121;
+ MergeRows merge_rows = 122;
// Extension point for optional, out-of-tree contrib scans (Delta, Lance, ...). The concrete
// scan message (e.g. `DeltaScan`) is packed into this envelope on the JVM side and dispatched
// by `type_url` on the native side. Using a single permanent field -- rather than a new oneof
@@ -959,6 +960,39 @@ message Expand {
int32 num_expr_per_project = 3;
}
+// Native counterpart of Spark's `MergeRowsExec` (row-level MERGE dispatch). Mirrors the real
+// Spark 4.x bytecode shape: `isSourceRowPresent` / `isTargetRowPresent` are predicates (not
+// column ordinals), and each instruction is uniformly `condition + outputs`, where the number
+// of output row projections (0/1/2) distinguishes Discard/Keep/Split -- there is no separate
+// instruction-kind enum on the Spark side, so we don't invent one here either.
+message MergeRows {
+ spark.spark_expression.Expr is_source_row_present = 1;
+ spark.spark_expression.Expr is_target_row_present = 2;
+
+ repeated MergeInstruction matched_instructions = 3;
+ repeated MergeInstruction not_matched_instructions = 4;
+ repeated MergeInstruction not_matched_by_source_instructions = 5;
+
+ // Ordinal (into the child row) of the target row-id column used for cardinality dedup.
+ // Mirrors `MergeRowsExec.checkCardinality`: present iff the check is on, in which case
+ // MERGE_CARDINALITY_VIOLATION is raised if a target row matches more than one source row.
+ optional int32 row_id_ordinal = 6;
+
+ // Schema of the emitted rows, matching `MergeRowsExec.output`.
+ repeated spark.spark_expression.DataType output_types = 7;
+}
+
+message MergeInstruction {
+ // Always present on the Spark side (Keep/Discard/Split.condition are non-optional).
+ spark.spark_expression.Expr condition = 1;
+ // 0 output rows = Discard, 1 = Keep, 2 = Split.
+ repeated MergeOutputRow outputs = 2;
+}
+
+message MergeOutputRow {
+ repeated spark.spark_expression.Expr exprs = 1;
+}
+
message Explode {
// The array expression to explode into multiple rows
spark.spark_expression.Expr child = 1;
diff --git a/spark/src/main/scala/org/apache/comet/CometConf.scala b/spark/src/main/scala/org/apache/comet/CometConf.scala
index eb05d9a747..ea58da4c02 100644
--- a/spark/src/main/scala/org/apache/comet/CometConf.scala
+++ b/spark/src/main/scala/org/apache/comet/CometConf.scala
@@ -277,6 +277,14 @@ object CometConf extends ShimCometConf {
createExecEnabledConfig("emptyRelation", defaultValue = true)
val COMET_EXEC_SAMPLE_ENABLED: ConfigEntry[Boolean] =
createExecEnabledConfig("sample", defaultValue = true)
+ val COMET_EXEC_MERGE_ROWS_ENABLED: ConfigEntry[Boolean] =
+ createExecEnabledConfig(
+ "mergeRows",
+ defaultValue = false,
+ notes = Some(
+ "Only takes effect on Spark 3.5 and 4.0. Spark 3.4 has no MergeRowsExec, and Spark " +
+ "4.1 and later keep MergeRowsExec on Spark so V2 writers can consume its row-level " +
+ "metrics (https://github.com/apache/datafusion-comet/issues/6606)"))
val COMET_EXEC_IN_MEMORY_CACHE_ENABLED: ConfigEntry[Boolean] =
conf("spark.comet.exec.inMemoryCache.enabled")
diff --git a/spark/src/main/scala/org/apache/comet/rules/CometExecRule.scala b/spark/src/main/scala/org/apache/comet/rules/CometExecRule.scala
index 9092407bfe..081de9b26d 100644
--- a/spark/src/main/scala/org/apache/comet/rules/CometExecRule.scala
+++ b/spark/src/main/scala/org/apache/comet/rules/CometExecRule.scala
@@ -60,7 +60,7 @@ import org.apache.comet.rules.CometExecRule.allExecs
import org.apache.comet.serde._
import org.apache.comet.serde.OperatorOuterClass.Operator
import org.apache.comet.serde.operator._
-import org.apache.comet.shims.{CometTypeShim, ShimCometStreaming, ShimCometWindowGroupLimit, ShimSubqueryBroadcast}
+import org.apache.comet.shims.{CometTypeShim, ShimCometMergeRows, ShimCometStreaming, ShimCometWindowGroupLimit, ShimSubqueryBroadcast}
object CometExecRule {
@@ -124,7 +124,11 @@ object CometExecRule {
// EmptyRelationExec was introduced in Spark 4.0.
ShimCometEmptyRelation.emptyRelationClass.map(_ -> CometEmptyRelationExec) ++
// WindowGroupLimitExec exists only on Spark 3.5+; the shim returns None on 3.4.
- ShimCometWindowGroupLimit.windowGroupLimitClass.map(_ -> CometWindowGroupLimitExec)
+ ShimCometWindowGroupLimit.windowGroupLimitClass.map(_ -> CometWindowGroupLimitExec) ++
+ // MergeRowsExec is registered for native execution on Spark 3.5 and 4.0 only. The shim is
+ // empty on 3.4, which has no MergeRowsExec, and on 4.1+, where Spark's V2 writer needs the
+ // concrete MergeRowsExec to build a MergeSummary.
+ ShimCometMergeRows.nativeExecs
/**
* Sinks that have a native plan of ScanExec.
diff --git a/spark/src/main/scala/org/apache/spark/sql/comet/operators.scala b/spark/src/main/scala/org/apache/spark/sql/comet/operators.scala
index 44aee93d3f..bb06248361 100644
--- a/spark/src/main/scala/org/apache/spark/sql/comet/operators.scala
+++ b/spark/src/main/scala/org/apache/spark/sql/comet/operators.scala
@@ -1765,6 +1765,89 @@ case class CometExpandExec(
override lazy val metrics: Map[String, SQLMetric] = Map.empty
}
+/**
+ * Native wrapper for Spark's `MergeRowsExec`. Predicates and instruction groups are real
+ * case-class fields so Catalyst can discover their references and scalar subqueries.
+ */
+case class CometMergeRowsExec(
+ override val nativeOp: Operator,
+ override val originalPlan: SparkPlan,
+ override val output: Seq[Attribute],
+ isSourceRowPresent: Expression,
+ isTargetRowPresent: Expression,
+ matchedInstructions: Seq[Expression],
+ notMatchedInstructions: Seq[Expression],
+ notMatchedBySourceInstructions: Seq[Expression],
+ checkCardinality: Boolean,
+ rowIdOrdinal: Option[Int],
+ child: SparkPlan,
+ override val serializedPlanOpt: SerializedPlan)
+ extends CometUnaryExec {
+ // Match Spark's MergeRowsExec partitioning contract.
+ override def outputPartitioning: Partitioning = UnknownPartitioning(0)
+
+ // Only attributes not already supplied by the child are produced here.
+ override def producedAttributes: AttributeSet =
+ AttributeSet(output.filterNot(child.outputSet.contains))
+
+ // Cardinality checking also reads Spark's synthetic ROW_ID column.
+ @transient
+ override lazy val references: AttributeSet = {
+ val rowIdExprs = rowIdOrdinal.flatMap(child.output.lift).toSeq
+ val expressionReferences =
+ AttributeSet.fromAttributeSets((rowIdExprs ++ expressions).map(_.references))
+ expressionReferences -- producedAttributes
+ }
+
+ override protected def withNewChildInternal(newChild: SparkPlan): SparkPlan =
+ this.copy(child = newChild)
+
+ override def stringArgs: Iterator[Any] =
+ Iterator(
+ output,
+ matchedInstructions,
+ notMatchedInstructions,
+ notMatchedBySourceInstructions,
+ checkCardinality,
+ child)
+
+ override def equals(obj: Any): Boolean = {
+ obj match {
+ case other: CometMergeRowsExec =>
+ this.output == other.output &&
+ this.isSourceRowPresent == other.isSourceRowPresent &&
+ this.isTargetRowPresent == other.isTargetRowPresent &&
+ this.matchedInstructions == other.matchedInstructions &&
+ this.notMatchedInstructions == other.notMatchedInstructions &&
+ this.notMatchedBySourceInstructions == other.notMatchedBySourceInstructions &&
+ this.checkCardinality == other.checkCardinality &&
+ this.rowIdOrdinal == other.rowIdOrdinal &&
+ this.child == other.child &&
+ this.serializedPlanOpt == other.serializedPlanOpt
+ case _ =>
+ false
+ }
+ }
+
+ override def hashCode(): Int =
+ Objects.hashCode(
+ output,
+ isSourceRowPresent,
+ isTargetRowPresent,
+ matchedInstructions,
+ notMatchedInstructions,
+ notMatchedBySourceInstructions,
+ Boolean.box(checkCardinality),
+ rowIdOrdinal,
+ child)
+
+ // Spark 4.1+ per-clause metrics require instruction context that earlier versions lack.
+ // Expose baseline metrics until that context is version-gated through native serde.
+ override lazy val metrics: Map[String, SQLMetric] =
+ CometMetricNode.baselineMetrics(sparkContext) ++ Map(
+ "output_batches" -> SQLMetrics.createMetric(sparkContext, "number of output batches"))
+}
+
object CometExplodeExec extends CometOperatorSerde[GenerateExec] {
override def enabledConfig: Option[ConfigEntry[Boolean]] = Some(
diff --git a/spark/src/main/spark-3.4/org/apache/comet/shims/ShimCometMergeRows.scala b/spark/src/main/spark-3.4/org/apache/comet/shims/ShimCometMergeRows.scala
new file mode 100644
index 0000000000..5ce851cae5
--- /dev/null
+++ b/spark/src/main/spark-3.4/org/apache/comet/shims/ShimCometMergeRows.scala
@@ -0,0 +1,32 @@
+/*
+ * 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.comet.shims
+
+import org.apache.spark.sql.execution.SparkPlan
+
+import org.apache.comet.serde.CometOperatorSerde
+
+/**
+ * Spark 3.4 predates the core `MergeRowsExec` implementation used by newer Spark versions.
+ * Nothing is registered here, so MERGE continues through the version-specific JVM path.
+ */
+object ShimCometMergeRows {
+ val nativeExecs: Map[Class[_ <: SparkPlan], CometOperatorSerde[_]] = Map.empty
+}
diff --git a/spark/src/main/spark-3.5/org/apache/comet/serde/operator/CometMergeRows.scala b/spark/src/main/spark-3.5/org/apache/comet/serde/operator/CometMergeRows.scala
new file mode 100644
index 0000000000..b4f81ad378
--- /dev/null
+++ b/spark/src/main/spark-3.5/org/apache/comet/serde/operator/CometMergeRows.scala
@@ -0,0 +1,242 @@
+/*
+ * 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.comet.serde.operator
+
+import scala.jdk.CollectionConverters._
+
+import org.apache.spark.sql.catalyst.expressions.Expression
+import org.apache.spark.sql.catalyst.plans.logical.MergeRows
+import org.apache.spark.sql.comet.{CometMergeRowsExec, SerializedPlan}
+import org.apache.spark.sql.execution.datasources.v2.MergeRowsExec
+import org.apache.spark.sql.types.{ArrayType, DataType, LongType, MapType, StructType}
+
+import org.apache.comet.CometConf
+import org.apache.comet.CometSparkSessionExtensions.withFallbackReason
+import org.apache.comet.ConfigEntry
+import org.apache.comet.serde.{CometOperatorSerde, Compatible, OperatorOuterClass, SupportLevel, Unsupported}
+import org.apache.comet.serde.OperatorOuterClass.{MergeInstruction, MergeOutputRow, Operator}
+import org.apache.comet.serde.QueryPlanSerde.{exprToProto, serializeDataType}
+
+/**
+ * Serde for Spark's `MergeRowsExec` (Spark 3.5+). An instruction is encoded as a condition plus
+ * zero, one, or two output rows for Discard, Keep, or Split.
+ */
+object CometMergeRows extends CometOperatorSerde[MergeRowsExec] {
+
+ override def enabledConfig: Option[ConfigEntry[Boolean]] =
+ Some(CometConf.COMET_EXEC_MERGE_ROWS_ENABLED)
+
+ override def getSupportLevel(op: MergeRowsExec): SupportLevel = {
+ if (!cardinalityCheckSatisfied(op)) {
+ Unsupported(Some(cardinalityCheckFallbackReason))
+ } else if (!instructionShapesSatisfied(op)) {
+ Unsupported(Some(instructionShapeFallbackReason))
+ } else {
+ Compatible(Some(compatibilityNote))
+ }
+ }
+
+ override def convert(
+ op: MergeRowsExec,
+ builder: Operator.Builder,
+ childOp: OperatorOuterClass.Operator*): Option[Operator] = {
+ val input = op.child.output
+ val expectedOutputTypes = op.output.map(_.dataType)
+
+ def convertInstruction(instr: MergeRows.Instruction): Option[MergeInstruction] = {
+ if (!instructionShapeSatisfied(instr, expectedOutputTypes)) {
+ return None
+ }
+
+ val condition = exprToProto(instr.condition, input)
+ val outputs = instr.outputs.map { row =>
+ val exprs = row.map(exprToProto(_, input))
+ if (exprs.forall(_.isDefined)) {
+ Some(MergeOutputRow.newBuilder().addAllExprs(exprs.map(_.get).asJava).build())
+ } else {
+ None
+ }
+ }
+
+ if (condition.isDefined && outputs.forall(_.isDefined)) {
+ Some(
+ MergeInstruction
+ .newBuilder()
+ .setCondition(condition.get)
+ .addAllOutputs(outputs.map(_.get).asJava)
+ .build())
+ } else {
+ None
+ }
+ }
+
+ val matched = op.matchedInstructions.map(convertInstruction)
+ val notMatched = op.notMatchedInstructions.map(convertInstruction)
+ val notMatchedBySource = op.notMatchedBySourceInstructions.map(convertInstruction)
+
+ val isSourcePresent = exprToProto(op.isSourceRowPresent, input)
+ val isTargetPresent = exprToProto(op.isTargetRowPresent, input)
+
+ val outputTypes = op.output.map(a => serializeDataType(a.dataType))
+
+ // Only wired when Spark asked for a cardinality check; if `checkCardinality` is false this
+ // must stay unset rather than default to 0. `row_id_ordinal` is `optional int32` (not a plain
+ // `int32`) precisely because 0 is a legitimate ordinal -- the row-id column could be the
+ // child's first column -- so presence must be distinguishable from a real value.
+ val rowIdOrd: Option[Int] = if (op.checkCardinality) rowIdOrdinal(op) else None
+
+ // `childOp` is empty when the child did not itself convert to a native operator --
+ // `CometExecRule.convertToComet` still calls `convert` in that case. Without this guard a
+ // childless `MergeRows` reaches the planner, where a missing child would otherwise be an
+ // invalid native plan rather than a clean JVM fallback.
+ if (childOp.nonEmpty && matched.forall(_.isDefined) && notMatched.forall(_.isDefined) &&
+ notMatchedBySource.forall(_.isDefined) && isSourcePresent.isDefined &&
+ isTargetPresent.isDefined && outputTypes.forall(_.isDefined) &&
+ cardinalityCheckSatisfied(op) && instructionShapesSatisfied(op)) {
+ val mergeBuilder = OperatorOuterClass.MergeRows
+ .newBuilder()
+ .setIsSourceRowPresent(isSourcePresent.get)
+ .setIsTargetRowPresent(isTargetPresent.get)
+ .addAllMatchedInstructions(matched.map(_.get).asJava)
+ .addAllNotMatchedInstructions(notMatched.map(_.get).asJava)
+ .addAllNotMatchedBySourceInstructions(notMatchedBySource.map(_.get).asJava)
+ .addAllOutputTypes(outputTypes.map(_.get).asJava)
+ rowIdOrd.foreach(mergeBuilder.setRowIdOrdinal)
+ Some(builder.setMergeRows(mergeBuilder).build())
+ } else if (childOp.isEmpty) {
+ withFallbackReason(op, "No child operator")
+ None
+ } else if (!cardinalityCheckSatisfied(op)) {
+ withFallbackReason(op, cardinalityCheckFallbackReason)
+ None
+ } else if (!instructionShapesSatisfied(op)) {
+ withFallbackReason(op, instructionShapeFallbackReason)
+ None
+ } else {
+ withFallbackReason(op, "Unsupported expression in MERGE instructions")
+ None
+ }
+ }
+
+ override def createExec(nativeOp: Operator, op: MergeRowsExec): CometMergeRowsExec = {
+ // Carry each instruction group and predicate across as its own field. `MergeRows.Instruction`
+ // is an `Expression`, so `Seq[Instruction]` widens to `Seq[Expression]` and Catalyst's
+ // expression machinery (subquery registration in particular) still sees every instruction --
+ // see `CometMergeRowsExec`'s scaladoc for why the groups must not be flattened together.
+ CometMergeRowsExec(
+ nativeOp,
+ op,
+ op.output,
+ op.isSourceRowPresent,
+ op.isTargetRowPresent,
+ op.matchedInstructions.map(i => i: Expression),
+ op.notMatchedInstructions.map(i => i: Expression),
+ op.notMatchedBySourceInstructions.map(i => i: Expression),
+ op.checkCardinality,
+ if (op.checkCardinality) rowIdOrdinal(op) else None,
+ op.child,
+ SerializedPlan(None))
+ }
+
+ private val compatibilityNote: String =
+ "Native MERGE preserves row values but may differ from Spark in physical output ordering " +
+ "and in which error is reported first when multiple rows fail in one input batch"
+
+ private val cardinalityCheckFallbackReason: String =
+ s"MERGE cardinality check requires a resolvable, Long-typed '${MergeRows.ROW_ID}' column"
+
+ private val instructionShapeFallbackReason: String =
+ "MERGE instruction must be Discard, Keep, or Split with output rows compatible with the plan schema"
+
+ /**
+ * True iff cardinality checking is off, or the target row-id column resolves to a usable
+ * ordinal. Shared by `getSupportLevel` (the planning-time gate) and `convert` (which must
+ * re-derive the same condition to pick its own fallback branch) so the two checks cannot desync
+ * -- `convert` is only reached after `getSupportLevel` already passed, so its branch for this
+ * case is otherwise unreachable and would silently stop guarding anything if the two drifted
+ * apart.
+ */
+ private def cardinalityCheckSatisfied(op: MergeRowsExec): Boolean =
+ !op.checkCardinality || rowIdOrdinal(op).isDefined
+
+ /**
+ * Preserve the `MergeRows.Instruction` wire contract at the JVM/native boundary. Spark
+ * currently constructs only Discard (0 rows), Keep (1 row), and Split (2 rows), with every
+ * projected row matching `MergeRowsExec.output`. Validate that shape explicitly so a future
+ * Spark change or a malformed internal plan falls back during planning instead of becoming an
+ * invalid native protobuf that the Rust executor would otherwise accept generically.
+ */
+ private def instructionShapesSatisfied(op: MergeRowsExec): Boolean = {
+ val outputTypes = op.output.map(_.dataType)
+ op.matchedInstructions.forall(instructionShapeSatisfied(_, outputTypes)) &&
+ op.notMatchedInstructions.forall(instructionShapeSatisfied(_, outputTypes)) &&
+ op.notMatchedBySourceInstructions.forall(instructionShapeSatisfied(_, outputTypes))
+ }
+
+ /**
+ * Validates both the Discard/Keep/Split row count and every projected leaf type. Nested
+ * nullability may widen from an instruction expression to Spark's declared output schema, but
+ * it may not narrow: stamping a nullable nested value as non-nullable would hide a real schema
+ * incompatibility.
+ */
+ private def instructionShapeSatisfied(
+ instruction: MergeRows.Instruction,
+ outputTypes: Seq[DataType]): Boolean = {
+ instruction.outputs.size <= 2 && instruction.outputs.forall { row =>
+ row.size == outputTypes.size && row.zip(outputTypes).forall { case (expr, expected) =>
+ dataTypeCompatible(expr.dataType, expected)
+ }
+ }
+ }
+
+ /** Spark-compatible type comparison that permits only safe nested-nullability widening. */
+ private def dataTypeCompatible(actual: DataType, expected: DataType): Boolean =
+ (actual, expected) match {
+ case (ArrayType(actualElement, actualNulls), ArrayType(expectedElement, expectedNulls)) =>
+ (expectedNulls || !actualNulls) && dataTypeCompatible(actualElement, expectedElement)
+ case (
+ MapType(actualKey, actualValue, actualNulls),
+ MapType(expectedKey, expectedValue, expectedNulls)) =>
+ (expectedNulls || !actualNulls) &&
+ dataTypeCompatible(actualKey, expectedKey) &&
+ dataTypeCompatible(actualValue, expectedValue)
+ case (StructType(actualFields), StructType(expectedFields)) =>
+ actualFields.length == expectedFields.length &&
+ actualFields.zip(expectedFields).forall { case (actualField, expectedField) =>
+ actualField.name == expectedField.name &&
+ (expectedField.nullable || !actualField.nullable) &&
+ dataTypeCompatible(actualField.dataType, expectedField.dataType)
+ }
+ case _ => actual == expected
+ }
+
+ /**
+ * Locates the ordinal of Spark's target row-id column (`MergeRows.ROW_ID`) in the child output,
+ * using the same SQLConf resolver as Spark's `MergeRowsExec.references`. Requiring `LongType`
+ * keeps the native `Int64Array` cardinality validator type-safe; an unexpected schema falls
+ * back during planning instead of failing inside native execution.
+ */
+ private def rowIdOrdinal(op: MergeRowsExec): Option[Int] = {
+ val idx = op.child.output.indexWhere { attr =>
+ op.conf.resolver(attr.name, MergeRows.ROW_ID) && attr.dataType == LongType
+ }
+ if (idx >= 0) Some(idx) else None
+ }
+}
diff --git a/spark/src/main/spark-3.5/org/apache/comet/shims/ShimCometMergeRows.scala b/spark/src/main/spark-3.5/org/apache/comet/shims/ShimCometMergeRows.scala
new file mode 100644
index 0000000000..8a772b9c1d
--- /dev/null
+++ b/spark/src/main/spark-3.5/org/apache/comet/shims/ShimCometMergeRows.scala
@@ -0,0 +1,35 @@
+/*
+ * 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.comet.shims
+
+import org.apache.spark.sql.execution.SparkPlan
+import org.apache.spark.sql.execution.datasources.v2.MergeRowsExec
+
+import org.apache.comet.serde.CometOperatorSerde
+import org.apache.comet.serde.operator.CometMergeRows
+
+/**
+ * `MergeRowsExec` (the row-level MERGE dispatch operator) exists on Spark 3.5+; this registers it
+ * for Spark 3.5 and 4.0. See `org.apache.comet.serde.operator.CometMergeRows` for conversion.
+ */
+object ShimCometMergeRows {
+ val nativeExecs: Map[Class[_ <: SparkPlan], CometOperatorSerde[_]] =
+ Map(classOf[MergeRowsExec] -> CometMergeRows)
+}
diff --git a/spark/src/main/spark-3.5/org/apache/spark/sql/comet/shims/ShimSparkErrorConverter.scala b/spark/src/main/spark-3.5/org/apache/spark/sql/comet/shims/ShimSparkErrorConverter.scala
index b148543853..6658b420bb 100644
--- a/spark/src/main/spark-3.5/org/apache/spark/sql/comet/shims/ShimSparkErrorConverter.scala
+++ b/spark/src/main/spark-3.5/org/apache/spark/sql/comet/shims/ShimSparkErrorConverter.scala
@@ -299,6 +299,9 @@ trait ShimSparkErrorConverter {
// multipleRowScalarSubqueryError was renamed to multipleRowSubqueryError in Spark 3.x
Some(QueryExecutionErrors.multipleRowSubqueryError(sqlCtx(context)))
+ case "MergeCardinalityViolation" =>
+ Some(QueryExecutionErrors.mergeCardinalityViolationError())
+
case "IntervalArithmeticOverflowWithSuggestion" =>
// Spark 3.x uses a single intervalArithmeticOverflowError method
Some(
diff --git a/spark/src/main/spark-4.0/org/apache/comet/serde/operator/CometMergeRows.scala b/spark/src/main/spark-4.0/org/apache/comet/serde/operator/CometMergeRows.scala
new file mode 100644
index 0000000000..b4f81ad378
--- /dev/null
+++ b/spark/src/main/spark-4.0/org/apache/comet/serde/operator/CometMergeRows.scala
@@ -0,0 +1,242 @@
+/*
+ * 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.comet.serde.operator
+
+import scala.jdk.CollectionConverters._
+
+import org.apache.spark.sql.catalyst.expressions.Expression
+import org.apache.spark.sql.catalyst.plans.logical.MergeRows
+import org.apache.spark.sql.comet.{CometMergeRowsExec, SerializedPlan}
+import org.apache.spark.sql.execution.datasources.v2.MergeRowsExec
+import org.apache.spark.sql.types.{ArrayType, DataType, LongType, MapType, StructType}
+
+import org.apache.comet.CometConf
+import org.apache.comet.CometSparkSessionExtensions.withFallbackReason
+import org.apache.comet.ConfigEntry
+import org.apache.comet.serde.{CometOperatorSerde, Compatible, OperatorOuterClass, SupportLevel, Unsupported}
+import org.apache.comet.serde.OperatorOuterClass.{MergeInstruction, MergeOutputRow, Operator}
+import org.apache.comet.serde.QueryPlanSerde.{exprToProto, serializeDataType}
+
+/**
+ * Serde for Spark's `MergeRowsExec` (Spark 3.5+). An instruction is encoded as a condition plus
+ * zero, one, or two output rows for Discard, Keep, or Split.
+ */
+object CometMergeRows extends CometOperatorSerde[MergeRowsExec] {
+
+ override def enabledConfig: Option[ConfigEntry[Boolean]] =
+ Some(CometConf.COMET_EXEC_MERGE_ROWS_ENABLED)
+
+ override def getSupportLevel(op: MergeRowsExec): SupportLevel = {
+ if (!cardinalityCheckSatisfied(op)) {
+ Unsupported(Some(cardinalityCheckFallbackReason))
+ } else if (!instructionShapesSatisfied(op)) {
+ Unsupported(Some(instructionShapeFallbackReason))
+ } else {
+ Compatible(Some(compatibilityNote))
+ }
+ }
+
+ override def convert(
+ op: MergeRowsExec,
+ builder: Operator.Builder,
+ childOp: OperatorOuterClass.Operator*): Option[Operator] = {
+ val input = op.child.output
+ val expectedOutputTypes = op.output.map(_.dataType)
+
+ def convertInstruction(instr: MergeRows.Instruction): Option[MergeInstruction] = {
+ if (!instructionShapeSatisfied(instr, expectedOutputTypes)) {
+ return None
+ }
+
+ val condition = exprToProto(instr.condition, input)
+ val outputs = instr.outputs.map { row =>
+ val exprs = row.map(exprToProto(_, input))
+ if (exprs.forall(_.isDefined)) {
+ Some(MergeOutputRow.newBuilder().addAllExprs(exprs.map(_.get).asJava).build())
+ } else {
+ None
+ }
+ }
+
+ if (condition.isDefined && outputs.forall(_.isDefined)) {
+ Some(
+ MergeInstruction
+ .newBuilder()
+ .setCondition(condition.get)
+ .addAllOutputs(outputs.map(_.get).asJava)
+ .build())
+ } else {
+ None
+ }
+ }
+
+ val matched = op.matchedInstructions.map(convertInstruction)
+ val notMatched = op.notMatchedInstructions.map(convertInstruction)
+ val notMatchedBySource = op.notMatchedBySourceInstructions.map(convertInstruction)
+
+ val isSourcePresent = exprToProto(op.isSourceRowPresent, input)
+ val isTargetPresent = exprToProto(op.isTargetRowPresent, input)
+
+ val outputTypes = op.output.map(a => serializeDataType(a.dataType))
+
+ // Only wired when Spark asked for a cardinality check; if `checkCardinality` is false this
+ // must stay unset rather than default to 0. `row_id_ordinal` is `optional int32` (not a plain
+ // `int32`) precisely because 0 is a legitimate ordinal -- the row-id column could be the
+ // child's first column -- so presence must be distinguishable from a real value.
+ val rowIdOrd: Option[Int] = if (op.checkCardinality) rowIdOrdinal(op) else None
+
+ // `childOp` is empty when the child did not itself convert to a native operator --
+ // `CometExecRule.convertToComet` still calls `convert` in that case. Without this guard a
+ // childless `MergeRows` reaches the planner, where a missing child would otherwise be an
+ // invalid native plan rather than a clean JVM fallback.
+ if (childOp.nonEmpty && matched.forall(_.isDefined) && notMatched.forall(_.isDefined) &&
+ notMatchedBySource.forall(_.isDefined) && isSourcePresent.isDefined &&
+ isTargetPresent.isDefined && outputTypes.forall(_.isDefined) &&
+ cardinalityCheckSatisfied(op) && instructionShapesSatisfied(op)) {
+ val mergeBuilder = OperatorOuterClass.MergeRows
+ .newBuilder()
+ .setIsSourceRowPresent(isSourcePresent.get)
+ .setIsTargetRowPresent(isTargetPresent.get)
+ .addAllMatchedInstructions(matched.map(_.get).asJava)
+ .addAllNotMatchedInstructions(notMatched.map(_.get).asJava)
+ .addAllNotMatchedBySourceInstructions(notMatchedBySource.map(_.get).asJava)
+ .addAllOutputTypes(outputTypes.map(_.get).asJava)
+ rowIdOrd.foreach(mergeBuilder.setRowIdOrdinal)
+ Some(builder.setMergeRows(mergeBuilder).build())
+ } else if (childOp.isEmpty) {
+ withFallbackReason(op, "No child operator")
+ None
+ } else if (!cardinalityCheckSatisfied(op)) {
+ withFallbackReason(op, cardinalityCheckFallbackReason)
+ None
+ } else if (!instructionShapesSatisfied(op)) {
+ withFallbackReason(op, instructionShapeFallbackReason)
+ None
+ } else {
+ withFallbackReason(op, "Unsupported expression in MERGE instructions")
+ None
+ }
+ }
+
+ override def createExec(nativeOp: Operator, op: MergeRowsExec): CometMergeRowsExec = {
+ // Carry each instruction group and predicate across as its own field. `MergeRows.Instruction`
+ // is an `Expression`, so `Seq[Instruction]` widens to `Seq[Expression]` and Catalyst's
+ // expression machinery (subquery registration in particular) still sees every instruction --
+ // see `CometMergeRowsExec`'s scaladoc for why the groups must not be flattened together.
+ CometMergeRowsExec(
+ nativeOp,
+ op,
+ op.output,
+ op.isSourceRowPresent,
+ op.isTargetRowPresent,
+ op.matchedInstructions.map(i => i: Expression),
+ op.notMatchedInstructions.map(i => i: Expression),
+ op.notMatchedBySourceInstructions.map(i => i: Expression),
+ op.checkCardinality,
+ if (op.checkCardinality) rowIdOrdinal(op) else None,
+ op.child,
+ SerializedPlan(None))
+ }
+
+ private val compatibilityNote: String =
+ "Native MERGE preserves row values but may differ from Spark in physical output ordering " +
+ "and in which error is reported first when multiple rows fail in one input batch"
+
+ private val cardinalityCheckFallbackReason: String =
+ s"MERGE cardinality check requires a resolvable, Long-typed '${MergeRows.ROW_ID}' column"
+
+ private val instructionShapeFallbackReason: String =
+ "MERGE instruction must be Discard, Keep, or Split with output rows compatible with the plan schema"
+
+ /**
+ * True iff cardinality checking is off, or the target row-id column resolves to a usable
+ * ordinal. Shared by `getSupportLevel` (the planning-time gate) and `convert` (which must
+ * re-derive the same condition to pick its own fallback branch) so the two checks cannot desync
+ * -- `convert` is only reached after `getSupportLevel` already passed, so its branch for this
+ * case is otherwise unreachable and would silently stop guarding anything if the two drifted
+ * apart.
+ */
+ private def cardinalityCheckSatisfied(op: MergeRowsExec): Boolean =
+ !op.checkCardinality || rowIdOrdinal(op).isDefined
+
+ /**
+ * Preserve the `MergeRows.Instruction` wire contract at the JVM/native boundary. Spark
+ * currently constructs only Discard (0 rows), Keep (1 row), and Split (2 rows), with every
+ * projected row matching `MergeRowsExec.output`. Validate that shape explicitly so a future
+ * Spark change or a malformed internal plan falls back during planning instead of becoming an
+ * invalid native protobuf that the Rust executor would otherwise accept generically.
+ */
+ private def instructionShapesSatisfied(op: MergeRowsExec): Boolean = {
+ val outputTypes = op.output.map(_.dataType)
+ op.matchedInstructions.forall(instructionShapeSatisfied(_, outputTypes)) &&
+ op.notMatchedInstructions.forall(instructionShapeSatisfied(_, outputTypes)) &&
+ op.notMatchedBySourceInstructions.forall(instructionShapeSatisfied(_, outputTypes))
+ }
+
+ /**
+ * Validates both the Discard/Keep/Split row count and every projected leaf type. Nested
+ * nullability may widen from an instruction expression to Spark's declared output schema, but
+ * it may not narrow: stamping a nullable nested value as non-nullable would hide a real schema
+ * incompatibility.
+ */
+ private def instructionShapeSatisfied(
+ instruction: MergeRows.Instruction,
+ outputTypes: Seq[DataType]): Boolean = {
+ instruction.outputs.size <= 2 && instruction.outputs.forall { row =>
+ row.size == outputTypes.size && row.zip(outputTypes).forall { case (expr, expected) =>
+ dataTypeCompatible(expr.dataType, expected)
+ }
+ }
+ }
+
+ /** Spark-compatible type comparison that permits only safe nested-nullability widening. */
+ private def dataTypeCompatible(actual: DataType, expected: DataType): Boolean =
+ (actual, expected) match {
+ case (ArrayType(actualElement, actualNulls), ArrayType(expectedElement, expectedNulls)) =>
+ (expectedNulls || !actualNulls) && dataTypeCompatible(actualElement, expectedElement)
+ case (
+ MapType(actualKey, actualValue, actualNulls),
+ MapType(expectedKey, expectedValue, expectedNulls)) =>
+ (expectedNulls || !actualNulls) &&
+ dataTypeCompatible(actualKey, expectedKey) &&
+ dataTypeCompatible(actualValue, expectedValue)
+ case (StructType(actualFields), StructType(expectedFields)) =>
+ actualFields.length == expectedFields.length &&
+ actualFields.zip(expectedFields).forall { case (actualField, expectedField) =>
+ actualField.name == expectedField.name &&
+ (expectedField.nullable || !actualField.nullable) &&
+ dataTypeCompatible(actualField.dataType, expectedField.dataType)
+ }
+ case _ => actual == expected
+ }
+
+ /**
+ * Locates the ordinal of Spark's target row-id column (`MergeRows.ROW_ID`) in the child output,
+ * using the same SQLConf resolver as Spark's `MergeRowsExec.references`. Requiring `LongType`
+ * keeps the native `Int64Array` cardinality validator type-safe; an unexpected schema falls
+ * back during planning instead of failing inside native execution.
+ */
+ private def rowIdOrdinal(op: MergeRowsExec): Option[Int] = {
+ val idx = op.child.output.indexWhere { attr =>
+ op.conf.resolver(attr.name, MergeRows.ROW_ID) && attr.dataType == LongType
+ }
+ if (idx >= 0) Some(idx) else None
+ }
+}
diff --git a/spark/src/main/spark-4.0/org/apache/comet/shims/ShimCometMergeRows.scala b/spark/src/main/spark-4.0/org/apache/comet/shims/ShimCometMergeRows.scala
new file mode 100644
index 0000000000..8a772b9c1d
--- /dev/null
+++ b/spark/src/main/spark-4.0/org/apache/comet/shims/ShimCometMergeRows.scala
@@ -0,0 +1,35 @@
+/*
+ * 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.comet.shims
+
+import org.apache.spark.sql.execution.SparkPlan
+import org.apache.spark.sql.execution.datasources.v2.MergeRowsExec
+
+import org.apache.comet.serde.CometOperatorSerde
+import org.apache.comet.serde.operator.CometMergeRows
+
+/**
+ * `MergeRowsExec` (the row-level MERGE dispatch operator) exists on Spark 3.5+; this registers it
+ * for Spark 3.5 and 4.0. See `org.apache.comet.serde.operator.CometMergeRows` for conversion.
+ */
+object ShimCometMergeRows {
+ val nativeExecs: Map[Class[_ <: SparkPlan], CometOperatorSerde[_]] =
+ Map(classOf[MergeRowsExec] -> CometMergeRows)
+}
diff --git a/spark/src/main/spark-4.1+/org/apache/comet/shims/ShimCometMergeRows.scala b/spark/src/main/spark-4.1+/org/apache/comet/shims/ShimCometMergeRows.scala
new file mode 100644
index 0000000000..56cbbea54e
--- /dev/null
+++ b/spark/src/main/spark-4.1+/org/apache/comet/shims/ShimCometMergeRows.scala
@@ -0,0 +1,33 @@
+/*
+ * 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.comet.shims
+
+import org.apache.spark.sql.execution.SparkPlan
+
+import org.apache.comet.serde.CometOperatorSerde
+
+/**
+ * Spark 4.1+ derives a `MergeSummary` from Spark's concrete `MergeRowsExec` and passes it through
+ * the summary-aware V2 commit contract. Keep MergeRows on the JVM until Comet preserves that
+ * contract end to end.
+ */
+object ShimCometMergeRows {
+ val nativeExecs: Map[Class[_ <: SparkPlan], CometOperatorSerde[_]] = Map.empty
+}
diff --git a/spark/src/main/spark-4.x/org/apache/spark/sql/comet/shims/ShimSparkErrorConverter.scala b/spark/src/main/spark-4.x/org/apache/spark/sql/comet/shims/ShimSparkErrorConverter.scala
index dd9024e8ff..70d7a6a313 100644
--- a/spark/src/main/spark-4.x/org/apache/spark/sql/comet/shims/ShimSparkErrorConverter.scala
+++ b/spark/src/main/spark-4.x/org/apache/spark/sql/comet/shims/ShimSparkErrorConverter.scala
@@ -322,6 +322,9 @@ trait ShimSparkErrorConverter {
case "ScalarSubqueryTooManyRows" =>
Some(QueryExecutionErrors.multipleRowScalarSubqueryError(context.headOption.orNull))
+ case "MergeCardinalityViolation" =>
+ Some(QueryExecutionErrors.mergeCardinalityViolationError())
+
case "IntervalArithmeticOverflowWithSuggestion" =>
Some(
QueryExecutionErrors.withSuggestionIntervalArithmeticOverflowError(
diff --git a/spark/src/test/scala/org/apache/comet/CometIcebergWriteActionSuite.scala b/spark/src/test/scala/org/apache/comet/CometIcebergWriteActionSuite.scala
index e8aa36e2c5..93073f862a 100644
--- a/spark/src/test/scala/org/apache/comet/CometIcebergWriteActionSuite.scala
+++ b/spark/src/test/scala/org/apache/comet/CometIcebergWriteActionSuite.scala
@@ -43,7 +43,7 @@ import org.apache.spark.sql.DataFrame
import org.apache.spark.sql.Row
import org.apache.spark.sql.catalyst.InternalRow
import org.apache.spark.sql.catalyst.expressions.Attribute
-import org.apache.spark.sql.comet.{CometIcebergWriteExec, IcebergCommitExec, IcebergWriteExec}
+import org.apache.spark.sql.comet.{CometIcebergWriteExec, CometMergeRowsExec, IcebergCommitExec, IcebergWriteExec}
import org.apache.spark.sql.connector.catalog.InMemoryTableCatalog
import org.apache.spark.sql.connector.write.{BatchWrite, DataWriterFactory, PhysicalWriteInfo, Write, WriterCommitMessage}
import org.apache.spark.sql.execution.{ColumnarToRowTransition, LeafExecNode, SparkPlan}
@@ -1003,16 +1003,9 @@ class CometIcebergWriteActionSuite
}
}
- test("native acceleration: ReplaceData (CoW MERGE) falls back (MergeRowsExec not Comet)") {
- // TODO(comet-merge-rows): native MERGE engagement requires a Comet equivalent of Iceberg's
- // `MergeRowsExec` (the per-row dispatch operator that assigns __row_operation codes from
- // MATCHED/NOT MATCHED clauses). Without it, `MergeRowsExec` stays JVM, the upstream chain
- // breaks Comet-native partway, and `requiresNativeChildren=true` declines the
- // `IcebergWriteExec -> CometIcebergWriteExec` conversion. Until that lands, MERGE
- // falls back to the JVM two-op path -- this test pins that contract. Native `MergeRowsExec`
- // is being added in https://github.com/apache/datafusion-comet/pull/5318; when that lands
- // this test will start failing and needs to flip to `assertNativeWriteEngages`.
+ test("native acceleration: ReplaceData (CoW MERGE) honors the versioned native contract") {
assumeNativeAcceleration()
+
withIcebergCatalog { warehouseDir =>
createTable(
warehouseDir,
@@ -1022,7 +1015,8 @@ class CometIcebergWriteActionSuite
withSQLConf(CometConf.COMET_ICEBERG_WRITE_SPLIT_OPERATOR_ENABLED.key -> "false") {
coalesceInsert("native_cow_merge", Seq((1, "us-east", 10.0), (2, "us-west", 20.0)))
}
- assertNativeWriteDoesNotEngage("native_cow_merge", Seq(1, 2, 3)) {
+
+ def runMerge(): Unit = {
spark.sql("""
|MERGE INTO cat.db.native_cow_merge t
|USING (SELECT 2 AS id, 'us-west' AS region, 200.0 AS amount UNION ALL
@@ -1032,6 +1026,248 @@ class CometIcebergWriteActionSuite
|WHEN NOT MATCHED THEN INSERT (id, region, amount) VALUES (s.id, s.region, s.amount)
|""".stripMargin)
}
+
+ withSQLConf(CometConf.COMET_EXEC_MERGE_ROWS_ENABLED.key -> "true") {
+ if (isSpark41Plus || !isSpark35Plus) {
+ assertNativeWriteDoesNotEngage("native_cow_merge", Seq(1, 2, 3))(runMerge())
+ } else {
+ val snapshot = withNativeEnabled {
+ captureWrite("native_cow_merge")(runMerge())
+ }
+ assert(
+ snapshot.snapshotDelta == 1L,
+ s"expected exactly one Iceberg snapshot from native MERGE, got ${snapshot.snapshotDelta}")
+ val mergeExecs = snapshot.plans.flatMap { plan =>
+ collectWithSubqueries(plan) { case e: CometMergeRowsExec => e }
+ }
+ assert(
+ mergeExecs.nonEmpty,
+ "expected Iceberg MERGE to execute through CometMergeRowsExec. Plans:\n" +
+ snapshot.plans.mkString("\n--\n"))
+ val nativeWrites = snapshot.plans.flatMap { plan =>
+ collectWithSubqueries(plan) { case e: CometIcebergWriteExec => e }
+ }
+ assert(
+ nativeWrites.nonEmpty,
+ "expected Iceberg MERGE to feed CometIcebergWriteExec. Plans:\n" +
+ snapshot.plans.mkString("\n--\n"))
+ assertRows("native_cow_merge", expectedIds = Seq(1, 2, 3))
+ }
+ }
+
+ val updated = spark
+ .sql(s"SELECT amount FROM $catalog.$ns.native_cow_merge WHERE id = 2")
+ .collect()
+ assert(updated.length == 1 && updated.head.getDouble(0) == 200.0)
+ }
+ }
+
+ test("native MergeRows matches Spark on partitioned Iceberg copy-on-write and merge-on-read") {
+ assumeNativeAcceleration()
+ assume(
+ isSpark35Plus && !isSpark41Plus,
+ "native MergeRows is registered only on Spark 3.5 and 4.0")
+ withIcebergCatalog { warehouseDir =>
+ spark
+ .range(0, 20000, 1, 8)
+ .selectExpr(
+ "CAST(id AS INT) AS id",
+ "concat('r', CAST(id % 8 AS STRING)) AS region",
+ "CAST(id AS DOUBLE) AS amount")
+ .createOrReplaceTempView("merge_parity_seed")
+ spark
+ .range(10000, 30000, 1, 8)
+ .selectExpr(
+ "CAST(id AS INT) AS id",
+ "concat('s', CAST(id % 8 AS STRING)) AS region",
+ "CASE WHEN id % 11 = 0 THEN CAST(NULL AS DOUBLE) ELSE CAST(id * 2 AS DOUBLE) END AS amount")
+ .createOrReplaceTempView("merge_parity_source")
+
+ def merge(table: String): Unit = {
+ spark.sql(s"""
+ |MERGE INTO $catalog.$ns.$table t
+ |USING merge_parity_source s
+ |ON t.id = s.id
+ |WHEN MATCHED AND CAST(NULL AS BOOLEAN) THEN UPDATE SET t.amount = -999.0
+ |WHEN MATCHED AND s.amount IS NULL THEN DELETE
+ |WHEN MATCHED AND s.id % 5 = 0 THEN DELETE
+ |WHEN MATCHED THEN UPDATE SET t.region = s.region, t.amount = s.amount + 0.5
+ |WHEN NOT MATCHED AND s.id IS NOT NULL THEN
+ | INSERT (id, region, amount) VALUES (s.id, s.region, s.amount)
+ |WHEN NOT MATCHED BY SOURCE AND t.id % 7 = 0 THEN DELETE
+ |WHEN NOT MATCHED BY SOURCE THEN UPDATE SET t.amount = t.amount + 1.0
+ |""".stripMargin)
+ }
+
+ def rows(table: String): Seq[Row] =
+ spark
+ .sql(s"SELECT id, region, amount FROM $catalog.$ns.$table ORDER BY id")
+ .collect()
+ .toSeq
+
+ Seq(true, false).foreach { adaptiveEnabled =>
+ Seq("copy-on-write" -> "cow", "merge-on-read" -> "mor").foreach { case (mode, suffix) =>
+ val nativeTable = s"merge_parity_${suffix}_aqe_${adaptiveEnabled}_native"
+ val sparkTable = s"merge_parity_${suffix}_aqe_${adaptiveEnabled}_spark"
+ Seq(nativeTable, sparkTable).foreach { table =>
+ createTable(
+ warehouseDir,
+ table,
+ partitionSpec = "PARTITIONED BY (region)",
+ properties = Some(s"'format-version'='2', 'write.merge.mode'='$mode'"))
+ }
+
+ withSQLConf(
+ CometConf.COMET_ENABLED.key -> "false",
+ SQLConf.ADAPTIVE_EXECUTION_ENABLED.key -> adaptiveEnabled.toString,
+ "spark.sql.adaptive.coalescePartitions.enabled" -> "false",
+ "spark.sql.shuffle.partitions" -> "8") {
+ spark.sql(
+ s"INSERT INTO $catalog.$ns.$nativeTable SELECT id, region, amount FROM merge_parity_seed")
+ spark.sql(
+ s"INSERT INTO $catalog.$ns.$sparkTable SELECT id, region, amount FROM merge_parity_seed")
+ }
+
+ val inputFiles = spark
+ .sql(s"SELECT count(*) FROM $catalog.$ns.$nativeTable.data_files")
+ .collect()
+ .head
+ .getLong(0)
+ assert(inputFiles > 1L, s"expected a multi-file target, got $inputFiles file(s)")
+
+ var snapshot: Option[WriteSnapshot] = None
+ withSQLConf(
+ CometConf.COMET_EXEC_MERGE_ROWS_ENABLED.key -> "true",
+ SQLConf.ADAPTIVE_EXECUTION_ENABLED.key -> adaptiveEnabled.toString,
+ "spark.sql.adaptive.coalescePartitions.enabled" -> "false",
+ "spark.sql.shuffle.partitions" -> "8") {
+ snapshot = Some(withNativeEnabled {
+ captureWrite(nativeTable)(merge(nativeTable))
+ })
+ }
+ val writeSnapshot =
+ snapshot.getOrElse(fail(s"$mode MERGE did not produce a write snapshot"))
+ assert(
+ writeSnapshot.snapshotDelta == 1L,
+ s"expected exactly 1 new Iceberg snapshot for $mode, got ${writeSnapshot.snapshotDelta}. Plans:\n" +
+ writeSnapshot.plans.mkString("\n--\n"))
+ val commits = writeSnapshot.plans.flatMap { plan =>
+ collectWithSubqueries(plan) { case c: IcebergCommitExec => c }
+ }
+ if (mode == "copy-on-write") {
+ assert(
+ commits.nonEmpty,
+ s"expected >= 1 IcebergCommitExec for $mode, got 0. Plans:\n" +
+ writeSnapshot.plans.mkString("\n--\n"))
+ } else {
+ assert(
+ commits.isEmpty,
+ s"merge-on-read should stay on Iceberg WriteDelta, got ${commits.size} IcebergCommitExec. Plans:\n" +
+ writeSnapshot.plans.mkString("\n--\n"))
+ }
+ val mergeExecs = writeSnapshot.plans.flatMap { plan =>
+ collectWithSubqueries(plan) { case e: CometMergeRowsExec => e }
+ }
+ assert(
+ mergeExecs.nonEmpty,
+ s"expected CometMergeRowsExec for $mode. Plans:\n" +
+ writeSnapshot.plans.mkString("\n--\n"))
+
+ val nativeWrites = writeSnapshot.plans.flatMap { plan =>
+ collectWithSubqueries(plan) { case e: CometIcebergWriteExec => e }
+ }
+ if (mode == "copy-on-write") {
+ assert(
+ nativeWrites.nonEmpty,
+ "copy-on-write MERGE should feed the native Iceberg writer on this partitioned plan")
+ } else {
+ assert(
+ nativeWrites.isEmpty,
+ "merge-on-read uses Iceberg WriteDelta and must not engage CometIcebergWriteExec")
+ }
+
+ withSQLConf(
+ CometConf.COMET_ENABLED.key -> "false",
+ SQLConf.ADAPTIVE_EXECUTION_ENABLED.key -> adaptiveEnabled.toString,
+ "spark.sql.adaptive.coalescePartitions.enabled" -> "false",
+ "spark.sql.shuffle.partitions" -> "8") {
+ merge(sparkTable)
+ }
+ assert(rows(nativeTable) == rows(sparkTable), s"$mode MERGE result differs from Spark")
+ }
+ }
+ }
+ }
+
+ test("native MergeRows Iceberg cardinality violation matches Spark") {
+ assumeNativeAcceleration()
+ assume(
+ isSpark35Plus && !isSpark41Plus,
+ "native MergeRows is registered only on Spark 3.5 and 4.0")
+ withIcebergCatalog { warehouseDir =>
+ val nativeTable = "merge_cardinality_native"
+ val sparkTable = "merge_cardinality_spark"
+ Seq(nativeTable, sparkTable).foreach { table =>
+ createTable(
+ warehouseDir,
+ table,
+ partitionSpec = "PARTITIONED BY (region)",
+ properties = Some("'format-version'='2', 'write.merge.mode'='copy-on-write'"))
+ }
+ withSQLConf(CometConf.COMET_ENABLED.key -> "false") {
+ Seq(nativeTable, sparkTable).foreach { table =>
+ spark.sql(
+ s"INSERT INTO $catalog.$ns.$table VALUES " +
+ "(42, 'r2', 42.0), (43, 'r3', 43.0)")
+ }
+ }
+
+ def duplicateMerge(table: String): Unit = {
+ spark.sql(s"""
+ |MERGE INTO $catalog.$ns.$table t
+ |USING (
+ | SELECT 42 AS id, 'a' AS region, 420.0 AS amount
+ | UNION ALL
+ | SELECT 42 AS id, 'b' AS region, 421.0 AS amount
+ |) s
+ |ON t.id = s.id
+ |WHEN MATCHED THEN UPDATE SET t.amount = s.amount
+ |""".stripMargin)
+ }
+
+ val (nativePlans, nativeError) = captureFailedPlans(spark) {
+ withSQLConf(
+ CometConf.COMET_EXEC_MERGE_ROWS_ENABLED.key -> "true",
+ CometConf.COMET_ICEBERG_NATIVE_WRITE_ENABLED.key -> "false",
+ "spark.sql.autoBroadcastJoinThreshold" -> "-1") {
+ duplicateMerge(nativeTable)
+ }
+ }
+ val nativeMergeRows = nativePlans.flatMap { plan =>
+ collectWithSubqueries(plan) { case e: CometMergeRowsExec => e }
+ }
+ assert(
+ nativeMergeRows.nonEmpty,
+ "expected cardinality failure to execute through CometMergeRowsExec. Plans:\n" +
+ nativePlans.mkString("\n--\n"))
+ val nativeFailure =
+ nativeError.getOrElse(fail("native cardinality MERGE unexpectedly succeeded"))
+
+ val sparkError = intercept[Exception] {
+ withSQLConf(
+ CometConf.COMET_ENABLED.key -> "false",
+ "spark.sql.autoBroadcastJoinThreshold" -> "-1") {
+ duplicateMerge(sparkTable)
+ }
+ }
+ Seq("Comet" -> nativeFailure, "Spark" -> sparkError).foreach { case (engine, error) =>
+ assert(
+ exceptionChain(error).exists(t =>
+ Option(t.getMessage).exists(_.contains("MERGE_CARDINALITY_VIOLATION"))),
+ s"$engine did not surface MERGE_CARDINALITY_VIOLATION: $error")
+ }
+ assertRows(nativeTable, Seq(42, 43))
+ assertRows(sparkTable, Seq(42, 43))
}
}
@@ -1069,14 +1305,13 @@ class CometIcebergWriteActionSuite
}
test("native acceleration: ReplaceData (CoW MERGE) with AQE disabled") {
- // Unlike the unpartitioned MERGE above, this one *does* engage natively: partitioning the
- // table puts a `CometColumnarExchange` (REBALANCE_PARTITIONS_BY_COL) between the JVM
- // `MergeRowsExec` and the write, so the write's own child is Comet-native and
- // `requiresNativeChildren` is satisfied even though `MergeRowsExec` itself is not.
+ // Partitioning puts a `CometColumnarExchange` (REBALANCE_PARTITIONS_BY_COL) immediately
+ // above MergeRows, so the write still has a Comet-native child even when MergeRows itself
+ // stays on the JVM. This keeps the write-side transition contract covered independently of
+ // whether spark.comet.exec.mergeRows.enabled is on.
//
- // That makes this the strongest of the three CoW shapes for issue #5689: the subtree below
- // the write mixes a Spark-columnar `BatchScan`, a row-based `MergeRowsExec` and Comet
- // operators, so it needs transitions inserted in three different places.
+ // The subtree below the write mixes a Spark-columnar `BatchScan`, a row-based MergeRows
+ // path, and Comet operators, so it needs transitions inserted in three different places.
assumeNativeAcceleration()
withIcebergCatalog { warehouseDir =>
createTable(
@@ -3136,10 +3371,8 @@ class CometIcebergWriteActionSuite
}
/**
- * For writes that *should* fall back even when the native conf is on (e.g. CoW MERGE): exactly
- * one commit, no `CometIcebergWriteExec`, but the JVM two-op pair still present and rows
- * correct. Catches regressions where a trigger silently stops firing and we accidentally run
- * native for an unsupported case.
+ * For writes that should fall back even when the native writer is enabled: exactly one commit,
+ * no CometIcebergWriteExec, and the resulting row set is still correct.
*/
private def assertNativeWriteDoesNotEngage(tableName: String, expectedIds: Seq[Int])(
action: => Unit): Unit = {
diff --git a/spark/src/test/scala/org/apache/comet/exec/CometMergeRowsNativeSuiteBase.scala b/spark/src/test/scala/org/apache/comet/exec/CometMergeRowsNativeSuiteBase.scala
new file mode 100644
index 0000000000..c9459b1b74
--- /dev/null
+++ b/spark/src/test/scala/org/apache/comet/exec/CometMergeRowsNativeSuiteBase.scala
@@ -0,0 +1,493 @@
+/*
+ * 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.comet.exec
+
+import org.apache.spark.{CometListenerBusUtils, SparkConf}
+import org.apache.spark.sql.CometTestBase
+import org.apache.spark.sql.catalyst.expressions.SubqueryExpression
+import org.apache.spark.sql.comet.CometMergeRowsExec
+import org.apache.spark.sql.connector.catalog.InMemoryRowLevelOperationTableCatalog
+import org.apache.spark.sql.execution.{QueryExecution, ScalarSubquery}
+import org.apache.spark.sql.execution.adaptive.AdaptiveSparkPlanHelper
+import org.apache.spark.sql.util.QueryExecutionListener
+
+import org.apache.comet.CometConf
+import org.apache.comet.CometSparkSessionExtensions.isSpark35Plus
+
+/**
+ * `CometMergeRowsExec` converts Spark's `MergeRowsExec` and the `MergeRows` logical node that
+ * feeds it, both defined in Spark core (`execution.datasources.v2` / `catalyst.plans.logical`),
+ * not in any connector module. Spark plans a `MergeRowsExec` for MERGE INTO against any
+ * `SupportsRowLevelOperations` V2 table using group-based (copy-on-write) planning, independent
+ * of which connector implements the table.
+ *
+ * This suite pins that contract against Spark's own `InMemoryRowLevelOperationTableCatalog` test
+ * catalog rather than Iceberg. `InMemoryRowLevelOperationTable` selects its write shape via the
+ * `supports-deltas` table property: unset (default `false`) plans through group-based
+ * `MergeRows`; `supports-deltas=true` plans a JVM `WriteDelta` whose child is *also* a
+ * `MergeRowsExec` (and, with `split-updates=true`, emits `Split` for update-as-delete+insert).
+ * Comet's bottom-up conversion makes that child eligible for native execution under the JVM
+ * write, so both shapes are exercised here (`deltaMergeCase`) and checked against a pure-Spark
+ * baseline. See `CometIcebergWriteActionSuite` for MERGE INTO coverage against real Iceberg
+ * tables.
+ */
+abstract class CometMergeRowsNativeSuiteBase extends CometTestBase with AdaptiveSparkPlanHelper {
+
+ private val catalog = "generic_rowlevel"
+
+ override protected def sparkConf: SparkConf = {
+ super.sparkConf
+ .set(s"spark.sql.catalog.$catalog", classOf[InMemoryRowLevelOperationTableCatalog].getName)
+ // The test catalog's BatchScan is not a Comet-native scan. A broadcast join over these tiny
+ // fixtures therefore leaves MergeRowsExec on the JVM instead of exercising this suite's
+ // operator. Force the supported shuffle boundary while keeping AQE enabled.
+ .set("spark.sql.autoBroadcastJoinThreshold", "-1")
+ .set("spark.sql.adaptive.autoBroadcastJoinThreshold", "-1")
+ .set("spark.sql.shuffle.partitions", "4")
+ }
+
+ private def assumeMerge(): Unit = assume(isSpark35Plus, "MergeRowsExec requires Spark 3.5+")
+
+ test("MERGE all row-routing groups engage CometMergeRowsExec and match Spark") {
+ assumeMerge()
+ val target = s"$catalog.default.rowlevel_target"
+ val source = s"$catalog.default.rowlevel_source"
+
+ def resetTables(): Unit = {
+ sql(s"DROP TABLE IF EXISTS $target")
+ sql(s"DROP TABLE IF EXISTS $source")
+ sql(s"CREATE TABLE $target (id INT, region STRING, amount DOUBLE) USING parquet")
+ sql(s"CREATE TABLE $source (id INT, region STRING, amount DOUBLE) USING parquet")
+ sql(
+ s"INSERT INTO $target VALUES " +
+ (0 until 20).map(i => s"($i, 'r${i % 3}', ${i * 1.5})").mkString(", "))
+ sql(
+ s"INSERT INTO $source VALUES " +
+ (10 until 30).map(i => s"($i, 's${i % 3}', ${i * 2.0})").mkString(", "))
+ }
+
+ // Exercise all three MergeRows instruction groups in one end-to-end query: 10-19 are
+ // MATCHED, 20-29 are NOT MATCHED, and 0-9 are NOT MATCHED BY SOURCE. The predicate on the
+ // target-only clause also leaves 5-9 to Spark's generated catch-all Keep instruction.
+ val mergeSql =
+ s"""MERGE INTO $target t USING $source s ON t.id = s.id
+ |WHEN MATCHED THEN UPDATE SET t.amount = s.amount, t.region = s.region
+ |WHEN NOT MATCHED THEN INSERT (id, region, amount) VALUES (s.id, s.region, s.amount)
+ |WHEN NOT MATCHED BY SOURCE AND t.id < 5 THEN UPDATE SET t.amount = t.amount + 1000.0
+ |""".stripMargin
+
+ val captured = scala.collection.mutable.ArrayBuffer[QueryExecution]()
+ val listener = new QueryExecutionListener {
+ override def onSuccess(funcName: String, qe: QueryExecution, durationNs: Long): Unit =
+ captured += qe
+ override def onFailure(funcName: String, qe: QueryExecution, exception: Exception): Unit =
+ ()
+ }
+ spark.listenerManager.register(listener)
+ try {
+ resetTables()
+ captured.clear()
+ withSQLConf(CometConf.COMET_EXEC_MERGE_ROWS_ENABLED.key -> "true") {
+ sql(mergeSql)
+ }
+ CometListenerBusUtils.waitUntilEmpty(spark.sparkContext)
+ // Tree-string rendering uses Spark's stripped nodeName ("CometMergeRows"), not the Scala
+ // class name ("CometMergeRowsExec").
+ val engaged = captured.exists(_.executedPlan.toString.contains("CometMergeRows"))
+ val cometResult =
+ sql(s"SELECT id, region, amount FROM $target ORDER BY id").collect().map(_.toString)
+
+ resetTables()
+ withSQLConf(CometConf.COMET_ENABLED.key -> "false") {
+ sql(mergeSql)
+ }
+ val sparkResult =
+ sql(s"SELECT id, region, amount FROM $target ORDER BY id").collect().map(_.toString)
+
+ assert(
+ engaged,
+ "CometMergeRowsExec did not engage against a non-Iceberg SupportsRowLevelOperations " +
+ "table")
+ assert(
+ cometResult.toSeq == sparkResult.toSeq,
+ "native MergeRows output diverged from Spark's for a non-Iceberg source.\n" +
+ s"comet: ${cometResult.mkString(", ")}\nspark: ${sparkResult.mkString(", ")}")
+ } finally {
+ spark.listenerManager.unregister(listener)
+ }
+ }
+
+ test("MERGE cardinality violation matches Spark's structured exception") {
+ assumeMerge()
+ val target = s"$catalog.default.rowlevel_target_card"
+ val source = s"$catalog.default.rowlevel_source_card"
+
+ // Two source rows both match target row id=1 -> MERGE_CARDINALITY_VIOLATION.
+ sql(s"DROP TABLE IF EXISTS $target")
+ sql(s"DROP TABLE IF EXISTS $source")
+ sql(s"CREATE TABLE $target (id INT, amount DOUBLE) USING parquet")
+ sql(s"CREATE TABLE $source (id INT, amount DOUBLE) USING parquet")
+ sql(s"INSERT INTO $target VALUES (1, 10.0)")
+ sql(s"INSERT INTO $source VALUES (1, 20.0), (1, 30.0)")
+
+ val mergeSql =
+ s"""MERGE INTO $target t USING $source s ON t.id = s.id
+ |WHEN MATCHED THEN UPDATE SET t.amount = s.amount
+ |""".stripMargin
+
+ // `withSQLConf`'s block result isn't usable directly: under the Spark 3.5 / Scala 2.12 build
+ // its signature returns `Unit` regardless of the block's type (only the 4.x / Scala 2.13
+ // build is generic), so `val x = withSQLConf(...) { expr }` silently infers `x: Unit` there.
+ // Mutate a `var` from inside the block instead, which is portable across both.
+ val failedExecutions = scala.collection.mutable.ArrayBuffer[QueryExecution]()
+ val listener = new QueryExecutionListener {
+ override def onSuccess(funcName: String, qe: QueryExecution, durationNs: Long): Unit = ()
+ override def onFailure(funcName: String, qe: QueryExecution, exception: Exception): Unit =
+ failedExecutions += qe
+ }
+ spark.listenerManager.register(listener)
+ var cometEx: Throwable = null
+ try {
+ withSQLConf(CometConf.COMET_EXEC_MERGE_ROWS_ENABLED.key -> "true") {
+ cometEx = intercept[Exception](sql(mergeSql).collect())
+ }
+ CometListenerBusUtils.waitUntilEmpty(spark.sparkContext)
+ assert(
+ failedExecutions.exists(qe =>
+ find(qe.executedPlan) { case _: CometMergeRowsExec => true; case _ => false }.nonEmpty),
+ "cardinality-error coverage must execute through CometMergeRowsExec, not Spark fallback")
+ } finally {
+ spark.listenerManager.unregister(listener)
+ }
+ var sparkEx: Throwable = null
+ withSQLConf(CometConf.COMET_ENABLED.key -> "false") {
+ sparkEx = intercept[Exception](sql(mergeSql).collect())
+ }
+
+ // Spark 3.5 returns SparkException here while Spark 4.x returns SparkRuntimeException. The
+ // native path must follow the Spark version under test rather than hard-coding either class.
+ assert(
+ cometEx.getClass == sparkEx.getClass,
+ "Comet's native MERGE cardinality violation must use Spark's baseline exception type " +
+ s"${sparkEx.getClass.getName}, got ${cometEx.getClass.getName}: ${cometEx.getMessage}")
+
+ // Spark 4.x exposes the condition directly while Spark 3.5 can wrap the structured failure in
+ // a plain SparkException. Walk the cause chain first, then fall back to Spark's canonical
+ // bracketed condition token when a wrapper does not implement SparkThrowable itself.
+ val expectedCondition = "MERGE_CARDINALITY_VIOLATION"
+ def errorCondition(ex: Throwable): String = {
+ Iterator
+ .iterate(ex)(_.getCause)
+ .takeWhile(_ != null)
+ .flatMap { current =>
+ val structured = Seq("getCondition", "getErrorClass").iterator
+ .flatMap { methodName =>
+ try {
+ Option(
+ current.getClass.getMethod(methodName).invoke(current).asInstanceOf[String])
+ } catch {
+ case _: NoSuchMethodException => None
+ }
+ }
+ .find(_ != null)
+ structured.orElse(
+ Option(current.getMessage)
+ .filter(_.contains(s"[$expectedCondition]"))
+ .map(_ => expectedCondition))
+ }
+ .find(_ != null)
+ .getOrElse(fail(
+ s"${ex.getClass.getName} does not expose or carry Spark condition $expectedCondition"))
+ }
+
+ val sparkCondition = errorCondition(sparkEx)
+ val cometCondition = errorCondition(cometEx)
+ assert(
+ sparkCondition == expectedCondition,
+ s"expected Spark baseline condition $expectedCondition, got $sparkCondition")
+ assert(
+ cometCondition == sparkCondition,
+ s"Comet error condition $cometCondition did not match Spark baseline $sparkCondition")
+ }
+
+ /** Runs a MERGE and returns the native MergeRows node when conversion is enabled. */
+ private def runAndCaptureMergeExec(
+ mergeSql: String,
+ nativeMerge: Boolean = true): Option[CometMergeRowsExec] = {
+ val captured = scala.collection.mutable.ArrayBuffer[QueryExecution]()
+ val listener = new QueryExecutionListener {
+ override def onSuccess(funcName: String, qe: QueryExecution, durationNs: Long): Unit =
+ captured += qe
+ override def onFailure(funcName: String, qe: QueryExecution, exception: Exception): Unit =
+ ()
+ }
+ spark.listenerManager.register(listener)
+ try {
+ withSQLConf(CometConf.COMET_EXEC_MERGE_ROWS_ENABLED.key -> nativeMerge.toString) {
+ sql(mergeSql)
+ }
+ CometListenerBusUtils.waitUntilEmpty(spark.sparkContext)
+ captured
+ .flatMap(qe =>
+ find(qe.executedPlan) { case _: CometMergeRowsExec => true; case _ => false })
+ .collectFirst { case m: CometMergeRowsExec => m }
+ } finally {
+ spark.listenerManager.unregister(listener)
+ }
+ }
+
+ test("MERGE with a scalar-subquery assignment runs natively and matches Spark") {
+ assumeMerge()
+ val target = s"$catalog.default.subq_target"
+ val source = s"$catalog.default.subq_source"
+
+ def resetTables(): Unit = {
+ sql(s"DROP TABLE IF EXISTS $target")
+ sql(s"DROP TABLE IF EXISTS $source")
+ sql(s"CREATE TABLE $target (id INT, amount DOUBLE) USING parquet")
+ sql(s"CREATE TABLE $source (id INT, amount DOUBLE) USING parquet")
+ sql(s"INSERT INTO $target VALUES (1, 10.0), (2, 20.0), (3, 30.0)")
+ sql(s"INSERT INTO $source VALUES (2, 200.0), (3, 300.0), (4, 400.0)")
+ }
+
+ // Spark forbids subqueries in MERGE *conditions* but allows them in assignment values. The
+ // subquery lives on a `MergeRows.Instruction` (an Expression); `CometMergeRowsExec` must retain
+ // it as a node expression so `CometNativeExec.prepareSubqueries` registers it, otherwise
+ // execution fails with `Subquery ... not found for plan ...`.
+ val mergeSql =
+ s"""MERGE INTO $target t USING $source s ON t.id = s.id
+ |WHEN MATCHED THEN UPDATE SET t.amount = (SELECT max(amount) FROM $source)
+ |WHEN NOT MATCHED THEN INSERT (id, amount) VALUES (s.id, s.amount)
+ |""".stripMargin
+
+ resetTables()
+ val mergeExec = runAndCaptureMergeExec(mergeSql)
+ assert(
+ mergeExec.isDefined,
+ "expected the subquery MERGE to still run through CometMergeRowsExec")
+ // The node must expose the assignment's subquery so `CometNativeExec.prepareSubqueries`
+ // registers it -- either the planned `execution.ScalarSubquery` or, once AQE has run, a
+ // subquery-bearing expression tree. Absence here is what previously caused `Subquery not found`.
+ assert(
+ mergeExec.get.expressions.exists(e =>
+ e.exists(_.isInstanceOf[ScalarSubquery]) || SubqueryExpression.hasSubquery(e)),
+ "CometMergeRowsExec must expose the assignment subquery in `expressions`, got: " +
+ mergeExec.get.expressions.mkString("; "))
+ val cometResult =
+ sql(s"SELECT id, amount FROM $target ORDER BY id").collect().map(_.toString).toSeq
+
+ resetTables()
+ withSQLConf(CometConf.COMET_ENABLED.key -> "false")(sql(mergeSql))
+ val sparkResult =
+ sql(s"SELECT id, amount FROM $target ORDER BY id").collect().map(_.toString).toSeq
+
+ assert(
+ cometResult == sparkResult,
+ "native subquery MERGE diverged from Spark.\n" +
+ s"comet: ${cometResult.mkString(", ")}\nspark: ${sparkResult.mkString(", ")}")
+ }
+
+ // Executes a delta-backed MERGE with Comet enabled and requires the MergeRows child below the
+ // JVM WriteDelta to convert natively. The final table contents are then compared with a pure
+ // Spark run of the same statement. For split updates we also assert that Spark actually planned
+ // a Split instruction, so the test cannot silently stop exercising delete+reinsert semantics.
+ private def deltaMergeCase(name: String, splitUpdates: Boolean, matchedClause: String): Unit = {
+ test(s"delta-backed MERGE: $name") {
+ assumeMerge()
+ val target = s"$catalog.default.delta_t_${name.replaceAll("\\W", "_")}"
+ val source = s"$catalog.default.delta_s_${name.replaceAll("\\W", "_")}"
+
+ def reset(): Unit = {
+ sql(s"DROP TABLE IF EXISTS $target")
+ sql(s"DROP TABLE IF EXISTS $source")
+ sql(
+ s"CREATE TABLE $target (pk INT NOT NULL, amount INT) USING parquet " +
+ "TBLPROPERTIES ('supports-deltas' = 'true'" +
+ (if (splitUpdates) ", 'split-updates' = 'true')" else ")"))
+ sql(s"CREATE TABLE $source (pk INT NOT NULL, amount INT) USING parquet")
+ sql(s"INSERT INTO $target VALUES (1, 10), (2, 20), (3, 30)")
+ sql(s"INSERT INTO $source VALUES (2, 200), (3, 300), (4, 400)")
+ }
+
+ val mergeSql =
+ s"""MERGE INTO $target t USING $source s ON t.pk = s.pk
+ |$matchedClause
+ |WHEN NOT MATCHED THEN INSERT (pk, amount) VALUES (s.pk, s.amount)
+ |""".stripMargin
+
+ reset()
+ val mergeExec = runAndCaptureMergeExec(mergeSql)
+ assert(
+ mergeExec.isDefined,
+ s"delta MERGE '$name' must execute its MergeRows child natively under WriteDelta")
+ if (splitUpdates) {
+ assert(
+ mergeExec.get.matchedInstructions.exists(_.getClass.getSimpleName == "Split"),
+ s"delta MERGE '$name' must retain Spark's Split instruction for delete+reinsert")
+ }
+ val cometRows =
+ sql(s"SELECT pk, amount FROM $target ORDER BY pk").collect().map(_.toString).toSeq
+
+ reset()
+ withSQLConf(CometConf.COMET_ENABLED.key -> "false")(sql(mergeSql))
+ val sparkRows =
+ sql(s"SELECT pk, amount FROM $target ORDER BY pk").collect().map(_.toString).toSeq
+
+ assert(
+ cometRows == sparkRows,
+ s"native delta MERGE '$name' diverged from Spark.\n" +
+ s"comet: ${cometRows.mkString(", ")}\nspark: ${sparkRows.mkString(", ")}")
+ }
+ }
+
+ deltaMergeCase(
+ "matched update",
+ splitUpdates = false,
+ "WHEN MATCHED THEN UPDATE SET t.amount = s.amount")
+ deltaMergeCase(
+ "split update (delete + reinsert)",
+ splitUpdates = true,
+ "WHEN MATCHED THEN UPDATE SET t.amount = s.amount")
+ deltaMergeCase("matched delete", splitUpdates = false, "WHEN MATCHED THEN DELETE")
+
+ /** Drops the supplied row-level test tables when they exist. */
+ private def dropTables(names: String*): Unit =
+ names.foreach(name => sql(s"DROP TABLE IF EXISTS $name"))
+
+ test("disabled MergeRows flag falls back cleanly") {
+ assumeMerge()
+ val target = s"$catalog.default.flag_target"
+ val source = s"$catalog.default.flag_source"
+ dropTables(target, source)
+ sql(s"CREATE TABLE $target (id INT, value INT) USING parquet")
+ sql(s"CREATE TABLE $source (id INT, value INT) USING parquet")
+ sql(s"INSERT INTO $target VALUES (1, 10), (2, 20)")
+ sql(s"INSERT INTO $source VALUES (2, 200), (3, 300)")
+
+ val merge =
+ s"""MERGE INTO $target t USING $source s ON t.id = s.id
+ |WHEN MATCHED THEN UPDATE SET t.value = s.value
+ |WHEN NOT MATCHED THEN INSERT (id, value) VALUES (s.id, s.value)
+ |""".stripMargin
+
+ assert(runAndCaptureMergeExec(merge, nativeMerge = false).isEmpty)
+ assert(
+ sql(s"SELECT id, value FROM $target ORDER BY id").collect().map(_.toString).toSeq ==
+ Seq("[1,10]", "[2,200]", "[3,300]"))
+ }
+
+ test("copy-on-write matched delete runs through native MergeRows") {
+ assumeMerge()
+ val target = s"$catalog.default.delete_target"
+ val source = s"$catalog.default.delete_source"
+ dropTables(target, source)
+ sql(s"CREATE TABLE $target (id INT, value INT) USING parquet")
+ sql(s"CREATE TABLE $source (id INT) USING parquet")
+ sql(s"INSERT INTO $target VALUES (1, 10), (2, 20), (3, 30)")
+ sql(s"INSERT INTO $source VALUES (2)")
+
+ val merge =
+ s"""MERGE INTO $target t USING $source s ON t.id = s.id
+ |WHEN MATCHED THEN DELETE
+ |""".stripMargin
+
+ assert(runAndCaptureMergeExec(merge).isDefined)
+ assert(
+ sql(s"SELECT id, value FROM $target ORDER BY id").collect().map(_.toString).toSeq ==
+ Seq("[1,10]", "[3,30]"))
+ }
+
+ test("first matching clause prevents later ANSI predicate evaluation") {
+ assumeMerge()
+ val target = s"$catalog.default.order_target"
+ val source = s"$catalog.default.order_source"
+ dropTables(target, source)
+ sql(s"CREATE TABLE $target (id INT, value INT) USING parquet")
+ sql(s"CREATE TABLE $source (id INT, d INT) USING parquet")
+ sql(s"INSERT INTO $target VALUES (1, 10), (2, 20)")
+ sql(s"INSERT INTO $source VALUES (1, 0), (2, 2)")
+
+ val merge =
+ s"""MERGE INTO $target t USING $source s ON t.id = s.id
+ |WHEN MATCHED AND s.d = 0 THEN UPDATE SET t.value = 111
+ |WHEN MATCHED AND 2 / s.d > 0 THEN UPDATE SET t.value = 222
+ |""".stripMargin
+
+ withSQLConf("spark.sql.ansi.enabled" -> "true") {
+ assert(runAndCaptureMergeExec(merge).isDefined)
+ }
+ assert(
+ sql(s"SELECT id, value FROM $target ORDER BY id").collect().map(_.toString).toSeq ==
+ Seq("[1,111]", "[2,222]"))
+ }
+
+ test("CometMergeRowsExec semantic identity reflects instruction groups and cardinality flag") {
+ assumeMerge()
+ val target = s"$catalog.default.eq_target"
+ val source = s"$catalog.default.eq_source"
+ sql(s"DROP TABLE IF EXISTS $target")
+ sql(s"DROP TABLE IF EXISTS $source")
+ sql(s"CREATE TABLE $target (id INT, amount DOUBLE) USING parquet")
+ sql(s"CREATE TABLE $source (id INT, amount DOUBLE) USING parquet")
+ sql(s"INSERT INTO $source VALUES (1, 100.0), (3, 300.0)")
+
+ def merge(clauses: String): CometMergeRowsExec = {
+ sql(s"DROP TABLE IF EXISTS $target")
+ sql(s"CREATE TABLE $target (id INT, amount DOUBLE) USING parquet")
+ sql(s"INSERT INTO $target VALUES (1, 10.0), (2, 20.0)")
+ val m =
+ runAndCaptureMergeExec(s"MERGE INTO $target t USING $source s ON t.id = s.id\n$clauses\n")
+ assert(m.isDefined)
+ m.get
+ }
+
+ val update = merge("""WHEN MATCHED THEN UPDATE SET t.amount = s.amount
+ |WHEN NOT MATCHED THEN INSERT (id, amount) VALUES (s.id, s.amount)
+ |WHEN NOT MATCHED BY SOURCE THEN UPDATE SET t.amount = t.amount + 1""".stripMargin)
+ val delete = merge("""WHEN MATCHED THEN DELETE
+ |WHEN NOT MATCHED THEN INSERT (id, amount) VALUES (s.id, s.amount)""".stripMargin)
+
+ // equal to a structural copy (hash contract), unequal to a different MERGE
+ val same = update.copy()
+ assert(update == same && update.hashCode() == same.hashCode())
+ assert(update != delete, "different MERGE instructions must not compare equal")
+ assert(
+ update != update.copy(checkCardinality = !update.checkCardinality),
+ "nodes differing only in checkCardinality must not compare equal")
+
+ // The dangerous case: identical flattened expressions, different group partitioning. Moving
+ // the MATCHED instruction into the NOT MATCHED BY SOURCE group leaves `expressions` (and so a
+ // naive flat-list equality) unchanged, but the operator means something entirely different.
+ // Move the last MATCHED instruction to the front of the (adjacent) NOT MATCHED group so the
+ // flattened expression order is byte-for-byte unchanged; only the group boundary shifts.
+ assume(update.matchedInstructions.nonEmpty)
+ val shuffled = update.copy(
+ matchedInstructions = update.matchedInstructions.dropRight(1),
+ notMatchedInstructions =
+ update.matchedInstructions.takeRight(1) ++ update.notMatchedInstructions)
+ assert(
+ update.expressions.toList == shuffled.expressions.toList,
+ "test premise: the two nodes must have the same flattened expressions")
+ assert(update != shuffled, "instruction-group boundaries must be part of equality")
+ assert(
+ update.canonicalized != shuffled.canonicalized,
+ "instruction-group boundaries must survive canonicalization")
+ }
+}
diff --git a/spark/src/test/spark-3.4/org/apache/comet/exec/CometMergeRowsSuite.scala b/spark/src/test/spark-3.4/org/apache/comet/exec/CometMergeRowsSuite.scala
new file mode 100644
index 0000000000..b97c0e5bb5
--- /dev/null
+++ b/spark/src/test/spark-3.4/org/apache/comet/exec/CometMergeRowsSuite.scala
@@ -0,0 +1,31 @@
+/*
+ * 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.comet.exec
+
+import org.apache.spark.sql.CometTestBase
+
+import org.apache.comet.shims.ShimCometMergeRows
+
+/** Spark 3.4 compatibility coverage for the version-specific MergeRows registration shim. */
+class CometMergeRowsSuite extends CometTestBase {
+ test("Spark 3.4 leaves native MergeRows execution unregistered") {
+ assert(ShimCometMergeRows.nativeExecs.isEmpty)
+ }
+}
diff --git a/spark/src/test/spark-3.5/org/apache/comet/exec/CometMergeRowsSuite.scala b/spark/src/test/spark-3.5/org/apache/comet/exec/CometMergeRowsSuite.scala
new file mode 100644
index 0000000000..a621b5a9f5
--- /dev/null
+++ b/spark/src/test/spark-3.5/org/apache/comet/exec/CometMergeRowsSuite.scala
@@ -0,0 +1,23 @@
+/*
+ * 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.comet.exec
+
+/** Spark 3.5.x entry point for the shared native MergeRows contract suite. */
+class CometMergeRowsSuite extends CometMergeRowsNativeSuiteBase
diff --git a/spark/src/test/spark-4.0/org/apache/comet/exec/CometMergeRowsSuite.scala b/spark/src/test/spark-4.0/org/apache/comet/exec/CometMergeRowsSuite.scala
new file mode 100644
index 0000000000..f0da046a99
--- /dev/null
+++ b/spark/src/test/spark-4.0/org/apache/comet/exec/CometMergeRowsSuite.scala
@@ -0,0 +1,23 @@
+/*
+ * 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.comet.exec
+
+/** Spark 4.0 entry point for the shared native MergeRows contract suite. */
+class CometMergeRowsSuite extends CometMergeRowsNativeSuiteBase
diff --git a/spark/src/test/spark-4.1+/org/apache/comet/exec/CometMergeRowsSuite.scala b/spark/src/test/spark-4.1+/org/apache/comet/exec/CometMergeRowsSuite.scala
new file mode 100644
index 0000000000..f02ee073a7
--- /dev/null
+++ b/spark/src/test/spark-4.1+/org/apache/comet/exec/CometMergeRowsSuite.scala
@@ -0,0 +1,109 @@
+/*
+ * 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.comet.exec
+
+import scala.collection.mutable.ArrayBuffer
+
+import org.apache.spark.{CometListenerBusUtils, SparkConf}
+import org.apache.spark.sql.CometTestBase
+import org.apache.spark.sql.connector.catalog.InMemoryRowLevelOperationTableCatalog
+import org.apache.spark.sql.execution.QueryExecution
+import org.apache.spark.sql.execution.adaptive.AdaptiveSparkPlanHelper
+import org.apache.spark.sql.util.QueryExecutionListener
+
+import org.apache.comet.CometConf
+
+/**
+ * Spark 4.1+ compatibility coverage for MergeRowsExec.
+ *
+ * Spark 4.1 introduced writer-side MergeSummary discovery that specifically looks for Spark's
+ * concrete MergeRowsExec. Comet must therefore retain that JVM node until it can preserve the
+ * summary-aware BatchWrite.commit contract end-to-end.
+ */
+class CometMergeRowsSuite extends CometTestBase with AdaptiveSparkPlanHelper {
+
+ private val catalog = "generic_rowlevel"
+
+ override protected def sparkConf: SparkConf = {
+ super.sparkConf
+ .set(s"spark.sql.catalog.$catalog", classOf[InMemoryRowLevelOperationTableCatalog].getName)
+ .set("spark.sql.autoBroadcastJoinThreshold", "-1")
+ .set("spark.sql.adaptive.autoBroadcastJoinThreshold", "-1")
+ .set("spark.sql.shuffle.partitions", "4")
+ }
+
+ test("Spark 4.1+ MERGE retains Spark MergeRowsExec for write-summary compatibility") {
+ val target = s"$catalog.default.rowlevel_target"
+ val source = s"$catalog.default.rowlevel_source"
+
+ sql(s"DROP TABLE IF EXISTS $target")
+ sql(s"DROP TABLE IF EXISTS $source")
+ sql(s"CREATE TABLE $target (id INT, amount DOUBLE) USING parquet")
+ sql(s"CREATE TABLE $source (id INT, amount DOUBLE) USING parquet")
+ sql(s"INSERT INTO $target VALUES (1, 10.0), (2, 20.0)")
+ sql(s"INSERT INTO $source VALUES (2, 200.0), (3, 300.0)")
+
+ val captured = ArrayBuffer[QueryExecution]()
+ val listener = new QueryExecutionListener {
+ override def onSuccess(funcName: String, qe: QueryExecution, durationNs: Long): Unit =
+ captured += qe
+ override def onFailure(funcName: String, qe: QueryExecution, exception: Exception): Unit =
+ ()
+ }
+
+ spark.listenerManager.register(listener)
+ try {
+ withSQLConf(CometConf.COMET_EXEC_MERGE_ROWS_ENABLED.key -> "true") {
+ sql(s"""MERGE INTO $target t USING $source s ON t.id = s.id
+ |WHEN MATCHED THEN UPDATE SET t.amount = s.amount
+ |WHEN NOT MATCHED THEN INSERT (id, amount) VALUES (s.id, s.amount)
+ |""".stripMargin)
+ }
+ CometListenerBusUtils.waitUntilEmpty(spark.sparkContext)
+
+ val executedPlans = captured.map(_.executedPlan)
+ val sparkMergeRows = executedPlans.exists(plan =>
+ find(plan) {
+ case node if node.getClass.getSimpleName == "MergeRowsExec" => true
+ case _ => false
+ }.nonEmpty)
+ val cometMergeRows = executedPlans.exists(plan =>
+ find(plan) {
+ case node if node.getClass.getSimpleName == "CometMergeRowsExec" => true
+ case _ => false
+ }.nonEmpty)
+
+ assert(
+ sparkMergeRows,
+ "Spark 4.1+ MERGE must retain the concrete Spark MergeRowsExec so the V2 writer can " +
+ "derive MergeSummary")
+ assert(
+ !cometMergeRows,
+ "Spark 4.1+ must not replace MergeRowsExec until Comet preserves MergeSummary commit " +
+ "semantics")
+
+ val rows =
+ sql(s"SELECT id, amount FROM $target ORDER BY id").collect().map(_.toString).toSeq
+ assert(rows == Seq("[1,10.0]", "[2,200.0]", "[3,300.0]"))
+ } finally {
+ spark.listenerManager.unregister(listener)
+ }
+ }
+}
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@datafusion.apache.org
For additional commands, e-mail: commits-help@datafusion.apache.org