Skip to content

[spark] Add atomic replacement by business keys for Data Evolution - #11174

Open
JustinBinber wants to merge 10 commits into
apache:masterfrom
JustinBinber:codex/spark-de-atomic-replace-by-keys
Open

JustinBinber wants to merge 10 commits into
apache:masterfrom
JustinBinber:codex/spark-de-atomic-replace-by-keys

Conversation

@JustinBinber

@JustinBinber JustinBinber commented Nov 15, 2026 •

Copy link
Copy Markdown
Contributor

Purpose

Separate key-based DELETE and INSERT statements on a Data Evolution table publish two snapshots. Readers can observe the deletion-only snapshot, and an INSERT failure leaves those deletions committed. Add CALL sys.replace_by_keys(table, source_query, key_columns, target_filter) to prepare deletion vectors and appended files through the existing distributed paths, then publish both in one data commit.

The target is a Data Evolution append table with row tracking and deletion vectors, no primary key, and bucket=-1.

Behavior

Deletion uses positive SQL IN membership on complete business keys. The command constructs InSubquery/ListQuery from the original source keys and lets Spark analyze IN coercion before optimizing membership into a semi join. INSERT casts cannot change the deletion keys. Membership is analyzed against an empty relation with the target schema before empty-target or pruned-split shortcuts, then reused on the actual scan. Invalid key types are rejected independently of target contents. This also preserves mixed-type behavior such as STRING '01' against an INT target under LEGACY assignment with ANSI disabled.

Composite keys and ordinary SQL NULL semantics are supported. Every source row is appended, including duplicates; target_filter restricts deletion only. Source columns are aligned by name using existing Paimon INSERT casts and checks, without schema evolution. Replaced rows receive new RowIDs; unaffected rows retain theirs. The operation does not invoke native MERGE or reconstruct old target payload columns.

Repeatable reads and conflicts

Paimon source snapshots are fixed across key-only deletion preparation and full-row append preparation, preserving analyzed attributes, schema and effective options. Fallback components are pinned separately with Core partition precedence. Retained tags keep the resolved Snapshot after ordinary snapshot JSON expiry. Query-time expressions share one value, including inside subqueries.

Wholly unwritten source relations become immutable empty LocalRelation leaves, preserving their output attributes and preventing custom postpone merge-on-read readers from discovering a later first commit. Partially empty fallback sources retain frozen empty components without losing populated branches. An empty target baseline likewise cannot delete a concurrent writer's first append.

Checked commits detect overlapping partial-column updates using changed DV-anchor row ranges. Missing referenced anchors or changed physical identity/RowID mappings, including reassignment, reject stale commits and require replanning. Disjoint updates remain possible; unchanged vectors relocated during index repacking are compared by content to avoid false conflicts.

Limits

Streaming, command, nondeterministic, incremental/monitoring and projection-unstable sources are rejected; unstable batches require explicit materialization. Conflicts require replanning: the procedure does not automatically retry or enforce business-key uniqueness against concurrent appends.

Known staged messages are aborted on preparation failure. Publication exceptions can have an uncertain outcome and are not blindly aborted or retried. Inline compaction is disabled; both sets of commit metadata can coexist in memory.

Validation

At 00ce3a2, all 50 tests passed across ReplaceByKeysProcedureTest (18), ReplaceByKeysConflictTest (7) and ReplaceByKeysAcceptanceTest (25), with zero suite aborts. Coverage includes mixed/composite keys, NULLs/duplicates, actual INSERT assignment oracles, membership type rejection across empty/pruned/populated targets, empty-source freezing, logical PK/MOR and partial-update DE sources, historical/tag/fallback reads, failure atomicity, independent-reader visibility and maintenance/concurrency conflicts.

Focused execution used Linux JDK 17, Spark 3.5.9 and Scala 2.12, with archived source/class hashes and Java 8 bytecode targeting. Module-scoped Spotless apply/check passed for Spark common and UT. No performance result is claimed for this head.

Automatic CI completed successfully for exact head 00ce3a2: 18 checks succeeded and 1 was skipped. The 50 replacement tests passed separately on Spark 3.5.9 / Scala 2.12 / JDK 8, Spark 3.5.9 / Scala 2.13 / JDK 8, and Spark 4.1.4 / Scala 2.13 / JDK 17, including all four membership shortcut regressions. The dedicated Spark 4.2 job passed its own 47 tests; it does not select these replacement suites.

@JustinBinber
JustinBinber marked this pull request as ready for review November 15, 2026 16:04

@JingsongLi JingsongLi left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I reproduced two source-binding issues on Java 8 / Spark 3.5.9; details are inline. The existing six-case ReplaceByKeysProcedureTest suite passed.

@JingsongLi JingsongLi left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Requirement fit: SUPPORTED. Implementation: FINDINGS.

The atomic delete-plus-append operation has end-to-end value, and the revised source binding, empty-baseline handling and ordinary overlapping/disjoint-update cases pass. On this exact head, all 13 submitted Spark suites' cases and 76 related Core conflict/DV cases passed with JDK 8 / Spark 3.5.9 and normal Maven checks. An additional deterministic two-case real-operation probe passes its no-reassignment control but reproduces the silent row loss below after row-ID reassignment.

No production source changes were made; the temporary probe was removed from the worktree. Current exact-head CI remains queued. The confirmed P1 should block production use of this procedure until corrected.

@JingsongLi JingsongLi left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The updated fallback/tag binding, empty target baseline, and row-ID reassignment protections are covered by the submitted Spark tests and passed locally. Two separate public CALL probes on real tables found mixed-key deletion and empty source regressions.

@JingsongLi JingsongLi left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I verified in Spark 3.5.9 that the updated source fixes the previous mixed-key comparison and the two empty-source cases. There is one remaining difference from ordinary DELETE IN.

@JingsongLi

Copy link
Copy Markdown
Contributor

Could we use a single native MERGE INTO as the baseline for this proposal? For a fixed batch with the same business-key types as the target, the following statement replaces all rows for each incoming key in one snapshot. I ran it on Spark 3.5.7 with Paimon 2.2-SNAPSHOT against a Data Evolution table with deletion vectors enabled.

MERGE INTO lake.db.target AS t
USING (
    SELECT DISTINCT tenant, id, CAST(NULL AS STRING) AS payload, 'D' AS op
    FROM lake.db.batch
    UNION ALL
    SELECT tenant, id, payload, 'I' AS op
    FROM lake.db.batch
) AS s
ON  s.op = 'D'
AND t.tenant = s.tenant
AND t.id = s.id
AND t.tenant = 7  -- optional target_filter, applies only to deletion
WHEN MATCHED THEN DELETE
WHEN NOT MATCHED AND s.op = 'I' THEN
    INSERT (tenant, id, payload) VALUES (s.tenant, s.id, s.payload);

Each distinct key produces one delete marker that can match every old row for that key. Every insert row reaches the NOT MATCHED branch. In my test, both old rows for one key disappeared, both identical incoming rows received fresh row IDs, and the target advanced by exactly one snapshot. Old rows with a NULL key or outside tenant 7 retained their row IDs, while their incoming counterparts were appended.

The procedure does offer additional guarantees. It pins the Paimon source snapshots across both preparation jobs and follows Spark's IN (subquery) coercion for deletion. For example, with ANSI disabled and LEGACY assignment, I verified that an INT key of 1 matches a STRING key of '01' in the equality join above, while the positive IN predicate leaves that target row untouched.

Is there a representative workload that depends on those guarantees, or one where the dedicated path materially reduces I/O or runtime? A comparison against this statement on a wide table with a small replacement batch, reporting target bytes read, shuffle bytes, and end-to-end time, would help us decide. My preference is to document the SQL pattern first and review the deletion-vector conflict fix independently, then add a public procedure if the workload or measurements justify it.

@JustinBinber

Copy link
Copy Markdown
Contributor Author

In reply to the single native MERGE baseline.

Thanks for the single-statement baseline. We benchmarked your D-marker + INSERT form, ordinary UPDATE + INSERT MERGE, and the proposed CALL on the same fixed batch and 128-column Data Evolution target. The target had 4,096 rows in 64 files, with 32 matched and 8 new source rows. We enabled AQE and ran each arm three times in rotating order, with a fresh target copy and the same warm-cache policy.

SQL Mean end-to-end time Target Parquet bytes returned
MERGE with full-column UPDATE + INSERT 18.48 s 51.32 MB
Single native MERGE with DELETE + INSERT 17.56 s 9.22 MB
CALL replace_by_keys 12.34 s 5.00 MB

All executions passed full-row multiset and single-snapshot checks. The native DELETE + INSERT and CALL assign fresh RowIDs to replacements, while UPDATE preserves the matched RowIDs. The native statement provides atomic replacement for this workload. The measured benefit of CALL here is about 30% lower end-to-end time than that native baseline. The Parquet metric counts bytes returned by FileIO, including repeated reads.

This is one fixed workload and does not establish the benefit across batch sizes. Would this result and the source-snapshot binding be enough to justify keeping the public procedure, or would you prefer documenting the native MERGE pattern?

@JustinBinber

JustinBinber commented Nov 24, 2026 •

Copy link
Copy Markdown
Contributor Author

Thanks, @JingsongLi, for suggesting the single-statement MERGE baseline. I’ve incorporated the feedback and synced the PR with Apache master.

  • Merged current Apache master into the PR in 589ddc6a80. The merge conflict in DataEvolutionConflictDetection was confined to imports. The merged code retains both the upstream centroid-index checks and the replacement checks for concurrent column updates and RowID reassignment.
  • The earlier review fixes pin the resolved source snapshot, including tag reads, handle empty sources, and validate key membership under Spark's IN rules before the empty-target and pruned-scan shortcuts.
  • The native MERGE comparison includes three runs per arm on a fixed 128-column workload. Mean end-to-end time was 18.48 s for UPDATE + INSERT MERGE, 17.56 s for native DELETE + INSERT in one MERGE, and 12.34 s for CALL. Both replacement forms committed one snapshot and assigned fresh RowIDs to replaced rows.
  • After the merge, all 66 local ConflictDetectionTest cases passed. The new CI run has been triggered.

When you have a chance, I’d appreciate your feedback on the merged conflict checks and on whether the benchmark makes a case for adding the public procedure.

@JingsongLi

Copy link
Copy Markdown
Contributor

'18.48 s for UPDATE + INSERT MERGE, 17.56 s for native DELETE + INSERT in one MERGE, and 12.34 s for CALL'

Given this result, I don’t think there’s any need to move forward with the CALL; the improvement is too limited.

@JustinBinber

Copy link
Copy Markdown
Contributor Author

Thanks for the feedback. The first test was a small workload: 4,096 target rows in 64 files, with 32 replacements and 8 new rows. The native DELETE + INSERT MERGE reduced target Parquet reads from 51.32 MB to 9.22 MB. That is 82% less, or 42.10 MB in absolute terms. Both forms still incurred planning, scheduling, writing, and commit costs. The delete-marker form also had to build the markers and run the INSERT anti-join. These costs may help explain why the two native MERGE forms were only 0.92 s apart. The original measurements did not isolate each contribution.

I repeated the comparison on a 128-column Data Evolution table with 100,000 target rows in 512 Parquet files. The fixed source batch replaced 5,000 rows (5% of the target) and inserted 1,250. Each form ran three times in rotating order on a single host using Spark 3.5.9 with AQE, with a fresh target clone for each run.

SQL Median end-to-end time Target Parquet bytes returned Spark task CPU
Native full-column UPDATE + INSERT MERGE 110.59 s 2,515.15 MB 79.38 CPU-s
Native D-marker DELETE + INSERT MERGE 20.66 s 120.10 MB 11.22 CPU-s
CALL replace_by_keys 17.68 s 40.02 MB 8.50 CPU-s

In this workload, the replacement keys touched all 512 target files. The full-column UPDATE wrote about 2.47 GB of new data, while both replacement forms wrote 148.14 MB each. Against the native replacement baseline, the procedure saved 2.98 s in median elapsed time, read 66.7% fewer target Parquet bytes, and used 24.2% less Spark task CPU.

CALL replace_by_keys prepares deletion vectors using source-key membership, then prepares the appended data files directly from the source rows. It publishes both changes atomically in one Paimon snapshot. Readers see either the old snapshot or the completed replacement. If append preparation fails, no delete-only snapshot is published. The native single-statement MERGE provides the same atomic visibility. Its plan still constructs delete markers and runs a target anti-join for the INSERT branch, even though the ON condition excludes insert-marked rows from matching. The procedure preserves the single-snapshot guarantee while avoiding that extra work.

All nine runs passed full-row, RowID, and single-snapshot checks. This is a single-host result for one replacement pattern. The main additional evidence is the reduction in target reads and task CPU.

@JingsongLi JingsongLi left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The scoped run passed 50 Spark 3.5.9 replacement tests and 116 Core conflict/DV tests. I reproduced a stale commit after rollback reuses the target's numeric snapshot ID.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants