jayadeep-jayaraman opened a new pull request, #60791:
URL: https://github.com/apache/spark/pull/60791

   ### What changes were proposed in this pull request?
   
   This PR preserves the `RowLevelOperation` scan-to-write handoff on the 
insert-only `MERGE INTO` fast path (`InsertOnlyMerge`, i.e., `MERGE INTO` 
statements with only `WHEN NOT MATCHED THEN INSERT` actions) while keeping the 
`LeftAnti` join and append-only write optimization:
   
   1. **Opt-in DSv2 SPI (`SupportsRowLevelOperations`)**:
      - Adds a single backward-compatible default method 
`Optional<RowLevelOperationBuilder> 
newInsertOnlyMergeOperationBuilder(RowLevelOperationInfo info)` (defaulting to 
`Optional.empty()`, `@since 4.4.0`).
      - Connectors that opt in return a `RowLevelOperationBuilder` whose 
`RowLevelOperation` coordinates the `LeftAnti` target scan (`newScanBuilder`) 
and append write (`newWriteBuilder`), while receiving query-level `WITH (...)` 
options in `info.options()` so they can opt in/out dynamically (e.g., by 
isolation level).
   2. **Analyzer (`RewriteMergeIntoTable`, `v2Commands`, 
`RowLevelOperationTable`)**:
      - When the target implements `SupportsRowLevelOperations` (without 
`TableCapability.V1_BATCH_WRITE`) and returns a builder, wraps the target in a 
shared `RowLevelOperationTable(tbl, builder.build(), isInsertOnly = true)` used 
by both the `LeftAnti` scan and `InsertOnlyMerge`.
      - Retains `originalTable` on `InsertOnlyMerge` for 
`TableCapabilityCheck`, `AppendWrite`, and cache invalidation (matching 
`ReplaceData` and `WriteDelta`), and strips metadata columns from 
`writeRelation.output` while keeping referenced metadata columns on 
`readRelation`.
   3. **Optimizer & Planning (`V2Writes`, `DataSourceV2Strategy`, 
`PushDownLeftSemiAntiJoin`)**:
      - In `V2Writes`, invokes `operation.newWriteBuilder(info)` when the 
`RowLevelOperationTable` target scan survives optimization, and falls back 
directly to `underlyingTable.asWritable.newWriteBuilder(info)` if 
`PropagateEmptyRelation` pruned the target scan (e.g., `ON false` or an empty 
source).
      - In `DataSourceV2Strategy`, allows runtime filtering / DPP on 
group-based insert-only `RowLevelOperationTable` scans (`!t.isInsertOnly && 
!t.operation.isInstanceOf[SupportsDelta]`) and refreshes caches via 
`originalTable`.
      - In `PushDownLeftSemiAntiJoin`, avoids cloning `RowLevelOperationTable` 
across `Union` branches (`UNION ALL` sources) to preserve the 1:1 scan-to-write 
handoff, and skips `canPlanAsBroadcastHashJoin` when the right side contains an 
unpushed `DataSourceV2RelationBase` (`DISTINCT` / `GROUP BY` sources) so 
`computeStats()` is not called before `V2ScanRelationPushDown`.
   
   ### Why are the changes needed?
   
   Previously, `RewriteMergeIntoTable` rewrote insert-only `MERGE INTO` 
directly against the raw `DataSourceV2Relation`, completely bypassing 
`SupportsRowLevelOperations` / `RowLevelOperationTable`. Because the `LeftAnti` 
target scan (`table.newScanBuilder`) and append write (`table.newWriteBuilder`) 
were disconnected, DSv2 connectors (such as Apache Iceberg under 
`write.merge.isolation-level = 'serializable'`) never received the starting 
snapshot ID, pushed filters, or `MERGE` context during write planning/commit, 
causing unvalidated blind appends that violate `SERIALIZABLE` isolation:
   
   - **Phantom insert (duplicate keys)**: An insert-only `MERGE` inserting `(2, 
'eng')` when `id = 2` is absent commits concurrently with `INSERT INTO t VALUES 
(2, 'sales')`, leaving duplicate `id = 2`.
   - **Non-serializable write skew (lost insert)**: Starting from `[(1, 
'platinum'), (2, 'gold')]`, an insert-only `MERGE` with source `[(2, 'bronze'), 
(9, 'bronze')]` commits concurrently with `DELETE FROM t WHERE id IN (2, 9)`, 
leaving `[(1, 'platinum'), (9, 'bronze')]` — impossible under either serial 
order.
   
   This change lets connectors enforce `MERGE` isolation levels without losing 
the `LeftAnti` fast path or rewriting untouched files in copy-on-write tables, 
while remaining 100% backward-compatible for connectors that do not override 
the new default method (including DELETE/UPDATE-only connectors and un-upgraded 
CoW connectors).
   
   ### Does this PR introduce _any_ user-facing change?
   
   Yes (DSv2 connector SPI addition): adds a backward-compatible default method 
`SupportsRowLevelOperations.newInsertOnlyMergeOperationBuilder(RowLevelOperationInfo)`
 returning `Optional.empty()` by default. There is no behavior change for 
existing connectors unless they override this method.
   
   ### How was this patch tested?
   
   Added unit and end-to-end tests:
   - `InsertOnlyMergeIsolationSuite`: verifies scan-to-write handoff, `WITH` 
options, pushed filters, empty `rowIdSchema`/`metadataSchema`, concurrent 
`INSERT` phantom conflict detection, concurrent `DELETE` write-skew conflict 
detection, non-conflicting concurrent `INSERT` outside pushed filter, dynamic 
`Optional.empty()` fallback (e.g. `WITH ('isolation-level' = 'snapshot')`), 
`RequiresDistributionAndOrdering`, pruned target scans (`ON false`, empty 
source, `WHEN NOT MATCHED AND false`), DELETE/UPDATE-only connectors, 
`V1_BATCH_WRITE` tables, target metadata columns in `ON`, group-based runtime 
filtering, plain V2 tables in `V2Writes`, and `UNION ALL` / `DISTINCT` / `GROUP 
BY` sources.
   - `MergeIntoTableSuiteBase`: verifies shared `RowLevelOperationTable` 
identity between `LeftAnti` scan and `InsertOnlyMerge` write (single and multi 
`WHEN NOT MATCHED`) and relation cache refresh.
   - `AcceptAnySchemaMergeIntoTableSuiteBase`: verifies metadata column 
stripping on `InsertOnlyMerge.table.output` for both opt-in and default tables.
   - `TableCapabilityCheckSuite`: verifies batch write capability checks for 
raw and `RowLevelOperationTable`-wrapped `InsertOnlyMerge`.
   - `LeftSemiAntiJoinPushDownSuite`: verifies `PushDownLeftSemiAntiJoin` does 
not clone `RowLevelOperationTable` through `Union` or invoke `computeStats()` 
on unpushed `DataSourceV2Relation` through `Aggregate`.
   
   Verified with `build/sbt`:
   - `catalyst/testOnly *RowLevelOperationTableSuite 
*LeftSemiAntiJoinPushDownSuite` (90/90 passed)
   - `sql/testOnly *InsertOnlyMergeIsolationSuite *TableCapabilityCheckSuite 
*GroupBasedMergeIntoTableSuite *DeltaBasedMergeIntoTableSuite 
*GroupBasedNoMetadataMergeIntoTableSuite 
*DeltaBasedNoMetadataMergeIntoTableSuite 
*GroupBasedAcceptAnySchemaMergeIntoTableSuite 
*DeltaBasedAcceptAnySchemaMergeIntoTableSuite *MergeIntoDataFrameSuite 
*DataSourceV2EnhancedDeleteFilterSuite` (534/534 passed)
   - `catalyst/checkstyle`, `catalyst/scalastyle`, `catalyst/Test/scalastyle`, 
`sql/scalastyle`, `sql/Test/scalastyle` (0 errors, 0 warnings)
   
   ### Was this patch authored or co-authored using generative AI tooling?
   
   Yes


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