dongjoon-hyun opened a new pull request, #60511:
URL: https://github.com/apache/spark/pull/60511

   ### What changes were proposed in this pull request?
   
   This PR fixes a correctness issue of DSv2 `MERGE` on a table that accepts 
any schema (`TableCapability.ACCEPT_ANY_SCHEMA`) when the command references a 
metadata column of the table. It is the `MERGE` counterpart of SPARK-61683 
(#60486), which fixed `UPDATE`. `RewriteMergeIntoTable` now writes only the 
data columns of the target table and handles the assignments to metadata 
columns as follows:
   
   - In an `UPDATE` action, an assignment of a metadata column to itself, such 
as `index = index`, is removed. In an `INSERT` action, an assignment of a 
metadata column to a null literal, which the alignment adds for a nullable 
column without a value, is removed. The connector receives the metadata values 
that `MetadataColumn` defines (e.g. `PRESERVE_ON_UPDATE`) for updated rows and 
no metadata for inserted rows, as for any other `MERGE`.
   - Any other assignment to a metadata column, such as `index = 5`, fails with 
`DATATYPE_MISMATCH.INVALID_ROW_LEVEL_OPERATION_ASSIGNMENTS`, as it does on 
other tables since SPARK-60721 (#59930), unless 
`spark.sql.legacy.ignoreMetadataColumnAssignments` is `true`. With that config, 
it is ignored.
   - In a group-based `MERGE`, every instruction emits the metadata values in 
the order of the metadata columns that the carried over rows contain.
   
   The handling of the assignments from SPARK-61683 moves from 
`RewriteUpdateTable` to `RewriteRowLevelCommand`, so that `RewriteUpdateTable` 
and `RewriteMergeIntoTable` share it. `RewriteUpdateTable` behaves as before.
   
   Spark does not resolve a `MERGE` on such a table, and leaves it to the rules 
injected for that table. `RewriteMergeIntoTable` rewrites the command once its 
assignments are aligned with the output of its target table. When the command 
references a metadata column, `AddMetadataColumns` adds every metadata column 
to that output, which SPARK-60667 (#59895) kept on purpose for such tables. So 
a rule that aligns the assignments with the output of the target table, as 
`ResolveRowLevelCommandAssignments` does for other tables, adds an assignment 
for each metadata column. This happens when the target table has no alias, as 
in `MERGE INTO cat.db.t USING ...` or `Dataset.mergeInto`. 
`MergeIntoTable.skipSchemaResolution` looks through only one alias, so Spark 
aligns the assignments of a `MERGE` whose target table has an alias by itself.
   
   `RewriteMergeIntoTable` handled these assignments, and the metadata columns 
in the output of the target table, as data columns. As a result:
   
   - Group-based and delta-based `MERGE` pass the old value of a metadata 
column with `PRESERVE_ON_UPDATE = false` to the connector for an updated row, 
instead of `null`, and pass the value of any assignment to a metadata column, 
such as `index = 5`, without any error.
   - They also pass the metadata columns in every row as data columns, and 
report them in `LogicalWriteInfo.schema()`. An insert-only `MERGE` appends the 
metadata columns as data columns.
   - With whole-stage codegen, a `MERGE` with an `UPDATE` action fails with 
`java.lang.AssertionError`, because its instructions produce more values than 
the output of `MergeRows`.
   
   For example, take an in-memory table `t` (`pk INT NOT NULL, id INT, dep 
STRING`, partitioned by `dep`) that accepts any schema, with the metadata 
columns `index` (`PRESERVE_ON_UPDATE = false`) and `_partition`, and the rows 
`(1, 1, 'hr')`, `(2, 2, 'software')` and `(3, 3, 'hr')`, a source `s` with the 
rows `(1, 10, 'hr')`, `(3, 30, 'hr')` and `(4, 40, 'hr')`, and a rule that 
resolves and aligns the `MERGE` as above:
   
   ```sql
   MERGE INTO t USING s ON t.pk = s.pk
   WHEN MATCHED AND t._partition = 'hr' THEN UPDATE SET id = -1
   -- Issue 1: Without whole-stage codegen, the connector should receive the 
metadata (hr, null)
   --          and the write schema struct<pk:int,id:int,dep:string>, but it 
receives the metadata
   --          (hr, 0) and the write schema 
struct<pk:int,id:int,dep:string,index:int,_partition:string>.
   -- Issue 2: With whole-stage codegen, the statement should succeed,
   --          but it fails with java.lang.AssertionError: assertion failed (in 
MergeRowsExec).
   
   MERGE INTO t USING s ON t.pk = s.pk
   WHEN MATCHED AND t._partition = 'hr' THEN UPDATE SET id = -1, index = 5
   -- Issue 3: It should fail as on a table that does not accept any schema, 
but it passes
   --          analysis, and without whole-stage codegen, the connector 
receives the metadata (hr, 5).
   
   -- with nullable metadata columns
   MERGE INTO t USING s ON t.pk = s.pk AND t._partition = s.dep
   WHEN NOT MATCHED THEN INSERT (pk, id, dep) VALUES (s.pk, s.id, s.dep)
   -- Issue 4: The connector should receive the write schema 
struct<pk:int,id:int,dep:string>,
   --          but it receives 
struct<pk:int,id:int,dep:string,index:int,_partition:string>,
   --          and the in-memory table adds `index` and `_partition` to its 
data columns.
   ```
   
   **AFTER**
   
   The first statement writes what the same `MERGE` writes on a table that does 
not accept any schema: the connector receives the metadata `(hr, null)` and the 
write schema `struct<pk:int,id:int,dep:string>`, with and without whole-stage 
codegen, in group-based and delta-based plans, and also when the update is 
represented as a delete and an insert. The second statement fails:
   
   ```
   [DATATYPE_MISMATCH.INVALID_ROW_LEVEL_OPERATION_ASSIGNMENTS] Cannot resolve 
"pk = pk", "id = -1 AS id", "dep = dep", "index = 5 AS index", "_partition = 
_partition" due to data type mismatch:
   - Cannot assign to metadata column 'index' SQLSTATE: 42K09
   ```
   
   The third statement appends rows with the write schema 
`struct<pk:int,id:int,dep:string>`, and the table keeps its columns.
   
   ### Why are the changes needed?
   
   This is a correctness issue. `MetadataColumn.PRESERVE_ON_UPDATE` says that 
the metadata value is replaced with `null` if it is false. However, such a 
`MERGE` passes the old value to the connector without any error. Row lineage in 
Iceberg and Delta Lake relies on this contract to reset the row version on 
update (SPARK-50820), so a connector that accepts such a write can record a 
stale row version. The same `MERGE` also passes metadata columns to the 
connector as data columns, and fails with whole-stage codegen when it has an 
`UPDATE` action.
   
   SPARK-60667 (#59895) fixed the same problems for tables that do not accept 
any schema, and SPARK-61683 (#60486) fixed them for `UPDATE` on tables that 
accept any schema.
   
   ### Does this PR introduce _any_ user-facing change?
   
   Yes. This is a bug fix for DSv2 `MERGE` statements on tables that accept any 
schema when they reference metadata columns of the table:
   
   - Metadata columns with `PRESERVE_ON_UPDATE = false` are replaced with 
`null` for updated rows, as documented, and connectors no longer receive 
metadata columns as data columns.
   - A `MERGE` with an `UPDATE` action no longer fails with whole-stage codegen.
   - Any assignment to a metadata column other than those that the alignment 
adds fails, as on other tables. To ignore such assignments instead, set 
`spark.sql.legacy.ignoreMetadataColumnAssignments` to `true`.
   
   By code reading, this has happened since Spark started to rewrite `MERGE` on 
DSv2 tables that support row-level operations in Apache Spark 
[3.5.0](https://github.com/apache/spark/releases/tag/v3.5.0) (2023-09-09).
   
   ### How was this patch tested?
   
   Pass the CIs with the newly added test suites. 
`GroupBasedAcceptAnySchemaMergeIntoTableSuite`, 
`DeltaBasedAcceptAnySchemaMergeIntoTableSuite` and 
`DeltaBasedAcceptAnySchemaMergeIntoTableUpdateAsDeleteAndInsertSuite` run 
`MERGE` on in-memory tables that accept any schema. A test-only session 
extension injects a rule that resolves and aligns such a `MERGE`. The in-memory 
test table has a new table property `nullable-metadata-columns`, so that 
`INSERT` actions can be aligned with its metadata columns.
   
   - `SPARK-61725: merge into a table accepting any schema handles metadata 
columns correctly` runs a `MERGE` with `WHEN MATCHED ... UPDATE`, `WHEN NOT 
MATCHED ... INSERT` and `WHEN NOT MATCHED BY SOURCE ... UPDATE` actions, and 
checks the result, the write schema and the rows and metadata that the 
connector receives.
   - `SPARK-61725: insert-only merge into a table accepting any schema writes 
data columns` runs insert-only `MERGE` statements with one and two `NOT 
MATCHED` actions, and checks the result and the write schema.
   - `SPARK-61725: merge into a table accepting any schema rejects metadata 
column assignments` runs `MERGE` statements that assign a metadata column in an 
`UPDATE` action and in an `INSERT` action, and runs them again with the legacy 
config.
   
   All of them fail without this fix.
   
   ```
   build/sbt "sql/testOnly *AcceptAnySchemaMergeIntoTable* -- -z SPARK-61725"
   ```
   
   ### Was this patch authored or co-authored using generative AI tooling?
   
   Generated-by: Claude Opus 5.5
   


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]


---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]

Reply via email to