From a2ad862ccde0c9586d0f2a9423e27a5ef38f7159 Mon Sep 17 00:00:00 2001 From: Eunjin Song Date: Wed, 8 Jul 2026 13:07:33 -0700 Subject: [PATCH 1/9] [Spark] Reader-side conflict-time data skipping to reduce unnecessary conflicts Conflict detection filters candidate files by partition only; for unpartitioned (incl. liquid-clustered) tables the append check conflicts on any concurrently-added file. This adds column-statistics data skipping: added files whose stats prove they cannot match the current transaction's read predicates are excluded, so operations touching disjoint data ranges no longer falsely conflict. - DataSkippingReaderBase.buildDataSkippingPredicate + filterFilesByDataSkipping reuse the reader's DataFiltersBuilder / verifyStatsForFilter and the shared parseAndDecodeStats, applying 'expr || !verifyStatsForFilter(...)' for one-way safety (skip only when stats prove no match; missing stats keep the file). - ConflictChecker.getFirstFileMatchingPartitionPredicates applies skipping per read predicate and unions survivors (OR across reads; a read's own data predicates are ANDed), and never skips for a whole-table read. Emits a delta.conflictDetection.dataSkipping.filesSkipped event. - Gated by spark.databricks.delta.conflictDetection.dataSkipping.enabled (internal, default off). - Adds ConflictDataSkippingSuite (disjoint / overlapping / disabled / missing-stats / partitioned). Part of #3. Implements #4. Co-Authored-By: Claude Opus 4.8 --- .../spark/sql/delta/ConflictChecker.scala | 31 +++- .../sql/delta/sources/DeltaSQLConf.scala | 11 ++ .../sql/delta/stats/DataSkippingReader.scala | 86 ++++++++- .../sql/delta/ConflictDataSkippingSuite.scala | 171 ++++++++++++++++++ 4 files changed, 292 insertions(+), 7 deletions(-) create mode 100644 spark/src/test/scala/org/apache/spark/sql/delta/ConflictDataSkippingSuite.scala diff --git a/spark/src/main/scala/org/apache/spark/sql/delta/ConflictChecker.scala b/spark/src/main/scala/org/apache/spark/sql/delta/ConflictChecker.scala index d5cd7be1beb..b92392e0c87 100644 --- a/spark/src/main/scala/org/apache/spark/sql/delta/ConflictChecker.scala +++ b/spark/src/main/scala/org/apache/spark/sql/delta/ConflictChecker.scala @@ -994,14 +994,41 @@ private[delta] class ConflictChecker( return None } + // Reader-side data skipping: narrow the candidate files using the read snapshot's column-stats + // skipping. A concurrently-added file whose stats prove it cannot match the read predicates is + // not a conflict -- this is what lets unpartitioned / liquid-clustered tables avoid conflicting + // on every added file below. Data predicates are applied *per read predicate* and the survivors + // unioned (OR across reads), because independent reads have OR, not AND, semantics: a file is a + // candidate if it could match ANY read; it is dropped only if its stats prove it fails EVERY + // read. Skipping is not applied for a whole-table read, where every added file must conflict. + val candidateFiles = + if (spark.conf.get(DeltaSQLConf.DELTA_CONFLICT_DETECTION_DATA_SKIPPING_ENABLED) && + !currentTransactionInfo.readWholeTable) { + val readSnapshot = currentTransactionInfo.readSnapshot + val survivingPaths = currentTransactionInfo.readPredicates.iterator.flatMap { rp => + readSnapshot.filterFilesByDataSkipping(files, rp.dataPredicates) + }.map(_.path).toSet + val remaining = files.filter(f => survivingPaths.contains(f.path)) + if (remaining.size < files.size) { + recordDeltaEvent(deltaLog, + opType = "delta.conflictDetection.dataSkipping.filesSkipped", + data = Map( + "candidateFiles" -> files.size, + "skippedFiles" -> (files.size - remaining.size))) + } + remaining + } else { + files + } + // There is no reason to filter files if the table is not partitioned. if (currentTransactionInfo.readWholeTable || currentTransactionInfo.readSnapshot.metadata.partitionColumns.isEmpty) { - return files.headOption + return candidateFiles.headOption } import org.apache.spark.sql.delta.implicits._ - val filesDf = files.toDF(spark) + val filesDf = candidateFiles.toDF(spark) spark.conf.get(DeltaSQLConf.DELTA_CONFLICT_DETECTION_WIDEN_NONDETERMINISTIC_PREDICATES) match { case DeltaSQLConf.NonDeterministicPredicateWidening.OFF => diff --git a/spark/src/main/scala/org/apache/spark/sql/delta/sources/DeltaSQLConf.scala b/spark/src/main/scala/org/apache/spark/sql/delta/sources/DeltaSQLConf.scala index d4d9c813b6c..f8edb294261 100644 --- a/spark/src/main/scala/org/apache/spark/sql/delta/sources/DeltaSQLConf.scala +++ b/spark/src/main/scala/org/apache/spark/sql/delta/sources/DeltaSQLConf.scala @@ -534,6 +534,17 @@ trait DeltaSQLConfBase extends DeltaSQLConfUtils { .booleanConf .createWithDefault(true) + val DELTA_CONFLICT_DETECTION_DATA_SKIPPING_ENABLED = + buildConf("conflictDetection.dataSkipping.enabled") + .internal() + .doc( + """When enabled, conflict detection uses column-statistics data skipping to exclude + |concurrently-added files whose stats prove they cannot match the current transaction's + |read predicates, reducing unnecessary conflicts (especially on unpartitioned tables). + |One-way safe: a file is excluded only when its stats prove no match.""".stripMargin) + .booleanConf + .createWithDefault(false) + val DELTA_PROTOCOL_DEFAULT_WRITER_VERSION = buildConf("properties.defaults.minWriterVersion") .doc("The default writer protocol version to create new tables with, unless a feature " + diff --git a/spark/src/main/scala/org/apache/spark/sql/delta/stats/DataSkippingReader.scala b/spark/src/main/scala/org/apache/spark/sql/delta/stats/DataSkippingReader.scala index 574e0e3008e..05fd8fd6fe1 100644 --- a/spark/src/main/scala/org/apache/spark/sql/delta/stats/DataSkippingReader.scala +++ b/spark/src/main/scala/org/apache/spark/sql/delta/stats/DataSkippingReader.scala @@ -286,22 +286,29 @@ trait DataSkippingReaderBase DeltaSQLConf.DELTA_DATASKIPPING_PARTITION_LIKE_FILTERS_ADDITIONAL_SUPPORTED_EXPRESSIONS) .toSet.flatMap((exprs: String) => exprs.split(",")) - /** Returns a DataFrame expression to obtain a list of files with parsed statistics. */ - private def withStatsInternal0: DataFrame = { - val parsedStats = from_json(col("stats"), statsSchema) + /** + * Parses (and, when the schema contains VariantType, Z85-decodes) the JSON `statsCol` into the + * `statsSchema` struct. Shared by [[withStatsInternal0]] and conflict-detection data skipping + * ([[filterFilesByDataSkipping]]) so both parse stats the same way. + */ + private def parseAndDecodeStats(statsCol: Column): Column = { + val parsedStats = from_json(statsCol, statsSchema) // Only use DecodeNestedZ85EncodedVariant if the schema contains VariantType. // This avoids performance overhead for tables without variant columns. // `DecodeNestedZ85EncodedVariant` is a temporary workaround since the Spark 4.1 from_json // expression has no way to decode a VariantVal from an encoded Z85 string. // TODO: Add Z85 decoding to Variant in Spark 4.2 and use that from_json option here. - val decodedStats = if (SchemaUtils.checkForVariantTypeColumnsRecursively(statsSchema)) { + if (SchemaUtils.checkForVariantTypeColumnsRecursively(statsSchema)) { Column(DecodeNestedZ85EncodedVariant(parsedStats.expr)) } else { parsedStats } - allFiles.withColumn("stats", decodedStats) } + /** Returns a DataFrame expression to obtain a list of files with parsed statistics. */ + private def withStatsInternal0: DataFrame = + allFiles.withColumn("stats", parseAndDecodeStats(col("stats"))) + private lazy val withStatsCache = cacheDS(withStatsInternal0, s"Delta Table State with Stats #$version - $redactedPath") @@ -641,6 +648,75 @@ trait DataSkippingReaderBase files.toSeq -> Seq(DataSize(totalSize), DataSize(partitionSize), DataSize(scanSize)) } + /** + * Builds a single [[DataSkippingPredicate]] (skipping expression + the stats it references) from + * `dataFilters`, mirroring [[filesForScan]]'s eligibility filtering, per-filter construction and + * conjunction fold. Returns None when stats skipping is unavailable or no eligible filter yields + * a predicate. The filters are AND-combined, so callers must pass filters from a single logical + * read (predicates from independent reads have OR, not AND, semantics). + */ + private[delta] def buildDataSkippingPredicate( + dataFilters: Seq[Expression]): Option[DataSkippingPredicate] = { + import DeltaTableUtils._ + if (!useStats) return None + // Mirror filesForScan eligibility: drop subquery / non-deterministic / metadata filters, so we + // never build a skipping predicate that could wrongly exclude a matching file. + val eligibleFilters = dataFilters.filterNot { f => + containsSubquery(f) || !f.deterministic || f.exists { + case MetadataAttribute(_) => true + case _ => false + } + } + val constructDataFilters = new DataFiltersBuilder( + spark = spark, + dataSkippingType = DeltaDataSkippingType.dataSkippingOnlyV1, + getStatsColumnOpt = (s: StatsColumn) => getStatsColumnOpt(s)) + eligibleFilters + .flatMap(f => constructDataFilters(f)) + .reduceOption((skip1, skip2) => DataSkippingPredicate( + skip1.expr && skip2.expr, skip1.referencedStats ++ skip2.referencedStats)) + } + + /** + * Conflict-detection helper (reader-side data skipping): returns the subset of `files` whose + * statistics do NOT prove they fail `dataFilters` -- i.e. the files that could still match and + * therefore must be treated as conflicts. Files with missing/insufficient stats (or when skipping + * is unavailable) are kept. + * + * `dataFilters` must come from a single logical read: they are AND-combined via + * [[buildDataSkippingPredicate]]. Callers with multiple independent reads must invoke this per + * read and union the survivors (OR semantics). + * + * One-way safe: it applies `expr || !verifyStatsForFilter(...)` exactly as + * [[getDataSkippedFiles]], so a file is dropped only when its stats *prove* it cannot match -- a + * real conflict is never turned into a false negative. Returns the original [[AddFile]]s (matched + * by path), stats untouched. + */ + private[delta] def filterFilesByDataSkipping( + files: Seq[AddFile], + dataFilters: Seq[Expression]): Seq[AddFile] = { + import org.apache.spark.sql.delta.implicits._ + if (files.isEmpty || dataFilters.isEmpty || schema.isEmpty) return files + buildDataSkippingPredicate(dataFilters) match { + // No usable data-skipping predicate -> keep all files (conservative). + case None => files + case Some(pred) => + val survivingPaths = recordFrameProfile( + "Delta", "DataSkippingReader.filterFilesByDataSkipping") { + // `expr || !verifyStatsForFilter(...)` keeps any file whose referenced stats are + // missing/NULL (mirrors getDataSkippedFiles): only skip when stats prove no match. + files.toDF(spark) + .withColumn("stats", parseAndDecodeStats(col("stats"))) + .where(pred.expr || !verifyStatsForFilter(pred.referencedStats)) + .select("path") + .collect() + .map(_.getString(0)) + .toSet + } + files.filter(f => survivingPaths.contains(f.path)) + } + } + private def getCorrectDataSkippingType( dataSkippingType: DeltaDataSkippingType): DeltaDataSkippingType = { dataSkippingType diff --git a/spark/src/test/scala/org/apache/spark/sql/delta/ConflictDataSkippingSuite.scala b/spark/src/test/scala/org/apache/spark/sql/delta/ConflictDataSkippingSuite.scala new file mode 100644 index 00000000000..112862ac131 --- /dev/null +++ b/spark/src/test/scala/org/apache/spark/sql/delta/ConflictDataSkippingSuite.scala @@ -0,0 +1,171 @@ +/* + * Copyright (2021) The Delta Lake Project Authors. + * + * Licensed 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.spark.sql.delta + +import java.io.File + +import scala.concurrent.duration.Duration + +import org.apache.spark.sql.delta.concurrency.PhaseLockingTestMixin +import org.apache.spark.sql.delta.concurrency.TransactionExecutionTestMixin +import org.apache.spark.sql.delta.sources.DeltaSQLConf +import org.apache.spark.sql.delta.test.DeltaSQLCommandTest + +import org.apache.spark.SparkException +import org.apache.spark.sql.{QueryTest, Row} +import org.apache.spark.sql.functions.lit +import org.apache.spark.sql.test.SharedSparkSession +import org.apache.spark.util.ThreadUtils + +/** + * Tests for reader-side conflict-time data skipping + * ([[DeltaSQLConf.DELTA_CONFLICT_DETECTION_DATA_SKIPPING_ENABLED]]). + * + * A concurrently-added file whose column stats prove it cannot match the current transaction's read + * predicates should NOT cause an append conflict, especially on unpartitioned tables, where the + * append check would otherwise conflict on any added file. Skipping must be one-way safe: a file + * with missing stats is always kept, so a real conflict is never missed. + */ +class ConflictDataSkippingSuite extends QueryTest + with SharedSparkSession + with DeltaSQLCommandTest + with PhaseLockingTestMixin + with TransactionExecutionTestMixin { + + private def tableRef(dir: File): String = s"delta.`${dir.getCanonicalPath}`" + + /** + * Unpartitioned table with `id` in [0, 1000) across 10 files (file i covers [100i, 100i+100)), + * committed at Serializable isolation so that concurrent (blind) appends are conflict-checked. + * When `numIndexedCols` is set, stats collection is limited accordingly (0 = no stats). + */ + private def createTable(dir: File, numIndexedCols: Option[Int] = None): Unit = { + spark.range(start = 0, end = 1000, step = 1, numPartitions = 10) + .write.format("delta").mode("append").save(dir.getAbsolutePath) + val extraProps = numIndexedCols + .map(n => s", '${DeltaConfigs.DATA_SKIPPING_NUM_INDEXED_COLS.key}' = '$n'") + .getOrElse("") + sql(s"ALTER TABLE ${tableRef(dir)} SET TBLPROPERTIES " + + s"('${DeltaConfigs.ISOLATION_LEVEL.key}' = 'Serializable'$extraProps)") + } + + /** A DELETE that runs under the given data-skipping setting (evaluated on its commit thread). */ + private def deleteTxn(dir: File, condition: String, dataSkipping: Boolean): () => Array[Row] = + () => { + withSQLConf( + DeltaSQLConf.DELTA_CONFLICT_DETECTION_DATA_SKIPPING_ENABLED.key -> dataSkipping.toString) { + sql(s"DELETE FROM ${tableRef(dir)} WHERE $condition").collect() + } + Array.empty[Row] + } + + /** A blind append of `id` in [start, end), optionally into partition `p`. */ + private def appendTxn( + dir: File, start: Long, end: Long, partition: Option[Int] = None): () => Array[Row] = + () => { + var df = spark.range(start, end).toDF() + partition.foreach(p => df = df.withColumn("p", lit(p))) + df.write.format("delta").mode("append").save(dir.getAbsolutePath) + Array.empty[Row] + } + + /** Expected surviving ids after deleting id<50 and appending [1000, 1100). */ + private val disjointExpected: Seq[Row] = + ((50L until 1000L) ++ (1000L until 1100L)).map(Row(_)) + + private def assertConcurrentAppend(e: SparkException): Unit = + assert(e.getCause.isInstanceOf[io.delta.exceptions.ConcurrentAppendException], + s"Expected ConcurrentAppendException, got: ${e.getCause}") + + test("disjoint data ranges: added file is skipped, no conflict") { + withTempDir { dir => + createTable(dir) + // A (loser) deletes id<50; B (winner) appends [1000,1100), disjoint from A's predicate. + val txnA = deleteTxn(dir, "id < 50", dataSkipping = true) + val txnB = appendTxn(dir, 1000, 1100) + + val (futureA, futureB) = runTxnsWithOrder__A_Start__B__A_End(txnA, txnB) + ThreadUtils.awaitResult(futureA, Duration.Inf) + ThreadUtils.awaitResult(futureB, Duration.Inf) + + // Both committed: id<50 deleted, [1000,1100) appended. + checkAnswer( + spark.read.format("delta").load(dir.getAbsolutePath).select("id"), disjointExpected) + } + } + + test("overlapping data ranges: added file matches the predicate, still conflicts") { + withTempDir { dir => + createTable(dir) + // A's predicate id>=950 overlaps B's appended [1000,1100) file range -> not skippable. + val txnA = deleteTxn(dir, "id >= 950", dataSkipping = true) + val txnB = appendTxn(dir, 1000, 1100) + + val (futureA, futureB) = runTxnsWithOrder__A_Start__B__A_End(txnA, txnB) + ThreadUtils.awaitResult(futureB, Duration.Inf) + val e = intercept[SparkException] { ThreadUtils.awaitResult(futureA, Duration.Inf) } + assertConcurrentAppend(e) + } + } + + test("feature disabled: disjoint data ranges still conflict") { + withTempDir { dir => + createTable(dir) + val txnA = deleteTxn(dir, "id < 50", dataSkipping = false) + val txnB = appendTxn(dir, 1000, 1100) + + val (futureA, futureB) = runTxnsWithOrder__A_Start__B__A_End(txnA, txnB) + ThreadUtils.awaitResult(futureB, Duration.Inf) + val e = intercept[SparkException] { ThreadUtils.awaitResult(futureA, Duration.Inf) } + assertConcurrentAppend(e) + } + } + + test("missing stats: disjoint ranges still conflict (one-way safety)") { + withTempDir { dir => + // No indexed columns -> the appended file has no id stats -> must NOT be skipped. + createTable(dir, numIndexedCols = Some(0)) + val txnA = deleteTxn(dir, "id < 50", dataSkipping = true) + val txnB = appendTxn(dir, 1000, 1100) + + val (futureA, futureB) = runTxnsWithOrder__A_Start__B__A_End(txnA, txnB) + ThreadUtils.awaitResult(futureB, Duration.Inf) + val e = intercept[SparkException] { ThreadUtils.awaitResult(futureA, Duration.Inf) } + assertConcurrentAppend(e) + } + } + + test("partitioned table: data skipping on a non-partition column avoids the conflict") { + withTempDir { dir => + // Partitioned by `p`; the appended file shares the partition but its id range is disjoint. + spark.range(start = 0, end = 1000, step = 1, numPartitions = 10).withColumn("p", lit(0)) + .write.partitionBy("p").format("delta").mode("append").save(dir.getAbsolutePath) + sql(s"ALTER TABLE ${tableRef(dir)} SET TBLPROPERTIES " + + s"('${DeltaConfigs.ISOLATION_LEVEL.key}' = 'Serializable')") + + val txnA = deleteTxn(dir, "id < 50", dataSkipping = true) + val txnB = appendTxn(dir, 1000, 1100, partition = Some(0)) + + val (futureA, futureB) = runTxnsWithOrder__A_Start__B__A_End(txnA, txnB) + ThreadUtils.awaitResult(futureA, Duration.Inf) + ThreadUtils.awaitResult(futureB, Duration.Inf) + + checkAnswer( + spark.read.format("delta").load(dir.getAbsolutePath).select("id"), disjointExpected) + } + } +} From f6b092fd032c6291efc67ba48495225ff786cafa Mon Sep 17 00:00:00 2001 From: Eunjin Song Date: Mon, 3 Aug 2026 11:19:09 -0700 Subject: [PATCH 2/9] Guard conflict-time data skipping on non-empty read predicates Fix a Serializable soundness gap in reader-side conflict-time data skipping. A non-blind-append transaction can record no read predicates (e.g. it removes files without reading the table). With skipping enabled its empty read set produced an empty survivor set, so getFirstFileMatchingPartitionPredicates returned None and a real ConcurrentAppendException was silently suppressed. Skipping is now applied only when the transaction has at least one read predicate; otherwise every concurrently added file stays a conflict candidate, matching behavior with the feature disabled. Add ConflictDataSkippingSuite coverage: - empty read predicates on a non-blind-append txn still conflict (regression test for the fix above); - a whole-table read is never skipped and conflicts with a concurrent append; - filterFilesByDataSkipping AND-combines predicates within a single read. Co-Authored-By: Claude Opus 4.8 --- .../spark/sql/delta/ConflictChecker.scala | 9 +- .../sql/delta/ConflictDataSkippingSuite.scala | 83 ++++++++++++++++++- 2 files changed, 89 insertions(+), 3 deletions(-) diff --git a/spark/src/main/scala/org/apache/spark/sql/delta/ConflictChecker.scala b/spark/src/main/scala/org/apache/spark/sql/delta/ConflictChecker.scala index b92392e0c87..9e7db8589e1 100644 --- a/spark/src/main/scala/org/apache/spark/sql/delta/ConflictChecker.scala +++ b/spark/src/main/scala/org/apache/spark/sql/delta/ConflictChecker.scala @@ -1000,10 +1000,15 @@ private[delta] class ConflictChecker( // on every added file below. Data predicates are applied *per read predicate* and the survivors // unioned (OR across reads), because independent reads have OR, not AND, semantics: a file is a // candidate if it could match ANY read; it is dropped only if its stats prove it fails EVERY - // read. Skipping is not applied for a whole-table read, where every added file must conflict. + // read. Skipping is not applied for a whole-table read, nor when there are no read predicates + // at all: a transaction can be a non-blind-append (e.g. it removed files) yet have no read + // predicates, and in that case every added file must remain a conflict candidate, exactly as + // when the feature is disabled. Guarding on non-empty read predicates avoids an empty survivor + // set silently suppressing a real conflict. val candidateFiles = if (spark.conf.get(DeltaSQLConf.DELTA_CONFLICT_DETECTION_DATA_SKIPPING_ENABLED) && - !currentTransactionInfo.readWholeTable) { + !currentTransactionInfo.readWholeTable && + currentTransactionInfo.readPredicates.nonEmpty) { val readSnapshot = currentTransactionInfo.readSnapshot val survivingPaths = currentTransactionInfo.readPredicates.iterator.flatMap { rp => readSnapshot.filterFilesByDataSkipping(files, rp.dataPredicates) diff --git a/spark/src/test/scala/org/apache/spark/sql/delta/ConflictDataSkippingSuite.scala b/spark/src/test/scala/org/apache/spark/sql/delta/ConflictDataSkippingSuite.scala index 112862ac131..b003835bd13 100644 --- a/spark/src/test/scala/org/apache/spark/sql/delta/ConflictDataSkippingSuite.scala +++ b/spark/src/test/scala/org/apache/spark/sql/delta/ConflictDataSkippingSuite.scala @@ -20,15 +20,18 @@ import java.io.File import scala.concurrent.duration.Duration +import org.apache.spark.sql.delta.actions.AddFile import org.apache.spark.sql.delta.concurrency.PhaseLockingTestMixin import org.apache.spark.sql.delta.concurrency.TransactionExecutionTestMixin import org.apache.spark.sql.delta.sources.DeltaSQLConf import org.apache.spark.sql.delta.test.DeltaSQLCommandTest import org.apache.spark.SparkException -import org.apache.spark.sql.{QueryTest, Row} +import org.apache.spark.sql.{QueryTest, Row, SaveMode} +import org.apache.spark.sql.catalyst.expressions.{AttributeReference, GreaterThanOrEqual, LessThan, Literal} import org.apache.spark.sql.functions.lit import org.apache.spark.sql.test.SharedSparkSession +import org.apache.spark.sql.types.LongType import org.apache.spark.util.ThreadUtils /** @@ -168,4 +171,82 @@ class ConflictDataSkippingSuite extends QueryTest spark.read.format("delta").load(dir.getAbsolutePath).select("id"), disjointExpected) } } + + private def manufacturedAdd(name: String): AddFile = + AddFile(name, Map.empty[String, String], size = 1L, modificationTime = 1L, dataChange = true) + + test("empty read predicates on a non-blind-append txn: added file still conflicts") { + // Soundness of the Serializable blind-append case. A transaction can be a NON-blind append + // (it removes a file, so onlyAddFiles = false) and yet record no read predicates. With data + // skipping enabled such a txn must still conflict-check every concurrently added file, exactly + // as it does with the feature disabled. Before the guard on non-empty read predicates, the + // empty read set produced an empty survivor set and the conflict was silently suppressed. + withTempDir { dir => + createTable(dir) + val log = DeltaLog.forTable(spark, dir.getCanonicalPath) + // An existing file to remove, which makes the loser a non-blind append with no reads. + val existingRemove = log.update().allFiles.collect().head.remove + withSQLConf( + DeltaSQLConf.DELTA_CONFLICT_DETECTION_DATA_SKIPPING_ENABLED.key -> "true") { + val loser = log.startTransaction() + // Winner: a blind append committed while the loser is still open. + log.startTransaction().commit( + Seq(manufacturedAdd("winner.parquet")), DeltaOperations.Write(SaveMode.Append)) + // Loser adds AND removes without reading -> not a blind append, no read predicates. + intercept[io.delta.exceptions.ConcurrentAppendException] { + loser.commit( + Seq(manufacturedAdd("loser.parquet"), existingRemove), + DeltaOperations.Write(SaveMode.Append)) + } + } + } + } + + test("whole-table read is never skipped: conflicts with a concurrent append") { + // A whole-table read must treat every concurrently added file as a conflict, even with data + // skipping enabled -- the feature is deliberately bypassed for readWholeTable. + withTempDir { dir => + createTable(dir) + val log = DeltaLog.forTable(spark, dir.getCanonicalPath) + withSQLConf( + DeltaSQLConf.DELTA_CONFLICT_DETECTION_DATA_SKIPPING_ENABLED.key -> "true") { + val loser = log.startTransaction() + loser.readWholeTable() + log.startTransaction().commit( + Seq(manufacturedAdd("winner.parquet")), DeltaOperations.Write(SaveMode.Append)) + intercept[io.delta.exceptions.ConcurrentAppendException] { + loser.commit( + Seq(manufacturedAdd("loser.parquet")), DeltaOperations.Write(SaveMode.Append)) + } + } + } + } + + test("filterFilesByDataSkipping AND-combines predicates within one read") { + // Predicates from a SINGLE read have AND semantics (OR is only across independent reads, which + // ConflictChecker unions by construction). This exercises that AND directly. + withTempDir { dir => + createTable(dir) + val log = DeltaLog.forTable(spark, dir.getCanonicalPath) + val snapshot = log.update() + val allFiles = snapshot.allFiles.collect().toSeq + assert(allFiles.size == 10) + + // Resolved catalyst predicates on the `id` column; built directly so the literal stays a + // bare Long (a parsed `id >= 200` would wrap it in a Cast, which is not skipping-eligible). + val id = AttributeReference("id", LongType)() + val ge200 = GreaterThanOrEqual(id, Literal(200L)) + val lt300 = LessThan(id, Literal(300L)) + + // Only the [200, 300) file can match `id >= 200 AND id < 300`. OR semantics would keep every + // file with id >= 200 or id < 300, i.e. all 10. + val survivors = snapshot.filterFilesByDataSkipping(allFiles, Seq(ge200, lt300)) + assert(survivors.size == 1, + s"expected exactly the [200,300) file, got ${survivors.map(_.path).sorted}") + + // Sanity: a single predicate keeps its whole matching range (files with max id >= 200). + val geOnly = snapshot.filterFilesByDataSkipping(allFiles, Seq(ge200)) + assert(geOnly.size == 8, s"expected 8 files with id >= 200, got ${geOnly.size}") + } + } } From e2f12cb539879cd2b9a05992816e5a8d759b9c4c Mon Sep 17 00:00:00 2001 From: Eunjin Song Date: Fri, 7 Aug 2026 18:16:18 -0700 Subject: [PATCH 3/9] Address review: single-job multi-read skipping + eval fallback Combine per-read data-skipping into one Spark job and fail safe on evaluation errors, per review comments on #7358. - filterFilesMatchingAnyReadPredicate(files, dataFiltersPerRead): builds one skipping predicate per read and OR-combines them into a single `where`, so all read predicates are evaluated in one Spark job instead of one job per read. A read with no usable predicate matches everything -> short-circuit and keep all files, no job. - filterFilesByDataSkipping is now the single-read case delegating to it. - Wrap build+eval in try/catch(NonFatal): on failure log a warning and return all candidate files (default conflict behavior), so a skipping error can never abort a valid commit. - ConflictChecker calls the new method once instead of flatMap-per-read. - Test: OR-combines independent reads in one call. Co-Authored-By: Claude Opus 4.8 --- .../spark/sql/delta/ConflictChecker.scala | 21 +++-- .../sql/delta/stats/DataSkippingReader.scala | 90 +++++++++++++------ .../sql/delta/ConflictDataSkippingSuite.scala | 30 ++++++- 3 files changed, 103 insertions(+), 38 deletions(-) diff --git a/spark/src/main/scala/org/apache/spark/sql/delta/ConflictChecker.scala b/spark/src/main/scala/org/apache/spark/sql/delta/ConflictChecker.scala index 9e7db8589e1..0201dfe8403 100644 --- a/spark/src/main/scala/org/apache/spark/sql/delta/ConflictChecker.scala +++ b/spark/src/main/scala/org/apache/spark/sql/delta/ConflictChecker.scala @@ -998,22 +998,21 @@ private[delta] class ConflictChecker( // skipping. A concurrently-added file whose stats prove it cannot match the read predicates is // not a conflict -- this is what lets unpartitioned / liquid-clustered tables avoid conflicting // on every added file below. Data predicates are applied *per read predicate* and the survivors - // unioned (OR across reads), because independent reads have OR, not AND, semantics: a file is a - // candidate if it could match ANY read; it is dropped only if its stats prove it fails EVERY - // read. Skipping is not applied for a whole-table read, nor when there are no read predicates - // at all: a transaction can be a non-blind-append (e.g. it removed files) yet have no read - // predicates, and in that case every added file must remain a conflict candidate, exactly as - // when the feature is disabled. Guarding on non-empty read predicates avoids an empty survivor - // set silently suppressing a real conflict. + // OR-combined, because independent reads have OR, not AND, semantics: a file is a candidate if + // it could match ANY read; it is dropped only if its stats prove it fails EVERY read. All reads + // are evaluated in a single Spark job by filterFilesMatchingAnyReadPredicate. Skipping is not + // applied for a whole-table read, nor when there are no read predicates at all: a transaction + // can be a non-blind-append (e.g. it removed files) yet have no read predicates, and in that + // case every added file must remain a conflict candidate, exactly as when the feature is + // disabled. Guarding on non-empty read predicates avoids an empty survivor set silently + // suppressing a real conflict. val candidateFiles = if (spark.conf.get(DeltaSQLConf.DELTA_CONFLICT_DETECTION_DATA_SKIPPING_ENABLED) && !currentTransactionInfo.readWholeTable && currentTransactionInfo.readPredicates.nonEmpty) { val readSnapshot = currentTransactionInfo.readSnapshot - val survivingPaths = currentTransactionInfo.readPredicates.iterator.flatMap { rp => - readSnapshot.filterFilesByDataSkipping(files, rp.dataPredicates) - }.map(_.path).toSet - val remaining = files.filter(f => survivingPaths.contains(f.path)) + val remaining = readSnapshot.filterFilesMatchingAnyReadPredicate( + files, currentTransactionInfo.readPredicates.map(_.dataPredicates).toSeq) if (remaining.size < files.size) { recordDeltaEvent(deltaLog, opType = "delta.conflictDetection.dataSkipping.filesSkipped", diff --git a/spark/src/main/scala/org/apache/spark/sql/delta/stats/DataSkippingReader.scala b/spark/src/main/scala/org/apache/spark/sql/delta/stats/DataSkippingReader.scala index 05fd8fd6fe1..6c9673c55a4 100644 --- a/spark/src/main/scala/org/apache/spark/sql/delta/stats/DataSkippingReader.scala +++ b/spark/src/main/scala/org/apache/spark/sql/delta/stats/DataSkippingReader.scala @@ -20,6 +20,7 @@ package org.apache.spark.sql.delta.stats import java.io.Closeable import scala.collection.mutable.ArrayBuffer +import scala.util.control.NonFatal import org.apache.spark.sql.delta.skipping.clustering.{ClusteredTableUtils, ClusteringColumnInfo} import org.apache.spark.sql.delta.ClassicColumnConversions._ @@ -684,36 +685,73 @@ trait DataSkippingReaderBase * is unavailable) are kept. * * `dataFilters` must come from a single logical read: they are AND-combined via - * [[buildDataSkippingPredicate]]. Callers with multiple independent reads must invoke this per - * read and union the survivors (OR semantics). - * - * One-way safe: it applies `expr || !verifyStatsForFilter(...)` exactly as - * [[getDataSkippedFiles]], so a file is dropped only when its stats *prove* it cannot match -- a - * real conflict is never turned into a false negative. Returns the original [[AddFile]]s (matched - * by path), stats untouched. + * [[buildDataSkippingPredicate]]. This is the one-read case of + * [[filterFilesMatchingAnyReadPredicate]]; callers with multiple independent reads should use + * that method so all reads are evaluated in a single Spark job. */ private[delta] def filterFilesByDataSkipping( files: Seq[AddFile], - dataFilters: Seq[Expression]): Seq[AddFile] = { + dataFilters: Seq[Expression]): Seq[AddFile] = + filterFilesMatchingAnyReadPredicate(files, Seq(dataFilters)) + + /** + * Conflict-detection helper (reader-side data skipping) over several INDEPENDENT reads: returns + * the subset of `files` that could still match ANY read and therefore must be treated as + * conflicts. Each inner `Seq[Expression]` is one logical read's data filters (AND-combined via + * [[buildDataSkippingPredicate]]); the reads are OR-combined, matching read semantics -- a file + * is a candidate if it could match any one of them. + * + * All reads are evaluated in a SINGLE Spark job: the per-read skipping predicates are OR-ed + * together into one `where` clause, rather than filtering per read and unioning the survivors + * (which launched one job per read). Note we cannot instead flatten every read's filters into one + * predicate -- that would AND them (read1 AND read2), the opposite of the OR we need. + * + * One-way safe: each read contributes `expr || !verifyStatsForFilter(...)` exactly as + * [[getDataSkippedFiles]], so a file is dropped only when its stats *prove* it fails EVERY read + * -- a real conflict is never a false negative. Files with missing/insufficient stats, a + * read with no usable skipping predicate (empty / ineligible filters -> matches everything), or a + * table without stats are all kept. Returns the original [[AddFile]]s (matched by path). + * + * Fail-safe: skipping here is a pure optimization over correct (conservative) conflict detection, + * so if building or evaluating the predicate throws we fall back to the default behavior of + * keeping all `files` as conflict candidates rather than failing the commit. + */ + private[delta] def filterFilesMatchingAnyReadPredicate( + files: Seq[AddFile], + dataFiltersPerRead: Seq[Seq[Expression]]): Seq[AddFile] = { import org.apache.spark.sql.delta.implicits._ - if (files.isEmpty || dataFilters.isEmpty || schema.isEmpty) return files - buildDataSkippingPredicate(dataFilters) match { - // No usable data-skipping predicate -> keep all files (conservative). - case None => files - case Some(pred) => - val survivingPaths = recordFrameProfile( - "Delta", "DataSkippingReader.filterFilesByDataSkipping") { - // `expr || !verifyStatsForFilter(...)` keeps any file whose referenced stats are - // missing/NULL (mirrors getDataSkippedFiles): only skip when stats prove no match. - files.toDF(spark) - .withColumn("stats", parseAndDecodeStats(col("stats"))) - .where(pred.expr || !verifyStatsForFilter(pred.referencedStats)) - .select("path") - .collect() - .map(_.getString(0)) - .toSet - } - files.filter(f => survivingPaths.contains(f.path)) + if (files.isEmpty || dataFiltersPerRead.isEmpty || schema.isEmpty) return files + try { + // One skipping predicate per read. A read with no usable predicate (empty or ineligible + // filters) matches every file -> nothing can be skipped, so keep all files without a job. + val perReadPredicates = dataFiltersPerRead.map { dataFilters => + if (dataFilters.isEmpty) None else buildDataSkippingPredicate(dataFilters) + } + if (perReadPredicates.exists(_.isEmpty)) return files + // Survive if the file could match ANY read. Per read, `expr || !verifyStatsForFilter(...)` + // keeps any file whose referenced stats are missing/NULL (mirrors getDataSkippedFiles): only + // skip when stats prove no match. OR the reads so a match against any one keeps the file. + val survivorCondition = perReadPredicates.flatten + .map(pred => pred.expr || !verifyStatsForFilter(pred.referencedStats)) + .reduce(_ || _) + val survivingPaths = recordFrameProfile( + "Delta", "DataSkippingReader.filterFilesMatchingAnyReadPredicate") { + files.toDF(spark) + .withColumn("stats", parseAndDecodeStats(col("stats"))) + .where(survivorCondition) + .select("path") + .collect() + .map(_.getString(0)) + .toSet + } + files.filter(f => survivingPaths.contains(f.path)) + } catch { + case NonFatal(e) => + // Optimization only: never let a skipping failure abort a commit. Fall back to the default + // (feature-off) behavior of treating every added file as a conflict candidate. + logWarning(log"Conflict-time data skipping failed to evaluate; falling back to treating " + + log"all added files as conflict candidates", e) + files } } diff --git a/spark/src/test/scala/org/apache/spark/sql/delta/ConflictDataSkippingSuite.scala b/spark/src/test/scala/org/apache/spark/sql/delta/ConflictDataSkippingSuite.scala index b003835bd13..bf5648ce97e 100644 --- a/spark/src/test/scala/org/apache/spark/sql/delta/ConflictDataSkippingSuite.scala +++ b/spark/src/test/scala/org/apache/spark/sql/delta/ConflictDataSkippingSuite.scala @@ -28,7 +28,7 @@ import org.apache.spark.sql.delta.test.DeltaSQLCommandTest import org.apache.spark.SparkException import org.apache.spark.sql.{QueryTest, Row, SaveMode} -import org.apache.spark.sql.catalyst.expressions.{AttributeReference, GreaterThanOrEqual, LessThan, Literal} +import org.apache.spark.sql.catalyst.expressions.{AttributeReference, Expression, GreaterThanOrEqual, LessThan, Literal} import org.apache.spark.sql.functions.lit import org.apache.spark.sql.test.SharedSparkSession import org.apache.spark.sql.types.LongType @@ -249,4 +249,32 @@ class ConflictDataSkippingSuite extends QueryTest assert(geOnly.size == 8, s"expected 8 files with id >= 200, got ${geOnly.size}") } } + + test("filterFilesMatchingAnyReadPredicate OR-combines independent reads in one call") { + // Independent reads have OR semantics: a file survives if it could match ANY read. This is the + // multi-read path ConflictChecker uses -- all reads are evaluated together in a single job. + withTempDir { dir => + createTable(dir) + val log = DeltaLog.forTable(spark, dir.getCanonicalPath) + val snapshot = log.update() + val allFiles = snapshot.allFiles.collect().toSeq + assert(allFiles.size == 10) + + val id = AttributeReference("id", LongType)() + // Read 1: id in [200, 300) -> the single [200,300) file. Read 2: id >= 800 -> the [800,900) + // and [900,1000) files. Their union (OR across reads) is exactly 3 files. + val read1 = Seq[Expression]( + GreaterThanOrEqual(id, Literal(200L)), LessThan(id, Literal(300L))) + val read2 = Seq[Expression](GreaterThanOrEqual(id, Literal(800L))) + val survivors = + snapshot.filterFilesMatchingAnyReadPredicate(allFiles, Seq(read1, read2)) + assert(survivors.size == 3, + s"expected [200,300) + [800,1000), got ${survivors.map(_.path).sorted}") + + // A read with no usable predicate matches everything, so nothing can be skipped -> all kept. + val allKept = snapshot.filterFilesMatchingAnyReadPredicate(allFiles, Seq(read1, Seq.empty)) + assert(allKept.size == allFiles.size, + s"a read with no predicate must keep all files, got ${allKept.size}") + } + } } From e4ac0dab359c229a0b4a3f0700051ff8e20092a7 Mon Sep 17 00:00:00 2001 From: Eunjin Song Date: Wed, 12 Aug 2026 22:59:17 -0700 Subject: [PATCH 4/9] Address review: isolate conflict-time skipping in a self-typed trait Move buildDataSkippingPredicate / filterFilesByDataSkipping / filterFilesMatchingAnyReadPredicate out of DataSkippingReaderBase into a new self-typed trait ConflictDataSkippingReader (self: DataSkippingReaderBase), mixed into the base. Existing data-skipping code is left untouched: withStatsInternal0 is reverted to its original inline form, so the only change to DataSkippingReader.scala is the one-line trait mixin. parseAndDecodeStats is duplicated (trait-private) rather than shared with withStatsInternal0, keeping the feature a fully isolated additive unit per review feedback. Co-Authored-By: Claude Opus 4.8 --- .../stats/ConflictDataSkippingReader.scala | 172 ++++++++++++++++++ .../sql/delta/stats/DataSkippingReader.scala | 125 +------------ 2 files changed, 178 insertions(+), 119 deletions(-) create mode 100644 spark/src/main/scala/org/apache/spark/sql/delta/stats/ConflictDataSkippingReader.scala diff --git a/spark/src/main/scala/org/apache/spark/sql/delta/stats/ConflictDataSkippingReader.scala b/spark/src/main/scala/org/apache/spark/sql/delta/stats/ConflictDataSkippingReader.scala new file mode 100644 index 00000000000..2305397b7f5 --- /dev/null +++ b/spark/src/main/scala/org/apache/spark/sql/delta/stats/ConflictDataSkippingReader.scala @@ -0,0 +1,172 @@ +/* + * Copyright (2021) The Delta Lake Project Authors. + * + * Licensed 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.spark.sql.delta.stats + +import scala.util.control.NonFatal + +import org.apache.spark.sql.delta.ClassicColumnConversions._ +import org.apache.spark.sql.delta.DeltaTableUtils +import org.apache.spark.sql.delta.actions.AddFile +import org.apache.spark.sql.delta.expressions.DecodeNestedZ85EncodedVariant +import org.apache.spark.sql.delta.metering.DeltaLogging +import org.apache.spark.sql.delta.schema.SchemaUtils +import org.apache.spark.sql.delta.sources.DeltaSQLConf + +import org.apache.spark.sql.Column +import org.apache.spark.sql.catalyst.expressions._ +import org.apache.spark.sql.functions.{col, from_json} + +/** + * Reader-side data skipping used during conflict detection (row-level concurrency Case 1: writers + * touching disjoint data ranges). + * + * Mixed into [[DataSkippingReaderBase]] as a self-typed trait so this feature is a single isolated + * unit that only ADDS methods -- it does not modify any existing data-skipping code. It is opt-in: + * the caller ([[org.apache.spark.sql.delta.ConflictChecker]]) invokes these methods only behind + * `DeltaSQLConf.DELTA_CONFLICT_DETECTION_DATA_SKIPPING_ENABLED`, and each is one-way safe -- a file + * is dropped only when its stats *prove* it cannot match, so a real conflict is never a false + * negative. + */ +trait ConflictDataSkippingReader extends DeltaLogging { self: DataSkippingReaderBase => + + /** + * Parses (and, when the schema contains VariantType, Z85-decodes) the JSON `statsCol` into the + * `statsSchema` struct, mirroring [[withStatsInternal0]]. Deliberately kept private to this trait + * rather than shared with `withStatsInternal0`, so the existing stats path stays untouched. + */ + private def parseAndDecodeStats(statsCol: Column): Column = { + val parsedStats = from_json(statsCol, statsSchema) + // Only use DecodeNestedZ85EncodedVariant if the schema contains VariantType. + // This avoids performance overhead for tables without variant columns. + // `DecodeNestedZ85EncodedVariant` is a temporary workaround since the Spark 4.1 from_json + // expression has no way to decode a VariantVal from an encoded Z85 string. + // TODO: Add Z85 decoding to Variant in Spark 4.2 and use that from_json option here. + if (SchemaUtils.checkForVariantTypeColumnsRecursively(statsSchema)) { + Column(DecodeNestedZ85EncodedVariant(parsedStats.expr)) + } else { + parsedStats + } + } + + /** + * Builds a single [[DataSkippingPredicate]] (skipping expression + the stats it references) from + * `dataFilters`, mirroring [[filesForScan]]'s eligibility filtering, per-filter construction and + * conjunction fold. Returns None when stats skipping is unavailable or no eligible filter yields + * a predicate. The filters are AND-combined, so callers must pass filters from a single logical + * read (predicates from independent reads have OR, not AND, semantics). + */ + private[delta] def buildDataSkippingPredicate( + dataFilters: Seq[Expression]): Option[DataSkippingPredicate] = { + import DeltaTableUtils._ + // Stats-skipping conf, inlined from DataSkippingReaderBase.useStats (file-private, so not + // visible here). Reading it inline avoids widening that member's visibility. + if (!spark.sessionState.conf.getConf(DeltaSQLConf.DELTA_STATS_SKIPPING)) return None + // Mirror filesForScan eligibility: drop subquery / non-deterministic / metadata filters, so we + // never build a skipping predicate that could wrongly exclude a matching file. + val eligibleFilters = dataFilters.filterNot { f => + containsSubquery(f) || !f.deterministic || f.exists { + case MetadataAttribute(_) => true + case _ => false + } + } + val constructDataFilters = new DataFiltersBuilder( + spark = spark, + dataSkippingType = DeltaDataSkippingType.dataSkippingOnlyV1, + getStatsColumnOpt = (s: StatsColumn) => getStatsColumnOpt(s)) + eligibleFilters + .flatMap(f => constructDataFilters(f)) + .reduceOption((skip1, skip2) => DataSkippingPredicate( + skip1.expr && skip2.expr, skip1.referencedStats ++ skip2.referencedStats)) + } + + /** + * Conflict-detection helper (reader-side data skipping): returns the subset of `files` whose + * statistics do NOT prove they fail `dataFilters` -- i.e. the files that could still match and + * therefore must be treated as conflicts. Files with missing/insufficient stats (or when skipping + * is unavailable) are kept. + * + * `dataFilters` must come from a single logical read: they are AND-combined via + * [[buildDataSkippingPredicate]]. This is the one-read case of + * [[filterFilesMatchingAnyReadPredicate]]; callers with multiple independent reads should use + * that method so all reads are evaluated in a single Spark job. + */ + private[delta] def filterFilesByDataSkipping( + files: Seq[AddFile], + dataFilters: Seq[Expression]): Seq[AddFile] = + filterFilesMatchingAnyReadPredicate(files, Seq(dataFilters)) + + /** + * Conflict-detection helper (reader-side data skipping) over several INDEPENDENT reads: returns + * the subset of `files` that could still match ANY read and therefore must be treated as + * conflicts. Each inner `Seq[Expression]` is one logical read's data filters (AND-combined via + * [[buildDataSkippingPredicate]]); the reads are OR-combined, matching read semantics -- a file + * is a candidate if it could match any one of them. + * + * All reads are evaluated in a SINGLE Spark job: the per-read skipping predicates are OR-ed + * together into one `where` clause, rather than filtering per read and unioning the survivors + * (which launched one job per read). Note we cannot instead flatten every read's filters into one + * predicate -- that would AND them (read1 AND read2), the opposite of the OR we need. + * + * One-way safe: each read contributes `expr || !verifyStatsForFilter(...)` exactly as + * [[getDataSkippedFiles]], so a file is dropped only when its stats *prove* it fails EVERY read + * -- a real conflict is never a false negative. Files with missing/insufficient stats, a + * read with no usable skipping predicate (empty / ineligible filters -> matches everything), or a + * table without stats are all kept. Returns the original [[AddFile]]s (matched by path). + * + * Fail-safe: skipping here is a pure optimization over correct (conservative) conflict detection, + * so if building or evaluating the predicate throws we fall back to the default behavior of + * keeping all `files` as conflict candidates rather than failing the commit. + */ + private[delta] def filterFilesMatchingAnyReadPredicate( + files: Seq[AddFile], + dataFiltersPerRead: Seq[Seq[Expression]]): Seq[AddFile] = { + import org.apache.spark.sql.delta.implicits._ + if (files.isEmpty || dataFiltersPerRead.isEmpty || schema.isEmpty) return files + try { + // One skipping predicate per read. A read with no usable predicate (empty or ineligible + // filters) matches every file -> nothing can be skipped, so keep all files without a job. + val perReadPredicates = dataFiltersPerRead.map { dataFilters => + if (dataFilters.isEmpty) None else buildDataSkippingPredicate(dataFilters) + } + if (perReadPredicates.exists(_.isEmpty)) return files + // Survive if the file could match ANY read. Per read, `expr || !verifyStatsForFilter(...)` + // keeps any file whose referenced stats are missing/NULL (mirrors getDataSkippedFiles): only + // skip when stats prove no match. OR the reads so a match against any one keeps the file. + val survivorCondition = perReadPredicates.flatten + .map(pred => pred.expr || !verifyStatsForFilter(pred.referencedStats)) + .reduce(_ || _) + val survivingPaths = recordFrameProfile( + "Delta", "DataSkippingReader.filterFilesMatchingAnyReadPredicate") { + files.toDF(spark) + .withColumn("stats", parseAndDecodeStats(col("stats"))) + .where(survivorCondition) + .select("path") + .collect() + .map(_.getString(0)) + .toSet + } + files.filter(f => survivingPaths.contains(f.path)) + } catch { + case NonFatal(e) => + // Optimization only: never let a skipping failure abort a commit. Fall back to the default + // (feature-off) behavior of treating every added file as a conflict candidate. + logWarning(log"Conflict-time data skipping failed to evaluate; falling back to treating " + + log"all added files as conflict candidates", e) + files + } + } +} diff --git a/spark/src/main/scala/org/apache/spark/sql/delta/stats/DataSkippingReader.scala b/spark/src/main/scala/org/apache/spark/sql/delta/stats/DataSkippingReader.scala index 6c9673c55a4..73999236511 100644 --- a/spark/src/main/scala/org/apache/spark/sql/delta/stats/DataSkippingReader.scala +++ b/spark/src/main/scala/org/apache/spark/sql/delta/stats/DataSkippingReader.scala @@ -20,7 +20,6 @@ package org.apache.spark.sql.delta.stats import java.io.Closeable import scala.collection.mutable.ArrayBuffer -import scala.util.control.NonFatal import org.apache.spark.sql.delta.skipping.clustering.{ClusteredTableUtils, ClusteringColumnInfo} import org.apache.spark.sql.delta.ClassicColumnConversions._ @@ -265,6 +264,7 @@ trait DataSkippingReaderBase with StatisticsCollection with ReadsMetadataFields with StateCache + with ConflictDataSkippingReader with DeltaLogging { import DataSkippingReader._ @@ -287,29 +287,22 @@ trait DataSkippingReaderBase DeltaSQLConf.DELTA_DATASKIPPING_PARTITION_LIKE_FILTERS_ADDITIONAL_SUPPORTED_EXPRESSIONS) .toSet.flatMap((exprs: String) => exprs.split(",")) - /** - * Parses (and, when the schema contains VariantType, Z85-decodes) the JSON `statsCol` into the - * `statsSchema` struct. Shared by [[withStatsInternal0]] and conflict-detection data skipping - * ([[filterFilesByDataSkipping]]) so both parse stats the same way. - */ - private def parseAndDecodeStats(statsCol: Column): Column = { - val parsedStats = from_json(statsCol, statsSchema) + /** Returns a DataFrame expression to obtain a list of files with parsed statistics. */ + private def withStatsInternal0: DataFrame = { + val parsedStats = from_json(col("stats"), statsSchema) // Only use DecodeNestedZ85EncodedVariant if the schema contains VariantType. // This avoids performance overhead for tables without variant columns. // `DecodeNestedZ85EncodedVariant` is a temporary workaround since the Spark 4.1 from_json // expression has no way to decode a VariantVal from an encoded Z85 string. // TODO: Add Z85 decoding to Variant in Spark 4.2 and use that from_json option here. - if (SchemaUtils.checkForVariantTypeColumnsRecursively(statsSchema)) { + val decodedStats = if (SchemaUtils.checkForVariantTypeColumnsRecursively(statsSchema)) { Column(DecodeNestedZ85EncodedVariant(parsedStats.expr)) } else { parsedStats } + allFiles.withColumn("stats", decodedStats) } - /** Returns a DataFrame expression to obtain a list of files with parsed statistics. */ - private def withStatsInternal0: DataFrame = - allFiles.withColumn("stats", parseAndDecodeStats(col("stats"))) - private lazy val withStatsCache = cacheDS(withStatsInternal0, s"Delta Table State with Stats #$version - $redactedPath") @@ -649,112 +642,6 @@ trait DataSkippingReaderBase files.toSeq -> Seq(DataSize(totalSize), DataSize(partitionSize), DataSize(scanSize)) } - /** - * Builds a single [[DataSkippingPredicate]] (skipping expression + the stats it references) from - * `dataFilters`, mirroring [[filesForScan]]'s eligibility filtering, per-filter construction and - * conjunction fold. Returns None when stats skipping is unavailable or no eligible filter yields - * a predicate. The filters are AND-combined, so callers must pass filters from a single logical - * read (predicates from independent reads have OR, not AND, semantics). - */ - private[delta] def buildDataSkippingPredicate( - dataFilters: Seq[Expression]): Option[DataSkippingPredicate] = { - import DeltaTableUtils._ - if (!useStats) return None - // Mirror filesForScan eligibility: drop subquery / non-deterministic / metadata filters, so we - // never build a skipping predicate that could wrongly exclude a matching file. - val eligibleFilters = dataFilters.filterNot { f => - containsSubquery(f) || !f.deterministic || f.exists { - case MetadataAttribute(_) => true - case _ => false - } - } - val constructDataFilters = new DataFiltersBuilder( - spark = spark, - dataSkippingType = DeltaDataSkippingType.dataSkippingOnlyV1, - getStatsColumnOpt = (s: StatsColumn) => getStatsColumnOpt(s)) - eligibleFilters - .flatMap(f => constructDataFilters(f)) - .reduceOption((skip1, skip2) => DataSkippingPredicate( - skip1.expr && skip2.expr, skip1.referencedStats ++ skip2.referencedStats)) - } - - /** - * Conflict-detection helper (reader-side data skipping): returns the subset of `files` whose - * statistics do NOT prove they fail `dataFilters` -- i.e. the files that could still match and - * therefore must be treated as conflicts. Files with missing/insufficient stats (or when skipping - * is unavailable) are kept. - * - * `dataFilters` must come from a single logical read: they are AND-combined via - * [[buildDataSkippingPredicate]]. This is the one-read case of - * [[filterFilesMatchingAnyReadPredicate]]; callers with multiple independent reads should use - * that method so all reads are evaluated in a single Spark job. - */ - private[delta] def filterFilesByDataSkipping( - files: Seq[AddFile], - dataFilters: Seq[Expression]): Seq[AddFile] = - filterFilesMatchingAnyReadPredicate(files, Seq(dataFilters)) - - /** - * Conflict-detection helper (reader-side data skipping) over several INDEPENDENT reads: returns - * the subset of `files` that could still match ANY read and therefore must be treated as - * conflicts. Each inner `Seq[Expression]` is one logical read's data filters (AND-combined via - * [[buildDataSkippingPredicate]]); the reads are OR-combined, matching read semantics -- a file - * is a candidate if it could match any one of them. - * - * All reads are evaluated in a SINGLE Spark job: the per-read skipping predicates are OR-ed - * together into one `where` clause, rather than filtering per read and unioning the survivors - * (which launched one job per read). Note we cannot instead flatten every read's filters into one - * predicate -- that would AND them (read1 AND read2), the opposite of the OR we need. - * - * One-way safe: each read contributes `expr || !verifyStatsForFilter(...)` exactly as - * [[getDataSkippedFiles]], so a file is dropped only when its stats *prove* it fails EVERY read - * -- a real conflict is never a false negative. Files with missing/insufficient stats, a - * read with no usable skipping predicate (empty / ineligible filters -> matches everything), or a - * table without stats are all kept. Returns the original [[AddFile]]s (matched by path). - * - * Fail-safe: skipping here is a pure optimization over correct (conservative) conflict detection, - * so if building or evaluating the predicate throws we fall back to the default behavior of - * keeping all `files` as conflict candidates rather than failing the commit. - */ - private[delta] def filterFilesMatchingAnyReadPredicate( - files: Seq[AddFile], - dataFiltersPerRead: Seq[Seq[Expression]]): Seq[AddFile] = { - import org.apache.spark.sql.delta.implicits._ - if (files.isEmpty || dataFiltersPerRead.isEmpty || schema.isEmpty) return files - try { - // One skipping predicate per read. A read with no usable predicate (empty or ineligible - // filters) matches every file -> nothing can be skipped, so keep all files without a job. - val perReadPredicates = dataFiltersPerRead.map { dataFilters => - if (dataFilters.isEmpty) None else buildDataSkippingPredicate(dataFilters) - } - if (perReadPredicates.exists(_.isEmpty)) return files - // Survive if the file could match ANY read. Per read, `expr || !verifyStatsForFilter(...)` - // keeps any file whose referenced stats are missing/NULL (mirrors getDataSkippedFiles): only - // skip when stats prove no match. OR the reads so a match against any one keeps the file. - val survivorCondition = perReadPredicates.flatten - .map(pred => pred.expr || !verifyStatsForFilter(pred.referencedStats)) - .reduce(_ || _) - val survivingPaths = recordFrameProfile( - "Delta", "DataSkippingReader.filterFilesMatchingAnyReadPredicate") { - files.toDF(spark) - .withColumn("stats", parseAndDecodeStats(col("stats"))) - .where(survivorCondition) - .select("path") - .collect() - .map(_.getString(0)) - .toSet - } - files.filter(f => survivingPaths.contains(f.path)) - } catch { - case NonFatal(e) => - // Optimization only: never let a skipping failure abort a commit. Fall back to the default - // (feature-off) behavior of treating every added file as a conflict candidate. - logWarning(log"Conflict-time data skipping failed to evaluate; falling back to treating " + - log"all added files as conflict candidates", e) - files - } - } - private def getCorrectDataSkippingType( dataSkippingType: DeltaDataSkippingType): DeltaDataSkippingType = { dataSkippingType From 56f12d4ae9e113ca0cbda43afeceab48d6c432f3 Mon Sep 17 00:00:00 2001 From: Eunjin Song Date: Wed, 14 Oct 2026 22:04:02 -0700 Subject: [PATCH 5/9] Address review: pair each read's data skipping with its own partition probe Fuse the conflict-time data-skipping filter into the per-read partition probe so a file conflicts iff it could match (P_i AND D_i) for some read, instead of the looser (P_1 OR P_2) AND (D_1 OR D_2). Partition pruning now runs first and no extra Spark job is launched. Move the evaluation fallback into ConflictChecker and record it as a delta event; record the noConflict event only after all checks against the winning commit pass. Add multi-read, null-stats, and event tests. Co-Authored-By: Claude Opus 5.5 --- .../spark/sql/delta/ConflictChecker.scala | 148 +++++++++++++----- .../stats/ConflictDataSkippingReader.scala | 106 ++++++------- .../sql/delta/ConflictDataSkippingSuite.scala | 105 ++++++++++++- 3 files changed, 260 insertions(+), 99 deletions(-) diff --git a/spark/src/main/scala/org/apache/spark/sql/delta/ConflictChecker.scala b/spark/src/main/scala/org/apache/spark/sql/delta/ConflictChecker.scala index 0201dfe8403..e6d6fb9179c 100644 --- a/spark/src/main/scala/org/apache/spark/sql/delta/ConflictChecker.scala +++ b/spark/src/main/scala/org/apache/spark/sql/delta/ConflictChecker.scala @@ -20,6 +20,7 @@ package org.apache.spark.sql.delta import java.util.concurrent.TimeUnit import scala.collection.mutable +import scala.util.control.NonFatal import org.apache.spark.sql.delta.DeltaOperations.{OP_SET_TBLPROPERTIES, ROW_TRACKING_BACKFILL_OPERATION_NAME, ROW_TRACKING_UNBACKFILL_OPERATION_NAME} import org.apache.spark.sql.delta.RowId.RowTrackingMetadataDomain @@ -231,6 +232,12 @@ private[delta] class ConflictChecker( protected def recordSkippedPhase(phase: String): Unit = timingStats += phase -> 0 + /** + * Set when conflict-time data skipping was applied to a checked-appends probe that then found no + * conflicting file. Reported once the whole check against the winning commit has passed. + */ + private var dataSkippingAppliedWithoutConflict = false + /** * This function checks conflict of the `initialCurrentTransactionInfo` against the * `winningCommitVersion` and returns an updated [[CurrentTransactionInfo]] that represents @@ -306,6 +313,12 @@ private[delta] class ConflictChecker( checkForDeletedFilesAgainstCurrentTxnDeletedFiles() resolveTimestampOrderingConflicts() + if (dataSkippingAppliedWithoutConflict) { + recordDeltaEvent(deltaLog, + opType = "delta.conflictDetection.dataSkipping.noConflict", + data = Map("winningCommitVersion" -> winningCommitVersion)) + } + logMetrics() currentTransactionInfo } @@ -994,58 +1007,44 @@ private[delta] class ConflictChecker( return None } - // Reader-side data skipping: narrow the candidate files using the read snapshot's column-stats - // skipping. A concurrently-added file whose stats prove it cannot match the read predicates is - // not a conflict -- this is what lets unpartitioned / liquid-clustered tables avoid conflicting - // on every added file below. Data predicates are applied *per read predicate* and the survivors - // OR-combined, because independent reads have OR, not AND, semantics: a file is a candidate if - // it could match ANY read; it is dropped only if its stats prove it fails EVERY read. All reads - // are evaluated in a single Spark job by filterFilesMatchingAnyReadPredicate. Skipping is not - // applied for a whole-table read, nor when there are no read predicates at all: a transaction - // can be a non-blind-append (e.g. it removed files) yet have no read predicates, and in that - // case every added file must remain a conflict candidate, exactly as when the feature is - // disabled. Guarding on non-empty read predicates avoids an empty survivor set silently - // suppressing a real conflict. - val candidateFiles = - if (spark.conf.get(DeltaSQLConf.DELTA_CONFLICT_DETECTION_DATA_SKIPPING_ENABLED) && - !currentTransactionInfo.readWholeTable && - currentTransactionInfo.readPredicates.nonEmpty) { - val readSnapshot = currentTransactionInfo.readSnapshot - val remaining = readSnapshot.filterFilesMatchingAnyReadPredicate( - files, currentTransactionInfo.readPredicates.map(_.dataPredicates).toSeq) - if (remaining.size < files.size) { - recordDeltaEvent(deltaLog, - opType = "delta.conflictDetection.dataSkipping.filesSkipped", - data = Map( - "candidateFiles" -> files.size, - "skippedFiles" -> (files.size - remaining.size))) - } - remaining - } else { - files - } + // Reader-side data skipping: a concurrently-added file whose column stats prove it cannot match + // the read predicates is not a conflict -- this is what lets unpartitioned / liquid-clustered + // tables avoid conflicting on every added file. Not applied for a whole-table read, nor when + // there are no read predicates: a non-blind-append (e.g. it removed files) can have no read + // predicates, and then every added file must remain a conflict candidate, exactly as when the + // feature is disabled. + val useDataSkipping = + spark.conf.get(DeltaSQLConf.DELTA_CONFLICT_DETECTION_DATA_SKIPPING_ENABLED) && + !currentTransactionInfo.readWholeTable && + currentTransactionInfo.readPredicates.nonEmpty + + import org.apache.spark.sql.delta.implicits._ // There is no reason to filter files if the table is not partitioned. if (currentTransactionInfo.readWholeTable || currentTransactionInfo.readSnapshot.metadata.partitionColumns.isEmpty) { - return candidateFiles.headOption + if (!useDataSkipping || files.isEmpty) return files.headOption + return getFirstFileMatchingDataPredicates( + files.toDF(spark), currentTransactionInfo.readPredicates.map(_.dataPredicates)) } - import org.apache.spark.sql.delta.implicits._ - val filesDf = candidateFiles.toDF(spark) + val filesDf = files.toDF(spark) spark.conf.get(DeltaSQLConf.DELTA_CONFLICT_DETECTION_WIDEN_NONDETERMINISTIC_PREDICATES) match { case DeltaSQLConf.NonDeterministicPredicateWidening.OFF => getFirstFileMatchingPartitionPredicatesInternal( - filesDf, shouldWidenNonDeterministicPredicates = false, shouldWidenAllUdf = false) + filesDf, shouldWidenNonDeterministicPredicates = false, shouldWidenAllUdf = false, + useDataSkipping) case wideningMode => val fileWithWidening = getFirstFileMatchingPartitionPredicatesInternal( - filesDf, shouldWidenNonDeterministicPredicates = true, shouldWidenAllUdf = true) + filesDf, shouldWidenNonDeterministicPredicates = true, shouldWidenAllUdf = true, + useDataSkipping) fileWithWidening.flatMap { fileWithWidening => val fileWithoutWidening = getFirstFileMatchingPartitionPredicatesInternal( - filesDf, shouldWidenNonDeterministicPredicates = false, shouldWidenAllUdf = false) + filesDf, shouldWidenNonDeterministicPredicates = false, shouldWidenAllUdf = false, + useDataSkipping) if (fileWithoutWidening.isEmpty) { // Conflict due to widening of non-deterministic predicate. recordDeltaEvent(deltaLog, @@ -1071,7 +1070,8 @@ private[delta] class ConflictChecker( private def getFirstFileMatchingPartitionPredicatesInternal( filesDf: DataFrame, shouldWidenNonDeterministicPredicates: Boolean, - shouldWidenAllUdf: Boolean): Option[AddFile] = { + shouldWidenAllUdf: Boolean, + useDataSkipping: Boolean): Option[AddFile] = { def rewritePredicateFn( predicate: Expression, @@ -1101,15 +1101,44 @@ private[delta] class ConflictChecker( canonicalRewrites ++ canonicalNonRewrites } + // With data skipping, each probe is a partition predicate plus the data predicates of the reads + // that share it, so a read's data predicates are only combined with that same read's partition + // predicate: a file conflicts iff it could match (P_i AND D_i) for some read i, not the looser + // (P_1 OR P_2) AND (D_1 OR D_2). Like ExpressionSet, non-deterministic predicates are never + // merged. + val probes: Seq[(DeltaTableReadPredicate, Seq[Seq[Expression]])] = if (useDataSkipping) { + val groups = + mutable.LinkedHashMap[Any, (DeltaTableReadPredicate, mutable.Buffer[Seq[Expression]])]() + currentTransactionInfo.readPredicates.zipWithIndex.foreach { case (rp, i) => + val key = if (rp.partitionPredicate.deterministic) { + (rp.shouldRewriteFilter, rp.partitionPredicate.canonicalized) + } else { + i + } + groups.getOrElseUpdate(key, (rp, mutable.ArrayBuffer.empty))._2 += rp.dataPredicates + } + groups.values.toSeq.map { case (rp, dataFiltersPerRead) => + rewritePredicateFn(rp.partitionPredicate, rp.shouldRewriteFilter) -> + dataFiltersPerRead.toSeq + } + } else { + canonicalPredicates.toSeq.map(_ -> Seq.empty[Seq[Expression]]) + } + import org.apache.spark.sql.delta.implicits._ - val filesMatchingPartitionPredicates = canonicalPredicates.iterator - .flatMap { readPredicate => - val matchingFileOpt = DeltaLog.filterFileList( + val filesMatchingPartitionPredicates = probes.iterator + .flatMap { case (readPredicate, dataFiltersPerRead) => + val filesMatchingPartition = DeltaLog.filterFileList( partitionSchema = currentTransactionInfo.partitionSchemaAtReadTime, files = filesDf, partitionFilters = readPredicate.partitionPredicates, shouldRewritePartitionFilters = readPredicate.shouldRewriteFilter - ).as[AddFile].head(1).headOption + ) + val matchingFileOpt = if (useDataSkipping) { + getFirstFileMatchingDataPredicates(filesMatchingPartition, dataFiltersPerRead) + } else { + filesMatchingPartition.as[AddFile].head(1).headOption + } matchingFileOpt.foreach { f => logInfo(log"Partition predicate is matching a file changed by the winning transaction: " + log"predicate=${MDC(DeltaLogKeys.DATA_FILTER, @@ -1122,6 +1151,43 @@ private[delta] class ConflictChecker( filesMatchingPartitionPredicates.headOption } + /** + * Returns the first file in `filesDf` whose column stats do not prove it fails every read in + * `dataFiltersPerRead`, i.e. a file that must still be treated as a conflict. The skipping filter + * is fused into the same `head(1)` job as the caller's partition filter, which is applied first. + * + * Skipping is a pure optimization over conservative conflict detection: if building or + * evaluating the skipping filter fails, this records an event and falls back to checking without + * skipping, exactly as when the feature is disabled. + */ + private def getFirstFileMatchingDataPredicates( + filesDf: DataFrame, + dataFiltersPerRead: Seq[Seq[Expression]]): Option[AddFile] = { + import org.apache.spark.sql.delta.implicits._ + def firstFile(df: DataFrame): Option[AddFile] = df.as[AddFile].head(1).headOption + try { + currentTransactionInfo.readSnapshot + .filterFilesDfMatchingAnyReadPredicate(filesDf, dataFiltersPerRead) match { + case Some(skippedDf) => + val matchingFileOpt = firstFile(skippedDf) + if (matchingFileOpt.isEmpty) dataSkippingAppliedWithoutConflict = true + matchingFileOpt + case None => firstFile(filesDf) + } + } catch { + case NonFatal(e) => + logWarning(log"Conflict-time data skipping failed; falling back to treating all added " + + log"files as conflict candidates", e) + recordDeltaEvent(deltaLog, + opType = "delta.conflictDetection.dataSkipping.fallback", + data = Map( + "winningCommitVersion" -> winningCommitVersion, + "exceptionClass" -> e.getClass.getName, + "exceptionMessage" -> e.getMessage)) + firstFile(filesDf) + } + } + /** * RowTrackingBackfill does not do any data change. If backfill is the winning commit, the * current transaction does not need to read its AddFiles -- the exact same AddFiles have diff --git a/spark/src/main/scala/org/apache/spark/sql/delta/stats/ConflictDataSkippingReader.scala b/spark/src/main/scala/org/apache/spark/sql/delta/stats/ConflictDataSkippingReader.scala index 2305397b7f5..c7e84fda0bb 100644 --- a/spark/src/main/scala/org/apache/spark/sql/delta/stats/ConflictDataSkippingReader.scala +++ b/spark/src/main/scala/org/apache/spark/sql/delta/stats/ConflictDataSkippingReader.scala @@ -16,8 +16,6 @@ package org.apache.spark.sql.delta.stats -import scala.util.control.NonFatal - import org.apache.spark.sql.delta.ClassicColumnConversions._ import org.apache.spark.sql.delta.DeltaTableUtils import org.apache.spark.sql.delta.actions.AddFile @@ -26,7 +24,7 @@ import org.apache.spark.sql.delta.metering.DeltaLogging import org.apache.spark.sql.delta.schema.SchemaUtils import org.apache.spark.sql.delta.sources.DeltaSQLConf -import org.apache.spark.sql.Column +import org.apache.spark.sql.{Column, DataFrame} import org.apache.spark.sql.catalyst.expressions._ import org.apache.spark.sql.functions.{col, from_json} @@ -102,7 +100,7 @@ trait ConflictDataSkippingReader extends DeltaLogging { self: DataSkippingReader * `dataFilters` must come from a single logical read: they are AND-combined via * [[buildDataSkippingPredicate]]. This is the one-read case of * [[filterFilesMatchingAnyReadPredicate]]; callers with multiple independent reads should use - * that method so all reads are evaluated in a single Spark job. + * that method. */ private[delta] def filterFilesByDataSkipping( files: Seq[AddFile], @@ -112,61 +110,61 @@ trait ConflictDataSkippingReader extends DeltaLogging { self: DataSkippingReader /** * Conflict-detection helper (reader-side data skipping) over several INDEPENDENT reads: returns * the subset of `files` that could still match ANY read and therefore must be treated as - * conflicts. Each inner `Seq[Expression]` is one logical read's data filters (AND-combined via - * [[buildDataSkippingPredicate]]); the reads are OR-combined, matching read semantics -- a file - * is a candidate if it could match any one of them. - * - * All reads are evaluated in a SINGLE Spark job: the per-read skipping predicates are OR-ed - * together into one `where` clause, rather than filtering per read and unioning the survivors - * (which launched one job per read). Note we cannot instead flatten every read's filters into one - * predicate -- that would AND them (read1 AND read2), the opposite of the OR we need. - * - * One-way safe: each read contributes `expr || !verifyStatsForFilter(...)` exactly as - * [[getDataSkippedFiles]], so a file is dropped only when its stats *prove* it fails EVERY read - * -- a real conflict is never a false negative. Files with missing/insufficient stats, a - * read with no usable skipping predicate (empty / ineligible filters -> matches everything), or a - * table without stats are all kept. Returns the original [[AddFile]]s (matched by path). - * - * Fail-safe: skipping here is a pure optimization over correct (conservative) conflict detection, - * so if building or evaluating the predicate throws we fall back to the default behavior of - * keeping all `files` as conflict candidates rather than failing the commit. + * conflicts. Collecting wrapper around [[filterFilesDfMatchingAnyReadPredicate]]. */ private[delta] def filterFilesMatchingAnyReadPredicate( files: Seq[AddFile], dataFiltersPerRead: Seq[Seq[Expression]]): Seq[AddFile] = { import org.apache.spark.sql.delta.implicits._ - if (files.isEmpty || dataFiltersPerRead.isEmpty || schema.isEmpty) return files - try { - // One skipping predicate per read. A read with no usable predicate (empty or ineligible - // filters) matches every file -> nothing can be skipped, so keep all files without a job. - val perReadPredicates = dataFiltersPerRead.map { dataFilters => - if (dataFilters.isEmpty) None else buildDataSkippingPredicate(dataFilters) - } - if (perReadPredicates.exists(_.isEmpty)) return files - // Survive if the file could match ANY read. Per read, `expr || !verifyStatsForFilter(...)` - // keeps any file whose referenced stats are missing/NULL (mirrors getDataSkippedFiles): only - // skip when stats prove no match. OR the reads so a match against any one keeps the file. - val survivorCondition = perReadPredicates.flatten - .map(pred => pred.expr || !verifyStatsForFilter(pred.referencedStats)) - .reduce(_ || _) - val survivingPaths = recordFrameProfile( - "Delta", "DataSkippingReader.filterFilesMatchingAnyReadPredicate") { - files.toDF(spark) - .withColumn("stats", parseAndDecodeStats(col("stats"))) - .where(survivorCondition) - .select("path") - .collect() - .map(_.getString(0)) - .toSet - } - files.filter(f => survivingPaths.contains(f.path)) - } catch { - case NonFatal(e) => - // Optimization only: never let a skipping failure abort a commit. Fall back to the default - // (feature-off) behavior of treating every added file as a conflict candidate. - logWarning(log"Conflict-time data skipping failed to evaluate; falling back to treating " + - log"all added files as conflict candidates", e) - files + if (files.isEmpty) return files + filterFilesDfMatchingAnyReadPredicate(files.toDF(spark), dataFiltersPerRead) match { + case None => files + case Some(df) => + val survivingPaths = recordFrameProfile( + "Delta", "DataSkippingReader.filterFilesMatchingAnyReadPredicate") { + df.select("path").collect().map(_.getString(0)).toSet + } + files.filter(f => survivingPaths.contains(f.path)) + } + } + + /** + * Lazily restricts `filesDf` (a DataFrame of [[AddFile]]s with JSON `stats`) to the files that + * could still match ANY of several INDEPENDENT reads. Each inner `Seq[Expression]` is one logical + * read's data filters (AND-combined via [[buildDataSkippingPredicate]]); the reads are + * OR-combined, matching read semantics -- a file is a candidate if it could match any one of + * them. Returns None when nothing can be skipped: no reads, a table without stats, or a read + * with no usable skipping predicate (empty / ineligible filters match every file). + * + * No job is launched here, so callers can fuse the filter into their own query, e.g. after a + * partition filter so stats are only parsed for files in matching partitions. The returned + * DataFrame keeps the input's columns, with `stats` still the original JSON string. + * + * One-way safe: each read contributes `expr || !verifyStatsForFilter(...)` exactly as + * [[getDataSkippedFiles]], so a file is dropped only when its stats *prove* it fails EVERY read + * -- a real conflict is never a false negative. Files with missing/insufficient stats are kept. + */ + private[delta] def filterFilesDfMatchingAnyReadPredicate( + filesDf: DataFrame, + dataFiltersPerRead: Seq[Seq[Expression]]): Option[DataFrame] = { + if (dataFiltersPerRead.isEmpty || schema.isEmpty) return None + val perReadPredicates = dataFiltersPerRead.map { dataFilters => + if (dataFilters.isEmpty) None else buildDataSkippingPredicate(dataFilters) } + if (perReadPredicates.exists(_.isEmpty)) return None + // Per read, `expr || !verifyStatsForFilter(...)` keeps any file whose referenced stats are + // missing/NULL (mirrors getDataSkippedFiles); OR the reads so a match against any one keeps it. + val survivorCondition = perReadPredicates.flatten + .map(pred => pred.expr || !verifyStatsForFilter(pred.referencedStats)) + .reduce(_ || _) + // The skipping expressions reference the parsed `stats` struct; keep the raw JSON aside so the + // result still has the AddFile shape. + val rawStatsCol = "__conflict_skipping_raw_stats" + Some(filesDf + .withColumn(rawStatsCol, col("stats")) + .withColumn("stats", parseAndDecodeStats(col("stats"))) + .where(survivorCondition) + .withColumn("stats", col(rawStatsCol)) + .drop(rawStatsCol)) } } diff --git a/spark/src/test/scala/org/apache/spark/sql/delta/ConflictDataSkippingSuite.scala b/spark/src/test/scala/org/apache/spark/sql/delta/ConflictDataSkippingSuite.scala index bf5648ce97e..9786920e58f 100644 --- a/spark/src/test/scala/org/apache/spark/sql/delta/ConflictDataSkippingSuite.scala +++ b/spark/src/test/scala/org/apache/spark/sql/delta/ConflictDataSkippingSuite.scala @@ -19,8 +19,12 @@ package org.apache.spark.sql.delta import java.io.File import scala.concurrent.duration.Duration +import scala.util.Try + +import com.databricks.spark.util.Log4jUsageLogger import org.apache.spark.sql.delta.actions.AddFile +import org.apache.spark.sql.delta.DeltaTestUtils.filterUsageRecords import org.apache.spark.sql.delta.concurrency.PhaseLockingTestMixin import org.apache.spark.sql.delta.concurrency.TransactionExecutionTestMixin import org.apache.spark.sql.delta.sources.DeltaSQLConf @@ -28,10 +32,10 @@ import org.apache.spark.sql.delta.test.DeltaSQLCommandTest import org.apache.spark.SparkException import org.apache.spark.sql.{QueryTest, Row, SaveMode} -import org.apache.spark.sql.catalyst.expressions.{AttributeReference, Expression, GreaterThanOrEqual, LessThan, Literal} +import org.apache.spark.sql.catalyst.expressions.{AttributeReference, EqualTo, Expression, GreaterThanOrEqual, LessThan, Literal} import org.apache.spark.sql.functions.lit import org.apache.spark.sql.test.SharedSparkSession -import org.apache.spark.sql.types.LongType +import org.apache.spark.sql.types.{IntegerType, LongType} import org.apache.spark.util.ThreadUtils /** @@ -172,8 +176,11 @@ class ConflictDataSkippingSuite extends QueryTest } } - private def manufacturedAdd(name: String): AddFile = - AddFile(name, Map.empty[String, String], size = 1L, modificationTime = 1L, dataChange = true) + private def manufacturedAdd( + name: String, partitionValues: Map[String, String] = Map.empty): AddFile = + AddFile(name, partitionValues, size = 1L, modificationTime = 1L, dataChange = true) + + private val noConflictEvent = "delta.conflictDetection.dataSkipping.noConflict" test("empty read predicates on a non-blind-append txn: added file still conflicts") { // Soundness of the Serializable blind-append case. A transaction can be a NON-blind append @@ -277,4 +284,94 @@ class ConflictDataSkippingSuite extends QueryTest s"a read with no predicate must keep all files, got ${allKept.size}") } } + + test("files with null stats are kept while files whose stats prove no match are skipped") { + // Exercises the per-file `!verifyStatsForFilter` keep path: the skipping predicate IS built + // (the table has min/max stats), but one candidate file carries no stats at all. + withTempDir { dir => + createTable(dir) + val snapshot = DeltaLog.forTable(spark, dir.getCanonicalPath).update() + val allFiles = snapshot.allFiles.collect().toSeq + val noStats = manufacturedAdd("no-stats.parquet") + assert(noStats.stats == null) + + val id = AttributeReference("id", LongType)() + val survivors = snapshot.filterFilesByDataSkipping(allFiles :+ noStats, + Seq(LessThan(id, Literal(50L)))) + // Only the [0,100) file can match id<50; the other 9 are skipped by their stats. The file + // without stats cannot be proven to miss, so it is kept. + assert(survivors.size == 2, s"got ${survivors.map(_.path).sorted}") + assert(survivors.exists(_.path == noStats.path)) + } + } + + test("concurrently added file with null stats still conflicts") { + withTempDir { dir => + createTable(dir) + val log = DeltaLog.forTable(spark, dir.getCanonicalPath) + val id = AttributeReference("id", LongType)() + withSQLConf(DeltaSQLConf.DELTA_CONFLICT_DETECTION_DATA_SKIPPING_ENABLED.key -> "true") { + val loser = log.startTransaction() + loser.filterFiles(Seq(LessThan(id, Literal(50L)))) + log.startTransaction().commit( + Seq(manufacturedAdd("winner-no-stats.parquet")), DeltaOperations.Write(SaveMode.Append)) + intercept[io.delta.exceptions.ConcurrentAppendException] { + loser.commit( + Seq(manufacturedAdd("loser.parquet")), DeltaOperations.Write(SaveMode.Append)) + } + } + } + } + + test("multiple reads: data predicates are paired with their own partition predicate") { + // Reads `p=1 AND id<50` and `p=2 AND id>=100`. A file in p=1 with id=150 matches neither read, + // but matches (p=1 OR p=2) AND (id<50 OR id>=100), so evaluating partition and data + // predicates independently would report a false conflict. + withTempDir { dir => + spark.range(0, 1000, 1, 4).withColumn("p", lit(1)) + .union(spark.range(0, 1000, 1, 4).withColumn("p", lit(2))) + .write.partitionBy("p").format("delta").save(dir.getAbsolutePath) + sql(s"ALTER TABLE ${tableRef(dir)} SET TBLPROPERTIES " + + s"('${DeltaConfigs.ISOLATION_LEVEL.key}' = 'Serializable')") + val log = DeltaLog.forTable(spark, dir.getCanonicalPath) + val id = AttributeReference("id", LongType)() + val p = AttributeReference("p", IntegerType)() + var loserCount = 0 + + /** Runs the two-read loser against a winner appending `id` in [start, end) to `winnerP`. */ + def run(start: Long, end: Long, winnerP: Int, dataSkipping: Boolean): Try[Long] = { + loserCount += 1 + withSQLConf(DeltaSQLConf.DELTA_CONFLICT_DETECTION_DATA_SKIPPING_ENABLED.key -> + dataSkipping.toString) { + val loser = log.startTransaction() + loser.filterFiles(Seq(EqualTo(p, Literal(1)), LessThan(id, Literal(50L)))) + loser.filterFiles(Seq(EqualTo(p, Literal(2)), GreaterThanOrEqual(id, Literal(100L)))) + appendTxn(dir, start, end, partition = Some(winnerP))() + Try(loser.commit( + Seq(manufacturedAdd(s"loser-$loserCount.parquet", Map("p" -> "1"))), + DeltaOperations.Write(SaveMode.Append))) + } + } + + def assertConflict(result: Try[Long]): Unit = assert( + result.failed.toOption.exists( + _.isInstanceOf[io.delta.exceptions.ConcurrentAppendException]), + s"Expected ConcurrentAppendException, got: $result") + + // Cross terms (P1 AND D2) and (P2 AND D1): no read matches -> no conflict. + val usageLogs = Log4jUsageLogger.track { + assert(run(150, 151, winnerP = 1, dataSkipping = true).isSuccess) + assert(run(10, 11, winnerP = 2, dataSkipping = true).isSuccess) + } + assert(filterUsageRecords(usageLogs, noConflictEvent).size == 2) + // A file matching one of the reads still conflicts, and records no noConflict event. + val conflictLogs = Log4jUsageLogger.track { + assertConflict(run(10, 11, winnerP = 1, dataSkipping = true)) + assertConflict(run(150, 151, winnerP = 2, dataSkipping = true)) + } + assert(filterUsageRecords(conflictLogs, noConflictEvent).isEmpty) + // Feature disabled: partition pruning alone keeps the file -> conflict. + assertConflict(run(150, 151, winnerP = 1, dataSkipping = false)) + } + } } From 536ae8a9a3c6d63e50ffa752f6fa0b71b8dbe70f Mon Sep 17 00:00:00 2001 From: Eunjin Song Date: Thu, 15 Oct 2026 09:24:01 -0700 Subject: [PATCH 6/9] Test the conflict-time data skipping evaluation fallback Co-Authored-By: Claude Opus 5.5 --- .../sql/delta/ConflictDataSkippingSuite.scala | 29 +++++++++++++++++++ 1 file changed, 29 insertions(+) diff --git a/spark/src/test/scala/org/apache/spark/sql/delta/ConflictDataSkippingSuite.scala b/spark/src/test/scala/org/apache/spark/sql/delta/ConflictDataSkippingSuite.scala index 9786920e58f..09d34ff76cd 100644 --- a/spark/src/test/scala/org/apache/spark/sql/delta/ConflictDataSkippingSuite.scala +++ b/spark/src/test/scala/org/apache/spark/sql/delta/ConflictDataSkippingSuite.scala @@ -374,4 +374,33 @@ class ConflictDataSkippingSuite extends QueryTest assertConflict(run(150, 151, winnerP = 1, dataSkipping = false)) } } + + test("skipping evaluation failure falls back to treating added files as conflicts") { + // `id < 'abc'` builds a skipping predicate over the long `id` stats that fails once evaluated + // (the string does not cast to a long). The loser records it with stats skipping off so its own + // scan does not fail, then commits with skipping on. + withTempDir { dir => + createTable(dir) + val log = DeltaLog.forTable(spark, dir.getCanonicalPath) + val id = AttributeReference("id", LongType)() + val loser = withSQLConf(DeltaSQLConf.DELTA_STATS_SKIPPING.key -> "false") { + val txn = log.startTransaction() + txn.filterFiles(Seq(LessThan(id, Literal("abc")))) + txn + } + // A stats-bearing winner file that the predicate cannot match if evaluated. + appendTxn(dir, 1000, 1100)() + val usageLogs = Log4jUsageLogger.track { + withSQLConf(DeltaSQLConf.DELTA_CONFLICT_DETECTION_DATA_SKIPPING_ENABLED.key -> "true") { + intercept[io.delta.exceptions.ConcurrentAppendException] { + loser.commit( + Seq(manufacturedAdd("loser.parquet")), DeltaOperations.Write(SaveMode.Append)) + } + } + } + val fallbackEvent = "delta.conflictDetection.dataSkipping.fallback" + assert(filterUsageRecords(usageLogs, fallbackEvent).size == 1) + assert(filterUsageRecords(usageLogs, noConflictEvent).isEmpty) + } + } } From 9f7735fbb4c32050e6711e5beffbf844232a0ecc Mon Sep 17 00:00:00 2001 From: Eunjin Song Date: Thu, 15 Oct 2026 15:34:03 -0700 Subject: [PATCH 7/9] Address review: batch conflict-time skipping, skip toDF when unusable, report on commit - Check whether a skipping condition can be built before constructing any DataFrame; an unpartitioned check with nothing to skip returns files.headOption directly. - Evaluate candidates in bounded batches (internal conf conflictDetection.dataSkipping.batchSize, default 1000) and stop at the first batch holding a conflicting file: a filter over a local relation is evaluated over every row before the limit applies. - Group reads by their partition predicate after widening. - Report delta.conflictDetection.dataSkipping.applied once, from OptimisticTransaction, when the transaction commits. Co-Authored-By: Claude Opus 5.5 Signed-off-by: Eunjin Song --- .../spark/sql/delta/ConflictChecker.scala | 109 +++++++++++------- .../sql/delta/OptimisticTransaction.scala | 12 ++ .../sql/delta/sources/DeltaSQLConf.scala | 11 ++ .../stats/ConflictDataSkippingReader.scala | 50 +++++--- .../sql/delta/ConflictDataSkippingSuite.scala | 40 ++++++- 5 files changed, 157 insertions(+), 65 deletions(-) diff --git a/spark/src/main/scala/org/apache/spark/sql/delta/ConflictChecker.scala b/spark/src/main/scala/org/apache/spark/sql/delta/ConflictChecker.scala index 52f0621c50a..959a2f5c9b6 100644 --- a/spark/src/main/scala/org/apache/spark/sql/delta/ConflictChecker.scala +++ b/spark/src/main/scala/org/apache/spark/sql/delta/ConflictChecker.scala @@ -287,11 +287,14 @@ private[delta] class ConflictChecker( protected def recordSkippedPhase(phase: String): Unit = timingStats += phase -> 0 + /** Set when conflict-time data skipping was evaluated by a checked-appends probe. */ + private var dataSkippingApplied = false + /** - * Set when conflict-time data skipping was applied to a checked-appends probe that then found no - * conflicting file. Reported once the whole check against the winning commit has passed. + * Whether conflict-time data skipping was applied while checking against the winning commit. + * Read by the transaction, which reports it once the commit succeeds. */ - private var dataSkippingAppliedWithoutConflict = false + private[delta] def conflictDataSkippingApplied: Boolean = dataSkippingApplied /** * This function checks conflict of the `initialCurrentTransactionInfo` against the @@ -365,12 +368,6 @@ private[delta] class ConflictChecker( checkForDeletedFilesAgainstCurrentTxnDeletedFiles() resolveTimestampOrderingConflicts() - if (dataSkippingAppliedWithoutConflict) { - recordDeltaEvent(deltaLog, - opType = "delta.conflictDetection.dataSkipping.noConflict", - data = Map("winningCommitVersion" -> winningCommitVersion)) - } - // Fold the winning commit into our transaction info before the next attempt: this advances // `preCommitLatestAMTCheckpointOpt` to the winner's inline AMT checkpoint (when the winner // wrote one) and clears `currentCommitAttemptAMTCheckpointOpt`. @@ -1078,33 +1075,33 @@ private[delta] class ConflictChecker( !currentTransactionInfo.readWholeTable && currentTransactionInfo.readPredicates.nonEmpty - import org.apache.spark.sql.delta.implicits._ + val candidates = new CandidateFiles( + files, spark.conf.get(DeltaSQLConf.DELTA_CONFLICT_DETECTION_DATA_SKIPPING_BATCH_SIZE)) // There is no reason to filter files if the table is not partitioned. if (currentTransactionInfo.readWholeTable || currentTransactionInfo.readSnapshot.metadata.partitionColumns.isEmpty) { if (!useDataSkipping || files.isEmpty) return files.headOption return getFirstFileMatchingDataPredicates( - files.toDF(spark), currentTransactionInfo.readPredicates.map(_.dataPredicates)) + candidates, currentTransactionInfo.readPredicates.map(_.dataPredicates), + partitionFilter = None) } - val filesDf = files.toDF(spark) - spark.conf.get(DeltaSQLConf.DELTA_CONFLICT_DETECTION_WIDEN_NONDETERMINISTIC_PREDICATES) match { case DeltaSQLConf.NonDeterministicPredicateWidening.OFF => getFirstFileMatchingPartitionPredicatesInternal( - filesDf, shouldWidenNonDeterministicPredicates = false, shouldWidenAllUdf = false, + candidates, shouldWidenNonDeterministicPredicates = false, shouldWidenAllUdf = false, useDataSkipping) case wideningMode => val fileWithWidening = getFirstFileMatchingPartitionPredicatesInternal( - filesDf, shouldWidenNonDeterministicPredicates = true, shouldWidenAllUdf = true, + candidates, shouldWidenNonDeterministicPredicates = true, shouldWidenAllUdf = true, useDataSkipping) fileWithWidening.flatMap { fileWithWidening => val fileWithoutWidening = getFirstFileMatchingPartitionPredicatesInternal( - filesDf, shouldWidenNonDeterministicPredicates = false, shouldWidenAllUdf = false, - useDataSkipping) + candidates, shouldWidenNonDeterministicPredicates = false, + shouldWidenAllUdf = false, useDataSkipping) if (fileWithoutWidening.isEmpty) { // Conflict due to widening of non-deterministic predicate. recordDeltaEvent(deltaLog, @@ -1128,7 +1125,7 @@ private[delta] class ConflictChecker( } private def getFirstFileMatchingPartitionPredicatesInternal( - filesDf: DataFrame, + candidates: CandidateFiles, shouldWidenNonDeterministicPredicates: Boolean, shouldWidenAllUdf: Boolean, useDataSkipping: Boolean): Option[AddFile] = { @@ -1164,22 +1161,23 @@ private[delta] class ConflictChecker( // With data skipping, each probe is a partition predicate plus the data predicates of the reads // that share it, so a read's data predicates are only combined with that same read's partition // predicate: a file conflicts iff it could match (P_i AND D_i) for some read i, not the looser - // (P_1 OR P_2) AND (D_1 OR D_2). Like ExpressionSet, non-deterministic predicates are never - // merged. + // (P_1 OR P_2) AND (D_1 OR D_2). Reads are grouped by their partition predicate after widening, + // so predicates that widen to the same one share a probe. Like ExpressionSet, non-deterministic + // predicates are never merged. val probes: Seq[(DeltaTableReadPredicate, Seq[Seq[Expression]])] = if (useDataSkipping) { val groups = mutable.LinkedHashMap[Any, (DeltaTableReadPredicate, mutable.Buffer[Seq[Expression]])]() currentTransactionInfo.readPredicates.zipWithIndex.foreach { case (rp, i) => - val key = if (rp.partitionPredicate.deterministic) { - (rp.shouldRewriteFilter, rp.partitionPredicate.canonicalized) + val widened = rewritePredicateFn(rp.partitionPredicate, rp.shouldRewriteFilter) + val key = if (widened.partitionPredicate.deterministic) { + (widened.shouldRewriteFilter, widened.partitionPredicate.canonicalized) } else { i } - groups.getOrElseUpdate(key, (rp, mutable.ArrayBuffer.empty))._2 += rp.dataPredicates + groups.getOrElseUpdate(key, (widened, mutable.ArrayBuffer.empty))._2 += rp.dataPredicates } - groups.values.toSeq.map { case (rp, dataFiltersPerRead) => - rewritePredicateFn(rp.partitionPredicate, rp.shouldRewriteFilter) -> - dataFiltersPerRead.toSeq + groups.values.toSeq.map { case (widened, dataFiltersPerRead) => + widened -> dataFiltersPerRead.toSeq } } else { canonicalPredicates.toSeq.map(_ -> Seq.empty[Seq[Expression]]) @@ -1188,16 +1186,17 @@ private[delta] class ConflictChecker( import org.apache.spark.sql.delta.implicits._ val filesMatchingPartitionPredicates = probes.iterator .flatMap { case (readPredicate, dataFiltersPerRead) => - val filesMatchingPartition = DeltaLog.filterFileList( + def filterByPartition(filesDf: DataFrame): DataFrame = DeltaLog.filterFileList( partitionSchema = currentTransactionInfo.partitionSchemaAtReadTime, files = filesDf, partitionFilters = readPredicate.partitionPredicates, shouldRewritePartitionFilters = readPredicate.shouldRewriteFilter ) val matchingFileOpt = if (useDataSkipping) { - getFirstFileMatchingDataPredicates(filesMatchingPartition, dataFiltersPerRead) + getFirstFileMatchingDataPredicates( + candidates, dataFiltersPerRead, partitionFilter = Some(filterByPartition)) } else { - filesMatchingPartition.as[AddFile].head(1).headOption + filterByPartition(candidates.all).as[AddFile].head(1).headOption } matchingFileOpt.foreach { f => logInfo(log"Partition predicate is matching a file changed by the winning transaction: " + @@ -1212,28 +1211,52 @@ private[delta] class ConflictChecker( } /** - * Returns the first file in `filesDf` whose column stats do not prove it fails every read in - * `dataFiltersPerRead`, i.e. a file that must still be treated as a conflict. The skipping filter - * is fused into the same `head(1)` job as the caller's partition filter, which is applied first. + * The concurrently-added files to check, as the DataFrames the probes need. Built lazily on first + * use and shared by every probe. + */ + private class CandidateFiles(val files: Seq[AddFile], batchSize: Int) { + import org.apache.spark.sql.delta.implicits._ + lazy val all: DataFrame = files.toDF(spark) + // The files form a local relation, whose filters the optimizer evaluates over every row before + // applying a limit, so `head(1)` alone does not stop early. Bounded batches let a probe stop at + // the first batch that holds a conflicting file. + lazy val batches: LazyList[DataFrame] = + files.grouped(batchSize).map(_.toDF(spark)).to(LazyList) + } + + /** + * Returns the first candidate file that passes `partitionFilter` and whose column stats do not + * prove it fails every read in `dataFiltersPerRead`, i.e. a file that must still be treated as a + * conflict. The partition and skipping filters are fused into the same query, run over bounded + * batches of candidates until one holds a match. When nothing can be skipped, no stats are parsed + * and an unpartitioned check (`partitionFilter = None`) runs no query at all. * * Skipping is a pure optimization over conservative conflict detection: if building or * evaluating the skipping filter fails, this records an event and falls back to checking without * skipping, exactly as when the feature is disabled. */ private def getFirstFileMatchingDataPredicates( - filesDf: DataFrame, - dataFiltersPerRead: Seq[Seq[Expression]]): Option[AddFile] = { + candidates: CandidateFiles, + dataFiltersPerRead: Seq[Seq[Expression]], + partitionFilter: Option[DataFrame => DataFrame]): Option[AddFile] = { import org.apache.spark.sql.delta.implicits._ def firstFile(df: DataFrame): Option[AddFile] = df.as[AddFile].head(1).headOption + def firstFileWithoutSkipping: Option[AddFile] = partitionFilter match { + case Some(filter) => firstFile(filter(candidates.all)) + case None => candidates.files.headOption + } + val readSnapshot = currentTransactionInfo.readSnapshot try { - currentTransactionInfo.readSnapshot - .filterFilesDfMatchingAnyReadPredicate(filesDf, dataFiltersPerRead) match { - case Some(skippedDf) => - val matchingFileOpt = firstFile(skippedDf) - if (matchingFileOpt.isEmpty) dataSkippingAppliedWithoutConflict = true - matchingFileOpt - case None => firstFile(filesDf) - } + readSnapshot.conflictSkippingCondition(dataFiltersPerRead) match { + case None => firstFileWithoutSkipping + case Some(condition) => + val matchingFileOpt = candidates.batches.iterator.map { batch => + val filtered = partitionFilter.map(filter => filter(batch)).getOrElse(batch) + firstFile(readSnapshot.applyConflictSkippingCondition(filtered, condition)) + }.collectFirst { case Some(file) => file } + dataSkippingApplied = true + matchingFileOpt + } } catch { case NonFatal(e) => logWarning(log"Conflict-time data skipping failed; falling back to treating all added " + @@ -1244,7 +1267,7 @@ private[delta] class ConflictChecker( "winningCommitVersion" -> winningCommitVersion, "exceptionClass" -> e.getClass.getName, "exceptionMessage" -> e.getMessage)) - firstFile(filesDf) + firstFileWithoutSkipping } } diff --git a/spark/src/main/scala/org/apache/spark/sql/delta/OptimisticTransaction.scala b/spark/src/main/scala/org/apache/spark/sql/delta/OptimisticTransaction.scala index fbe1210005f..4bcb590ee2a 100644 --- a/spark/src/main/scala/org/apache/spark/sql/delta/OptimisticTransaction.scala +++ b/spark/src/main/scala/org/apache/spark/sql/delta/OptimisticTransaction.scala @@ -483,6 +483,12 @@ trait OptimisticTransactionImpl extends TransactionHelper */ protected var commitAttemptStartTimeMillis: Long = _ + /** + * Whether conflict-time data skipping was applied while checking this transaction against any + * winning commit, across all commit attempts. Reported once the transaction commits. + */ + private var conflictDataSkippingApplied = false + /** * Tracks actions within the transaction, will commit along with the passed-in actions in the * commit function. @@ -3609,6 +3615,7 @@ trait OptimisticTransactionImpl extends TransactionHelper winningCommitSummary, firstWinningVersion, updatedCurrentTransactionInfo).getOrElse { conflictChecker.checkConflictsAndValidateActions() } + conflictDataSkippingApplied ||= conflictChecker.conflictDataSkippingApplied logInfo(logPrefix + log"No conflicts in version ${MDC(DeltaLogKeys.VERSION, otherCommitVersion)}, " + @@ -3733,6 +3740,11 @@ trait OptimisticTransactionImpl extends TransactionHelper committedTransactionInfoOpt.map(_.finalActionsToCommit).getOrElse(Seq.empty) val catalogTableForCommittedTransaction = committedTransactionInfoOpt.flatMap(_.catalogTable).orElse(catalogTable) + if (conflictDataSkippingApplied) { + recordDeltaEvent(deltaLog, + opType = "delta.conflictDetection.dataSkipping.applied", + data = Map("committedVersion" -> committedVersion)) + } committed = Some(CommittedTransaction( txnId = txnId, deltaLog = deltaLog, diff --git a/spark/src/main/scala/org/apache/spark/sql/delta/sources/DeltaSQLConf.scala b/spark/src/main/scala/org/apache/spark/sql/delta/sources/DeltaSQLConf.scala index 855c3278a8b..41faac651bf 100644 --- a/spark/src/main/scala/org/apache/spark/sql/delta/sources/DeltaSQLConf.scala +++ b/spark/src/main/scala/org/apache/spark/sql/delta/sources/DeltaSQLConf.scala @@ -618,6 +618,17 @@ trait DeltaSQLConfBase extends DeltaSQLConfUtils { .booleanConf .createWithDefault(false) + val DELTA_CONFLICT_DETECTION_DATA_SKIPPING_BATCH_SIZE = + buildConf("conflictDetection.dataSkipping.batchSize") + .internal() + .doc( + """Number of concurrently-added files evaluated per batch by conflict-time data skipping. + |Each batch's stats are parsed and filtered in full, so smaller batches stop sooner once a + |conflicting file is found.""".stripMargin) + .intConf + .checkValue(_ > 0, "must be positive") + .createWithDefault(1000) + val DELTA_PROTOCOL_DEFAULT_WRITER_VERSION = buildConf("properties.defaults.minWriterVersion") .doc("The default writer protocol version to create new tables with, unless a feature " + diff --git a/spark/src/main/scala/org/apache/spark/sql/delta/stats/ConflictDataSkippingReader.scala b/spark/src/main/scala/org/apache/spark/sql/delta/stats/ConflictDataSkippingReader.scala index c7e84fda0bb..49f25d619ab 100644 --- a/spark/src/main/scala/org/apache/spark/sql/delta/stats/ConflictDataSkippingReader.scala +++ b/spark/src/main/scala/org/apache/spark/sql/delta/stats/ConflictDataSkippingReader.scala @@ -130,23 +130,29 @@ trait ConflictDataSkippingReader extends DeltaLogging { self: DataSkippingReader /** * Lazily restricts `filesDf` (a DataFrame of [[AddFile]]s with JSON `stats`) to the files that - * could still match ANY of several INDEPENDENT reads. Each inner `Seq[Expression]` is one logical - * read's data filters (AND-combined via [[buildDataSkippingPredicate]]); the reads are - * OR-combined, matching read semantics -- a file is a candidate if it could match any one of - * them. Returns None when nothing can be skipped: no reads, a table without stats, or a read - * with no usable skipping predicate (empty / ineligible filters match every file). - * - * No job is launched here, so callers can fuse the filter into their own query, e.g. after a - * partition filter so stats are only parsed for files in matching partitions. The returned - * DataFrame keeps the input's columns, with `stats` still the original JSON string. + * could still match ANY of several INDEPENDENT reads, or returns None when nothing can be + * skipped. Combines [[conflictSkippingCondition]] and [[applyConflictSkippingCondition]]. + */ + private[delta] def filterFilesDfMatchingAnyReadPredicate( + filesDf: DataFrame, + dataFiltersPerRead: Seq[Seq[Expression]]): Option[DataFrame] = + conflictSkippingCondition(dataFiltersPerRead).map(applyConflictSkippingCondition(filesDf, _)) + + /** + * Builds the condition a file must satisfy to possibly match ANY of several INDEPENDENT reads. + * Each inner `Seq[Expression]` is one logical read's data filters (AND-combined via + * [[buildDataSkippingPredicate]]); the reads are OR-combined, matching read semantics -- a file + * is a candidate if it could match any one of them. Returns None when nothing can be skipped: no + * reads, a table without stats, or a read with no usable skipping predicate (empty / ineligible + * filters match every file). Needs no DataFrame, so callers can check whether skipping applies + * before building one. * * One-way safe: each read contributes `expr || !verifyStatsForFilter(...)` exactly as * [[getDataSkippedFiles]], so a file is dropped only when its stats *prove* it fails EVERY read * -- a real conflict is never a false negative. Files with missing/insufficient stats are kept. */ - private[delta] def filterFilesDfMatchingAnyReadPredicate( - filesDf: DataFrame, - dataFiltersPerRead: Seq[Seq[Expression]]): Option[DataFrame] = { + private[delta] def conflictSkippingCondition( + dataFiltersPerRead: Seq[Seq[Expression]]): Option[Column] = { if (dataFiltersPerRead.isEmpty || schema.isEmpty) return None val perReadPredicates = dataFiltersPerRead.map { dataFilters => if (dataFilters.isEmpty) None else buildDataSkippingPredicate(dataFilters) @@ -154,17 +160,27 @@ trait ConflictDataSkippingReader extends DeltaLogging { self: DataSkippingReader if (perReadPredicates.exists(_.isEmpty)) return None // Per read, `expr || !verifyStatsForFilter(...)` keeps any file whose referenced stats are // missing/NULL (mirrors getDataSkippedFiles); OR the reads so a match against any one keeps it. - val survivorCondition = perReadPredicates.flatten + Some(perReadPredicates.flatten .map(pred => pred.expr || !verifyStatsForFilter(pred.referencedStats)) - .reduce(_ || _) + .reduce(_ || _)) + } + + /** + * Lazily applies a [[conflictSkippingCondition]] to `filesDf`. No job is launched here, so + * callers can fuse the filter into their own query, e.g. with a partition filter. The returned + * DataFrame keeps the input's columns, with `stats` still the original JSON string. + */ + private[delta] def applyConflictSkippingCondition( + filesDf: DataFrame, + condition: Column): DataFrame = { // The skipping expressions reference the parsed `stats` struct; keep the raw JSON aside so the // result still has the AddFile shape. val rawStatsCol = "__conflict_skipping_raw_stats" - Some(filesDf + filesDf .withColumn(rawStatsCol, col("stats")) .withColumn("stats", parseAndDecodeStats(col("stats"))) - .where(survivorCondition) + .where(condition) .withColumn("stats", col(rawStatsCol)) - .drop(rawStatsCol)) + .drop(rawStatsCol) } } diff --git a/spark/src/test/scala/org/apache/spark/sql/delta/ConflictDataSkippingSuite.scala b/spark/src/test/scala/org/apache/spark/sql/delta/ConflictDataSkippingSuite.scala index 09d34ff76cd..8a0ea046d63 100644 --- a/spark/src/test/scala/org/apache/spark/sql/delta/ConflictDataSkippingSuite.scala +++ b/spark/src/test/scala/org/apache/spark/sql/delta/ConflictDataSkippingSuite.scala @@ -180,7 +180,7 @@ class ConflictDataSkippingSuite extends QueryTest name: String, partitionValues: Map[String, String] = Map.empty): AddFile = AddFile(name, partitionValues, size = 1L, modificationTime = 1L, dataChange = true) - private val noConflictEvent = "delta.conflictDetection.dataSkipping.noConflict" + private val appliedEvent = "delta.conflictDetection.dataSkipping.applied" test("empty read predicates on a non-blind-append txn: added file still conflicts") { // Soundness of the Serializable blind-append case. A transaction can be a NON-blind append @@ -363,13 +363,13 @@ class ConflictDataSkippingSuite extends QueryTest assert(run(150, 151, winnerP = 1, dataSkipping = true).isSuccess) assert(run(10, 11, winnerP = 2, dataSkipping = true).isSuccess) } - assert(filterUsageRecords(usageLogs, noConflictEvent).size == 2) - // A file matching one of the reads still conflicts, and records no noConflict event. + assert(filterUsageRecords(usageLogs, appliedEvent).size == 2) + // A file matching one of the reads still conflicts, and records no applied event. val conflictLogs = Log4jUsageLogger.track { assertConflict(run(10, 11, winnerP = 1, dataSkipping = true)) assertConflict(run(150, 151, winnerP = 2, dataSkipping = true)) } - assert(filterUsageRecords(conflictLogs, noConflictEvent).isEmpty) + assert(filterUsageRecords(conflictLogs, appliedEvent).isEmpty) // Feature disabled: partition pruning alone keeps the file -> conflict. assertConflict(run(150, 151, winnerP = 1, dataSkipping = false)) } @@ -400,7 +400,37 @@ class ConflictDataSkippingSuite extends QueryTest } val fallbackEvent = "delta.conflictDetection.dataSkipping.fallback" assert(filterUsageRecords(usageLogs, fallbackEvent).size == 1) - assert(filterUsageRecords(usageLogs, noConflictEvent).isEmpty) + assert(filterUsageRecords(usageLogs, appliedEvent).isEmpty) + } + } + + test("skipping evaluates candidates in batches and finds a conflict in a later batch") { + withTempDir { dir => + createTable(dir) + val log = DeltaLog.forTable(spark, dir.getCanonicalPath) + val id = AttributeReference("id", LongType)() + // Winner adds four files: three whose stats prove they miss `id < 50`, then the [0,100) file, + // which matches. Reusing the table's files gives them real stats. + val (matching, missing) = log.update().allFiles.collect().toSeq + .partition(_.stats.contains("\"minValues\":{\"id\":0}")) + val winnerAdds = missing.take(3) ++ matching + assert(winnerAdds.size == 4) + + def run(adds: Seq[AddFile]): scala.util.Try[Long] = withSQLConf( + DeltaSQLConf.DELTA_CONFLICT_DETECTION_DATA_SKIPPING_ENABLED.key -> "true", + DeltaSQLConf.DELTA_CONFLICT_DETECTION_DATA_SKIPPING_BATCH_SIZE.key -> "1") { + val loser = log.startTransaction() + loser.filterFiles(Seq(LessThan(id, Literal(50L)))) + log.startTransaction().commit(adds, DeltaOperations.Write(SaveMode.Append)) + scala.util.Try(loser.commit( + Seq(manufacturedAdd(s"loser-${adds.size}.parquet")), + DeltaOperations.Write(SaveMode.Append))) + } + // Only the three non-matching files: every batch is skipped, no conflict. + assert(run(winnerAdds.take(3).map(f => f.copy(path = "a-" + f.path))).isSuccess) + // The matching file is the fourth batch: still found. + assert(run(winnerAdds.map(f => f.copy(path = "b-" + f.path))).failed.toOption + .exists(_.isInstanceOf[io.delta.exceptions.ConcurrentAppendException])) } } } From 25db6f64ec04908d7b11da7144cfe46dc62ec8a3 Mon Sep 17 00:00:00 2001 From: Eunjin Song Date: Thu, 19 Nov 2026 10:03:08 -0800 Subject: [PATCH 8/9] Address review: no skipping report without candidates, retry failed batches, share stats helpers - Return early when there are no candidate files, so a winning commit that adds no files to check does not report conflict-time data skipping as applied. - Group the candidate files before building their DataFrames, so a probe that fails to build a batch does not make the next probe skip that batch. The candidate set is now ConflictCandidateFiles, with an injectable toDF for tests. - Share stats parsing (parseStats), filter eligibility (isIneligibleForDataSkipping) and the stats-skipping check (useStats) with the scan path. Remove the filterFiles* wrappers, which had no production callers. - Tests: pin ANSI mode in the evaluation-failure test and add a partitioned case; add tests for concurrent UPDATE and MERGE, deletion vectors, column mapping, non-deterministic and unusable predicates, disabled stats skipping, and the applied event across several winning commits. Co-Authored-By: Claude Opus 5.5 Signed-off-by: Eunjin Song --- .../spark/sql/delta/ConflictChecker.scala | 55 ++- .../stats/ConflictDataSkippingReader.scala | 102 +--- .../sql/delta/stats/DataSkippingReader.scala | 31 +- .../sql/delta/ConflictDataSkippingSuite.scala | 457 ++++++++++++++++-- 4 files changed, 485 insertions(+), 160 deletions(-) diff --git a/spark/src/main/scala/org/apache/spark/sql/delta/ConflictChecker.scala b/spark/src/main/scala/org/apache/spark/sql/delta/ConflictChecker.scala index 959a2f5c9b6..26266bcdce9 100644 --- a/spark/src/main/scala/org/apache/spark/sql/delta/ConflictChecker.scala +++ b/spark/src/main/scala/org/apache/spark/sql/delta/ConflictChecker.scala @@ -1075,13 +1075,18 @@ private[delta] class ConflictChecker( !currentTransactionInfo.readWholeTable && currentTransactionInfo.readPredicates.nonEmpty - val candidates = new CandidateFiles( - files, spark.conf.get(DeltaSQLConf.DELTA_CONFLICT_DETECTION_DATA_SKIPPING_BATCH_SIZE)) + val candidates = { + import org.apache.spark.sql.delta.implicits._ + new ConflictCandidateFiles( + files, + spark.conf.get(DeltaSQLConf.DELTA_CONFLICT_DETECTION_DATA_SKIPPING_BATCH_SIZE), + toDF = _.toDF(spark)) + } // There is no reason to filter files if the table is not partitioned. if (currentTransactionInfo.readWholeTable || currentTransactionInfo.readSnapshot.metadata.partitionColumns.isEmpty) { - if (!useDataSkipping || files.isEmpty) return files.headOption + if (!useDataSkipping) return files.headOption return getFirstFileMatchingDataPredicates( candidates, currentTransactionInfo.readPredicates.map(_.dataPredicates), partitionFilter = None) @@ -1125,7 +1130,7 @@ private[delta] class ConflictChecker( } private def getFirstFileMatchingPartitionPredicatesInternal( - candidates: CandidateFiles, + candidates: ConflictCandidateFiles, shouldWidenNonDeterministicPredicates: Boolean, shouldWidenAllUdf: Boolean, useDataSkipping: Boolean): Option[AddFile] = { @@ -1210,35 +1215,24 @@ private[delta] class ConflictChecker( filesMatchingPartitionPredicates.headOption } - /** - * The concurrently-added files to check, as the DataFrames the probes need. Built lazily on first - * use and shared by every probe. - */ - private class CandidateFiles(val files: Seq[AddFile], batchSize: Int) { - import org.apache.spark.sql.delta.implicits._ - lazy val all: DataFrame = files.toDF(spark) - // The files form a local relation, whose filters the optimizer evaluates over every row before - // applying a limit, so `head(1)` alone does not stop early. Bounded batches let a probe stop at - // the first batch that holds a conflicting file. - lazy val batches: LazyList[DataFrame] = - files.grouped(batchSize).map(_.toDF(spark)).to(LazyList) - } - /** * Returns the first candidate file that passes `partitionFilter` and whose column stats do not * prove it fails every read in `dataFiltersPerRead`, i.e. a file that must still be treated as a * conflict. The partition and skipping filters are fused into the same query, run over bounded - * batches of candidates until one holds a match. When nothing can be skipped, no stats are parsed - * and an unpartitioned check (`partitionFilter = None`) runs no query at all. + * batches of candidates until one holds a match. When there are no candidates or nothing can be + * skipped, no stats are parsed, and an unpartitioned check (`partitionFilter = None`) runs no + * query at all. * * Skipping is a pure optimization over conservative conflict detection: if building or * evaluating the skipping filter fails, this records an event and falls back to checking without * skipping, exactly as when the feature is disabled. */ private def getFirstFileMatchingDataPredicates( - candidates: CandidateFiles, + candidates: ConflictCandidateFiles, dataFiltersPerRead: Seq[Seq[Expression]], partitionFilter: Option[DataFrame => DataFrame]): Option[AddFile] = { + // Nothing to check, so nothing is skipped: do not report skipping as applied. + if (candidates.files.isEmpty) return None import org.apache.spark.sql.delta.implicits._ def firstFile(df: DataFrame): Option[AddFile] = df.as[AddFile].head(1).headOption def firstFileWithoutSkipping: Option[AddFile] = partitionFilter match { @@ -1890,3 +1884,22 @@ private[delta] object ConflictChecker extends DeltaLogging { } } } + +/** + * The concurrently-added files a conflict check tests against the current transaction's reads, + * as the DataFrames its probes need. Built lazily on first use and shared by every probe. + * + * @param toDF builds a DataFrame of [[AddFile]]s from a group of files. + */ +private[delta] class ConflictCandidateFiles( + val files: Seq[AddFile], + batchSize: Int, + toDF: Seq[AddFile] => DataFrame) { + lazy val all: DataFrame = toDF(files) + // The files form a local relation, whose filters the optimizer evaluates over every row before + // applying a limit, so `head(1)` alone does not stop early. Bounded batches let a probe stop at + // the first batch that holds a conflicting file. The groups are memoized before `toDF` runs, so + // a `toDF` failure is retried for the same group by the next probe instead of skipping it. + lazy val batches: LazyList[DataFrame] = + files.grouped(batchSize).to(LazyList).map(toDF) +} diff --git a/spark/src/main/scala/org/apache/spark/sql/delta/stats/ConflictDataSkippingReader.scala b/spark/src/main/scala/org/apache/spark/sql/delta/stats/ConflictDataSkippingReader.scala index 49f25d619ab..abe08b023de 100644 --- a/spark/src/main/scala/org/apache/spark/sql/delta/stats/ConflictDataSkippingReader.scala +++ b/spark/src/main/scala/org/apache/spark/sql/delta/stats/ConflictDataSkippingReader.scala @@ -17,70 +17,41 @@ package org.apache.spark.sql.delta.stats import org.apache.spark.sql.delta.ClassicColumnConversions._ -import org.apache.spark.sql.delta.DeltaTableUtils -import org.apache.spark.sql.delta.actions.AddFile -import org.apache.spark.sql.delta.expressions.DecodeNestedZ85EncodedVariant import org.apache.spark.sql.delta.metering.DeltaLogging -import org.apache.spark.sql.delta.schema.SchemaUtils -import org.apache.spark.sql.delta.sources.DeltaSQLConf import org.apache.spark.sql.{Column, DataFrame} import org.apache.spark.sql.catalyst.expressions._ -import org.apache.spark.sql.functions.{col, from_json} +import org.apache.spark.sql.functions.col /** * Reader-side data skipping used during conflict detection (row-level concurrency Case 1: writers * touching disjoint data ranges). * - * Mixed into [[DataSkippingReaderBase]] as a self-typed trait so this feature is a single isolated - * unit that only ADDS methods -- it does not modify any existing data-skipping code. It is opt-in: - * the caller ([[org.apache.spark.sql.delta.ConflictChecker]]) invokes these methods only behind + * Mixed into [[DataSkippingReaderBase]] as a self-typed trait that keeps the conflict-detection + * logic in one place, while sharing the scan path's stats parsing ([[parseStats]]) and filter + * eligibility ([[DataSkippingReader.isIneligibleForDataSkipping]]). It is opt-in: the caller + * ([[org.apache.spark.sql.delta.ConflictChecker]]) invokes these methods only behind * `DeltaSQLConf.DELTA_CONFLICT_DETECTION_DATA_SKIPPING_ENABLED`, and each is one-way safe -- a file * is dropped only when its stats *prove* it cannot match, so a real conflict is never a false * negative. */ trait ConflictDataSkippingReader extends DeltaLogging { self: DataSkippingReaderBase => - /** - * Parses (and, when the schema contains VariantType, Z85-decodes) the JSON `statsCol` into the - * `statsSchema` struct, mirroring [[withStatsInternal0]]. Deliberately kept private to this trait - * rather than shared with `withStatsInternal0`, so the existing stats path stays untouched. - */ - private def parseAndDecodeStats(statsCol: Column): Column = { - val parsedStats = from_json(statsCol, statsSchema) - // Only use DecodeNestedZ85EncodedVariant if the schema contains VariantType. - // This avoids performance overhead for tables without variant columns. - // `DecodeNestedZ85EncodedVariant` is a temporary workaround since the Spark 4.1 from_json - // expression has no way to decode a VariantVal from an encoded Z85 string. - // TODO: Add Z85 decoding to Variant in Spark 4.2 and use that from_json option here. - if (SchemaUtils.checkForVariantTypeColumnsRecursively(statsSchema)) { - Column(DecodeNestedZ85EncodedVariant(parsedStats.expr)) - } else { - parsedStats - } - } - /** * Builds a single [[DataSkippingPredicate]] (skipping expression + the stats it references) from - * `dataFilters`, mirroring [[filesForScan]]'s eligibility filtering, per-filter construction and + * `dataFilters`, with [[filesForScan]]'s eligibility filtering, per-filter construction and * conjunction fold. Returns None when stats skipping is unavailable or no eligible filter yields * a predicate. The filters are AND-combined, so callers must pass filters from a single logical * read (predicates from independent reads have OR, not AND, semantics). */ private[delta] def buildDataSkippingPredicate( dataFilters: Seq[Expression]): Option[DataSkippingPredicate] = { - import DeltaTableUtils._ - // Stats-skipping conf, inlined from DataSkippingReaderBase.useStats (file-private, so not - // visible here). Reading it inline avoids widening that member's visibility. - if (!spark.sessionState.conf.getConf(DeltaSQLConf.DELTA_STATS_SKIPPING)) return None - // Mirror filesForScan eligibility: drop subquery / non-deterministic / metadata filters, so we - // never build a skipping predicate that could wrongly exclude a matching file. - val eligibleFilters = dataFilters.filterNot { f => - containsSubquery(f) || !f.deterministic || f.exists { - case MetadataAttribute(_) => true - case _ => false - } - } + if (!useStats) return None + // Same eligibility as filesForScan: drop subquery / non-deterministic / metadata filters, so we + // never build a skipping predicate that could wrongly exclude a matching file. Dropping a + // conjunct only widens the predicate. + val eligibleFilters = + dataFilters.filterNot(DataSkippingReader.isIneligibleForDataSkipping) val constructDataFilters = new DataFiltersBuilder( spark = spark, dataSkippingType = DeltaDataSkippingType.dataSkippingOnlyV1, @@ -91,53 +62,6 @@ trait ConflictDataSkippingReader extends DeltaLogging { self: DataSkippingReader skip1.expr && skip2.expr, skip1.referencedStats ++ skip2.referencedStats)) } - /** - * Conflict-detection helper (reader-side data skipping): returns the subset of `files` whose - * statistics do NOT prove they fail `dataFilters` -- i.e. the files that could still match and - * therefore must be treated as conflicts. Files with missing/insufficient stats (or when skipping - * is unavailable) are kept. - * - * `dataFilters` must come from a single logical read: they are AND-combined via - * [[buildDataSkippingPredicate]]. This is the one-read case of - * [[filterFilesMatchingAnyReadPredicate]]; callers with multiple independent reads should use - * that method. - */ - private[delta] def filterFilesByDataSkipping( - files: Seq[AddFile], - dataFilters: Seq[Expression]): Seq[AddFile] = - filterFilesMatchingAnyReadPredicate(files, Seq(dataFilters)) - - /** - * Conflict-detection helper (reader-side data skipping) over several INDEPENDENT reads: returns - * the subset of `files` that could still match ANY read and therefore must be treated as - * conflicts. Collecting wrapper around [[filterFilesDfMatchingAnyReadPredicate]]. - */ - private[delta] def filterFilesMatchingAnyReadPredicate( - files: Seq[AddFile], - dataFiltersPerRead: Seq[Seq[Expression]]): Seq[AddFile] = { - import org.apache.spark.sql.delta.implicits._ - if (files.isEmpty) return files - filterFilesDfMatchingAnyReadPredicate(files.toDF(spark), dataFiltersPerRead) match { - case None => files - case Some(df) => - val survivingPaths = recordFrameProfile( - "Delta", "DataSkippingReader.filterFilesMatchingAnyReadPredicate") { - df.select("path").collect().map(_.getString(0)).toSet - } - files.filter(f => survivingPaths.contains(f.path)) - } - } - - /** - * Lazily restricts `filesDf` (a DataFrame of [[AddFile]]s with JSON `stats`) to the files that - * could still match ANY of several INDEPENDENT reads, or returns None when nothing can be - * skipped. Combines [[conflictSkippingCondition]] and [[applyConflictSkippingCondition]]. - */ - private[delta] def filterFilesDfMatchingAnyReadPredicate( - filesDf: DataFrame, - dataFiltersPerRead: Seq[Seq[Expression]]): Option[DataFrame] = - conflictSkippingCondition(dataFiltersPerRead).map(applyConflictSkippingCondition(filesDf, _)) - /** * Builds the condition a file must satisfy to possibly match ANY of several INDEPENDENT reads. * Each inner `Seq[Expression]` is one logical read's data filters (AND-combined via @@ -178,7 +102,7 @@ trait ConflictDataSkippingReader extends DeltaLogging { self: DataSkippingReader val rawStatsCol = "__conflict_skipping_raw_stats" filesDf .withColumn(rawStatsCol, col("stats")) - .withColumn("stats", parseAndDecodeStats(col("stats"))) + .withColumn("stats", parseStats(col("stats"))) .where(condition) .withColumn("stats", col(rawStatsCol)) .drop(rawStatsCol) diff --git a/spark/src/main/scala/org/apache/spark/sql/delta/stats/DataSkippingReader.scala b/spark/src/main/scala/org/apache/spark/sql/delta/stats/DataSkippingReader.scala index e448074efe8..53be8f06a51 100644 --- a/spark/src/main/scala/org/apache/spark/sql/delta/stats/DataSkippingReader.scala +++ b/spark/src/main/scala/org/apache/spark/sql/delta/stats/DataSkippingReader.scala @@ -254,6 +254,16 @@ private[delta] object DataSkippingReader { TimestampAdd("MILLISECOND", Literal(1L, LongType), col.expr)) Column(Cast(adjustedExpr, tsType)) } + + /** + * Whether `filter` must not be used for data skipping: it involves a subquery, is + * non-deterministic, or references file metadata struct fields. + */ + def isIneligibleForDataSkipping(filter: Expression): Boolean = + DeltaTableUtils.containsSubquery(filter) || !filter.deterministic || filter.exists { + case MetadataAttribute(_) => true + case _ => false + } } /** @@ -279,7 +289,7 @@ trait DataSkippingReaderBase private[delta] def numOfFilesIfKnown: Option[Long] def redactedPath: String - private def useStats = spark.sessionState.conf.getConf(DeltaSQLConf.DELTA_STATS_SKIPPING) + protected def useStats = spark.sessionState.conf.getConf(DeltaSQLConf.DELTA_STATS_SKIPPING) private lazy val limitPartitionLikeFiltersToClusteringColumns = spark.sessionState.conf.getConf( DeltaSQLConf.DELTA_DATASKIPPING_PARTITION_LIKE_FILTERS_CLUSTERING_COLUMNS_ONLY) @@ -288,22 +298,24 @@ trait DataSkippingReaderBase DeltaSQLConf.DELTA_DATASKIPPING_PARTITION_LIKE_FILTERS_ADDITIONAL_SUPPORTED_EXPRESSIONS) .toSet.flatMap((exprs: String) => exprs.split(",")) - /** Returns a DataFrame expression to obtain a list of files with parsed statistics. */ - private def withStatsInternal0: DataFrame = { - val parsedStats = from_json(col("stats"), statsSchema) + /** Parses the JSON stats in `statsCol` into the `statsSchema` struct. */ + protected def parseStats(statsCol: Column): Column = { + val parsedStats = from_json(statsCol, statsSchema) // Only use DecodeNestedZ85EncodedVariant if the schema contains VariantType. // This avoids performance overhead for tables without variant columns. // `DecodeNestedZ85EncodedVariant` is a temporary workaround since the Spark 4.1 from_json // expression has no way to decode a VariantVal from an encoded Z85 string. // TODO: Add Z85 decoding to Variant in Spark 4.2 and use that from_json option here. - val decodedStats = if (SchemaUtils.checkForVariantTypeColumnsRecursively(statsSchema)) { + if (SchemaUtils.checkForVariantTypeColumnsRecursively(statsSchema)) { Column(DecodeNestedZ85EncodedVariant(parsedStats.expr)) } else { parsedStats } - allFiles.withColumn("stats", decodedStats) } + /** Returns a DataFrame expression to obtain a list of files with parsed statistics. */ + private def withStatsInternal0: DataFrame = allFiles.withColumn("stats", parseStats(col("stats"))) + private lazy val withStatsCache = cacheDS(withStatsInternal0, s"Delta Table State with Stats #$version - $redactedPath") @@ -702,12 +714,7 @@ trait DataSkippingReaderBase // 1. involve subqueries. // 2. are non-deterministic. // 3. involve file metadata struct fields - var (ineligibleFilters, eligibleFilters) = filters.partition { - case f => containsSubquery(f) || !f.deterministic || f.exists { - case MetadataAttribute(_) => true - case _ => false - } - } + var (ineligibleFilters, eligibleFilters) = filters.partition(isIneligibleForDataSkipping) val (partitionFilters, dataFilters) = eligibleFilters diff --git a/spark/src/test/scala/org/apache/spark/sql/delta/ConflictDataSkippingSuite.scala b/spark/src/test/scala/org/apache/spark/sql/delta/ConflictDataSkippingSuite.scala index 8a0ea046d63..611306ef673 100644 --- a/spark/src/test/scala/org/apache/spark/sql/delta/ConflictDataSkippingSuite.scala +++ b/spark/src/test/scala/org/apache/spark/sql/delta/ConflictDataSkippingSuite.scala @@ -18,10 +18,11 @@ package org.apache.spark.sql.delta import java.io.File +import scala.collection.mutable import scala.concurrent.duration.Duration import scala.util.Try -import com.databricks.spark.util.Log4jUsageLogger +import com.databricks.spark.util.{Log4jUsageLogger, UsageRecord} import org.apache.spark.sql.delta.actions.AddFile import org.apache.spark.sql.delta.DeltaTestUtils.filterUsageRecords @@ -29,11 +30,13 @@ import org.apache.spark.sql.delta.concurrency.PhaseLockingTestMixin import org.apache.spark.sql.delta.concurrency.TransactionExecutionTestMixin import org.apache.spark.sql.delta.sources.DeltaSQLConf import org.apache.spark.sql.delta.test.DeltaSQLCommandTest +import org.apache.spark.sql.delta.util.JsonUtils import org.apache.spark.SparkException import org.apache.spark.sql.{QueryTest, Row, SaveMode} -import org.apache.spark.sql.catalyst.expressions.{AttributeReference, EqualTo, Expression, GreaterThanOrEqual, LessThan, Literal} +import org.apache.spark.sql.catalyst.expressions.{AttributeReference, Cast, EqualTo, Expression, GreaterThanOrEqual, LessThan, Literal, Multiply, Rand, Remainder} import org.apache.spark.sql.functions.lit +import org.apache.spark.sql.internal.SQLConf import org.apache.spark.sql.test.SharedSparkSession import org.apache.spark.sql.types.{IntegerType, LongType} import org.apache.spark.util.ThreadUtils @@ -70,16 +73,43 @@ class ConflictDataSkippingSuite extends QueryTest s"('${DeltaConfigs.ISOLATION_LEVEL.key}' = 'Serializable'$extraProps)") } - /** A DELETE that runs under the given data-skipping setting (evaluated on its commit thread). */ - private def deleteTxn(dir: File, condition: String, dataSkipping: Boolean): () => Array[Row] = + /** Runs `sqlText` with `confs` set while it runs (including its commit). */ + private def sqlTxn(sqlText: String, confs: (String, String)*): () => Array[Row] = () => { - withSQLConf( - DeltaSQLConf.DELTA_CONFLICT_DETECTION_DATA_SKIPPING_ENABLED.key -> dataSkipping.toString) { - sql(s"DELETE FROM ${tableRef(dir)} WHERE $condition").collect() - } + withSQLConf(confs: _*) { sql(sqlText).collect() } Array.empty[Row] } + private def dataSkippingConf(enabled: Boolean): (String, String) = + DeltaSQLConf.DELTA_CONFLICT_DETECTION_DATA_SKIPPING_ENABLED.key -> enabled.toString + + /** A DELETE that runs under the given data-skipping setting (evaluated on its commit thread). */ + private def deleteTxn( + dir: File, + condition: String, + dataSkipping: Boolean, + confs: (String, String)*): () => Array[Row] = + sqlTxn(s"DELETE FROM ${tableRef(dir)} WHERE $condition", + dataSkippingConf(dataSkipping) +: confs: _*) + + /** + * The subset of `files` that conflict-time data skipping keeps as conflict candidates for the + * reads `dataFiltersPerRead`: the files that could still match any of them. + */ + private def survivingFiles( + snapshot: Snapshot, + files: Seq[AddFile], + dataFiltersPerRead: Seq[Seq[Expression]]): Seq[AddFile] = { + import org.apache.spark.sql.delta.implicits._ + snapshot.conflictSkippingCondition(dataFiltersPerRead) match { + case None => files + case Some(condition) => + val paths = snapshot.applyConflictSkippingCondition(files.toDF(spark), condition) + .select("path").collect().map(_.getString(0)).toSet + files.filter(f => paths.contains(f.path)) + } + } + /** A blind append of `id` in [start, end), optionally into partition `p`. */ private def appendTxn( dir: File, start: Long, end: Long, partition: Option[Int] = None): () => Array[Row] = @@ -229,7 +259,7 @@ class ConflictDataSkippingSuite extends QueryTest } } - test("filterFilesByDataSkipping AND-combines predicates within one read") { + test("data skipping AND-combines predicates within one read") { // Predicates from a SINGLE read have AND semantics (OR is only across independent reads, which // ConflictChecker unions by construction). This exercises that AND directly. withTempDir { dir => @@ -247,17 +277,17 @@ class ConflictDataSkippingSuite extends QueryTest // Only the [200, 300) file can match `id >= 200 AND id < 300`. OR semantics would keep every // file with id >= 200 or id < 300, i.e. all 10. - val survivors = snapshot.filterFilesByDataSkipping(allFiles, Seq(ge200, lt300)) + val survivors = survivingFiles(snapshot, allFiles, Seq(Seq(ge200, lt300))) assert(survivors.size == 1, s"expected exactly the [200,300) file, got ${survivors.map(_.path).sorted}") // Sanity: a single predicate keeps its whole matching range (files with max id >= 200). - val geOnly = snapshot.filterFilesByDataSkipping(allFiles, Seq(ge200)) + val geOnly = survivingFiles(snapshot, allFiles, Seq(Seq(ge200))) assert(geOnly.size == 8, s"expected 8 files with id >= 200, got ${geOnly.size}") } } - test("filterFilesMatchingAnyReadPredicate OR-combines independent reads in one call") { + test("data skipping OR-combines independent reads in one condition") { // Independent reads have OR semantics: a file survives if it could match ANY read. This is the // multi-read path ConflictChecker uses -- all reads are evaluated together in a single job. withTempDir { dir => @@ -273,13 +303,12 @@ class ConflictDataSkippingSuite extends QueryTest val read1 = Seq[Expression]( GreaterThanOrEqual(id, Literal(200L)), LessThan(id, Literal(300L))) val read2 = Seq[Expression](GreaterThanOrEqual(id, Literal(800L))) - val survivors = - snapshot.filterFilesMatchingAnyReadPredicate(allFiles, Seq(read1, read2)) + val survivors = survivingFiles(snapshot, allFiles, Seq(read1, read2)) assert(survivors.size == 3, s"expected [200,300) + [800,1000), got ${survivors.map(_.path).sorted}") // A read with no usable predicate matches everything, so nothing can be skipped -> all kept. - val allKept = snapshot.filterFilesMatchingAnyReadPredicate(allFiles, Seq(read1, Seq.empty)) + val allKept = survivingFiles(snapshot, allFiles, Seq(read1, Seq.empty)) assert(allKept.size == allFiles.size, s"a read with no predicate must keep all files, got ${allKept.size}") } @@ -296,8 +325,8 @@ class ConflictDataSkippingSuite extends QueryTest assert(noStats.stats == null) val id = AttributeReference("id", LongType)() - val survivors = snapshot.filterFilesByDataSkipping(allFiles :+ noStats, - Seq(LessThan(id, Literal(50L)))) + val survivors = survivingFiles(snapshot, allFiles :+ noStats, + Seq(Seq(LessThan(id, Literal(50L))))) // Only the [0,100) file can match id<50; the other 9 are skipped by their stats. The file // without stats cannot be proven to miss, so it is kept. assert(survivors.size == 2, s"got ${survivors.map(_.path).sorted}") @@ -375,32 +404,82 @@ class ConflictDataSkippingSuite extends QueryTest } } + private val fallbackEvent = "delta.conflictDetection.dataSkipping.fallback" + test("skipping evaluation failure falls back to treating added files as conflicts") { - // `id < 'abc'` builds a skipping predicate over the long `id` stats that fails once evaluated - // (the string does not cast to a long). The loser records it with stats skipping off so its own - // scan does not fail, then commits with skipping on. - withTempDir { dir => - createTable(dir) - val log = DeltaLog.forTable(spark, dir.getCanonicalPath) - val id = AttributeReference("id", LongType)() - val loser = withSQLConf(DeltaSQLConf.DELTA_STATS_SKIPPING.key -> "false") { - val txn = log.startTransaction() - txn.filterFiles(Seq(LessThan(id, Literal("abc")))) - txn + // `id < 'abc'` builds a skipping predicate over the long `id` stats that fails once evaluated: + // under ANSI mode the string does not cast to a long. (Without ANSI the cast yields NULL and + // nothing fails, so the mode is pinned.) The loser records it with stats skipping off so its + // own scan does not fail, then commits with skipping on. + withSQLConf(SQLConf.ANSI_ENABLED.key -> "true") { + withTempDir { dir => + createTable(dir) + val log = DeltaLog.forTable(spark, dir.getCanonicalPath) + val id = AttributeReference("id", LongType)() + val loser = withSQLConf(DeltaSQLConf.DELTA_STATS_SKIPPING.key -> "false") { + val txn = log.startTransaction() + txn.filterFiles(Seq(LessThan(id, Literal("abc")))) + txn + } + // A stats-bearing winner file that the predicate cannot match if evaluated. + appendTxn(dir, 1000, 1100)() + val usageLogs = Log4jUsageLogger.track { + withSQLConf(dataSkippingConf(enabled = true)) { + intercept[io.delta.exceptions.ConcurrentAppendException] { + loser.commit( + Seq(manufacturedAdd("loser.parquet")), DeltaOperations.Write(SaveMode.Append)) + } + } + } + assert(filterUsageRecords(usageLogs, fallbackEvent).size == 1) + assert(filterUsageRecords(usageLogs, appliedEvent).isEmpty) } - // A stats-bearing winner file that the predicate cannot match if evaluated. - appendTxn(dir, 1000, 1100)() - val usageLogs = Log4jUsageLogger.track { - withSQLConf(DeltaSQLConf.DELTA_CONFLICT_DETECTION_DATA_SKIPPING_ENABLED.key -> "true") { - intercept[io.delta.exceptions.ConcurrentAppendException] { - loser.commit( - Seq(manufacturedAdd("loser.parquet")), DeltaOperations.Write(SaveMode.Append)) + } + } + + test("skipping evaluation failure on a partitioned table keeps partition filtering") { + // Same failing skipping predicate, paired with the partition predicate `p = 1`. The fallback + // drops only the data skipping: a file in another partition still does not conflict. + withSQLConf(SQLConf.ANSI_ENABLED.key -> "true") { + withTempDir { dir => + spark.range(0, 1000, 1, 4).withColumn("p", lit(1)) + .union(spark.range(0, 1000, 1, 4).withColumn("p", lit(2))) + .write.partitionBy("p").format("delta").save(dir.getAbsolutePath) + sql(s"ALTER TABLE ${tableRef(dir)} SET TBLPROPERTIES " + + s"('${DeltaConfigs.ISOLATION_LEVEL.key}' = 'Serializable')") + val log = DeltaLog.forTable(spark, dir.getCanonicalPath) + val id = AttributeReference("id", LongType)() + val p = AttributeReference("p", IntegerType)() + + /** Commits a loser reading `p = 1 AND id < 'abc'` after a winner appends to `winnerP`. */ + def run(winnerP: Int): (Try[Long], Seq[UsageRecord]) = { + val loser = withSQLConf(DeltaSQLConf.DELTA_STATS_SKIPPING.key -> "false") { + val txn = log.startTransaction() + txn.filterFiles(Seq(EqualTo(p, Literal(1)), LessThan(id, Literal("abc")))) + txn } + appendTxn(dir, 1000, 1100, partition = Some(winnerP))() + var result: Try[Long] = null + val usageLogs = Log4jUsageLogger.track { + withSQLConf(dataSkippingConf(enabled = true)) { + result = Try(loser.commit( + Seq(manufacturedAdd(s"loser-$winnerP.parquet", Map("p" -> "1"))), + DeltaOperations.Write(SaveMode.Append))) + } + } + (result, usageLogs) } + + val (otherPartition, otherLogs) = run(winnerP = 2) + assert(otherPartition.isSuccess, s"got $otherPartition") + assert(filterUsageRecords(otherLogs, fallbackEvent).size == 1) + val (samePartition, sameLogs) = run(winnerP = 1) + assert(samePartition.failed.toOption.exists( + _.isInstanceOf[io.delta.exceptions.ConcurrentAppendException]), s"got $samePartition") + // Once the widened probe finds a file, the probe re-runs without widening (default on), + // which falls back again. + assert(filterUsageRecords(sameLogs, fallbackEvent).nonEmpty) } - val fallbackEvent = "delta.conflictDetection.dataSkipping.fallback" - assert(filterUsageRecords(usageLogs, fallbackEvent).size == 1) - assert(filterUsageRecords(usageLogs, appliedEvent).isEmpty) } } @@ -433,4 +512,306 @@ class ConflictDataSkippingSuite extends QueryTest .exists(_.isInstanceOf[io.delta.exceptions.ConcurrentAppendException])) } } + + test("winner adding no files to check: data skipping is not reported as applied") { + // The winner only removes files, so there is no added file to check and nothing is skipped. + // The partitioned path still builds a skipping condition for its probe. + Seq(true, false).foreach { partitioned => + withTempDir { dir => + val df = spark.range(start = 0, end = 1000, step = 1, numPartitions = 10) + if (partitioned) { + df.withColumn("p", (df("id") % 2).cast("int")) + .write.partitionBy("p").format("delta").save(dir.getAbsolutePath) + } else { + df.write.format("delta").save(dir.getAbsolutePath) + } + sql(s"ALTER TABLE ${tableRef(dir)} SET TBLPROPERTIES " + + s"('${DeltaConfigs.ISOLATION_LEVEL.key}' = 'Serializable')") + val log = DeltaLog.forTable(spark, dir.getCanonicalPath) + val id = AttributeReference("id", LongType)() + val p = AttributeReference("p", IntegerType)() + withSQLConf(dataSkippingConf(enabled = true)) { + val loser = log.startTransaction() + val readFilters = + if (partitioned) Seq(EqualTo(p, Literal(0)), LessThan(id, Literal(50L))) + else Seq(LessThan(id, Literal(50L))) + val readPaths = loser.filterFiles(readFilters).map(_.path).toSet + // Remove files the loser did not read, so the removal is not a conflict either. + val removes = log.update().allFiles.collect().filterNot(f => readPaths.contains(f.path)) + .take(2).map(_.remove) + assert(removes.nonEmpty) + log.startTransaction().commit(removes, DeltaOperations.ManualUpdate) + val usageLogs = Log4jUsageLogger.track { + val partitionValues = if (partitioned) Map("p" -> "0") else Map.empty[String, String] + loser.commit( + Seq(manufacturedAdd("loser.parquet", partitionValues)), + DeltaOperations.Write(SaveMode.Append)) + } + assert(filterUsageRecords(usageLogs, appliedEvent).isEmpty, + s"partitioned=$partitioned: no added file was checked, so skipping was not applied") + } + } + } + } + + test("a batch whose DataFrame fails to build is retried by the next probe, not skipped") { + // A probe that fails while building a batch's DataFrame falls back; the next probe traverses + // the same memoized batches and must still see that batch's files. + val files = (0 until 3).map(i => manufacturedAdd(s"f$i.parquet")) + var failOnce = true + val built = mutable.ArrayBuffer[Seq[String]]() + val candidates = new ConflictCandidateFiles(files, batchSize = 1, toDF = { group => + if (failOnce && group.head.path == "f1.parquet") { + failOnce = false + throw new IllegalStateException("injected toDF failure") + } + built += group.map(_.path) + spark.emptyDataFrame + }) + intercept[IllegalStateException] { candidates.batches.foreach(_ => ()) } + assert(candidates.batches.size == 3) + assert(built == Seq(Seq("f0.parquet"), Seq("f1.parquet"), Seq("f2.parquet"))) + } + + test("concurrent UPDATE moving a row into the read range conflicts, moving it elsewhere not") { + // The loser UPDATEs id < 50. The winner UPDATEs id 500, which lives in a file the loser did not + // read; the winner's rewritten file holds the new value. + def run(dir: File, newValue: Long): Try[Array[Row]] = { + createTable(dir) + val txnA = sqlTxn(s"UPDATE ${tableRef(dir)} SET id = -id WHERE id < 50", + dataSkippingConf(enabled = true)) + val txnB = sqlTxn(s"UPDATE ${tableRef(dir)} SET id = $newValue WHERE id = 500") + val (futureA, futureB) = runTxnsWithOrder__A_Start__B__A_End(txnA, txnB) + ThreadUtils.awaitResult(futureB, Duration.Inf) + Try(ThreadUtils.awaitResult(futureA, Duration.Inf)) + } + // Moved to 10: the rewritten file's stats [10, 599] overlap id < 50 -> must conflict. + withTempDir { dir => + val result = run(dir, newValue = 10L) + assert(result.failed.toOption.exists( + _.getCause.isInstanceOf[io.delta.exceptions.ConcurrentAppendException]), s"got $result") + } + // Moved to 700: the rewritten file's stats [501, 700] do not overlap -> both commit. + withTempDir { dir => + val result = run(dir, newValue = 700L) + assert(result.isSuccess, s"got $result") + checkAnswer(spark.read.format("delta").load(dir.getAbsolutePath).select("id"), + ((0L until 50L).map(-_) ++ (50L until 1000L).filter(_ != 500L) :+ 700L).map(Row(_))) + } + } + + test("concurrent MERGE: a disjoint append is skipped, an UPDATE moving a row into range is not") { + // The MERGE reads the target with its target-only predicate `t.id < 50`. + def mergeTxn(dir: File): () => Array[Row] = sqlTxn( + s"""MERGE INTO ${tableRef(dir)} t USING (SELECT id FROM range(0, 10)) s + |ON t.id = s.id AND t.id < 50 + |WHEN MATCHED THEN DELETE""".stripMargin, + dataSkippingConf(enabled = true)) + + withTempDir { dir => + createTable(dir) + val (futureA, futureB) = + runTxnsWithOrder__A_Start__B__A_End(mergeTxn(dir), appendTxn(dir, 1000, 1100)) + ThreadUtils.awaitResult(futureB, Duration.Inf) + ThreadUtils.awaitResult(futureA, Duration.Inf) + checkAnswer(spark.read.format("delta").load(dir.getAbsolutePath).select("id"), + ((10L until 1000L) ++ (1000L until 1100L)).map(Row(_))) + } + withTempDir { dir => + createTable(dir) + val (futureA, futureB) = runTxnsWithOrder__A_Start__B__A_End( + mergeTxn(dir), sqlTxn(s"UPDATE ${tableRef(dir)} SET id = 5 WHERE id = 500")) + ThreadUtils.awaitResult(futureB, Duration.Inf) + val e = intercept[SparkException] { ThreadUtils.awaitResult(futureA, Duration.Inf) } + assertConcurrentAppend(e) + } + } + + /** [[createTable]] with deletion vectors enabled. */ + private def createDvTable(dir: File): Unit = { + createTable(dir) + sql(s"ALTER TABLE ${tableRef(dir)} SET TBLPROPERTIES " + + s"('${DeltaConfigs.ENABLE_DELETION_VECTORS_CREATION.key}' = 'true')") + } + + /** The files added by the latest commit, which must carry deletion vectors. */ + private def lastCommitDvAdds(dir: File): Seq[AddFile] = { + val log = DeltaLog.forTable(spark, dir.getCanonicalPath) + val adds = log.getChanges(log.update().version).next()._2.collect { case a: AddFile => a } + assert(adds.nonEmpty && adds.forall(_.deletionVector != null), s"expected DV adds: $adds") + adds + } + + test("deletion vectors: DELETEs in disjoint files do not conflict") { + // The winner's DELETE re-adds the [500, 600) file with a deletion vector and that file's stats, + // which do not overlap the loser's id < 50. + Seq(true, false).foreach { dataSkipping => + withTempDir { dir => + createDvTable(dir) + val txnA = deleteTxn(dir, "id < 50", dataSkipping) + val txnB = sqlTxn(s"DELETE FROM ${tableRef(dir)} WHERE id = 550") + val (futureA, futureB) = runTxnsWithOrder__A_Start__B__A_End(txnA, txnB) + ThreadUtils.awaitResult(futureB, Duration.Inf) + if (dataSkipping) { + ThreadUtils.awaitResult(futureA, Duration.Inf) + assert(lastCommitDvAdds(dir).size == 1) + checkAnswer(spark.read.format("delta").load(dir.getAbsolutePath).select("id"), + (50L until 1000L).filter(_ != 550L).map(Row(_))) + } else { + // Without skipping, the re-added file conflicts like any added file. + val e = intercept[SparkException] { ThreadUtils.awaitResult(futureA, Duration.Inf) } + assertConcurrentAppend(e) + } + } + } + } + + test("deletion vectors: DELETEs of different rows in the same file conflict") { + withTempDir { dir => + createDvTable(dir) + val txnA = deleteTxn(dir, "id = 10", dataSkipping = true) + val txnB = sqlTxn(s"DELETE FROM ${tableRef(dir)} WHERE id = 20") + val (futureA, futureB) = runTxnsWithOrder__A_Start__B__A_End(txnA, txnB) + ThreadUtils.awaitResult(futureB, Duration.Inf) + val e = intercept[SparkException] { ThreadUtils.awaitResult(futureA, Duration.Inf) } + assertConcurrentAppend(e) + } + } + + test("deletion vectors: stats that still cover deleted rows are used conservatively") { + // The winner deletes id < 30 from the [0, 100) file. Its re-added file keeps the file's stats + // [0, 99] (not tight: they still cover the deleted rows), so the loser's id < 20, which only + // matches rows the winner deleted, still conflicts. + withTempDir { dir => + createDvTable(dir) + val txnA = deleteTxn(dir, "id < 20", dataSkipping = true) + val txnB = sqlTxn(s"DELETE FROM ${tableRef(dir)} WHERE id < 30") + val (futureA, futureB) = runTxnsWithOrder__A_Start__B__A_End(txnA, txnB) + ThreadUtils.awaitResult(futureB, Duration.Inf) + val e = intercept[SparkException] { ThreadUtils.awaitResult(futureA, Duration.Inf) } + assertConcurrentAppend(e) + val Seq(winnerAdd) = lastCommitDvAdds(dir) + assert(winnerAdd.tightBounds.contains(false), winnerAdd.stats) + } + } + + test("column mapping: stats keyed by physical names are matched to the logical column") { + Seq((1000L, 1100L, true), (0L, 10L, false)).foreach { case (start, end, commits) => + withTempDir { dir => + sql(s"CREATE TABLE ${tableRef(dir)} (id BIGINT) USING delta TBLPROPERTIES (" + + s"'${DeltaConfigs.COLUMN_MAPPING_MODE.key}' = 'name', " + + s"'${DeltaConfigs.ISOLATION_LEVEL.key}' = 'Serializable')") + spark.range(start = 0, end = 1000, step = 1, numPartitions = 10) + .write.format("delta").mode("append").save(dir.getAbsolutePath) + val snapshot = DeltaLog.forTable(spark, dir.getCanonicalPath).update() + val physicalName = DeltaColumnMapping.getPhysicalName(snapshot.schema("id")) + assert(physicalName != "id") + assert(snapshot.allFiles.collect().forall(_.stats.contains(s""""$physicalName":"""))) + + val txnA = deleteTxn(dir, "id < 50", dataSkipping = true) + val (futureA, futureB) = + runTxnsWithOrder__A_Start__B__A_End(txnA, appendTxn(dir, start, end)) + ThreadUtils.awaitResult(futureB, Duration.Inf) + if (commits) { + ThreadUtils.awaitResult(futureA, Duration.Inf) + checkAnswer(spark.read.format("delta").load(dir.getAbsolutePath).select("id"), + disjointExpected) + } else { + val e = intercept[SparkException] { ThreadUtils.awaitResult(futureA, Duration.Inf) } + assertConcurrentAppend(e) + } + } + } + } + + test("non-deterministic and unusable predicates are not used to skip, other conjuncts are") { + withTempDir { dir => + createTable(dir) + val log = DeltaLog.forTable(spark, dir.getCanonicalPath) + val id = AttributeReference("id", LongType)() + val lt50 = LessThan(id, Literal(50L)) + // id < cast(rand(0) * 50 as bigint): references id, but non-deterministic. + val nonDeterministic = + LessThan(id, Cast(Multiply(Rand(Literal(0L)), Literal(50.0)), LongType)) + assert(!nonDeterministic.deterministic) + // id % 7 = 3: deterministic, but min/max stats cannot evaluate it. + val unusable = EqualTo(Remainder(id, Literal(7L)), Literal(3L)) + var appended = 0L + + /** Commits a loser reading `readFilters` after a winner appends a disjoint id range. */ + def run(readFilters: Seq[Expression]): Try[Long] = + withSQLConf(dataSkippingConf(enabled = true)) { + val loser = log.startTransaction() + loser.filterFiles(readFilters) + val start = 1000L + appended + appended += 100 + appendTxn(dir, start, start + 100)() + Try(loser.commit( + Seq(manufacturedAdd(s"loser-$start.parquet")), DeltaOperations.Write(SaveMode.Append))) + } + def conflicted(result: Try[Long]): Boolean = result.failed.toOption.exists( + _.isInstanceOf[io.delta.exceptions.ConcurrentAppendException]) + + Seq(Seq(nonDeterministic), Seq(unusable), Seq(nonDeterministic, unusable)).foreach { read => + val result = run(read) + assert(conflicted(result), s"$read: nothing to skip with, expected a conflict: $result") + } + Seq(Seq(nonDeterministic, lt50), Seq(unusable, lt50)).foreach { read => + val result = run(read) + assert(result.isSuccess, s"$read: id < 50 alone proves the file cannot match: $result") + } + } + } + + test("stats skipping disabled: conflict-time data skipping does not apply") { + withTempDir { dir => + createTable(dir) + val txnA = deleteTxn(dir, "id < 50", dataSkipping = true, + DeltaSQLConf.DELTA_STATS_SKIPPING.key -> "false") + val txnB = appendTxn(dir, 1000, 1100) + val usageLogs = Log4jUsageLogger.track { + val (futureA, futureB) = runTxnsWithOrder__A_Start__B__A_End(txnA, txnB) + ThreadUtils.awaitResult(futureB, Duration.Inf) + val e = intercept[SparkException] { ThreadUtils.awaitResult(futureA, Duration.Inf) } + assertConcurrentAppend(e) + } + assert(filterUsageRecords(usageLogs, appliedEvent).isEmpty) + } + } + + test("applied event is reported once per commit across several winning commits") { + withTempDir { dir => + createTable(dir) + val log = DeltaLog.forTable(spark, dir.getCanonicalPath) + val id = AttributeReference("id", LongType)() + + /** Commits a loser reading id < 50 after winners appending each of `winnerRanges`. */ + def run(winnerRanges: (Long, Long)*): (Try[Long], Seq[UsageRecord]) = + withSQLConf(dataSkippingConf(enabled = true)) { + val loser = log.startTransaction() + loser.filterFiles(Seq(LessThan(id, Literal(50L)))) + winnerRanges.foreach { case (start, end) => appendTxn(dir, start, end)() } + var result: Try[Long] = null + val usageLogs = Log4jUsageLogger.track { + result = Try(loser.commit( + Seq(manufacturedAdd(s"loser-${log.update().version}.parquet")), + DeltaOperations.Write(SaveMode.Append))) + } + (result, usageLogs) + } + + // Two winners, both skipped: one event, for the version the loser committed. + val (committed, committedLogs) = run((1000L, 1100L), (1100L, 1200L)) + assert(committed.isSuccess, s"got $committed") + val events = filterUsageRecords(committedLogs, appliedEvent) + assert(events.size == 1) + val data = JsonUtils.mapper.readValue[Map[String, Any]](events.head.blob) + assert(data("committedVersion").toString == committed.get.toString) + // The first winner is skipped, the second conflicts: the commit fails, no event. + val (conflicted, conflictedLogs) = run((1200L, 1300L), (0L, 10L)) + assert(conflicted.failed.toOption.exists( + _.isInstanceOf[io.delta.exceptions.ConcurrentAppendException]), s"got $conflicted") + assert(filterUsageRecords(conflictedLogs, appliedEvent).isEmpty) + } + } } From cc19c11ee6d08bbf02a7948d9dd8bab0dcb71ea9 Mon Sep 17 00:00:00 2001 From: Eunjin Song Date: Thu, 19 Nov 2026 21:39:07 -0800 Subject: [PATCH 9/9] Keep useStats private and the stats parser in place Conflict-time skipping reads the stats-skipping conf inline again rather than widening DataSkippingReaderBase.useStats, and parseStats now follows withStatsInternal0 instead of replacing it, so the scan path changes only where it calls the two shared helpers. Co-Authored-By: Claude Opus 5.5 Signed-off-by: Eunjin Song --- .../sql/delta/stats/ConflictDataSkippingReader.scala | 5 ++++- .../spark/sql/delta/stats/DataSkippingReader.scala | 10 ++++++---- 2 files changed, 10 insertions(+), 5 deletions(-) diff --git a/spark/src/main/scala/org/apache/spark/sql/delta/stats/ConflictDataSkippingReader.scala b/spark/src/main/scala/org/apache/spark/sql/delta/stats/ConflictDataSkippingReader.scala index abe08b023de..23408a283b5 100644 --- a/spark/src/main/scala/org/apache/spark/sql/delta/stats/ConflictDataSkippingReader.scala +++ b/spark/src/main/scala/org/apache/spark/sql/delta/stats/ConflictDataSkippingReader.scala @@ -18,6 +18,7 @@ package org.apache.spark.sql.delta.stats import org.apache.spark.sql.delta.ClassicColumnConversions._ import org.apache.spark.sql.delta.metering.DeltaLogging +import org.apache.spark.sql.delta.sources.DeltaSQLConf import org.apache.spark.sql.{Column, DataFrame} import org.apache.spark.sql.catalyst.expressions._ @@ -46,7 +47,9 @@ trait ConflictDataSkippingReader extends DeltaLogging { self: DataSkippingReader */ private[delta] def buildDataSkippingPredicate( dataFilters: Seq[Expression]): Option[DataSkippingPredicate] = { - if (!useStats) return None + // Stats-skipping conf, inlined from DataSkippingReaderBase.useStats (file-private, so not + // visible here). Reading it inline avoids widening that member's visibility. + if (!spark.sessionState.conf.getConf(DeltaSQLConf.DELTA_STATS_SKIPPING)) return None // Same eligibility as filesForScan: drop subquery / non-deterministic / metadata filters, so we // never build a skipping predicate that could wrongly exclude a matching file. Dropping a // conjunct only widens the predicate. diff --git a/spark/src/main/scala/org/apache/spark/sql/delta/stats/DataSkippingReader.scala b/spark/src/main/scala/org/apache/spark/sql/delta/stats/DataSkippingReader.scala index 53be8f06a51..574c8778be7 100644 --- a/spark/src/main/scala/org/apache/spark/sql/delta/stats/DataSkippingReader.scala +++ b/spark/src/main/scala/org/apache/spark/sql/delta/stats/DataSkippingReader.scala @@ -289,7 +289,7 @@ trait DataSkippingReaderBase private[delta] def numOfFilesIfKnown: Option[Long] def redactedPath: String - protected def useStats = spark.sessionState.conf.getConf(DeltaSQLConf.DELTA_STATS_SKIPPING) + private def useStats = spark.sessionState.conf.getConf(DeltaSQLConf.DELTA_STATS_SKIPPING) private lazy val limitPartitionLikeFiltersToClusteringColumns = spark.sessionState.conf.getConf( DeltaSQLConf.DELTA_DATASKIPPING_PARTITION_LIKE_FILTERS_CLUSTERING_COLUMNS_ONLY) @@ -298,6 +298,11 @@ trait DataSkippingReaderBase DeltaSQLConf.DELTA_DATASKIPPING_PARTITION_LIKE_FILTERS_ADDITIONAL_SUPPORTED_EXPRESSIONS) .toSet.flatMap((exprs: String) => exprs.split(",")) + /** Returns a DataFrame expression to obtain a list of files with parsed statistics. */ + private def withStatsInternal0: DataFrame = { + allFiles.withColumn("stats", parseStats(col("stats"))) + } + /** Parses the JSON stats in `statsCol` into the `statsSchema` struct. */ protected def parseStats(statsCol: Column): Column = { val parsedStats = from_json(statsCol, statsSchema) @@ -313,9 +318,6 @@ trait DataSkippingReaderBase } } - /** Returns a DataFrame expression to obtain a list of files with parsed statistics. */ - private def withStatsInternal0: DataFrame = allFiles.withColumn("stats", parseStats(col("stats"))) - private lazy val withStatsCache = cacheDS(withStatsInternal0, s"Delta Table State with Stats #$version - $redactedPath")