← Back to Pull requests

[Spark] Prune MERGE target files by the join keys of a small source #8035

Open
unknown opened this pull request with 650 lines diff across 8 files
View on GitHub
unknown unknown commented on Nov 05, 2026 18:57 UTC
Author

Which Delta project/connector is this regarding?

  • Spark

  • Standalone

  • Flink

  • Kernel

  • Other (fill in here)
  • Description

    Resolves #8034.

    Motivation

    MERGE selects the target files it scans with the target-only conjuncts of its ON condition. An upsert with ON t.key = s.key has none, so it scans every target file, even for a one-row source on a table clustered by key.

    Adding the keys to the ON condition by hand only partly works. One key (AND t.key = 42) skips files. A list (AND t.key IN (42, 7000, 90000)) does not: data skipping only tests each file against the range from the list's smallest to its largest value. Keys spread over the key space overlap almost every file.

    Change

    1. Data skipping for IN lists (DataFiltersBuilder.constructLiteralInListDataFilters)

  • A file is kept only if one of the values lies in its min/max range, as for a = v.

  • The check is a new predicate on the file's min and max, SortedValuesInRange. It binary-searches the sorted values for the smallest value >= min and checks that it is <= max.

  • It costs O(log n) per file, and its generated code does not grow with n. One min <= v AND v <= max term per value went over the 64 KB limit for a generated method at 150 to 200 BIGINT values (Code grows beyond 64 KB).

  • It returns null when min or max is null, like the comparisons used today.

  • It applies to lists of 2 to skipping.inList.exactMaxValues values (default 10000). It is not used for strings with a non-binary collation or for non-column builders; these keep the current range test.

  • It only skips files that the range test keeps. It never keeps a file the range test skips.
  • 2. MERGE with a small source (MergeIntoCommandBase.getSourceKeyFilePruningPredicates, used by findTouchedFiles and the insert-only writeOnlyInserts)

  • When: MERGE has no WHEN NOT MATCHED BY SOURCE clause, and its ON condition has a conjunct target_column = source_expression.

  • - The target side must be a column that data skipping can use.
    - The source side must be a deterministic expression of the source, of the same type.
    - FLOAT/DOUBLE keys (-0.0 = 0.0, NaN), strings with a non-binary collation, and null-safe equality are not used.
  • What: MERGE reads at most maxSourceRows + 1 rows of these source expressions from the materialized source, with take.

  • - If the source has more rows, nothing changes.
    - Otherwise, MERGE adds target_column IN (distinct non-null values) per key to the predicates passed to filterFiles. Data skipping and partition pruning then drop the files that cannot hold any of the keys.
    - If a key has no non-null value, no target row can match, and the predicate is false.
  • Same result: the predicate only selects files; the join still uses the ON condition. A target row can only satisfy the ON condition if its key equals the value of source_expression for some source row.

  • Materialized source only: the keys are read from the source that MERGE materialized for the join (merge.materializeSource). So they are exactly the keys the join sees, and collecting them reads the cached rows, not the source data again. A key missing from them could prune the file of a matching row, and that row would be inserted a second time. Sources that MERGE does not materialize are not pruned: most often a direct read of a Delta table (only deterministic filters and projections), and also insert-only MERGE in auto mode and materializeSource=none.

  • Conflict detection: filterFiles records the predicate and the selected files as read, as when the keys are written into the ON condition by hand.

  • - A concurrent transaction that only removes files this MERGE skipped no longer conflicts with it.
    - For a partition column key, the partition read predicate is narrower.
  • Observability: a usage event delta.dml.merge.sourceKeyFilePruning records whether the pruning was applied, whether the source was materialized and why, the number of key columns, and the source rows read.
  • | Config (spark.databricks.delta. prefix, internal) | Default |
    |---|---|
    | merge.sourceKeyFilePruning.enabled | true |
    | merge.sourceKeyFilePruning.maxSourceRows (0 disables) | 1000 |
    | skipping.inList.exactMaxValues (1 or less: range test only) | 10000 |

    How was this patch tested?

    New MergeIntoSourceKeyFilePruningSuite (19 tests). Each test runs the MERGE on two copies of a 10-file target, with and without the pruning. It checks that both copies end with the same rows, the number of target files read (numTargetFilesAfterSkipping), and the usage event. Cases:

  • Upsert with sources materialized in auto and all mode, from a view and from a Delta table, with and without deletion vectors.

  • Delete, conditional update and insert clauses; matched-only; insert-only with a materialized source.

  • Multi-column keys; a source key expression; string keys longer than the 32-character statistics prefix; a partition column key.

  • Sources with only NULL keys or no rows: no target file is read.

  • A 1,000-row source (the default maximum).

  • Not applied: above maxSourceRows; with NOT MATCHED BY SOURCE; for sources that are not materialized (materializeSource=none, a Delta table source in auto mode, insert-only MERGE in auto mode); and without a usable equality (<=>, DOUBLE keys, abs(t.key), no equality between target and source).
  • New tests in DataSkippingDeltaTests. These run in every suite that mixes it in; locally DataSkippingDeltaV1Suite and DataSkippingDeltaV1ColMapNameModeSuite.

  • IN lists hit or miss per value: top-level, nested and string columns, NULL in the list, and lists of 1,000 and 2,000 values.

  • TIMESTAMP and TIMESTAMP_NTZ IN lists against millisecond-truncated statistics.

  • skipping.inList.exactMaxValues = 1 keeps the range test.
  • Negative control. With the IN-list change reverted, the main upsert test reads 9 files instead of 2.

    Existing suites run locally with this change (pruning enabled by default): MergeIntoBasic (path-based, DVs, CDC, column mapping, Scala), MergeIntoSuiteBaseMisc (path-based, DVs), MergeIntoExtendedSyntaxSQLPathBasedSuite, MergeIntoNestedDataSQLPathBasedSuite, MergeIntoNotMatchedBySourceSQLPathBasedSuite, MergeIntoMaterializeSourceMergePersistentDVOffSuite, MergeIntoDVsSQLPathBasedDVsPredPushOnSuite, MergeCDCSQLPathBasedCDCOnSuite, MergeIntoAccumulatorSuite, MergeIntoTimestampConsistencySuite, MergeIntoEmptySchemaTargetSuite, ImplicitMergeCastingSuite, DescribeDeltaHistorySuite, RowTrackingMergeCommonNameBasedCDCOnSuite, DataSkippingDeltaV1Suite, DataSkippingDeltaV1ColMapNameModeSuite, PartitionLikeDataSkippingSuite, StatsCollectionSuite, DeleteMetricsSuite: 1408 tests. An earlier revision also pruned sources that MERGE does not materialize, by reading them again. It failed insert only merge - target data skipping (the source of an insert-only MERGE was scanned twice) and materialize source preserves dataframe hints (an extra query over the source). This revision reads only the materialized source, and getHints in MergeIntoMaterializeSourceSuite skips plans without a join (the plan that reads the keys); these suites pass.

    Local benchmark (not part of the PR). A 1,000-file, 5M-row (194 MB) table, range-partitioned on key, on a laptop, local mode. Each run is a fresh shallow clone. The MERGE is an upsert on t.key = s.key; times are best of 3:

    | Source | Target files read (off → on) | Scan time | MERGE time |
    |---|---|---|---|
    | 1 key | 1000 → 1 | 520 → 171 ms | 1312 → 855 ms |
    | 100 keys, spread | 1000 → 100 | 447 → 188 ms | 1358 → 1208 ms |
    | 1000 keys in ~10 files | 1000 → 10 | 447 → 185 ms | 1146 → 944 ms |
    | 1000 keys, one per file | 1000 → 965 | 596 → 489 ms | 3819 → 3401 ms |
    | 1001 keys (above maxSourceRows) | 1000 → 1000 | 465 → 478 ms | 3321 → 3374 ms |

    The scan of the target falls with the number of files it can skip. When the keys hit almost every file there is little to skip. Above maxSourceRows, the only extra cost is reading maxSourceRows + 1 rows of the materialized source.

    Does this PR introduce _any_ user-facing changes?

    No change in query or MERGE results.

  • A MERGE with a small source scans fewer target files, visible in numTargetFilesAfterSkipping.

  • Queries with IN lists of up to 10000 values can skip more files.

  • Three new internal configs.
  • 🤖 Generated with Claude Code

    Diff: 650 lines (+487 / -163) across 8 files Reviewer: sezruby Review duration: 25591m
    All Vouch review confidence checks passed
    Residual risk 0.28 = Change Risk (0.52) × (1 − Review Confidence (0.47)). Review depth and reviewer attention state are adequate.
    Model 1 · Change Risk (XGBoost)
    Score: 0.52 · 650 lines diff across 8 files
    0.52
    Model 2 · Review Depth (DistilBERT)
    Depth Score: 0.02 · 1 substantive comment(s)
    0.02
    Model 3 · Review Timing & Attention
    Session adequacy: 100% · Reviewer familiarity: 35%
    46%
    Bedrock Claude 3 · Risk Narration
    (disconnected)
    Groq
    Groq Risk Narration
    AWS Bedrock is currently disconnected. Generate high-confidence PR triage narration on-demand using Groq.
    Model 1 · Change Risk Attribution
    SHAP Weights
    Diff Size diff_size
    0.388
    Shallow Review Depth shallow_review_depth
    0.344
    Real PR Conversation Timeline
    1 comments
    "Review active on #8035"
    general weight: 0.35
    Reviewers
    Assignees
    Unassigned
    Labels
    risk: low confidence: 46.7% reviewed
    Vouch Risk Breakdown
    AI-powered review risk analysis
    Change Risk
    Change Risk · Model 1 (XGBoost)
    Predicted defect probability (0.00–1.00) based on diff churn, modified sensitive files, and author risk history.
    Score: 52% (MEDIUM) · Higher = larger blast radius
    52%
    Review Confidence
    Review Confidence · Models 2 & 3
    Scrutiny score (0.00–1.00) combining DistilBERT semantic review depth with reviewer familiarity and session dwell time.
    Score: 46.7% · Lower = rushed or shallow review
    46.7%
    Residual Risk
    Residual Risk · Core Equation
    Residual = Change × (1 − Confidence)
    Unmitigated risk surviving review. ≥ 0.65 triggers an automated re-queue to protect production.
    Score: 27.7% · Safe to merge
    27.7%
    Repository